An open source design system that's fully customizable and agent ready
TypeScript
Compile every doc kind from one resolver, and give themes typed descriptors (#6498)
Joey34b4692a3a9a
diff --git a/.changeset/authoring-docs-debug-and-gap-report.md b/.changeset/authoring-docs-debug-and-gap-report.mdnew file mode 100644index 0000000000..fa06474100--- /dev/null+++ b/.changeset/authoring-docs-debug-and-gap-report.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] `astryx docs authoring` now documents the `DebugEvent` a `debug` handler receives and the `GapReportHandler` contract, field by field. Both types were exported from `@astryxdesign/cli/authoring` with no section of their own.++@josephfarinadiff --git a/.changeset/cli-docs-topic.md b/.changeset/cli-docs-topic.mdnew file mode 100644index 0000000000..29835eb8a1--- /dev/null+++ b/.changeset/cli-docs-topic.md@@ -0,0 +1,9 @@+---+'@astryxdesign/cli': patch+---++[feat] Read every command and API function with `astryx docs cli`.++`astryx docs cli` has one section for each command (`commands-<name>`) and for each API function, plus the JSON output envelope, error codes, and response types (`api-<name>`). Every command, API function, schema, and enum doc the CLI ships now declares the `namespace` that reads it, and `astryx doctor` fails when one has none or names one no topic reads.++@josephfarinadiff --git a/.changeset/doctor-authoring-surface.md b/.changeset/doctor-authoring-surface.mdnew file mode 100644index 0000000000..bdee769fb7--- /dev/null+++ b/.changeset/doctor-authoring-surface.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] `astryx doctor` now fails when a type that `@astryxdesign/cli/authoring` exports has no doc in `astryx docs authoring`, or when a listed self-doc documents nothing the package exports. The message names each type, the module that declares it, and the self-doc that is missing or not listed.++@josephfarinadiff --git a/.changeset/doctor-integration-fixes.md b/.changeset/doctor-integration-fixes.mdnew file mode 100644index 0000000000..7e28c12cd4--- /dev/null+++ b/.changeset/doctor-integration-fixes.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx doctor integration validate` now ends each finding about a misplaced contribution, a stray codemod file, a mis-named codemod folder, a component doc without its source, or a component source without a doc with a fix that works when followed as written: where to move the file and the manifest line to add, the version folder a codemod belongs in, or the file to add. Codemod files are named by their path inside the package instead of an absolute path. A hidden component doc no longer draws the missing-doc warning, and a codemods root at the package root no longer reports the manifest as a stray codemod.++@josephfarinadiff --git a/.changeset/extends-keeps-topic-title.md b/.changeset/extends-keeps-topic-title.mdnew file mode 100644index 0000000000..384d336fa7--- /dev/null+++ b/.changeset/extends-keeps-topic-title.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] An integration topic that `extends` another no longer renames it. `astryx docs theme` with an extension installed used to print the extension's own title and description; the topic now keeps its own, and the extension only adds or replaces sections. A topic that `replaces` another still renames it.++@josephfarinadiff --git a/.changeset/first-party-theme-descriptors.md b/.changeset/first-party-theme-descriptors.mdnew file mode 100644index 0000000000..93530f9122--- /dev/null+++ b/.changeset/first-party-theme-descriptors.md@@ -0,0 +1,13 @@+---+'@astryxdesign/theme-butter': patch+'@astryxdesign/theme-chocolate': patch+'@astryxdesign/theme-gothic': patch+'@astryxdesign/theme-matcha': patch+'@astryxdesign/theme-neutral': patch+'@astryxdesign/theme-stone': patch+'@astryxdesign/theme-y2k': patch+---++[feat] Ship a typed `ThemeDoc` descriptor beside each first-party theme source.++@josephfarinadiff --git a/.changeset/typed-theme-descriptors.md b/.changeset/typed-theme-descriptors.mdnew file mode 100644index 0000000000..df1cc1b526--- /dev/null+++ b/.changeset/typed-theme-descriptors.md@@ -0,0 +1,11 @@+---+'@astryxdesign/cli': minor+---++[breaking] Integration themes use typed same-stem descriptors, not a central catalog.++A themes root no longer holds `manifest.json`, the theme catalog that `astryx integration add theme` wrote in 0.6 (stable since 0.6.3). Each theme carries a strongly typed `<name>Theme.doc.mjs` beside its source instead, and a themes root that still holds the catalog is refused. To migrate an integration package, run `astryx upgrade --from 0.6.3 --path . --apply` in it: a codemod writes each theme's descriptor from its catalog entry and removes the catalog. Until a package is migrated, apps that install it get none of its themes or doc topics.++Theme discovery reads descriptors and checks integration theme sources without executing them, and `theme add` copies an integration theme's complete directory. `astryx doctor integration validate` warns about a folder in the themes root that looks like a theme but is not read as one. New component, topic, and template scaffolds also emit type-annotated `.doc.mjs`; released `.template.*` inputs remain readable.++@josephfarinadiff --git a/AGENTS.md b/AGENTS.mdindex dffd25af35..07f94e56d2 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -41,6 +41,10 @@ nested `AGENTS.md`.applicable design spec under `docs/design/`, and current architecture under`docs/architecture/`.- Consequential shared-system changes: use a record under `docs/specs/`.+- Integration contribution work: read `docs/specs/AST-039/spec.md`. Every new+ discoverable item owns a strongly typed, same-stem `.doc.mjs`; root manifests+ locate directories and never catalog their items. No catalog file (like+ `themes/manifest.json`) and no per-item map in the manifest, ever.## Authoritydiff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex 4182100b7f..4a99ef2b81 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -1698,6 +1698,10 @@ async function generateDocsRegistry() {if (DOCSITE_TARGET !== 'canary' && topic === 'shadcn-compatibility') {continue;}+ // /docs/cli is the @astryxdesign/cli package page. The CLI reference topic+ // (`astryx docs cli`) joins the site when its namespace page takes that+ // URL; packages/cli/test/doc-routes.test.mjs records the same skip.+ if (topic === 'cli') continue;const docPath = path.join(DOCS_DIR, file);let title = '';diff --git a/apps/docsite/src/__tests__/strip-html-comments.test.ts b/apps/docsite/src/__tests__/strip-html-comments.test.tsnew file mode 100644index 0000000000..ff6c7bb624--- /dev/null+++ b/apps/docsite/src/__tests__/strip-html-comments.test.ts@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {stripHtmlComments} from '../components/docs/stripHtmlComments';++describe('stripHtmlComments', () => {+ it('hides the markers a generated README carries, and nothing else', () => {+ const readme =+ '# CLI\n\n<!-- BEGIN commands -->\n| a | b |\n<!-- Generated by a script.\nRun it. -->\n<!-- END commands -->\nText <b>kept</b>.\n';+ expect(stripHtmlComments(readme)).toBe(+ '# CLI\n\n| a | b |\nText <b>kept</b>.\n',+ );+ });+});diff --git a/apps/docsite/src/components/docs/PackageStubPage.tsx b/apps/docsite/src/components/docs/PackageStubPage.tsxindex e0b8aa4a0c..19a00a2ae6 100644--- a/apps/docsite/src/components/docs/PackageStubPage.tsx+++ b/apps/docsite/src/components/docs/PackageStubPage.tsx@@ -9,6 +9,7 @@ import {Text, Heading} from '@astryxdesign/core/Text';import {Markdown} from '@astryxdesign/core/Markdown';import {Divider} from '@astryxdesign/core/Divider';import {parseOutlineFromMarkdown} from '@astryxdesign/core/Outline';+import {stripHtmlComments} from './stripHtmlComments';import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';import {DocPageLayout} from './DocPageLayout';import {PackageActions, type InstallStep} from './PackageActions';@@ -82,7 +83,7 @@ export function PackageStubPage({stripSections,stripIntro,}: PackageStubPageProps) {- let body = readme ? readme.replace(/^# .+\n+/, '') : null;+ let body = readme ? stripHtmlComments(readme).replace(/^# .+\n+/, '') : null;if (body && stripIntro) {// Remove leading prose up to the first ## section heading.diff --git a/apps/docsite/src/components/docs/stripHtmlComments.ts b/apps/docsite/src/components/docs/stripHtmlComments.tsnew file mode 100644index 0000000000..4ec6facff2--- /dev/null+++ b/apps/docsite/src/components/docs/stripHtmlComments.ts@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Drop HTML comments from Markdown before rendering: GitHub and npm hide+ * them, and core's Markdown would print them as text.+ */++/** @param text Markdown source. */+export function stripHtmlComments(text: string): string {+ return text.replace(/<!--[\s\S]*?-->[ \t]*\n?/g, '');+}diff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.mdindex 807199d54f..8b643f75f4 100644--- a/docs/architecture/cli-surface.md+++ b/docs/architecture/cli-surface.md@@ -22,6 +22,9 @@ verified_by:foundation/integrations/autolink.test.mjs,foundation/integrations/manifest-writer.test.mjs,foundation/integrations/contribution-inventory.test.mjs,+ foundation/discovery/theme-discovery.test.mjs,+ authoring/doctypes/doctypes-new.test.mjs,+ scripts/check-cli-theme-bundle.test.mjs,clients/cli/commands/integration-authoring.test.mjs,clients/cli/commands/integration-real-world.test.mjs,api/integration/add-contribution.test.mjs,@@ -165,13 +168,18 @@ test, applicable text, and consumer-documentation projections.and records its issue; a package-scoped theme lookup surfaces that package'sblocking catalog error instead of misreporting the theme as unknown.- **INV19 — Integration themes are packaged editable source.** The manifest's- `themes` root contains a versioned catalog. Each entry names its slug, source- entry, named runtime export, and complete file list. Discovery parses the entry- without executing it, requires every local static import and re-export to name- a file in that list, and rejects missing or type-only named exports. Pack- verification preserves that identity; `theme list` retains package ownership;- `theme add --package` copies every listed file, including nested palette/token- modules, before `theme build` compiles the consumer-owned copy.+ `themes` root contains one directory per slug. Every theme source has a mandatory+ same-stem, strongly typed `ThemeDoc`; there is no root item catalog. Discovery+ derives the source entry and required named runtime export from the shared stem,+ parses source without executing it, and rejects escaped local imports and missing+ or type-only runtime exports. The theme directory is the recursive copy and pack+ boundary; dot entries and files npm never publishes belong to no theme. A+ dot-folder, or a folder holding neither a descriptor nor a `<name>Theme`+ source, is not a theme and is neither read nor packed, and doctor warns about+ one that looks like a theme; a folder with a theme source and no descriptor+ fails. `theme list` retains package+ ownership, and `theme add --package` copies the complete directory before+ `theme build` compiles the consumer-owned copy.- **INV20 — A command's API subject has one layout.** A command's behavior livesin `api/<subject>/`. `<subject>.mjs` is the subject's entry, and `api/index.mjs`re-exports what it exports. A subject with more than one operation puts each in@@ -208,6 +216,21 @@ test, applicable text, and consumer-documentation projections.no renderer of its own; it maps its data onto records, lists, and sections. Ablock kind is added to the kit, with its tests and its line in the help"Output format" list, only as `spec:AST-042` FR3 allows.+- **INV24 — Every discoverable integration item owns one typed descriptor.** New+ authoring emits `<source-stem>.doc.mjs`, annotated with its public type from+ `@astryxdesign/cli/authoring`, beside the source or payload it describes. The+ descriptor is the sole per-item metadata authority; `astryx.integration.*`+ locates roots and integration-level capabilities but never catalogs items:+ there is no catalog file under a root and no per-item map or list in the+ manifest (`spec:AST-039/FR11`). A released alternate reader is an isolated+ compatibility path, not a second authoring convention.+- **INV25 — Every CLI doc names the topic that reads it.** Each command, API+ function, schema, and enum doc the CLI ships declares a `namespace`.+ `cli/commands` and `cli/api` docs are sections of `astryx docs cli`, keyed+ `commands-<name>` and `api-<name>`; `authoring` docs are sections of+ `astryx docs authoring` and appear in its list. `astryx doctor` fails when a+ CLI doc has no namespace, names one no topic reads, or disagrees with the+ authoring list, so every doc the CLI ships stays readable from the CLI.Some modules predate INV20–INV23 and do not meet them yet; `spec:AST-042` liststhe known gaps.@@ -226,12 +249,14 @@ updated in the same pull request when it moves an invariant:- changing the file layout under `clients/cli/commands`;- adding an API subject, leaf, adapter, or exported function, or giving an APImodule access to the environment (INV20–INV21);+- adding a command, API function, schema, or enum doc, or a namespace a CLI+ doc may declare (INV25);- changing an integration writer's receipt, no-clobber/rollback behavior,package.json mutation policy, or public subpath spelling;- changing what `integration pack --check` executes, resolves, or proves aboutthe tarball;- changing local, configured, or autolinked integration precedence;-- changing the integration theme catalog or consumer copy contract.+- changing an integration item descriptor, the theme directory boundary, or the consumer copy contract.`pnpm check:cli-structure` enforces the layout. The contract tests listed in`verified_by` enforce the envelope, the exit codes, the error codes, and the@@ -257,8 +282,8 @@ non-interactive guarantee.packed contribution identity/file contract.- `api/integration` — contribution writers, diagnostics, and packed-artifactverification.-- `foundation/discovery/theme-discovery.mjs` and `api/theme` — integration theme- catalog discovery, package-aware selection, source copy, and build.+- `foundation/discovery/theme-discovery.mjs` and `api/theme` — typed integration+ theme descriptor discovery, package-aware selection, source copy, and build.- `foundation/agent-docs` — the shared expected-block renderer and managed-filewriter used by init and upgrade.- `api/index.mjs` — the public programmatic API, `@astryxdesign/cli/api`, which@@ -297,6 +322,8 @@ non-interactive guarantee.| INV21 | Review of imports under `api/**`; no mechanical check yet | A module other than a subject's adapter reads or writes files, contacts the network, starts a subprocess, loads the project, or runs discovery. || INV22 | Review of imports under `clients/cli/commands/**`; the docs drift harness checks each `CommandDoc` against the live command | A handler reaches the environment itself, an executable command's `CommandDoc` names no `fn`, or a non-command file sits in the directory. || INV23 | `clients/cli/formatters/index.test.mjs` for the kit; review of handlers; no mechanical check yet | A handler pads, aligns, or draws text itself, or a block kind is missing from the help "Output format" list. |+| INV24 | `api/integration/add-contribution.test.mjs`, `api/integration/add-theme.test.mjs`, `foundation/discovery/theme-discovery.test.mjs` | New authoring emits an untyped or non-`.doc.mjs` item, adding one item edits a shared file, or an item catalog becomes authoritative. |+| INV25 | `foundation/discovery/cli-self-docs.test.mjs`, `api/doctor/doctor.test.mjs` | A CLI doc with no namespace, a namespace no topic reads, or no section in its topic passes doctor. |## Open questionsdiff --git a/docs/contributing/cli-conventions.md b/docs/contributing/cli-conventions.mdindex dee419f35d..8a00e2c7cf 100644--- a/docs/contributing/cli-conventions.md+++ b/docs/contributing/cli-conventions.md@@ -163,6 +163,32 @@ manifest are generated from it, so an undocumented flag is an invisible flag.Give at least one example that an agent would actually run, including a `--json`one.+## Every integration item ships a typed doc++A discoverable contribution is not done without a strongly typed+`<source-stem>.doc.mjs` beside its source or payload. Export the descriptor type+from `@astryxdesign/cli/authoring`, annotate the descriptor with that type, and+use the kind's canonical typed export. New descriptor kinds use the stamped+default export. The descriptor is the only place for item metadata. The root+integration manifest points at directories; it does not enumerate the items+inside them.++When an item spans several files, define one confined item-local ownership+boundary and make discovery, materialization, and pack verification enumerate the+same complete set. Never repeat source identity in the descriptor when the+same-stem pair proves it.++Never catalog items centrally, for any kind: no file under a root that lists its+items (like `themes/manifest.json`), and no per-item map or list in the+integration manifest (like a map of template replacements). Per-item options+such as `replaces` go in the item's own `.doc.mjs`. Adding one item changes no+file its siblings share, apart from declaring a new root. 0.6 shipped a theme+catalog and had to remove it as a breaking change; do not repeat it.++Released alternate readers may remain for compatibility, but new writers,+examples, and contribution kinds use `.doc.mjs`. See `spec:AST-039` for the+compatibility transition and the mandatory theme descriptor contract.+## Marking work in progressSome of the surface is not finished, and today nothing on it says so. Callers@@ -180,6 +206,8 @@ change.- [ ] The handler only parses, calls one exported `api/` function, and renders;the subject's adapter does any file, network, or project access.- [ ] One file per command, with its sibling doc file.+- [ ] Every new integration item has a typed, same-stem `.doc.mjs`; the root+ manifest only locates its directory. No catalog file, no per-item map.- [ ] `--json` returns one envelope; the `type` matches the API function.- [ ] Every failure path carries a code; new codes are appended, never edited.- [ ] No `console.log`; all human output goes through the formatters, with no@@ -194,6 +222,9 @@ change.## Common review smells+- **An item catalog below an integration root, or a per-item map in the+ manifest.** Put metadata and options in the typed, same-stem `.doc.mjs`; the+ root manifest points at the directory.- **A flag that only a maintainer would pass.** It is a debugging affordance;keep it out of the surface.- **A new command whose summary contains "and".** Two commands.diff --git a/docs/specs/AST-039/spec.md b/docs/specs/AST-039/spec.mdnew file mode 100644index 0000000000..671e565f62--- /dev/null+++ b/docs/specs/AST-039/spec.md@@ -0,0 +1,236 @@+---+schema_version: 4+template_version: 1+kind: system-spec+id: spec:AST-039+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+phase: implementing+owners: [josephfarina]+affects_architecture: [architecture:cli-surface]+affects_families: []+affects_contributing: [contributing:cli-conventions]+affects_consumer_docs: [cli-integrations]+---++# Integration contribution descriptor system spec++## Intent++Every discoverable item that an Astryx integration contributes has one local,+strongly typed description beside the item it describes. A contributor can+understand, author, validate, move, and package one item without editing a+second catalog elsewhere in the package.++The canonical descriptor is `<source-stem>.doc.mjs`. It is the only source of+per-item metadata. The integration manifest locates contribution roots and+holds integration-level capabilities; it does not catalog the items below a+root. There is no central catalog of items anywhere, in any form (FR11): 0.6+shipped one for themes by mistake, and it had to be removed as a breaking+change.++## Non-goals++- Remove a released compatibility reader before the normal breaking-change and+ migration process permits it.+- Make runtime integration features such as `debug` or `gapReport` into item+ contributions. Their typed named-export contract remains owned by+ `spec:AST-031`.+- Put build receipts, generated output manifests, or consumer runtime data into+ authoring descriptors.+- Require a separate executable source file for a reference doc whose+ `.doc.mjs` is itself the complete payload.+- Execute contributed source during discovery to learn its metadata.++## Requirements++- **FR1 — Every discoverable item owns one canonical descriptor.** A new or+ newly authored component, template, theme, doc topic, codemod, or future item+ contribution MUST have exactly one `<source-stem>.doc.mjs` descriptor. When+ the item has a primary source or payload file, the descriptor MUST be beside+ it and MUST use the same stem. A reference doc is both descriptor and payload.+- **FR2 — Descriptors are strongly typed authoring modules.** Every descriptor+ kind MUST export a public TypeScript type from+ `@astryxdesign/cli/authoring`, use that type in a JSDoc annotation, and+ expose its value through the kind's canonical export (the stamped default+ export for a new descriptor kind). Discovery MUST parse the loaded value through the kind's public authoring parser at the load+ boundary. A new kind is incomplete without its type, parser, self-doc, and+ parser tests.+- **FR3 — The descriptor is the sole item-metadata authority.** Per-item names,+ labels, descriptions, readiness or maintenance state, source relationship,+ and copy metadata MUST NOT be duplicated in a root JSON catalog, an array in+ `astryx.integration.*`, or another package-level registry. The integration+ manifest MAY locate roots and declare integration-level metadata or runtime+ capabilities. It MUST NOT enumerate the items under a root. Per-item options,+ such as `replaces` and `extends`, belong in the item's own descriptor.+- **FR4 — Pair identity is structural.** Discovery MUST derive the primary+ source path and any source-bound runtime export identity from the shared+ descriptor/source stem when that relationship is structural. The descriptor+ owns the stable public item identity. Discovery MUST reject a missing source,+ more than one eligible same-stem source, an invalid inferred export name, or+ a descriptor whose authored identity conflicts with its required directory+ identity.+- **FR5 — Multi-file items have one confined ownership boundary.** A kind whose+ item needs nested source, token, palette, asset, or receipt files MUST define+ one item-local copy and pack boundary. Discovery and authoring MUST enumerate+ that boundary without a second catalog, keep every path inside it, and copy+ the complete owned set. A missing local dependency, an escaped path, and an+ unexpected symlink target MUST fail before consumer writes.+- **FR6 — Discovery does not execute contributed payload source.** Loading a+ descriptor follows the established doc-module boundary. Executable component,+ theme, template, and codemod payloads MUST be inspected or resolved without+ running them during discovery. Static validation MUST reject type-only or+ missing runtime exports where a runtime binding is part of the contract.+- **FR7 — One discovery seam serves every downstream surface.** Listing,+ package ownership, ambiguity handling, authoring verification, Doctor,+ package inventory, packed-consumer verification, and materialization MUST+ consume the same normalized discovered record. A writer MUST verify its output+ through that seam rather than reimplementing the format.+- **FR8 — Authoring emits only the canonical form.** `astryx integration add`+ and its typed APIs MUST write `.doc.mjs`, the public JSDoc type annotation,+ and the conventional export. They MUST NOT create a new legacy alias, central+ item catalog, untyped object, or duplicated metadata source.+- **FR9 — Released aliases are compatibility inputs, not authoring precedent.**+ Readers MAY retain a released alternate suffix or combined module while the+ compatibility policy requires it. New writers and examples MUST use the+ canonical descriptor. Each retained alias MUST be isolated, tested as a+ compatibility path, and excluded from the design of new contribution kinds.+ Canary-only formats have no compatibility claim.+- **FR10 — Theme registration is the first clean application.** A theme root+ contains one directory per lower-kebab slug. That directory contains a theme+ source and mandatory same-stem `.doc.mjs`. `ThemeDoc` owns `name`,+ `displayName`, `description`, and `maintained`; the source entry and named+ runtime export come from the shared stem. The directory is the recursive copy+ and pack boundary. `themes/manifest.json` MUST NOT remain as a fallback+ reader. The catalog shipped in stable `0.6.3`, so its removal is a breaking+ change: it ships in a minor release with a codemod that turns each catalog+ entry into that theme's descriptor, and a themes root that still holds the+ catalog fails with a message that names the migration.+- **FR11 — Never catalog items centrally.** No change MAY add, for any kind, a+ file under a root that lists that root's items (`themes/manifest.json`, a+ `components/index.json`, or similar), a per-item map or list in+ `astryx.integration.*` (for example a map of template replacements or a list+ of themes), or a registry that authors keep in sync by hand. Adding one item+ MUST NOT change a file its siblings share; only the integration manifest and+ `package.json` may change, to declare a new root. Review MUST reject a change+ that adds a central catalog, and writer tests MUST fail on one.++### Compatibility transition++The final rule applies to every kind. Existing released inputs move to it+without pretending they were never released:++- components and reference docs already use `.doc.*`; new authoring narrows to+ strongly typed `.doc.mjs` while released suffixes remain readable;+- templates keep their released `.template.*` reader, but new authoring and+ examples use the already-supported `.doc.mjs` pair;+- themes replace the JSON catalog, released in `0.6.3`, as a breaking change:+ no dual reader, and a codemod converts each package;+- combined codemod modules and inline `agentDocs` remain released compatibility+ inputs until their paired-descriptor migrations ship; they do not permit+ another contribution kind to omit a descriptor.++## Current-state impact++This specification owns a distinct boundary that no current system spec covered.+`spec:AST-031` explicitly excludes default-manifest item contributions, while+`architecture:cli-surface` describes the implementation but cannot authorize a+new cross-kind authoring rule.++This specification replaces the catalog claim in+`architecture:cli-surface/INV19` with one mandatory per-theme descriptor. It+adds a general descriptor invariant to the CLI architecture and contributor+checklist. The theme change updates public authoring types, discovery, bundled+assets, integration authoring, package inventory, pack verification, consumer+docs, and real provider-to-consumer tests.++The contract does not change `DefineThemeInput` or `DefinedTheme`. Theme package+metadata stays outside Core runtime authoring, consistent with+`architecture:theme-authoring-contract/INV11`.++## Verification++| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| FR1–FR4 | authoring parser, discovery, and writer tests | valid pair; missing/duplicate source; bad identity; malformed/missing doc | a source without its typed same-stem descriptor becomes visible, or duplicated metadata can win |+| FR5–FR7 | contribution inventory, pack-check, materialization, and real-world integration tests | nested files; symlink/escape; missing import; local vs packed; duplicate package slug | a nested file is omitted, an escaped file is copied, or two surfaces disagree on ownership |+| FR6 | static source-graph and runtime-export tests | direct export; re-export; type-only export; source side effect | discovery executes source or accepts no runtime binding |+| FR8–FR9 | integration-add snapshots and compatibility fixtures | new writer output; released template/codemod/agent guidance input | a writer emits an untyped or non-`.doc.mjs` item, or a compatibility reader becomes the new canonical form |+| FR10 | bundled-theme, integration-theme, and provider-to-consumer tests | all bundled themes; multi-theme package; list/add/build; no JSON catalog | removing a theme doc still passes, or restoring `manifest.json` becomes necessary |+| FR11 | integration-add writer tests; catalog codemod tests | second item of a kind; leftover 0.6 catalog | adding an item writes a shared file, or a leftover catalog is read instead of refused |++## Decision log++### DEC-1 — Use one typed same-stem descriptor per contribution item++**Reference:** `spec:AST-039/DEC-1`+**Decider:** `joeyfarina`, `2026-09-12`++A contribution's description belongs beside the source or payload it describes.+One typed module gives editors and the CLI the same contract, makes the item+movable as a unit, and prevents a root catalog from drifting away from source.+The integration manifest remains a root locator and integration-capability+boundary.++Rejected: a central JSON catalog. It creates a theme-only authoring language,+duplicates source identity, and allowed the CLI to accept a format that does not+follow the repository's `.doc.mjs` convention.++Rejected: an optional descriptor layered over the JSON catalog. Two metadata+sources need precedence and drift rules and preserve the design defect.++### DEC-2 — Infer theme source identity and own the whole theme directory++**Reference:** `spec:AST-039/DEC-2`+**Decider:** `joeyfarina`, `2026-09-12`++A theme source and descriptor share one stem. That stem identifies the entry and+required named runtime export. The lower-kebab parent directory and `ThemeDoc.name`+agree on the CLI slug. The complete theme directory, including its descriptor, is+the copy and pack boundary, so nested files do not require an authored+allowlist.++Rejected: carrying `entry`, `exportName`, and `files` forward into `ThemeDoc`.+Those fields restate structure that discovery can prove directly and recreate+the catalog inside each file.++### DEC-3 — Preserve released readers without weakening new authoring++**Reference:** `spec:AST-039/DEC-3`+**Decider:** `joeyfarina`, `2026-09-12`++Stable `0.6.0` already reads template, codemod, and inline agent-guidance forms+that predate this rule. Compatibility readers remain until their normal+migration path permits removal. All new writers and new contribution kinds use+the canonical descriptor immediately. The theme catalog, which shipped in stable+`0.6.3` by mistake, receives no compatibility reader; it is removed as a+breaking change with a codemod (DEC-4).++Rejected: treating every historical form as a permanent equal convention. A+reader kept for compatibility does not define what the authoring system should+create next.++### DEC-4 — No central catalog or manifest map, for any kind++**Reference:** `spec:AST-039/DEC-4`+**Decider:** `joeyfarina`, `2026-09-24`++The theme catalog that `integration add theme` wrote in 0.6 was a bug: it put+per-item details in one central file, against the rule every other kind+follows. It reached stable `0.6.3` before anyone caught it. It is removed as a+breaking change, with a codemod that converts each package, and FR11 now+forbids the pattern outright so that no kind repeats it.++This supersedes `spec:AST-035/DEC-1`, a draft that keeps template replacements+as a map in the integration manifest: a template's `replaces` belongs in its own+descriptor.++Rejected: a manifest map for replacements only. It is the same central catalog,+one field at a time.++## Open questions++None.diff --git a/eslint.config.js b/eslint.config.jsindex e80e61f82c..27e16a109a 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -106,6 +106,7 @@ const docCompilerOnly = (allowed = []) =>'lowerReferenceTopic','linkReferenceTopic','linkReferenceSection',+ 'lowerDoc',].filter(name => !allowed.includes(name)),},]diff --git a/packages/cli/README.md b/packages/cli/README.mdindex adc09582e5..2bf71ca7b2 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -15,6 +15,25 @@ npx @astryxdesign/cli template --listOnce it's a project dependency (`npm install -D @astryxdesign/cli`), drop the scope and use the shorter `astryx` — e.g. `npx astryx component Button` or `pnpm exec astryx component Button`. Bare `astryx` resolves to an unrelated npm package until the CLI is installed, so prefer the scoped form above for first-run/one-off use.+## Reading the CLI's own docs++The CLI documents itself, so these commands print what the installed version does:++- `astryx <command> --help`: one command's arguments and options.+- `astryx manifest --json`: every command, option, and response type, as JSON.+- `astryx docs cli --index`: one section for each command (`commands-<name>`)+ and each API function, plus the JSON output envelope, error codes, and+ response types (`api-<name>`). Read one with `astryx docs cli <key>`, for+ example `astryx docs cli api-search`.+- `astryx docs authoring --index`: the authoring reference, with one section for+ each file an author writes: the `astryx.config.*` file, the+ `astryx.integration.*` manifest, codemods, and every doc type (`ComponentDoc`,+ `TemplateDoc`, `ThemeDoc`, and the rest). Read one section with+ `astryx docs authoring <section>`, for example `astryx docs authoring config`.+- `astryx docs cli-integrations`: the guide to building an integration package.+- `astryx docs`: every docs topic, including the design-system guides (for+ example `tokens`, `theme`, and `layout`).+## Finding things: `astryx search`When you don't know whether what you need is a component, a hook, a docs topic,@@ -179,7 +198,7 @@ if (isError(result)) {| `ERR_FILE_EXISTS` | Refused to overwrite an existing file. || `ERR_PATH_TRAVERSAL` | A path escaped its allowed root, or a name contained traversal markers. || `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |-| `ERR_THEME_INVALID` | A theme definition or contributed theme catalog is invalid. |+| `ERR_THEME_INVALID` | A theme definition or contributed theme descriptor is invalid. || `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a defineTheme result. || `ERR_PALETTE_GENERATION` | A palette generation request or one of its constraints was invalid. || `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |diff --git a/packages/cli/api/blog/blog.doc.mjs b/packages/cli/api/blog/blog.doc.mjsindex 21f5cb7d1d..71f63da5ce 100644--- a/packages/cli/api/blog/blog.doc.mjs+++ b/packages/cli/api/blog/blog.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'blog',+ namespace: 'cli/api',displayName: 'blog()',summary: 'List blog posts, or read one, from the published RSS feed.',description:diff --git a/packages/cli/api/build/build.doc.mjs b/packages/cli/api/build/build.doc.mjsindex 63a67caa48..de33d2a2d2 100644--- a/packages/cli/api/build/build.doc.mjs+++ b/packages/cli/api/build/build.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'build',+ namespace: 'cli/api',displayName: 'build()',summary:'Page-building assistant: the how-to-build playbook, or a composition kit for an idea.',diff --git a/packages/cli/api/component/component.doc.mjs b/packages/cli/api/component/component.doc.mjsindex 1ca001bde4..625e443cf8 100644--- a/packages/cli/api/component/component.doc.mjs+++ b/packages/cli/api/component/component.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'component',+ namespace: 'cli/api',displayName: 'component()',summary:'Resolve a component by name, or list the catalog, with optional focused slices (props, source, showcase, blocks).',diff --git a/packages/cli/api/discover/discover.doc.mjs b/packages/cli/api/discover/discover.doc.mjsindex abfde20c5a..938fd3d49f 100644--- a/packages/cli/api/discover/discover.doc.mjs+++ b/packages/cli/api/discover/discover.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'discover',+ namespace: 'cli/api',displayName: 'discover()',summary: 'Browse and search components from configured external packages.',description:diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjsindex 3dcf11ab79..3e2c696610 100644--- a/packages/cli/api/docs/_adapter.mjs+++ b/packages/cli/api/docs/_adapter.mjs@@ -10,24 +10,29 @@* @output Catalog access, the compiler input for a topic, and the compiled* node for it: lowered (overlaid, extensions merged, keys stamped) or linked* (token references resolved too), memoized per catalog.- * @position Sits beside docs.mjs (api/docs/). Loads authored files and hands- * them to foundation/doc-compiler, so no leaf, doctor check or search loads,- * merges, or resolves docs on its own. Discovery itself lives in+ * @position Sits beside docs.mjs (api/docs/). Hands topics to+ * foundation/doc-compiler (which loads their files) and memoizes the nodes+ * per catalog, so no leaf, doctor check or search loads, merges, or resolves+ * docs on its own. Discovery itself lives in* foundation/discovery/docs-discovery, which the catalog comes from.*/-import * as fs from 'node:fs';-import * as path from 'node:path';-import {pathToFileURL} from 'node:url';import {Project} from '../../foundation/config/project.mjs';import {DocsCatalog} from '../../foundation/discovery/docs-discovery.mjs';import {linkReferenceTopic,lowerReferenceTopic,} from '../../foundation/doc-compiler/compile.mjs';+import {+ deepFreeze,+ loadTopicInput,+ OVERLAY_LANGUAGES,+ overlayLanguages,+} from '../../foundation/doc-compiler/read.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';-import {parseDoc} from '../../authoring/doctypes/parse.mjs';++export {OVERLAY_LANGUAGES, overlayLanguages};/*** The project's topics: the built-in ones plus whatever the configured@@ -51,34 +56,6 @@ export async function loadDocsCatalog(cwd = process.cwd()) {}}-/** The localized overlays a docs read can apply. */-export const OVERLAY_LANGUAGES = ['zh', 'dense'];--/**- * Where the `lang` overlay of a doc file lives: `{topic}.doc.{lang}.mjs`.- * @param {string} docPath- * @param {string} lang- * @returns {string}- */-function overlayPath(docPath, lang) {- return path.join(- path.dirname(docPath),- `${path.basename(docPath, '.doc.mjs')}.doc.${lang}.mjs`,- );-}--/**- * The overlay languages a topic ships for its own file or any extension.- * @param {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} entry- * @returns {string[]}- */-export function overlayLanguages(entry) {- const files = [entry.path, ...entry.extensions.map(ext => ext.path)];- return OVERLAY_LANGUAGES.filter(lang =>- files.some(file => fs.existsSync(overlayPath(file, lang))),- );-}-/*** The overlay a read applies: none for the authored language.* @param {string | null | undefined} lang@@ -88,61 +65,6 @@ function overlayLanguage(lang) {return lang && lang !== 'en' ? lang : null;}-/**- * Load one authored file and the overlay for `lang`. A failure is recorded on- * the result, not thrown, so the compiler reports it in reading order.- * @param {string} docPath- * @param {string | null} lang- * @returns {Promise<import('../../foundation/doc-compiler/compile.mjs').AuthoredFile>}- */-async function loadAuthoredFile(docPath, lang) {- const file = path.basename(docPath);- let doc;- try {- const mod = await import(pathToFileURL(docPath).href);- doc = parseDoc(mod.docs ?? mod.default, file);- } catch (error) {- return {file, error};- }- if (!lang) return {file, doc};- const translationPath = overlayPath(docPath, lang);- if (!fs.existsSync(translationPath)) return {file, doc};- try {- const translationMod = await import(pathToFileURL(translationPath).href);- return {- file,- doc,- overlay: translationMod.docsZh || translationMod.docsDense || null,- };- } catch (overlayError) {- return {file, doc, overlayError};- }-}--/**- * Everything the compiler needs for one topic, read from disk.- * @param {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} entry- * @param {string | null} lang- * @returns {Promise<import('../../foundation/doc-compiler/compile.mjs').ReferenceTopicInput>}- */-async function loadCompilerInput(entry, lang) {- const extensions = [];- for (const extension of entry.extensions) {- extensions.push({- ...(await loadAuthoredFile(extension.path, lang)),- provider: extension.package,- });- }- return {- id: entry.name,- provider: entry.package,- replaces: entry.replaces ?? null,- lang,- base: await loadAuthoredFile(entry.path, lang),- extensions,- };-}-/** @type {WeakMap<DocsCatalog, Map<string, Promise<import('../../foundation/doc-compiler/compile.mjs').CompiledReferenceNode>>>} */const loweredByCatalog = new WeakMap();@@ -166,7 +88,7 @@ export function lowerTopic(catalog, entry, lang = null) {const key = `${entry.name.toLowerCase()}\u0000${overlay ?? ''}`;let lowered = cache.get(key);if (!lowered) {- lowered = loadCompilerInput(entry, overlay).then(input =>+ lowered = loadTopicInput(entry, overlay).then(input =>deepFreeze(lowerReferenceTopic(input)),);cache.set(key, lowered);@@ -174,20 +96,6 @@ export function lowerTopic(catalog, entry, lang = null) {return lowered;}-/**- * Freeze a value and everything in it.- * @template T- * @param {T} value- * @returns {T}- */-function deepFreeze(value) {- if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {- Object.freeze(value);- for (const child of Object.values(value)) deepFreeze(child);- }- return value;-}-/*** How a token reference finds its target: the topic it names in `catalog`,* lowered for the same language.diff --git a/packages/cli/api/docs/docs.doc.mjs b/packages/cli/api/docs/docs.doc.mjsindex c220664af7..c0922d5f0c 100644--- a/packages/cli/api/docs/docs.doc.mjs+++ b/packages/cli/api/docs/docs.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'docs',+ namespace: 'cli/api',displayName: 'docs()',summary:'Read the reference docs: list every topic, one topic\'s sections, one section, or a whole topic.',diff --git a/packages/cli/api/docs/list/list.mjs b/packages/cli/api/docs/list/list.mjsindex 4882b64b87..9a1fb62867 100644--- a/packages/cli/api/docs/list/list.mjs+++ b/packages/cli/api/docs/list/list.mjs@@ -14,7 +14,7 @@* @position Leaf under api/docs. Sibling of detail; both share _adapter.mjs.*/-import {pathToFileURL} from 'node:url';+import {loadTopicFile} from '../../../foundation/doc-compiler/read.mjs';import {loadDocsCatalog} from '../_adapter.mjs';/**@@ -29,12 +29,8 @@ export async function list({cwd} = {}) {for (const entry of catalog.entries()) {let description = entry.description ?? '';if (entry.description == null) {- try {- const mod = await import(pathToFileURL(entry.path).href);- description = (mod.docs ?? mod.default)?.description ?? '';- } catch {- description = '';- }+ const file = await loadTopicFile(entry.path, null);+ description = file.doc?.description ?? '';}/** @type {import('../docs.type.mjs').DocsListEntry} */const listed = {diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjsindex 007a973e76..fb01e356cd 100644--- a/packages/cli/api/doctor/doctor.doc.mjs+++ b/packages/cli/api/doctor/doctor.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'doctor',+ namespace: 'cli/api',displayName: 'doctor()',summary: 'Read-only project + environment health check.',description:diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex 6b61ca4993..2005272ea8 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -34,8 +34,8 @@ import {docsIndexBytes,oversizedDocSections,} from '../../foundation/discovery/docs-output-budget.mjs';-import {compileTopic, overlayLanguages} from '../docs/_adapter.mjs';-import {detailView} from '../../foundation/doc-compiler/lenses.mjs';+import {compileTopic, lowerTopic, overlayLanguages} from '../docs/_adapter.mjs';+import {detailView, indexView} from '../../foundation/doc-compiler/lenses.mjs';import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs';/**@@ -721,38 +721,144 @@ function joinProblems(problems) {: `${problems.length} problems: ${problems.join('; ')}`;}+/** How the self-doc audit's problems are fixed. */+const AUTHORING_DOCS_FIX =+ 'List every authoring self-doc in AUTHORING_SELF_DOCS, fix the one that fails to load, and split a section that is too large.';++/** How the public-surface audit's problems are fixed. */+const AUTHORING_SURFACE_FIX =+ 'Put a self-doc beside each module whose types @astryxdesign/cli/authoring exports and list it in AUTHORING_SELF_DOCS; export what each listed self-doc documents, or remove that self-doc.';++/** Types one problem names before it counts the rest. */+const NAMED_TYPES = 40;++/**+ * @param {string[]} names+ * @returns {string}+ */+function nameTypes(names) {+ return names.length <= NAMED_TYPES+ ? names.join(', ')+ : `${names.slice(0, NAMED_TYPES).join(', ')} and ${names.length - NAMED_TYPES} more`;+}++/**+ * The section keys `astryx docs authoring --index` lists, read the way that+ * command reads them.+ * @returns {Promise<{keys: Set<string>} | {keys: null, error: string}>}+ */+async function authoringTopicKeys() {+ try {+ const catalog = DocsCatalog.fromBuiltins();+ const entry = catalog.resolve('authoring');+ if (!entry) return {keys: null, error: 'it is not a built-in topic'};+ const index = indexView(await lowerTopic(catalog, entry));+ return {keys: new Set(index.sections.map(section => section.id))};+ } catch (err) {+ return {+ keys: null,+ error: err instanceof Error ? err.message : String(err),+ };+ }+}++/**+ * @param {Awaited<ReturnType<typeof import('../../foundation/discovery/authoring-surface.mjs').auditAuthoringSurface>>} surface+ * @returns {string[]}+ */+function surfaceProblems(surface) {+ /** @type {string[]} */+ const problems = [];+ if (surface.types === 0 && surface.untraced.length === 0) {+ problems.push(+ '@astryxdesign/cli/authoring exports no types, so nothing was compared with `astryx docs authoring`',+ );+ }+ for (const {module, names, reason, source, key} of surface.unreadable) {+ const why =+ reason === 'no-self-doc'+ ? `no self-doc sits beside ${module}`+ : reason === 'unregistered'+ ? `${source} is not listed in AUTHORING_SELF_DOCS`+ : reason === 'failed'+ ? `${source} does not load`+ : `${source} renders section "${key}", which the topic's index does not list`;+ problems.push(+ `${nameTypes(names)} from ${module} ${names.length === 1 ? 'has' : 'have'} no doc in \`astryx docs authoring\`: ${why}`,+ );+ }+ for (const {name, reason} of surface.untraced) {+ problems.push(+ `${name} cannot be traced to the module that declares it: ${reason}`,+ );+ }+ for (const {source, subject} of surface.unmatched) {+ problems.push(+ subject+ ? `${source} documents ${subject}, which @astryxdesign/cli/authoring does not export`+ : `${source} documents no type @astryxdesign/cli/authoring exports`,+ );+ }+ return problems;+}+/*** Every authoring self-doc is reachable from `astryx docs authoring`, loads,- * and fits in one read. The audit is imported here, inside the try, so a- * malformed self-doc is reported rather than taking Doctor down.+ * and fits in one read, and every type `@astryxdesign/cli/authoring` exports+ * has its doc there: the self-doc beside the module that declares it. The+ * audits are imported here, inside the try, so a malformed self-doc is+ * reported rather than taking Doctor down.* @param {DoctorContext} [_ctx]+ * @param {{root?: string, sources?: string[], topicKeys?: Set<string> | null}} [options]+ * Another authoring tree, list, or topic index to audit (for tests).* @returns {Promise<DoctorCheck>}*/-export async function checkAuthoringDocs(_ctx) {+export async function checkAuthoringDocs(_ctx, options = {}) {const id = 'authoring-docs';const label = 'Authoring docs';try {- const {auditAuthoringSelfDocs} = await import(- '../../foundation/discovery/authoring-self-docs.mjs'- );- const audit = await auditAuthoringSelfDocs();+ const {auditAuthoringSelfDocs} =+ await import('../../foundation/discovery/authoring-self-docs.mjs');+ const {auditAuthoringSurface} =+ await import('../../foundation/discovery/authoring-surface.mjs');+ const {root, sources} = options;+ const audit = await auditAuthoringSelfDocs({root, sources});const problems = [...audit.unreachable.map(source => `${source} is not in \`astryx docs authoring\``,),- ...audit.failed.map(({source, error}) => `${source} failed to load: ${error}`),+ ...audit.failed.map(+ ({source, error}) => `${source} failed to load: ${error}`,+ ),...audit.oversized.map(({key, bytes}) =>`authoring section "${key}" is ${kilobytes(bytes)}, over the ${kilobytes(DOC_OUTPUT_BUDGET_BYTES)} one read may return`,),];- if (problems.length > 0) {+ const topic =+ options.topicKeys === undefined+ ? await authoringTopicKeys()+ : {keys: options.topicKeys};+ const surface = [+ ...('error' in topic+ ? [`\`astryx docs authoring\` could not be read: ${topic.error}`]+ : []),+ ...surfaceProblems(+ await auditAuthoringSurface({root, sources, topicKeys: topic.keys}),+ ),+ ];+ if (problems.length + surface.length > 0) {return {id,label,status: 'fail',- message: joinProblems(problems),- fix: 'List every authoring self-doc in AUTHORING_SELF_DOCS, fix the one that fails to load, and split a section that is too large.',+ message: joinProblems([...problems, ...surface]),+ fix: [+ problems.length > 0 ? AUTHORING_DOCS_FIX : null,+ surface.length > 0 ? AUTHORING_SURFACE_FIX : null,+ ]+ .filter(Boolean)+ .join(' '),};}return {@@ -772,6 +878,71 @@ export async function checkAuthoringDocs(_ctx) {}}+/** How the CLI-docs audit's problems are fixed. */+const CLI_DOCS_FIX =+ "Set `namespace` on each CLI doc to the one that reads it: cli/commands for a command, cli/api for an API function or the output schema, error codes, and response types, and authoring for a file an author writes (and list it in AUTHORING_SELF_DOCS).";++/**+ * Every command, API function, schema, and enum doc the CLI ships declares a+ * namespace, and the topic that namespace names reads it: `astryx docs cli`+ * for `cli/commands` and `cli/api`, `astryx docs authoring` for `authoring`.+ * @param {DoctorContext | Partial<DoctorContext>} _ctx+ * @param {{root?: string, sources?: string[], authoringSources?: string[]}} [options]+ * test seams: the CLI root, the docs to audit, and the authoring topic's list+ * @returns {Promise<DoctorCheck>}+ */+export async function checkCliDocs(_ctx, options = {}) {+ const id = 'cli-docs';+ const label = 'CLI docs';+ try {+ const {auditCliSelfDocs} =+ await import('../../foundation/discovery/cli-self-docs.mjs');+ const audit = await auditCliSelfDocs(options);+ const problems = [+ ...audit.missing.map(+ source =>+ `${source} has no namespace, so no \`astryx docs\` topic reads it`,+ ),+ ...audit.unknown.map(+ ({source, namespace}) =>+ `${source} has namespace "${namespace}", which no \`astryx docs\` topic reads`,+ ),+ ...audit.misfiled.map(({message}) => message),+ ...audit.failed.map(+ ({source, error}) => `${source} failed to load: ${error}`,+ ),+ ...audit.keyProblems.map(problem => `\`astryx docs cli\`: ${problem}`),+ ...audit.oversized.map(+ ({key, bytes}) =>+ `cli section "${key}" is ${kilobytes(bytes)}, over the ${kilobytes(DOC_OUTPUT_BUDGET_BYTES)} one read may return`,+ ),+ ];+ if (problems.length > 0) {+ return {+ id,+ label,+ status: 'fail',+ message: joinProblems(problems),+ fix: CLI_DOCS_FIX,+ };+ }+ return {+ id,+ label,+ status: 'pass',+ message: `All ${audit.docs} CLI docs are readable: ${audit.sections} in \`astryx docs cli\` and ${audit.authoring} in \`astryx docs authoring\`.`,+ };+ } catch (err) {+ return {+ id,+ label,+ status: 'fail',+ message: `The CLI docs could not be audited: ${err instanceof Error ? err.message : String(err)}`,+ fix: 'Reinstall @astryxdesign/cli.',+ };+ }+}+/*** Every topic reads progressively, in every language it ships: it loads, its* section index and each of its sections fit in one read, and no contributed@@ -929,6 +1100,7 @@ export async function runChecks(options = {}) {}}checks.push(await checkAuthoringDocs(ctx));+ checks.push(await checkCliDocs(ctx));checks.push(await checkDocsProgressiveDisclosure(ctx));const summary = {pass: 0, warn: 0, fail: 0, info: 0};diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjsindex ff313d4e24..7e18fbd1cc 100644--- a/packages/cli/api/doctor/doctor.test.mjs+++ b/packages/cli/api/doctor/doctor.test.mjs@@ -6,15 +6,23 @@* invariant (the counts must always add up to the number of checks).*/-import {describe, it, expect, afterEach} from 'vitest';+import {describe, it, expect, afterEach, vi} from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {DocsCatalog} from '../../foundation/discovery/docs-discovery.mjs';+import {+ AUTHORING_ROOT,+ AUTHORING_SELF_DOCS,+ auditAuthoringSelfDocs,+} from '../../foundation/discovery/authoring-self-docs.mjs';+import {docs} from '../docs/docs.mjs';+import {auditCliSelfDocs} from '../../foundation/discovery/cli-self-docs.mjs';import {doctor,checkAuthoringDocs,+ checkCliDocs,checkDocsProgressiveDisclosure,checkImplicitIntegrations,checkProviderIdentity,@@ -444,6 +452,323 @@ describe('checkAuthoringDocs', () => {}, SLOW);});+describe('checkCliDocs', () => {+ const CLI_DOCS_FIX =+ 'Set `namespace` on each CLI doc to the one that reads it: cli/commands for a command, cli/api for an API function or the output schema, error codes, and response types, and authoring for a file an author writes (and list it in AUTHORING_SELF_DOCS).';++ /** A doc tree under the working directory, as the CLI root. */+ function writeRoot(/** @type {Record<string, any>} */ docsByPath) {+ const root = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doctor-cli-docs-'));+ tmpDirs.push(root);+ for (const [rel, doc] of Object.entries(docsByPath)) {+ const file = path.join(root, rel);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, `export const doc = ${JSON.stringify(doc)};\n`);+ }+ return root;+ }++ it(+ 'passes on this repo, counting where each CLI doc is read',+ async () => {+ const audit = await auditCliSelfDocs();+ expect(await checkCliDocs()).toEqual({+ id: 'cli-docs',+ label: 'CLI docs',+ status: 'pass',+ message: `All ${audit.docs} CLI docs are readable: ${audit.sections} in \`astryx docs cli\` and ${audit.authoring} in \`astryx docs authoring\`.`,+ });+ },+ SLOW,+ );++ it(+ 'fails on a doc with no namespace and one no topic reads, and names the fix',+ async () => {+ const root = writeRoot({+ 'api/alpha/alpha.doc.mjs': {+ type: 'function',+ kind: 'api',+ name: 'alpha',+ displayName: 'alpha()',+ summary: 'The alpha function.',+ params: [],+ returns: [{type: 'alpha', description: 'The alpha.'}],+ },+ 'clients/cli/commands/beta.doc.mjs': {+ type: 'command',+ name: 'beta',+ displayName: 'astryx beta',+ namespace: 'cli',+ summary: 'Do beta',+ },+ });+ expect(+ await checkCliDocs(undefined, {root, authoringSources: []}),+ ).toEqual({+ id: 'cli-docs',+ label: 'CLI docs',+ status: 'fail',+ message:+ '2 problems: api/alpha/alpha.doc.mjs has no namespace, so no `astryx docs` topic reads it; clients/cli/commands/beta.doc.mjs has namespace "cli", which no `astryx docs` topic reads',+ fix: CLI_DOCS_FIX,+ });+ },+ SLOW,+ );+});++describe('checkAuthoringDocs against the public authoring surface', () => {+ const NAMESPACE = 'doctypes/namespace/namespace.doc.mjs';+ const NAMESPACE_TYPES =+ 'NamespaceDoc, NamespaceProviderScope, NamespaceSlotAcceptance, NamespaceSlot, NamespaceAdoptionSource, NamespaceAdoptionRule from doctypes/namespace/type.ts have no doc in `astryx docs authoring`';+ const SURFACE_FIX =+ 'Put a self-doc beside each module whose types @astryxdesign/cli/authoring exports and list it in AUTHORING_SELF_DOCS; export what each listed self-doc documents, or remove that self-doc.';++ /** A copy of this repo's authoring tree, to break one piece of at a time. */+ function copyAuthoring() {+ const root = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-doctor-authoring-'),+ );+ tmpDirs.push(root);+ fs.cpSync(AUTHORING_ROOT, root, {+ recursive: true,+ filter: src => !src.endsWith('.test.mjs'),+ });+ return root;+ }++ /** @param {string} source */+ const without = source => AUTHORING_SELF_DOCS.filter(s => s !== source);++ /** @param {string} text */+ const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');++ it(+ 'passes on this repo and prints exactly what it printed before',+ async () => {+ expect(await checkAuthoringDocs()).toEqual({+ id: 'authoring-docs',+ label: 'Authoring docs',+ status: 'pass',+ message: `All ${AUTHORING_SELF_DOCS.length} authoring schemas are readable in \`astryx docs authoring\`.`,+ });+ },+ SLOW,+ );++ it(+ 'passes on an unchanged copy of the tree, and writes nothing to it',+ async () => {+ const root = copyAuthoring();+ const before = snapshot(root);+ expect(await checkAuthoringDocs(undefined, {root})).toMatchObject({+ status: 'pass',+ });+ expect(snapshot(root)).toEqual(before);+ },+ SLOW,+ );++ it(+ 'fails when the NamespaceDoc self-doc is left out of AUTHORING_SELF_DOCS',+ async () => {+ const root = copyAuthoring();+ const c = await checkAuthoringDocs(undefined, {+ root,+ sources: without(NAMESPACE),+ });+ expect(c.status).toBe('fail');+ expect(c.message).toBe(+ `2 problems: ${NAMESPACE} is not in \`astryx docs authoring\`; ${NAMESPACE_TYPES}: ${NAMESPACE} is not listed in AUTHORING_SELF_DOCS`,+ );+ },+ SLOW,+ );++ it(+ "fails when the topic's index no longer exposes the NamespaceDoc section",+ async () => {+ const index = await docs('authoring', undefined, {index: true});+ const topicKeys = new Set(+ index.data.sections+ .map((/** @type {any} */ s) => s.id)+ .filter((/** @type {string} */ id) => id !== 'namespace-doc'),+ );+ const c = await checkAuthoringDocs(undefined, {topicKeys});+ expect(c).toMatchObject({+ status: 'fail',+ message: `${NAMESPACE_TYPES}: ${NAMESPACE} renders section "namespace-doc", which the topic's index does not list`,+ fix: SURFACE_FIX,+ });+ },+ SLOW,+ );++ it(+ 'fails when @astryxdesign/cli/authoring stops exporting NamespaceDoc',+ async () => {+ const root = copyAuthoring();+ const index = path.join(root, 'index.d.ts');+ const before = fs.readFileSync(index, 'utf8');+ const after = before.replace(+ /^export type \{NamespaceDoc\} from .*\n/m,+ '',+ );+ expect(after).not.toBe(before);+ fs.writeFileSync(index, after);+ expect(await checkAuthoringDocs(undefined, {root})).toMatchObject({+ status: 'fail',+ message: `${NAMESPACE} documents NamespaceDoc, which @astryxdesign/cli/authoring does not export`,+ fix: SURFACE_FIX,+ });+ },+ SLOW,+ );++ it.each([+ [+ 'the graph-fields doc',+ 'doctypes/base/graph-fields.doc.mjs',+ 'doctypes/base/type.ts',+ [+ 'AuthoredDocKind',+ 'DocAudience',+ 'DocPlacement',+ 'AuthoredDocGraphFields',+ ],+ ],+ [+ 'the identity doc',+ 'identity/identity.doc.mjs',+ 'identity/type.ts',+ [+ 'ProviderId',+ 'ArtifactId',+ 'DocId',+ 'ProviderInstance',+ 'AuthoredDocEntry',+ ],+ ],+ [+ 'the semantic-block doc',+ 'doctypes/reference/reference.doc.mjs',+ 'doctypes/reference/type.ts',+ [+ 'WorkflowStep',+ 'WorkflowDocBlock',+ 'CollectionDocBlock',+ 'ReferenceDocBlock',+ ],+ ],+ ])(+ 'fails when %s is removed, which the self-doc audit alone passes',+ async (_what, source, module, names) => {+ const root = copyAuthoring();+ fs.rmSync(path.join(root, source));+ const sources = without(source);+ expect(await auditAuthoringSelfDocs({root, sources})).toEqual({+ sections: sources.length,+ unreachable: [],+ failed: [],+ oversized: [],+ });+ const c = await checkAuthoringDocs(undefined, {root, sources});+ expect(c.status).toBe('fail');+ expect(c.fix).toBe(SURFACE_FIX);+ expect(c.message).toMatch(+ new RegExp(+ `^[A-Za-z, ]+ from ${escape(module)} have no doc in \`astryx docs authoring\`: no self-doc sits beside ${escape(module)}$`,+ ),+ );+ for (const name of names) {+ expect(c.message).toMatch(new RegExp(`(^|, )${name}(,| from)`));+ }+ },+ SLOW,+ );++ it(+ 'keeps the message and fix of a failure only the self-doc audit reports',+ async () => {+ const root = copyAuthoring();+ fs.writeFileSync(+ path.join(root, 'identity', 'broken.doc.mjs'),+ 'export const doc = {;\n',+ );+ const c = await checkAuthoringDocs(undefined, {+ root,+ sources: [...AUTHORING_SELF_DOCS, 'identity/broken.doc.mjs'],+ });+ expect(c.status).toBe('fail');+ expect(c.message).toMatch(/^identity\/broken\.doc\.mjs failed to load: /);+ expect(c.fix).toBe(+ 'List every authoring self-doc in AUTHORING_SELF_DOCS, fix the one that fails to load, and split a section that is too large.',+ );+ },+ SLOW,+ );++ it(+ 'reports a topic it cannot read rather than skipping the comparison',+ async () => {+ const spy = vi+ .spyOn(DocsCatalog, 'fromBuiltins')+ .mockImplementationOnce(() => {+ throw new Error('no built-in docs');+ });+ try {+ expect(await checkAuthoringDocs()).toMatchObject({+ status: 'fail',+ message:+ '`astryx docs authoring` could not be read: no built-in docs',+ fix: SURFACE_FIX,+ });+ } finally {+ spy.mockRestore();+ }+ },+ SLOW,+ );++ it(+ 'fails rather than passes when the surface exports no types at all',+ async () => {+ const root = copyAuthoring();+ fs.writeFileSync(+ path.join(root, 'index.d.ts'),+ "export {parseDoc} from './doctypes/parse.mjs';\n",+ );+ const c = await checkAuthoringDocs(undefined, {root});+ expect(c.status).toBe('fail');+ expect(c.message).toContain(+ '@astryxdesign/cli/authoring exports no types, so nothing was compared with `astryx docs authoring`',+ );+ },+ SLOW,+ );+});++/**+ * Every file under `root` with its contents.+ * @param {string} root+ * @returns {Record<string, string>}+ */+function snapshot(root) {+ /** @type {Record<string, string>} */+ const out = {};+ /** @param {string} dir */+ const walk = dir => {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else out[path.relative(root, full)] = fs.readFileSync(full, 'utf8');+ }+ };+ walk(root);+ return out;+}+describe('doctor docs checks', () => {it('runs both docs checks and they pass on the repo', async () => {const r = await doctor({cwd});diff --git a/packages/cli/api/gap-report/gap-report.doc.mjs b/packages/cli/api/gap-report/gap-report.doc.mjsindex 7a78527a1b..9c53dfac63 100644--- a/packages/cli/api/gap-report/gap-report.doc.mjs+++ b/packages/cli/api/gap-report/gap-report.doc.mjs@@ -10,6 +10,7 @@ export const doc = {type: 'function',kind: 'api',name: 'gapReport',+ namespace: 'cli/api',displayName: 'gapReport()',summary: 'Route a design-system gap through the fan-out handler composition.',description:diff --git a/packages/cli/api/hook/_adapter.mjs b/packages/cli/api/hook/_adapter.mjsindex 6ef1699db4..859a00c12f 100644--- a/packages/cli/api/hook/_adapter.mjs+++ b/packages/cli/api/hook/_adapter.mjs@@ -15,7 +15,10 @@*/import {findCoreDir} from '../../foundation/fs/paths.mjs';-import {findHookDoc, getAllHookNames} from '../../foundation/discovery/hook-discovery.mjs';+import {+ findHookDoc,+ getAllHookNames,+} from '../../foundation/discovery/hook-discovery.mjs';import {loadDocs} from '../../foundation/discovery/component-loader.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';import {AstryxError} from '../error.mjs';@@ -30,7 +33,11 @@ import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';export function resolveCoreDir(cwd) {const coreDir = findCoreDir(cwd);if (!coreDir) {- throw new AstryxError('Could not find @astryxdesign/core package', undefined, ERROR_CODES.ERR_CORE_NOT_FOUND);+ throw new AstryxError(+ 'Could not find @astryxdesign/core package',+ undefined,+ ERROR_CODES.ERR_CORE_NOT_FOUND,+ );}return coreDir;}@@ -44,7 +51,11 @@ export function resolveCoreDir(cwd) {* @param {{zh?: boolean, lang?: string|null}} [opts]* @returns {Promise<import('./hook.type.mjs').HookDoc>}*/-export async function resolveHookDoc(coreDir, name, {zh = false, lang = null} = {}) {+export async function resolveHookDoc(+ coreDir,+ name,+ {zh = false, lang = null} = {},+) {const docPath = findHookDoc(coreDir, name);if (!docPath) {@@ -59,7 +70,10 @@ export async function resolveHookDoc(coreDir, name, {zh = false, lang = null} =.filter(m => m.distance <= 5).sort((a, b) => a.distance - b.distance).slice(0, 5)- .map(m => ({name: m.name, reason: `similar name (distance ${m.distance})`}));+ .map(m => ({+ name: m.name,+ reason: `similar name (distance ${m.distance})`,+ }));throw new AstryxError(`No hook named "${name}"`,@@ -68,5 +82,5 @@ export async function resolveHookDoc(coreDir, name, {zh = false, lang = null} =);}- return loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));+ return loadDocs(docPath, {zh, lang, root: 'hooks'});}diff --git a/packages/cli/api/hook/hook.doc.mjs b/packages/cli/api/hook/hook.doc.mjsindex e166d4f92f..df72906cc8 100644--- a/packages/cli/api/hook/hook.doc.mjs+++ b/packages/cli/api/hook/hook.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'hook',+ namespace: 'cli/api',displayName: 'hook()',summary:'Resolve a hook by name, or list the catalog, with an optional params-only slice.',diff --git a/packages/cli/api/hook/list/list.mjs b/packages/cli/api/hook/list/list.mjsindex 7679f25909..e2fe7ad03c 100644--- a/packages/cli/api/hook/list/list.mjs+++ b/packages/cli/api/hook/list/list.mjs@@ -13,7 +13,10 @@* @position api/hook/list/list.mjs — dispatched from ../hook.mjs*/-import {discoverHooks, findHookDoc} from '../../../foundation/discovery/hook-discovery.mjs';+import {+ discoverHooks,+ findHookDoc,+} from '../../../foundation/discovery/hook-discovery.mjs';import {loadDocs} from '../../../foundation/discovery/component-loader.mjs';import {AstryxError} from '../../error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';@@ -28,7 +31,13 @@ import {resolveCoreDir} from '../_adapter.mjs';* @param {string|null} [options.lang]* @returns {Promise<import('../hook.type.mjs').HookListResponse>}*/-export async function list({cwd = process.cwd(), category, detail = 'names', zh = false, lang = null} = {}) {+export async function list({+ cwd = process.cwd(),+ category,+ detail = 'names',+ zh = false,+ lang = null,+} = {}) {const coreDir = resolveCoreDir(cwd);const hooks = discoverHooks(coreDir);@@ -51,20 +60,31 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zhconst docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));+ const docs = await loadDocs(docPath, {zh, lang, root: 'hooks'});entries.push({name: hookName,description: docs.usage?.description || '',import: docs.importPath || '@astryxdesign/core/hooks',});} catch {- entries.push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});+ entries.push({+ name: hookName,+ description: '',+ import: '@astryxdesign/core/hooks',+ });}} else {- entries.push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});+ entries.push({+ name: hookName,+ description: '',+ import: '@astryxdesign/core/hooks',+ });}}- return {type: 'hook.list', data: {detail: 'compact', components: {[match[0]]: entries}}};+ return {+ type: 'hook.list',+ data: {detail: 'compact', components: {[match[0]]: entries}},+ };}if (detail === 'full') {@@ -74,19 +94,33 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zhconst docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- entries.push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));+ entries.push(await loadDocs(docPath, {zh, lang, root: 'hooks'}));} catch {- entries.push(/** @type {import('../hook.type.mjs').HookDoc} */ ({name: hookName}));+ entries.push(+ /** @type {import('../hook.type.mjs').HookDoc} */ ({+ name: hookName,+ }),+ );}} else {- entries.push(/** @type {import('../hook.type.mjs').HookDoc} */ ({name: hookName}));+ entries.push(+ /** @type {import('../hook.type.mjs').HookDoc} */ ({+ name: hookName,+ }),+ );}}- return {type: 'hook.list', data: {detail: 'full', components: {[match[0]]: entries}}};+ return {+ type: 'hook.list',+ data: {detail: 'full', components: {[match[0]]: entries}},+ };}// Default: names only- return {type: 'hook.list', data: {detail: 'names', components: {[match[0]]: match[1]}}};+ return {+ type: 'hook.list',+ data: {detail: 'names', components: {[match[0]]: match[1]}},+ };}// All hooks@@ -99,17 +133,25 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zhconst docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));+ const docs = await loadDocs(docPath, {zh, lang, root: 'hooks'});result[cat].push({name: hookName,description: docs.usage?.description || '',import: docs.importPath || '@astryxdesign/core/hooks',});} catch {- result[cat].push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});+ result[cat].push({+ name: hookName,+ description: '',+ import: '@astryxdesign/core/hooks',+ });}} else {- result[cat].push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});+ result[cat].push({+ name: hookName,+ description: '',+ import: '@astryxdesign/core/hooks',+ });}}}@@ -125,12 +167,22 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zhconst docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- result[cat].push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));+ result[cat].push(+ await loadDocs(docPath, {zh, lang, root: 'hooks'}),+ );} catch {- result[cat].push(/** @type {import('../hook.type.mjs').HookDoc} */ ({name: hookName}));+ result[cat].push(+ /** @type {import('../hook.type.mjs').HookDoc} */ ({+ name: hookName,+ }),+ );}} else {- result[cat].push(/** @type {import('../hook.type.mjs').HookDoc} */ ({name: hookName}));+ result[cat].push(+ /** @type {import('../hook.type.mjs').HookDoc} */ ({+ name: hookName,+ }),+ );}}}diff --git a/packages/cli/api/init/init.doc.mjs b/packages/cli/api/init/init.doc.mjsindex 03bef4f265..90ff52b47e 100644--- a/packages/cli/api/init/init.doc.mjs+++ b/packages/cli/api/init/init.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'init',+ namespace: 'cli/api',displayName: 'init()',summary:'Non-interactive project setup: install agent docs and point at the theme + build workflows.',diff --git a/packages/cli/api/integration/add-contribution.mjs b/packages/cli/api/integration/add-contribution.mjsindex 591b25c8b7..4a062c7e66 100644--- a/packages/cli/api/integration/add-contribution.mjs+++ b/packages/cli/api/integration/add-contribution.mjs@@ -5,8 +5,7 @@* contribution into an integration package.** Dispatches component, doc, template, codemod, and agent-doc. Theme- * delegates to the existing `integrationAddTheme` (not modified here).- * Every root-based kind shares: first add creates the manifest; one shared+ * delegates to the dedicated same-stem descriptor writer. Every root-based kind shares: first add creates the manifest; one shared* writer; never creates `files`/`exports`; atomic staged writes; no clobber;* dry-run receipt predicts real run; post-write verify through the real* discovery/parser seam.@@ -263,7 +262,7 @@ async function addComponent(name, options) {const sourcePath = projectPath(path.relative(packageDir, sourceFile));const extensionlessPath = sourcePath.replace(/\.tsx?$/u, '');const importSpecifier = `${owner}/${extensionlessPath}`;- const docContents = `export default {\n type: 'component',\n name: '${name}',\n import: ${JSON.stringify(importSpecifier)},\n description: '${name} component.',\n props: [],\n};\n`;+ const docContents = `/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */\nexport default {\n type: 'component',\n name: '${name}',\n displayName: '${name}',\n import: ${JSON.stringify(importSpecifier)},\n usage: {description: '${name} component.'},\n props: [],\n};\n`;const sourceContents = `export function ${name}() {\n return <div>${name}</div>;\n}\n`;/** @type {import('./add-helpers.mjs').WritePlan[]} */@@ -438,7 +437,7 @@ async function addDoc(name, options) {: options.extends? `\n extends: '${options.extends}',`: '';- const docContents = `export default {\n type: 'generic',\n name: '${name}',\n title: '${title}',\n description: '${title} documentation.',${relationship}\n sections: [\n {\n title: 'Overview',\n content: [\n { type: 'prose', text: '${title} documentation.' },\n ],\n },\n ],\n};\n`;+ const docContents = `/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */\nexport default {\n type: 'generic',\n name: '${name}',\n title: '${title}',\n description: '${title} documentation.',${relationship}\n sections: [\n {\n title: 'Overview',\n content: [\n { type: 'prose', text: '${title} documentation.' },\n ],\n },\n ],\n};\n`;/** @type {import('./add-helpers.mjs').WritePlan[]} */const plans = [{path: docFile, contents: docContents, createOnly: true}];@@ -565,8 +564,8 @@ async function addTemplate(name, options) {throw error;}- const specFile = assertWithin(`${name}.template.mjs`, root, {- label: 'template spec',+ const specFile = assertWithin(`${name}.doc.mjs`, root, {+ label: 'template descriptor',});const sourceFile = assertWithin(`${name}.tsx`, root, {label: 'template source',@@ -589,7 +588,8 @@ async function addTemplate(name, options) {const pascalName = kebabToPascal(name);const sourcePath = projectPath(path.relative(packageDir, sourceFile));const extensionlessPath = sourcePath.replace(/\.tsx?$/u, '');- const specContents = `export default {\n type: '${templateType}',\n name: '${name}',\n description: '${kebabToTitle(name)} template.',\n};\n`;+ const blockFields = templateType === 'block' ? '\n aspectRatio: 1,' : '';+ const specContents = `/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */\nexport default {\n type: '${templateType}',\n name: '${name}',\n displayName: '${kebabToTitle(name)}',\n description: '${kebabToTitle(name)} template.',${blockFields}\n};\n`;const sourceContents = `export default function ${pascalName}() {\n return <div>${kebabToTitle(name)}</div>;\n}\n`;/** @type {import('./add-helpers.mjs').WritePlan[]} */diff --git a/packages/cli/api/integration/add-contribution.test.mjs b/packages/cli/api/integration/add-contribution.test.mjsindex ed844eae3d..123eb3860c 100644--- a/packages/cli/api/integration/add-contribution.test.mjs+++ b/packages/cli/api/integration/add-contribution.test.mjs@@ -77,6 +77,7 @@ describe('integrationAdd component', () => {path.join(tmpDir, 'components/MyWidget.doc.mjs'),'utf-8',);+ expect(doc).toContain("@astryxdesign/cli/authoring').ComponentDoc");expect(doc).toContain("type: 'component'");expect(doc).toContain("name: 'MyWidget'");expect(doc).toContain('props: []');@@ -304,6 +305,7 @@ describe('integrationAdd doc', () => {path.join(tmpDir, 'docs/my-guide.doc.mjs'),'utf-8',);+ expect(doc).toContain("@astryxdesign/cli/authoring').ReferenceDoc");expect(doc).toContain("type: 'generic'");expect(doc).toContain("name: 'my-guide'");@@ -390,13 +392,14 @@ describe('integrationAdd template', () => {expect(result.data.kind).toBe('template');expect(result.data.name).toBe('my-widget');expect(result.data.root).toEqual({path: './templates', created: true});- expect(result.data.files).toContain('templates/my-widget.template.mjs');+ expect(result.data.files).toContain('templates/my-widget.doc.mjs');expect(result.data.files).toContain('templates/my-widget.tsx');const spec = fs.readFileSync(- path.join(tmpDir, 'templates/my-widget.template.mjs'),+ path.join(tmpDir, 'templates/my-widget.doc.mjs'),'utf-8',);+ expect(spec).toContain("@astryxdesign/cli/authoring').TemplateDoc");expect(spec).toContain("type: 'page'");expect(spec).toContain("name: 'my-widget'");@@ -432,10 +435,11 @@ describe('integrationAdd template', () => {templateType: 'block',});const spec = fs.readFileSync(- path.join(tmpDir, 'templates/my-card.template.mjs'),+ path.join(tmpDir, 'templates/my-card.doc.mjs'),'utf-8',);expect(spec).toContain("type: 'block'");+ expect(spec).toContain('aspectRatio: 1');});it('rejects an invalid template type', async () => {@@ -676,6 +680,35 @@ describe('custom root preservation', () => {});});+describe('typed descriptor conformance', () => {+ it('emits a strongly typed .doc.mjs for every canonical item writer', async () => {+ setup();+ await integrationAdd('component', 'MyWidget', {cwd: tmpDir});+ await integrationAdd('doc', 'my-guide', {cwd: tmpDir});+ await integrationAdd('template', 'my-page', {cwd: tmpDir});+ await integrationAdd('theme', 'ocean', {cwd: tmpDir});++ // Codemod and agent-doc keep their released formats for compatibility;+ // no new kind may copy those exceptions.+ for (const [relativePath, type] of [+ ['components/MyWidget.doc.mjs', 'ComponentDoc'],+ ['docs/my-guide.doc.mjs', 'ReferenceDoc'],+ ['templates/my-page.doc.mjs', 'TemplateDoc'],+ ['themes/ocean/oceanTheme.doc.mjs', 'ThemeDoc'],+ ]) {+ const source = fs.readFileSync(path.join(tmpDir, relativePath), 'utf-8');+ expect(source).toContain(`@astryxdesign/cli/authoring').${type}`);+ expect(source).toContain('export default {');+ }+ expect(+ fs.existsSync(path.join(tmpDir, 'templates/my-page.template.mjs')),+ ).toBe(false);+ expect(fs.existsSync(path.join(tmpDir, 'themes/manifest.json'))).toBe(+ false,+ );+ });+});+describe('public per-kind APIs', () => {it('exposes narrow functions for every non-theme contribution kind', async () => {setup();@@ -711,6 +744,7 @@ describe('public dispatcher', () => {const result = await integrationAdd('theme', 'ocean', {cwd: tmpDir});expect(result.data).toMatchObject({kind: 'theme', name: 'ocean'});expect(result.data.files).toContain('themes/ocean/oceanTheme.ts');+ expect(result.data.files).toContain('themes/ocean/oceanTheme.doc.mjs');});it('refuses a kind-specific option on the wrong kind', async () => {diff --git a/packages/cli/api/integration/add-theme.mjs b/packages/cli/api/integration/add-theme.mjsindex d82a0057d9..8891d49ee1 100644--- a/packages/cli/api/integration/add-theme.mjs+++ b/packages/cli/api/integration/add-theme.mjs@@ -1,9 +1,9 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file `astryx integration add theme` — scaffold one valid source theme into- * an integration package, update its theme catalog, and declare the root on- * first use.+ * @file `astryx integration add theme` — scaffold one strongly typed,+ * same-stem source/descriptor pair into an integration package and declare the+ * themes root on first use.*/import * as fs from 'node:fs';@@ -15,16 +15,14 @@ import {PathSafetyError,sanitizeName,} from '../../foundation/fs/path-safety.mjs';-import {- discoverThemeCatalog,- THEME_MANIFEST_BASENAME,-} from '../../foundation/discovery/theme-discovery.mjs';+import {discoverThemeDirectory} from '../../foundation/discovery/theme-discovery.mjs';import {findLocalIntegrationManifestOrNull,IntegrationRootConflictError,patchIntegrationRoot,} from '../../foundation/integrations/manifest-writer.mjs';import {loadManifestObject} from '../../foundation/integrations/integrations.mjs';+import {themeDescriptorSource} from '../../foundation/integrations/theme-descriptor.mjs';import {assertContributionVisible} from '../../foundation/integrations/contribution-inventory.mjs';import {applyWrites,@@ -70,6 +68,7 @@ function themeIdentity(slug) {displayName,exportName: `${identifier}Theme`,entry: `${identifier}Theme.ts`,+ descriptor: `${identifier}Theme.doc.mjs`,};}@@ -78,9 +77,20 @@ function themeSource(identity) {return `import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const ${identity.exportName} = defineTheme({\n name: '${identity.slug}',\n});\n`;}+/** @param {{slug: string, displayName: string}} identity */+function themeDescriptor(identity) {+ return themeDescriptorSource({+ type: 'theme',+ name: identity.slug,+ displayName: identity.displayName,+ description: `${identity.displayName} theme.`,+ maintained: true,+ });+}+/**- * Read the bytes back through the same integration-theme discovery seam Project- * uses. A write is not successful until the requested slug resolves.+ * Read bytes back through the same discovery seam Project uses. A write is not+ * successful until the requested slug resolves.* @param {string} packageDir* @param {string} manifestFile* @param {string} owner@@ -176,6 +186,9 @@ export async function integrationAddTheme(name, options = {}) {dryRun: true,createIfMissing: true,});+ if (fs.existsSync(root)) {+ discoverThemeDirectory(root, owner);+ }} catch (error) {if (error instanceof IntegrationRootConflictError) {throw new AstryxError(@@ -197,72 +210,29 @@ export async function integrationAddTheme(name, options = {}) {const sourceFile = assertWithin(identity.entry, themeDir, {label: 'theme source file',});- if (fs.existsSync(sourceFile)) {- throw new AstryxError(- `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, sourceFile))}.`,- undefined,- ERROR_CODES.ERR_FILE_EXISTS,- );- }-- const catalogFile = assertWithin(THEME_MANIFEST_BASENAME, root, {- label: 'theme catalog manifest',+ const descriptorFile = assertWithin(identity.descriptor, themeDir, {+ label: 'theme descriptor file',});- /** @type {{version: 1, themes: Array<Record<string, unknown>>, [key: string]: unknown}} */- let catalog = {version: 1, themes: []};- /** @type {Buffer|null} */- let catalogOriginal = null;- if (fs.existsSync(catalogFile)) {- try {- catalogOriginal = fs.readFileSync(catalogFile);- catalog = JSON.parse(catalogOriginal.toString('utf-8'));- // The discovery seam is the schema/source-of-truth validator. The write- // plan carries catalogOriginal, so any concurrent change between this read- // and publish is refused rather than overwritten with this snapshot.- discoverThemeCatalog(root, owner);- } catch (error) {+ // An existing folder is filled; only a file this would write is refused.+ for (const file of [sourceFile, descriptorFile]) {+ if (fs.existsSync(file)) {throw new AstryxError(- error instanceof Error ? error.message : String(error),+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,undefined,- ERROR_CODES.ERR_THEME_INVALID,+ ERROR_CODES.ERR_FILE_EXISTS,);}}- if (- catalog.themes.some(- theme =>- typeof theme.slug === 'string' &&- theme.slug.toLowerCase() === identity.slug.toLowerCase(),- )- ) {- throw new AstryxError(- `Theme "${identity.slug}" already exists in ${projectPath(path.relative(packageDir, catalogFile))}.`,- undefined,- ERROR_CODES.ERR_FILE_EXISTS,- );- }-- catalog.themes.push({- slug: identity.slug,- displayName: identity.displayName,- description: `${identity.displayName} theme.`,- maintained: true,- entry: identity.entry,- exportName: identity.exportName,- files: [identity.entry],- });/** @type {import('./add-helpers.mjs').WritePlan[]} */- const plans = [];- plans.push(+ const plans = [{path: sourceFile, contents: themeSource(identity), createOnly: true},{- path: catalogFile,- contents: `${JSON.stringify(catalog, null, 2)}\n`,- createOnly: catalogOriginal == null,- expectedOriginal: catalogOriginal ?? undefined,+ path: descriptorFile,+ contents: themeDescriptor(identity),+ createOnly: true,},- );+ ];const packageUpdate = packageJsonUpdate(packageFile,rootPath,diff --git a/packages/cli/api/integration/add-theme.test.mjs b/packages/cli/api/integration/add-theme.test.mjsindex cbc570eb82..3016c9a2f7 100644--- a/packages/cli/api/integration/add-theme.test.mjs+++ b/packages/cli/api/integration/add-theme.test.mjs@@ -32,7 +32,7 @@ afterEach(() => {});describe('integrationAddTheme', () => {- it('writes a valid source theme, catalog, root, package files entry, and receipt', async () => {+ it('writes a typed same-stem descriptor and source with no central catalog', async () => {setup();const result = await integrationAddTheme('ocean', {cwd: tmpDir});@@ -45,7 +45,7 @@ describe('integrationAddTheme', () => {manifest: 'astryx.integration.mjs',files: ['themes/ocean/oceanTheme.ts',- 'themes/manifest.json',+ 'themes/ocean/oceanTheme.doc.mjs','package.json','astryx.integration.mjs',],@@ -56,21 +56,17 @@ describe('integrationAddTheme', () => {expect(fs.readFileSync(path.join(tmpDir, 'themes/ocean/oceanTheme.ts'), 'utf-8'),).toContain('export const oceanTheme = defineTheme');- expect(- JSON.parse(- fs.readFileSync(path.join(tmpDir, 'themes/manifest.json'), 'utf-8'),- ),- ).toMatchObject({- version: 1,- themes: [- {- slug: 'ocean',- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts'],- },- ],- });++ const descriptor = fs.readFileSync(+ path.join(tmpDir, 'themes/ocean/oceanTheme.doc.mjs'),+ 'utf-8',+ );+ expect(descriptor).toContain("@astryxdesign/cli/authoring').ThemeDoc");+ expect(descriptor).toContain("type: 'theme'");+ expect(descriptor).toContain("name: 'ocean'");+ expect(fs.existsSync(path.join(tmpDir, 'themes/manifest.json'))).toBe(+ false,+ );expect(fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),).toContain("themes: './themes'");@@ -96,6 +92,7 @@ describe('integrationAddTheme', () => {expect(result.data.dryRun).toBe(true);expect(result.data.root).toEqual({path: './themes', created: true});expect(result.data.files).toContain('themes/ocean/oceanTheme.ts');+ expect(result.data.files).toContain('themes/ocean/oceanTheme.doc.mjs');expect(fs.existsSync(path.join(tmpDir, 'themes'))).toBe(false);expect(fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),@@ -125,22 +122,69 @@ describe('integrationAddTheme', () => {expect(fs.existsSync(path.join(tmpDir, 'src/themes/ocean/oceanTheme.ts')),).toBe(true);+ expect(+ fs.existsSync(path.join(tmpDir, 'src/themes/ocean/oceanTheme.doc.mjs')),+ ).toBe(true);});- it('refuses an invalid existing catalog without changing its bytes', async () => {+ it('keeps each theme to its own folder: a second theme touches no shared file', async () => {+ setup({manifest: "export default {themes: './themes'};\n"});+ await integrationAddTheme('ocean', {cwd: tmpDir});+ const shared = ['package.json', 'astryx.integration.mjs'].map(file =>+ fs.readFileSync(path.join(tmpDir, file), 'utf-8'),+ );++ const result = await integrationAddTheme('reef', {cwd: tmpDir});++ expect(result.data.files).toEqual([+ 'themes/reef/reefTheme.ts',+ 'themes/reef/reefTheme.doc.mjs',+ ]);+ expect(fs.readdirSync(path.join(tmpDir, 'themes')).sort()).toEqual([+ 'ocean',+ 'reef',+ ]);+ expect(+ ['package.json', 'astryx.integration.mjs'].map(file =>+ fs.readFileSync(path.join(tmpDir, file), 'utf-8'),+ ),+ ).toEqual(shared);+ });++ it('refuses an obsolete central catalog without changing its bytes', async () => {setup();fs.mkdirSync(path.join(tmpDir, 'themes'));const catalog = path.join(tmpDir, 'themes', 'manifest.json');- fs.writeFileSync(catalog, '{not-json\n');+ fs.writeFileSync(catalog, '{"version":1}\n');await expect(integrationAddTheme('ocean', {cwd: tmpDir}),).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});- expect(fs.readFileSync(catalog, 'utf-8')).toBe('{not-json\n');+ expect(fs.readFileSync(catalog, 'utf-8')).toBe('{"version":1}\n');expect(fs.existsSync(path.join(tmpDir, 'themes', 'ocean'))).toBe(false);});- it('refuses duplicate themes and existing source files', async () => {+ it('refuses an invalid existing descriptor without changing it', async () => {+ setup();+ const existing = path.join(tmpDir, 'themes', 'forest');+ fs.mkdirSync(existing, {recursive: true});+ const descriptor = path.join(existing, 'forestTheme.doc.mjs');+ fs.writeFileSync(descriptor, 'export default {type: "theme"};\n');+ fs.writeFileSync(+ path.join(existing, 'forestTheme.ts'),+ 'export const forestTheme = {};\n',+ );++ await expect(+ integrationAddTheme('ocean', {cwd: tmpDir}),+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});+ expect(fs.readFileSync(descriptor, 'utf-8')).toBe(+ 'export default {type: "theme"};\n',+ );+ expect(fs.existsSync(path.join(tmpDir, 'themes', 'ocean'))).toBe(false);+ });++ it('refuses a duplicate valid theme directory', async () => {setup();await integrationAddTheme('ocean', {cwd: tmpDir});await expect(@@ -148,6 +192,46 @@ describe('integrationAddTheme', () => {).rejects.toMatchObject({code: 'ERR_FILE_EXISTS'});});+ it('refuses an existing invalid theme directory', async () => {+ setup();+ fs.mkdirSync(path.join(tmpDir, 'themes', 'ocean'), {recursive: true});+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',+ );+ await expect(+ integrationAddTheme('ocean', {cwd: tmpDir}),+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});+ });++ it.each([+ ['an empty folder', []],+ ['a folder holding .gitkeep', ['.gitkeep']],+ ['a folder holding NOTES.md', ['NOTES.md']],+ ])('fills %s', async (_, files) => {+ setup();+ const dir = path.join(tmpDir, 'themes', 'ocean');+ fs.mkdirSync(dir, {recursive: true});+ for (const file of files) fs.writeFileSync(path.join(dir, file), 'x\n');+ const result = await integrationAddTheme('ocean', {cwd: tmpDir});+ expect(result.data.written).toBe(true);+ expect(fs.readdirSync(dir).sort()).toEqual(+ [...files, 'oceanTheme.doc.mjs', 'oceanTheme.ts'].sort(),+ );+ });++ it('refuses to overwrite a file it would write', async () => {+ setup();+ await integrationAddTheme('ocean', {cwd: tmpDir});+ await expect(+ integrationAddTheme('ocean', {cwd: tmpDir}),+ ).rejects.toMatchObject({+ code: 'ERR_FILE_EXISTS',+ message:+ 'Refusing to overwrite existing file themes/ocean/oceanTheme.ts.',+ });+ });+it.each(['../ocean', 'Ocean', 'ocean theme', '.ocean'])('refuses unsafe or noncanonical name %s',async name => {diff --git a/packages/cli/api/integration/authoring-checks.test.mjs b/packages/cli/api/integration/authoring-checks.test.mjsindex f658db4a91..e639da5d61 100644--- a/packages/cli/api/integration/authoring-checks.test.mjs+++ b/packages/cli/api/integration/authoring-checks.test.mjs@@ -33,7 +33,7 @@ function writeIntegration({id, name, type = 'block', root = tmpDir}) {const stem = path.join(root, 'templates', id);fs.mkdirSync(path.dirname(stem), {recursive: true});fs.writeFileSync(- `${stem}.template.mjs`,+ `${stem}.doc.mjs`,`export default {type: '${type}', name: ${JSON.stringify(name)}, description: 'fixture'};\n`,);fs.writeFileSync(@@ -176,7 +176,7 @@ describe('integrationTemplateConflicts', () => {);fs.mkdirSync(path.join(tmpDir, 'templates'), {recursive: true});fs.writeFileSync(- path.join(tmpDir, 'templates', 'broken.template.mjs'),+ path.join(tmpDir, 'templates', 'broken.doc.mjs'),`throw new Error('broken fixture');\n`,);fs.writeFileSync(@@ -221,7 +221,9 @@ describe('integrationComponentConflicts', () => {expect(core).toBeDefined();writeComponentIntegration(core.name);- const result = await integrationComponentConflicts(undefined, {cwd: tmpDir});+ const result = await integrationComponentConflicts(undefined, {+ cwd: tmpDir,+ });expect(result.type).toBe('integration.component-conflicts');expect(result.data.issues).toEqual([]);@@ -240,7 +242,9 @@ describe('integrationComponentConflicts', () => {it('does not flag an integration-only component name', async () => {writeComponentIntegration('AcmeOnlyWidget');- const result = await integrationComponentConflicts(undefined, {cwd: tmpDir});+ const result = await integrationComponentConflicts(undefined, {+ cwd: tmpDir,+ });expect(result.data.conflicts).toEqual([]);expect(result.data.issues).toEqual([]);diff --git a/packages/cli/api/integration/integration-block-exports.test.mjs b/packages/cli/api/integration/integration-block-exports.test.mjsindex 6d9fbcdf8f..3d735a35b7 100644--- a/packages/cli/api/integration/integration-block-exports.test.mjs+++ b/packages/cli/api/integration/integration-block-exports.test.mjs@@ -51,7 +51,7 @@ const ESBUILD_BIN = resolveBin('esbuild/bin/esbuild');let tmpDir;/**- * Build an @acme/widgets fixture: a block template (`.template.ts` doc ++ * Build an @acme/widgets fixture: a block template (released `.template.ts` compatibility descriptor +* same-stem `.tsx` source) under `templates/`, plus an astryx.integration* manifest, plus a caller-supplied `exports` map.* @param {Record<string, string> | undefined} exportsMap@@ -71,7 +71,7 @@ function makeWidgets(exportsMap) {path.join(pkgDir, 'astryx.integration.mjs'),`export default { templates: './templates' };\n`,);- // The template-spec doc (canonical `.template.*` family).+ // The released `.template.*` compatibility form remains resolvable.fs.writeFileSync(path.join(blockDir, 'GaugeShowcase.template.ts'),`export default { name: 'Gauge showcase', description: 'A gauge.' };\n`,@@ -127,10 +127,14 @@ function writeTsconfig() {/** @returns {{ok: boolean, out: string}} */function runTsc() {try {- execFileSync(process.execPath, [TSC_BIN, '--noEmit', '-p', 'tsconfig.json'], {- cwd: tmpDir,- stdio: 'pipe',- });+ execFileSync(+ process.execPath,+ [TSC_BIN, '--noEmit', '-p', 'tsconfig.json'],+ {+ cwd: tmpDir,+ stdio: 'pipe',+ },+ );return {ok: true, out: ''};} catch (e) {return {ok: false, out: `${e.stdout ?? ''}${e.stderr ?? ''}`};diff --git a/packages/cli/api/integration/integrationAdd.doc.mjs b/packages/cli/api/integration/integrationAdd.doc.mjsindex ff8871d70f..8776628dba 100644--- a/packages/cli/api/integration/integrationAdd.doc.mjs+++ b/packages/cli/api/integration/integrationAdd.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationAdd',+ namespace: 'cli/api',displayName: 'integrationAdd()',summary: 'Add one working contribution to an integration package.',description:diff --git a/packages/cli/api/integration/integrationAddAgentDoc.doc.mjs b/packages/cli/api/integration/integrationAddAgentDoc.doc.mjsindex f69156371d..b17b58bcc5 100644--- a/packages/cli/api/integration/integrationAddAgentDoc.doc.mjs+++ b/packages/cli/api/integration/integrationAddAgentDoc.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationAddAgentDoc',+ namespace: 'cli/api',displayName: 'integrationAddAgentDoc()',summary: 'Append one validated agent-guidance line.',description:diff --git a/packages/cli/api/integration/integrationAddCodemod.doc.mjs b/packages/cli/api/integration/integrationAddCodemod.doc.mjsindex 99dc36dd86..cb7676a2eb 100644--- a/packages/cli/api/integration/integrationAddCodemod.doc.mjs+++ b/packages/cli/api/integration/integrationAddCodemod.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationAddCodemod',+ namespace: 'cli/api',displayName: 'integrationAddCodemod()',summary: 'Add a safe identity codemod at an exact target version.',description:diff --git a/packages/cli/api/integration/integrationAddComponent.doc.mjs b/packages/cli/api/integration/integrationAddComponent.doc.mjsindex 1c4f7d895e..f779c611d8 100644--- a/packages/cli/api/integration/integrationAddComponent.doc.mjs+++ b/packages/cli/api/integration/integrationAddComponent.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationAddComponent',+ namespace: 'cli/api',displayName: 'integrationAddComponent()',summary: 'Add a complete component contribution.',description:diff --git a/packages/cli/api/integration/integrationAddDoc.doc.mjs b/packages/cli/api/integration/integrationAddDoc.doc.mjsindex d813612742..f97e1aed47 100644--- a/packages/cli/api/integration/integrationAddDoc.doc.mjs+++ b/packages/cli/api/integration/integrationAddDoc.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationAddDoc',+ namespace: 'cli/api',displayName: 'integrationAddDoc()',summary: 'Add a complete reference-doc contribution.',description:diff --git a/packages/cli/api/integration/integrationAddTemplate.doc.mjs b/packages/cli/api/integration/integrationAddTemplate.doc.mjsindex d50eb4d845..a3d4196f69 100644--- a/packages/cli/api/integration/integrationAddTemplate.doc.mjs+++ b/packages/cli/api/integration/integrationAddTemplate.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationAddTemplate',+ namespace: 'cli/api',displayName: 'integrationAddTemplate()',summary: 'Add a complete page or block template contribution.',description:diff --git a/packages/cli/api/integration/integrationAddTheme.doc.mjs b/packages/cli/api/integration/integrationAddTheme.doc.mjsindex f5a63708b2..552c143f17 100644--- a/packages/cli/api/integration/integrationAddTheme.doc.mjs+++ b/packages/cli/api/integration/integrationAddTheme.doc.mjs@@ -5,10 +5,11 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationAddTheme',+ namespace: 'cli/api',displayName: 'integrationAddTheme()',summary: 'Add a source theme to an integration package.',description:- 'Creates an integration manifest when the package has none, writes a minimal named-export defineTheme source file, adds its entry to the root theme catalog, declares the optional themes root on first use, and includes the manifest and root in package.json files when the package already uses an allowlist. Every path is confined to the package and existing theme files are never overwritten.',+ 'Creates an integration manifest when the package has none, writes a minimal named-export defineTheme source file plus its strongly typed same-stem ThemeDoc, declares the optional themes root on first use, and includes the manifest and root in package.json files when the package already uses an allowlist. Every path is confined to the package and existing theme directories are never overwritten.',importPath: '@astryxdesign/cli/api',signature:'integrationAddTheme(name: string, options?: IntegrationAddThemeOptions): Promise<IntegrationAddResponse>',@@ -17,7 +18,7 @@ export const doc = {{name: 'name',type: 'string',- description: 'Lowercase kebab-case theme name and catalog slug.',+ description: 'Lowercase kebab-case theme name and directory slug.',required: true,},{@@ -51,7 +52,7 @@ export const doc = {},{code: 'ERR_FILE_EXISTS',- when: 'the theme slug or source file already exists',+ when: 'the theme slug directory already exists',},{code: 'ERR_PATH_TRAVERSAL',@@ -63,7 +64,7 @@ export const doc = {},{code: 'ERR_THEME_INVALID',- when: 'the package, integration manifest, or theme catalog is invalid',+ when: 'the package, integration manifest, or theme descriptor is invalid',},{code: 'ERR_WRITE_FAILED',@@ -80,6 +81,6 @@ export const doc = {code: "await integrationAddTheme('ocean', {dryRun: true});",},],- command: 'integration add',+ command: 'integration add theme',related: ['themeList', 'themeAdd', 'validateIntegration'],};diff --git a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs b/packages/cli/api/integration/integrationComponentConflicts.doc.mjsindex db7028ef09..9cfacd8d74 100644--- a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs+++ b/packages/cli/api/integration/integrationComponentConflicts.doc.mjs@@ -7,6 +7,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationComponentConflicts',+ namespace: 'cli/api',displayName: 'integrationComponentConflicts()',summary: 'Find integration component names that also exist in Core.',description:diff --git a/packages/cli/api/integration/integrationDocConflicts.doc.mjs b/packages/cli/api/integration/integrationDocConflicts.doc.mjsindex 0e1365f080..4cebc89c04 100644--- a/packages/cli/api/integration/integrationDocConflicts.doc.mjs+++ b/packages/cli/api/integration/integrationDocConflicts.doc.mjs@@ -7,6 +7,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationDocConflicts',+ namespace: 'cli/api',displayName: 'integrationDocConflicts()',summary: 'Classify integration doc overlaps with Core topics.',description:diff --git a/packages/cli/api/integration/integrationPackCheck.doc.mjs b/packages/cli/api/integration/integrationPackCheck.doc.mjsindex 9d7d4b9deb..7acf10ca3d 100644--- a/packages/cli/api/integration/integrationPackCheck.doc.mjs+++ b/packages/cli/api/integration/integrationPackCheck.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationPackCheck',+ namespace: 'cli/api',displayName: 'integrationPackCheck()',summary: 'Prove an integration package survives npm packing.',description:diff --git a/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs b/packages/cli/api/integration/integrationTemplateConflicts.doc.mjsindex 97414f8f36..a7972da549 100644--- a/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs+++ b/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs@@ -9,6 +9,7 @@ export const doc = {type: 'function',kind: 'api',name: 'integrationTemplateConflicts',+ namespace: 'cli/api',displayName: 'integrationTemplateConflicts()',summary: 'Find integration template ids that also exist in Core.',description:diff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjsindex 12f1789a02..56e29d0311 100644--- a/packages/cli/api/integration/pack-check.test.mjs+++ b/packages/cli/api/integration/pack-check.test.mjs@@ -53,25 +53,10 @@ function writePackage({"import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const oceanTheme = defineTheme({name: 'ocean'});\n",);fs.writeFileSync(- path.join(root, 'manifest.json'),- JSON.stringify(- {- version: 1,- themes: [- {- slug: 'ocean',- displayName: 'Ocean',- description: 'Ocean theme.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts'],- },- ],- },- null,- 2,- ) + '\n',+ path.join(root, 'ocean', 'oceanTheme.doc.mjs'),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Ocean theme.', maintained: true};+`,);}if (components) {@@ -109,7 +94,7 @@ describe('integrationPackCheck', () => {);});- it('fails when a theme entry omits its catalog export', async () => {+ it('fails when a theme entry omits its inferred runtime export', async () => {writePackage({files: ['astryx.integration.mjs', 'themes']});fs.writeFileSync(path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),@@ -129,19 +114,12 @@ describe('integrationPackCheck', () => {);});- it('fails when a theme imports a file omitted from its catalog', async () => {+ it('fails when a theme imports a missing local file', async () => {writePackage({files: ['astryx.integration.mjs', 'themes']});- fs.mkdirSync(path.join(tmpDir, 'themes', 'ocean', 'tokens'), {- recursive: true,- });fs.writeFileSync(path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),"import {oceanPalette} from './tokens/ocean.palette';\nexport const oceanTheme = {oceanPalette};\n",);- fs.writeFileSync(- path.join(tmpDir, 'themes', 'ocean', 'tokens', 'ocean.palette.ts'),- 'export const oceanPalette = {};\n',- );const result = await integrationPackCheck({cwd: tmpDir});@@ -150,7 +128,7 @@ describe('integrationPackCheck', () => {expect.objectContaining({code: 'invalid_theme',message: expect.stringContaining(- 'must resolve to a listed file inside the theme directory',+ 'must resolve to a file inside the theme directory',),}),);@@ -231,7 +209,7 @@ describe('integrationPackCheck', () => {);fs.mkdirSync(path.join(tmpDir, 'templates'));fs.writeFileSync(- path.join(tmpDir, 'templates', 'account-page.template.mjs'),+ path.join(tmpDir, 'templates', 'account-page.doc.mjs'),"export default {type: 'page', name: 'Account page', description: 'Account page.'};\n",);fs.writeFileSync(@@ -314,10 +292,10 @@ describe('integrationPackCheck', () => {const script = ["const fs=require('fs')","fs.renameSync('themes/ocean','themes/storm')",- "const p='themes/manifest.json'",- 'const x=JSON.parse(fs.readFileSync(p))',- "x.themes[0].slug='storm'",- 'fs.writeFileSync(p,JSON.stringify(x))',+ "const p='themes/storm/oceanTheme.doc.mjs'",+ "let x=fs.readFileSync(p,'utf8')",+ "x=x.replace(/name: 'ocean'/, 'name: '+String.fromCharCode(39)+'storm'+String.fromCharCode(39))",+ 'fs.writeFileSync(p,x)',].join(';');writePackage({files: ['astryx.integration.mjs', 'themes'],@@ -513,23 +491,15 @@ describe('integrationPackCheck', () => {});describe('pack-check mutation tests', () => {- it('detects when a theme file is deleted after initial add', async () => {+ it('detects when a theme source is deleted after initial authoring', async () => {writePackage({files: ['astryx.integration.mjs', 'themes']});-- // Write a second theme file then delete it — catalog still references it- const catalog = JSON.parse(- fs.readFileSync(path.join(tmpDir, 'themes', 'manifest.json'), 'utf-8'),- );- catalog.themes[0].files.push('tokens.ts');- fs.writeFileSync(- path.join(tmpDir, 'themes', 'manifest.json'),- JSON.stringify(catalog, null, 2) + '\n',- );- // tokens.ts doesn't exist on disk → will be in inventory but not on disk- // (Phase 1 catches this; the file won't be in the pack list either)+ fs.rmSync(path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'));const result = await integrationPackCheck({cwd: tmpDir});expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({code: 'invalid_theme'}),+ );});it('detects when files[] is narrowed after add removes themes', async () => {diff --git a/packages/cli/api/integration/summarizeIssues.doc.mjs b/packages/cli/api/integration/summarizeIssues.doc.mjsindex ee7a444a0b..6d185b422a 100644--- a/packages/cli/api/integration/summarizeIssues.doc.mjs+++ b/packages/cli/api/integration/summarizeIssues.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'summarizeIssues',+ namespace: 'cli/api',displayName: 'summarizeIssues()',summary:'Tally integration issues by severity into error and warning counts.',diff --git a/packages/cli/api/integration/validate-integration-fixes.test.mjs b/packages/cli/api/integration/validate-integration-fixes.test.mjsnew file mode 100644index 0000000000..e0b40bfd9e--- /dev/null+++ b/packages/cli/api/integration/validate-integration-fixes.test.mjs@@ -0,0 +1,1389 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every `Fix:` that `astryx doctor integration validate` prints must hold+ * when followed literally: each test builds a package with one problem, reads+ * the fix, carries it out on a copy of the package, and validates again.+ *+ * The copy lives at a new path so the edited manifest is imported fresh rather+ * than served from the module cache. Temp dirs live under the repo root, as in+ * validate-integration.test.mjs.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {validateLocalIntegration} from './validate-integration.mjs';++let tmpDir;+let copies = 0;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-validate-fix-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++const MANIFEST = 'astryx.integration.mjs';+const THEME_TYPE =+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\n";++/** @param {Record<string, string>} roots */+const manifest = roots => `export default ${JSON.stringify(roots)};\n`;+/** @param {string} name */+const componentDoc = name =>+ `export default {type: 'component', name: '${name}', displayName: '${name}', usage: {description: '${name}.'}, props: []};\n`;+/** @param {string} name */+const componentSource = name => `export function ${name}() { return null; }\n`;+/** @param {string} name */+const topic = name =>+ `export default ${JSON.stringify({+ type: 'generic',+ name,+ title: name,+ description: `The ${name} topic.`,+ sections: [{title: 'Overview', content: [{type: 'prose', text: name}]}],+ })};\n`;+/** @param {string} name */+const themeDoc = name =>+ `${THEME_TYPE}export default {type: 'theme', name: '${name}', displayName: '${name}', description: 'A theme.', maintained: true};\n`;+/** @param {string} exportName */+const themeSource = exportName => `export const ${exportName} = {};\n`;+const codemod = `export default {type: 'code', title: 'Rename', transform: file => file.source};\n`;++/**+ * @param {Record<string, string>} files package-relative path -> contents+ * @returns {string} the package directory+ */+function writePackage(files) {+ const dir = path.join(tmpDir, 'pkg');+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: '@acme/kit', version: '1.0.0'}),+ );+ for (const [file, contents] of Object.entries(files)) {+ fs.mkdirSync(path.dirname(path.join(dir, file)), {recursive: true});+ fs.writeFileSync(path.join(dir, file), contents);+ }+ return dir;+}++/**+ * Carry out a fix on a fresh copy of the package.+ * @param {string} dir+ * @param {{move?: Array<[string, string]>, write?: Record<string, string>, mkdir?: string[]}} steps+ * @returns {string} the copy's directory+ */+function follow(dir, {move = [], write = {}, mkdir = []}) {+ copies += 1;+ const copy = path.join(tmpDir, `followed-${copies}`);+ fs.cpSync(dir, copy, {recursive: true});+ for (const folder of mkdir) {+ fs.mkdirSync(path.join(copy, folder), {recursive: true});+ }+ for (const [from, to] of move) {+ fs.mkdirSync(path.dirname(path.join(copy, to)), {recursive: true});+ fs.renameSync(path.join(copy, from), path.join(copy, to));+ }+ for (const [file, contents] of Object.entries(write)) {+ fs.writeFileSync(path.join(copy, file), contents);+ }+ return copy;+}++/** @param {string} dir */+async function issuesOf(dir) {+ return (await validateLocalIntegration(dir)).issues;+}++/**+ * The one issue with this code, which the test is about.+ * @param {Array<{code: string, message: string}>} issues+ * @param {string} code+ */+function only(issues, code) {+ const found = issues.filter(issue => issue.code === code);+ expect(found).toHaveLength(1);+ return found[0].message;+}++const unreachable = file =>+ `Found contribution metadata "${file}" outside every declared integration root, so it contributes nothing.`;+const good = {+ 'components/Good/Good.doc.mjs': componentDoc('Good'),+ 'components/Good/Good.tsx': componentSource('Good'),+};++describe('unreachable_contribution fixes hold when followed', () => {+ it('moves a theme at the package root into themes/<slug>/, never to a folder outside the package', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'oceanTheme.doc.mjs': themeDoc('ocean'),+ 'oceanTheme.ts': `import {tokens} from './oceanTokens';\nexport const oceanTheme = {tokens};\n`,+ 'oceanTokens.ts': 'export const tokens = {};\n',+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('oceanTheme.doc.mjs')} Fix: move oceanTheme.doc.mjs and oceanTheme.ts (with any local files it imports) into themes/ocean/ and set \`themes: './themes'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [+ ['oceanTheme.doc.mjs', 'themes/ocean/oceanTheme.doc.mjs'],+ ['oceanTheme.ts', 'themes/ocean/oceanTheme.ts'],+ ['oceanTokens.ts', 'themes/ocean/oceanTokens.ts'],+ ],+ write: {+ [MANIFEST]: manifest({components: './components', themes: './themes'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a theme folder at the top level under themes/, never making the package root the themes root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'sand/sandTheme.doc.mjs': themeDoc('sand'),+ 'sand/sandTheme.ts': themeSource('sandTheme'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('sand/sandTheme.doc.mjs')} Fix: move sand/ to themes/sand/ and set \`themes: './themes'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['sand', 'themes/sand']],+ write: {+ [MANIFEST]: manifest({components: './components', themes: './themes'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a stray theme folder into the declared themes root under its slug', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/ocean/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'themes/ocean/oceanTheme.ts': themeSource('oceanTheme'),+ 'extra/seaTheme.doc.mjs': themeDoc('sea'),+ 'extra/seaTheme.ts': themeSource('seaTheme'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('extra/seaTheme.doc.mjs')} Fix: move extra/ to themes/sea/.`,+ );++ const fixed = follow(dir, {move: [['extra', 'themes/sea']]});+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('keeps declaring a folder that holds only themes as the themes root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'palettes/sand/sandTheme.doc.mjs': themeDoc('sand'),+ 'palettes/sand/sandTheme.ts': themeSource('sandTheme'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('palettes/sand/sandTheme.doc.mjs')} Fix: set \`themes: './palettes'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ write: {+ [MANIFEST]: manifest({+ components: './components',+ themes: './palettes',+ }),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('offers either root for a theme when the declared themes root is empty', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/.keep': '',+ 'palettes/sand/sandTheme.doc.mjs': themeDoc('sand'),+ 'palettes/sand/sandTheme.ts': themeSource('sandTheme'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('palettes/sand/sandTheme.doc.mjs')} Fix: move palettes/sand/ to themes/sand/, or set \`themes: './palettes'\` in astryx.integration.mjs.`,+ );++ const moved = follow(dir, {move: [['palettes/sand', 'themes/sand']]});+ expect(await issuesOf(moved)).toEqual([]);+ const declared = follow(dir, {+ write: {[MANIFEST]: manifest({themes: './palettes'})},+ });+ expect(await issuesOf(declared)).toEqual([]);+ });++ it('declares themes/ as the root when its other folders are not themes', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'themes/ocean/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'themes/ocean/oceanTheme.ts': themeSource('oceanTheme'),+ 'themes/shared/colors.ts': 'export const colors = {};\n',+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('themes/ocean/oceanTheme.doc.mjs')} Fix: set \`themes: './themes'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ write: {+ [MANIFEST]: manifest({components: './components', themes: './themes'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('puts a theme in a folder of its own when themes/ holds a broken theme', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'themes/ocean/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'themes/ocean/oceanTheme.ts': themeSource('oceanTheme'),+ 'themes/draft/draftTheme.ts': themeSource('draftTheme'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('themes/ocean/oceanTheme.doc.mjs')} Fix: move themes/ocean/ into a folder that holds only themes, as ocean/, and set \`themes\` to that folder in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['themes/ocean', 'palettes/ocean']],+ write: {+ [MANIFEST]: manifest({+ components: './components',+ themes: './palettes',+ }),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a component doc at the package root with its source, never making the package root the components root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'Stray.doc.mjs': componentDoc('Stray'),+ 'Stray.tsx': componentSource('Stray'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('Stray.doc.mjs')} Fix: move it and Stray.tsx under components/ (the components root).`,+ );++ const fixed = follow(dir, {+ move: [+ ['Stray.doc.mjs', 'components/Stray/Stray.doc.mjs'],+ ['Stray.tsx', 'components/Stray/Stray.tsx'],+ ],+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a topic at the package root into docs/, never making the package root the docs root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'guide.doc.mjs': topic('guide'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('guide.doc.mjs')} Fix: move it into docs/ and set \`docs: './docs'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['guide.doc.mjs', 'docs/guide.doc.mjs']],+ write: {+ [MANIFEST]: manifest({components: './components', docs: './docs'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('declares a folder that holds only topics as the docs root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({}),+ 'src/guide.doc.mjs': topic('guide'),+ 'src/faq.doc.mjs': topic('faq'),+ });++ const issues = await issuesOf(dir);+ expect(issues.map(issue => issue.message)).toEqual([+ `${unreachable('src/faq.doc.mjs')} Fix: set \`docs: './src'\` in astryx.integration.mjs.`,+ `${unreachable('src/guide.doc.mjs')} Fix: set \`docs: './src'\` in astryx.integration.mjs.`,+ ]);++ const fixed = follow(dir, {write: {[MANIFEST]: manifest({docs: './src'})}});+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('never declares a folder that also holds another kind of doc as a root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({}),+ 'src/Button.doc.mjs': componentDoc('Button'),+ 'src/Button.tsx': componentSource('Button'),+ 'src/guide.doc.mjs': topic('guide'),+ });++ const issues = await issuesOf(dir);+ expect(issues.map(issue => issue.message)).toEqual([+ `${unreachable('src/Button.doc.mjs')} Fix: move it and Button.tsx into components/ and set \`components: './components'\` in astryx.integration.mjs.`,+ `${unreachable('src/guide.doc.mjs')} Fix: move it into docs/ and set \`docs: './docs'\` in astryx.integration.mjs.`,+ ]);++ const fixed = follow(dir, {+ move: [+ ['src/Button.doc.mjs', 'components/Button.doc.mjs'],+ ['src/Button.tsx', 'components/Button.tsx'],+ ['src/guide.doc.mjs', 'docs/guide.doc.mjs'],+ ],+ write: {+ [MANIFEST]: manifest({components: './components', docs: './docs'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('names a fresh folder when docs/ already holds another kind of doc', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({}),+ 'docs/Button.doc.mjs': componentDoc('Button'),+ 'docs/Button.tsx': componentSource('Button'),+ 'docs/guide.doc.mjs': topic('guide'),+ });++ const issues = await issuesOf(dir);+ expect(issues.map(issue => issue.message)).toEqual([+ `${unreachable('docs/Button.doc.mjs')} Fix: move it and Button.tsx into components/ and set \`components: './components'\` in astryx.integration.mjs.`,+ `${unreachable('docs/guide.doc.mjs')} Fix: move it into a folder that holds only topics, and set \`docs\` to that folder in astryx.integration.mjs.`,+ ]);++ const fixed = follow(dir, {+ move: [+ ['docs/Button.doc.mjs', 'components/Button.doc.mjs'],+ ['docs/Button.tsx', 'components/Button.tsx'],+ ['docs/guide.doc.mjs', 'guides/guide.doc.mjs'],+ ],+ write: {+ [MANIFEST]: manifest({components: './components', docs: './guides'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('only moves metadata into a declared root that already holds contributions', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({templates: './templates'}),+ 'templates/hero.doc.mjs': `export default {type: 'page', name: 'hero', displayName: 'Hero'};\n`,+ 'templates/hero.tsx': componentSource('Hero'),+ 'src/blocks/Carousel.doc.mjs': `export default {type: 'block', name: 'Carousel', displayName: 'Carousel', aspectRatio: 1};\n`,+ 'src/blocks/Carousel.tsx': componentSource('Carousel'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ // Pointing `templates` at src/blocks would orphan templates/hero.+ expect(message).toBe(+ `${unreachable('src/blocks/Carousel.doc.mjs')} Fix: move it and Carousel.tsx under templates/ (the templates root).`,+ );++ const fixed = follow(dir, {+ move: [+ ['src/blocks/Carousel.doc.mjs', 'templates/Carousel.doc.mjs'],+ ['src/blocks/Carousel.tsx', 'templates/Carousel.tsx'],+ ],+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('offers either root when the declared root is empty, and both hold', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({templates: './templates'}),+ 'templates/.keep': '',+ 'src/blocks/Carousel.doc.mjs': `export default {type: 'block', name: 'Carousel', displayName: 'Carousel', aspectRatio: 1};\n`,+ 'src/blocks/Carousel.tsx': componentSource('Carousel'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('src/blocks/Carousel.doc.mjs')} Fix: move it and Carousel.tsx under templates/ (the templates root), or set \`templates: './src/blocks'\` in astryx.integration.mjs.`,+ );++ const moved = follow(dir, {+ move: [+ ['src/blocks/Carousel.doc.mjs', 'templates/Carousel.doc.mjs'],+ ['src/blocks/Carousel.tsx', 'templates/Carousel.tsx'],+ ],+ });+ expect(await issuesOf(moved)).toEqual([]);+ const declared = follow(dir, {+ write: {[MANIFEST]: manifest({templates: './src/blocks'})},+ });+ expect(await issuesOf(declared)).toEqual([]);+ });+});++describe('unreachable_contribution fixes cover what the move leaves behind', () => {+ it('asks for the missing source a component doc needs once a root reads it', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'Stray.doc.mjs': componentDoc('Stray'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('Stray.doc.mjs')} Fix: move it under components/ (the components root). Also add Stray.tsx beside it.`,+ );++ const fixed = follow(dir, {+ move: [['Stray.doc.mjs', 'components/Stray.doc.mjs']],+ write: {'components/Stray.tsx': componentSource('Stray')},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('asks for the missing source a theme needs', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'sand/sandTheme.doc.mjs': themeDoc('sand'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('sand/sandTheme.doc.mjs')} Fix: move sand/ to themes/sand/ and set \`themes: './themes'\` in astryx.integration.mjs. Also add its same-stem theme source, such as sandTheme.ts, beside it.`,+ );++ const fixed = follow(dir, {+ move: [['sand', 'themes/sand']],+ write: {+ [MANIFEST]: manifest({components: './components', themes: './themes'}),+ 'themes/sand/sandTheme.ts': themeSource('sandTheme'),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('asks to rename a theme descriptor that is not a .doc.mjs file', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'sand/sandTheme.doc.ts': themeDoc('sand'),+ 'sand/sandTheme.ts': themeSource('sandTheme'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('sand/sandTheme.doc.ts')} Fix: move sand/ to themes/sand/ and set \`themes: './themes'\` in astryx.integration.mjs. Also rename sandTheme.doc.ts to sandTheme.doc.mjs: a theme descriptor is a .doc.mjs file.`,+ );++ const fixed = follow(dir, {+ move: [+ ['sand', 'themes/sand'],+ ['themes/sand/sandTheme.doc.ts', 'themes/sand/sandTheme.doc.mjs'],+ ],+ write: {+ [MANIFEST]: manifest({components: './components', themes: './themes'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('never declares a folder as a root when another doc in it would lose its source', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({}),+ 'src/Card.doc.mjs': componentDoc('Card'),+ 'src/Card.tsx': componentSource('Card'),+ 'src/Badge.doc.mjs': componentDoc('Badge'),+ });++ const issues = await issuesOf(dir);+ const card = issues.find(issue =>+ issue.message.includes('src/Card.doc.mjs'),+ );+ // A components root at src/ would read Badge, which has no source.+ expect(card?.message).toBe(+ `${unreachable('src/Card.doc.mjs')} Fix: move it and Card.tsx into components/ and set \`components: './components'\` in astryx.integration.mjs.`,+ );+ const badge = issues.find(issue =>+ issue.message.includes('src/Badge.doc.mjs'),+ );+ expect(badge?.message).toBe(+ `${unreachable('src/Badge.doc.mjs')} Fix: set \`components: './src'\` in astryx.integration.mjs. Also add Badge.tsx beside it.`,+ );++ const cardMoved = follow(dir, {+ move: [+ ['src/Card.doc.mjs', 'components/Card.doc.mjs'],+ ['src/Card.tsx', 'components/Card.tsx'],+ ],+ write: {[MANIFEST]: manifest({components: './components'})},+ });+ const left = await issuesOf(cardMoved);+ expect(left.map(issue => issue.code)).toEqual(['unreachable_contribution']);+ expect(left[0].message).toContain('src/Badge.doc.mjs');++ const badgeDeclared = follow(dir, {+ write: {+ [MANIFEST]: manifest({components: './src'}),+ 'src/Badge.tsx': componentSource('Badge'),+ },+ });+ expect(await issuesOf(badgeDeclared)).toEqual([]);+ });++ it('moves the target root out of another root that also reads it', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './src/components', docs: './src'}),+ 'src/overview.doc.mjs': topic('overview'),+ 'src/components/Good.doc.mjs': componentDoc('Good'),+ 'src/components/Good.tsx': componentSource('Good'),+ 'lib/Card.doc.mjs': componentDoc('Card'),+ 'lib/Card.tsx': componentSource('Card'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('lib/Card.doc.mjs')} Fix: move it and Card.tsx under src/components/ (the components root). The docs root src/ also reads src/components/; move src/components/ to components/ and set \`components: './components'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [+ ['lib/Card.doc.mjs', 'src/components/Card.doc.mjs'],+ ['lib/Card.tsx', 'src/components/Card.tsx'],+ ['src/components', 'components'],+ ],+ write: {+ [MANIFEST]: manifest({components: './components', docs: './src'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });+});++describe('fixes never move a contribution onto a name its root already has', () => {+ it('asks for a new slug when the themes root already has that theme', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/ocean/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'themes/ocean/oceanTheme.ts': themeSource('oceanTheme'),+ 'extra/ocean/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'extra/ocean/oceanTheme.ts': themeSource('oceanTheme'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('extra/ocean/oceanTheme.doc.mjs')} Fix: themes/ocean/ is taken, so give this theme a new lower-kebab slug: move extra/ocean/ to themes/<slug>/ and set \`name\` in oceanTheme.doc.mjs to <slug>.`,+ );++ const fixed = follow(dir, {+ move: [['extra/ocean', 'themes/deep-ocean']],+ write: {'themes/deep-ocean/oceanTheme.doc.mjs': themeDoc('deep-ocean')},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('asks for a new slug for a theme at the top of the codemods root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({codemods: './codemods', themes: './themes'}),+ 'themes/ocean/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'themes/ocean/oceanTheme.ts': themeSource('oceanTheme'),+ 'codemods/1.2.0/rename.mjs': codemod,+ 'codemods/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'codemods/oceanTheme.ts': themeSource('oceanTheme'),+ });++ const move =+ 'themes/ocean/ is taken, so give this theme a new lower-kebab slug: move oceanTheme.doc.mjs and oceanTheme.ts (with any local files it imports) into themes/<slug>/ and set `name` in oceanTheme.doc.mjs to <slug>.';+ expect(+ (await issuesOf(dir))+ .filter(issue => issue.code === 'codemod_outside_version')+ .map(issue => issue.message),+ ).toEqual([+ `Codemod file "codemods/oceanTheme.doc.mjs" is outside a version folder, so upgrade will never load it. Fix: oceanTheme.doc.mjs has type: 'theme', so it is not a codemod; ${move}`,+ `Codemod file "codemods/oceanTheme.ts" is outside a version folder, so upgrade will never load it. Fix: oceanTheme.ts is the source of oceanTheme.doc.mjs, which has type: 'theme', so neither is a codemod; ${move}`,+ ]);++ const fixed = follow(dir, {+ move: [+ ['codemods/oceanTheme.doc.mjs', 'themes/deep-ocean/oceanTheme.doc.mjs'],+ ['codemods/oceanTheme.ts', 'themes/deep-ocean/oceanTheme.ts'],+ ],+ write: {'themes/deep-ocean/oceanTheme.doc.mjs': themeDoc('deep-ocean')},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('asks for a new name when the docs root already has that topic', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({docs: './docs'}),+ 'docs/guide.doc.mjs': topic('guide'),+ 'extra/guide.doc.mjs': topic('guide'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('extra/guide.doc.mjs')} Fix: docs/ already has a topic named "guide" (docs/guide.doc.mjs), so give this one a new name: rename it to <name>.doc.mjs, set its \`name\` to <name>, and move it under docs/ (the docs root).`,+ );++ const fixed = follow(dir, {+ move: [['extra/guide.doc.mjs', 'docs/more-guide.doc.mjs']],+ write: {'docs/more-guide.doc.mjs': topic('more-guide')},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('asks for a new name when the components root already has that component', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ 'components/Foo/Foo.doc.mjs': componentDoc('Foo'),+ 'components/Foo/Foo.tsx': componentSource('Foo'),+ 'Foo.doc.mjs': componentDoc('Foo'),+ 'Foo.tsx': componentSource('Foo'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('Foo.doc.mjs')} Fix: components/ already has a component named Foo (components/Foo/Foo.doc.mjs), so give this one a new name: rename it and Foo.tsx to <Name>.doc.mjs and <Name>.tsx, set its \`name\` to <Name>, and move them under components/ (the components root).`,+ );++ const fixed = follow(dir, {+ move: [+ ['Foo.doc.mjs', 'components/FooPanel.doc.mjs'],+ ['Foo.tsx', 'components/FooPanel.tsx'],+ ],+ write: {'components/FooPanel.doc.mjs': componentDoc('FooPanel')},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ expect(+ fs.readFileSync(path.join(fixed, 'components/Foo/Foo.doc.mjs'), 'utf-8'),+ ).toBe(componentDoc('Foo'));+ });++ it('asks for a new name when the templates root already has that template', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({templates: './templates'}),+ 'templates/hero.doc.mjs': `export default {type: 'page', name: 'hero', displayName: 'Hero'};\n`,+ 'templates/hero.tsx': componentSource('Hero'),+ 'extra/hero.doc.mjs': `export default {type: 'page', name: 'hero', displayName: 'Hero'};\n`,+ 'extra/hero.tsx': componentSource('Hero'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('extra/hero.doc.mjs')} Fix: templates/ already has a template named hero (templates/hero.doc.mjs), so give this one a new name: rename it and hero.tsx to <name>.doc.mjs and <name>.tsx, set its \`name\` to <name>, and move them under templates/ (the templates root).`,+ );++ const fixed = follow(dir, {+ move: [+ ['extra/hero.doc.mjs', 'templates/hero-wide.doc.mjs'],+ ['extra/hero.tsx', 'templates/hero-wide.tsx'],+ ],+ write: {+ 'templates/hero-wide.doc.mjs': `export default {type: 'page', name: 'hero-wide', displayName: 'Hero'};\n`,+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('asks for a new name when the root a fix moves out already has that topic', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './src', docs: './src/zdocs'}),+ 'src/zdocs/guide.doc.mjs': topic('guide'),+ 'src/faq.doc.mjs': topic('guide'),+ });++ const [faq] = (await issuesOf(dir)).filter(issue =>+ issue.message.includes('Component "faq"'),+ );+ expect(faq.message).toBe(+ `Component "faq" is missing its same-stem source file faq.tsx. Fix: faq.doc.mjs has type: 'generic', so it is not a component, and the components root src/ also reads the docs root src/zdocs/ inside it; move src/zdocs/ to docs/ and set \`docs: './docs'\` in astryx.integration.mjs, then give it a new name: rename it to <name>.doc.mjs, set its \`name\` to <name>, and move it into docs/.`,+ );++ const fixed = follow(dir, {+ move: [+ ['src/zdocs', 'docs'],+ ['src/faq.doc.mjs', 'docs/more-guide.doc.mjs'],+ ],+ write: {+ [MANIFEST]: manifest({components: './src', docs: './docs'}),+ 'docs/more-guide.doc.mjs': topic('more-guide'),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('never declares a folder that holds one topic name twice', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({}),+ 'src/guide.doc.mjs': topic('guide'),+ 'src/more/guide.doc.mjs': topic('guide'),+ });++ const [first] = (await issuesOf(dir)).filter(issue =>+ issue.message.includes('"src/guide.doc.mjs"'),+ );+ expect(first.message).toBe(+ `${unreachable('src/guide.doc.mjs')} Fix: move it into docs/ and set \`docs: './docs'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['src/guide.doc.mjs', 'docs/guide.doc.mjs']],+ write: {[MANIFEST]: manifest({docs: './docs'})},+ });+ const left = await issuesOf(fixed);+ expect(left.map(issue => issue.code)).toEqual(['unreachable_contribution']);+ expect(left[0].message).toContain('"src/more/guide.doc.mjs"');+ });+});++describe('theme fixes bring along what the theme imports', () => {+ it('copies a file a moved theme folder imports from outside it', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'lib/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'lib/oceanTheme.ts': `import {tokens} from '../shared/tokens';\nexport const oceanTheme = {tokens};\n`,+ 'shared/tokens.ts': 'export const tokens = {};\n',+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('lib/oceanTheme.doc.mjs')} Fix: move lib/ to themes/ocean/ and set \`themes: './themes'\` in astryx.integration.mjs. Also copy shared/tokens.ts into themes/ocean/ and change the import of ../shared/tokens in oceanTheme.ts to ./tokens: a theme can import only files inside its own folder.`,+ );++ const fixed = follow(dir, {+ move: [['lib', 'themes/ocean']],+ write: {+ [MANIFEST]: manifest({components: './components', themes: './themes'}),+ 'themes/ocean/tokens.ts': 'export const tokens = {};\n',+ 'themes/ocean/oceanTheme.ts': `import {tokens} from './tokens';\nexport const oceanTheme = {tokens};\n`,+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('copies what a theme imports from outside the folder a fix declares', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'palettes/sand/sandTheme.doc.mjs': themeDoc('sand'),+ 'palettes/sand/sandTheme.ts': `import {tokens} from '../../shared/tokens.ts';\nexport const sandTheme = {tokens};\n`,+ 'shared/tokens.ts': 'export const tokens = {};\n',+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('palettes/sand/sandTheme.doc.mjs')} Fix: set \`themes: './palettes'\` in astryx.integration.mjs. Also copy shared/tokens.ts into palettes/sand/ and change the import of ../../shared/tokens.ts in sandTheme.ts to ./tokens.ts: a theme can import only files inside its own folder.`,+ );++ const fixed = follow(dir, {+ write: {+ [MANIFEST]: manifest({+ components: './components',+ themes: './palettes',+ }),+ 'palettes/sand/tokens.ts': 'export const tokens = {};\n',+ 'palettes/sand/sandTheme.ts': `import {tokens} from './tokens.ts';\nexport const sandTheme = {tokens};\n`,+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });+});++describe('a components root is offered only where every source has a doc', () => {+ it('moves the component instead of declaring a folder with a source no doc covers', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({docs: './docs'}),+ 'docs/guide.doc.mjs': topic('guide'),+ 'ui/Button.doc.mjs': componentDoc('Button'),+ 'ui/Button.tsx': componentSource('Button'),+ 'ui/Icon.tsx': componentSource('Icon'),+ });++ const message = only(await issuesOf(dir), 'unreachable_contribution');+ expect(message).toBe(+ `${unreachable('ui/Button.doc.mjs')} Fix: move it and Button.tsx into components/ and set \`components: './components'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [+ ['ui/Button.doc.mjs', 'components/Button.doc.mjs'],+ ['ui/Button.tsx', 'components/Button.tsx'],+ ],+ write: {+ [MANIFEST]: manifest({docs: './docs', components: './components'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });+});++describe('invalid_component fixes hold when followed', () => {+ it('names the real doc file for a .doc.ts component, and never says to delete it', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ 'components/Foo/Foo.doc.ts': componentDoc('Foo'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ 'Component "Foo" is missing its same-stem source file Foo.tsx. Fix: add Foo.tsx beside Foo.doc.ts.',+ );++ const fixed = follow(dir, {+ write: {'components/Foo/Foo.tsx': componentSource('Foo')},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('says to add the source beside a .doc.mjs component, and never to delete the doc', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ 'components/Widget.doc.mjs': componentDoc('Widget'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ 'Component "Widget" is missing its same-stem source file Widget.tsx. Fix: add Widget.tsx beside Widget.doc.mjs.',+ );++ const fixed = follow(dir, {+ write: {'components/Widget.tsx': componentSource('Widget')},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a docs root out of the components root that also reads it', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './src', docs: './src/docs'}),+ 'src/Good/Good.doc.mjs': componentDoc('Good'),+ 'src/Good/Good.tsx': componentSource('Good'),+ 'src/docs/intro.doc.mjs': topic('intro'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ `Component "intro" is missing its same-stem source file intro.tsx. Fix: intro.doc.mjs has type: 'generic', so it is not a component, and the components root src/ also reads the docs root src/docs/ inside it; move src/docs/ to docs/ and set \`docs: './docs'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['src/docs', 'docs']],+ write: {[MANIFEST]: manifest({components: './src', docs: './docs'})},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('also moves a topic that sits beside the overlapping docs root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './src', docs: './src/docs'}),+ 'src/Good/Good.doc.mjs': componentDoc('Good'),+ 'src/Good/Good.tsx': componentSource('Good'),+ 'src/docs/intro.doc.mjs': topic('intro'),+ 'src/guide.doc.mjs': topic('guide'),+ });++ const issues = (await issuesOf(dir)).filter(+ issue => issue.code === 'invalid_component',+ );+ expect(issues.map(issue => issue.message)).toContain(+ `Component "guide" is missing its same-stem source file guide.tsx. Fix: guide.doc.mjs has type: 'generic', so it is not a component, and the components root src/ also reads the docs root src/docs/ inside it; move src/docs/ to docs/ and set \`docs: './docs'\` in astryx.integration.mjs, then move it into docs/.`,+ );++ const fixed = follow(dir, {+ move: [+ ['src/docs', 'docs'],+ ['src/guide.doc.mjs', 'docs/guide.doc.mjs'],+ ],+ write: {[MANIFEST]: manifest({components: './src', docs: './docs'})},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('gives topics their own folder when the docs root and the components root are one folder', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './src', docs: './src'}),+ 'src/Good.doc.mjs': componentDoc('Good'),+ 'src/Good.tsx': componentSource('Good'),+ 'src/guide.doc.mjs': topic('guide'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ `Component "guide" is missing its same-stem source file guide.tsx. Fix: guide.doc.mjs has type: 'generic', so it is not a component, and the docs root and the components root are both src/; move the topics into docs/ and set \`docs: './docs'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['src/guide.doc.mjs', 'docs/guide.doc.mjs']],+ write: {[MANIFEST]: manifest({components: './src', docs: './docs'})},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a topic out of a components root that sits inside the docs root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './src/components', docs: './src'}),+ 'src/overview.doc.mjs': topic('overview'),+ 'src/components/guide.doc.mjs': topic('guide'),+ });++ const before = await issuesOf(dir);+ const message = only(before, 'invalid_component');+ expect(message).toBe(+ `Component "guide" is missing its same-stem source file guide.tsx. Fix: guide.doc.mjs has type: 'generic', so it is not a component; move it out of src/components/ (the components root) to another folder under src/ (the docs root).`,+ );++ const fixed = follow(dir, {+ move: [['src/components/guide.doc.mjs', 'src/guides/guide.doc.mjs']],+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a topic in the components root under the declared docs root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components', docs: './docs'}),+ ...good,+ 'components/guide.doc.mjs': topic('guide'),+ 'docs/faq.doc.mjs': topic('faq'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ `Component "guide" is missing its same-stem source file guide.tsx. Fix: guide.doc.mjs has type: 'generic', so it is not a component; move it under docs/ (the docs root).`,+ );++ const fixed = follow(dir, {+ move: [['components/guide.doc.mjs', 'docs/guide.doc.mjs']],+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a topic in the components root into a new docs root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'components/guide.doc.mjs': topic('guide'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ `Component "guide" is missing its same-stem source file guide.tsx. Fix: guide.doc.mjs has type: 'generic', so it is not a component; move it into docs/ and set \`docs: './docs'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['components/guide.doc.mjs', 'docs/guide.doc.mjs']],+ write: {+ [MANIFEST]: manifest({components: './components', docs: './docs'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a theme in the components root into themes/<slug>/', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ ...good,+ 'components/ocean/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'components/ocean/oceanTheme.ts': themeSource('oceanTheme'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ `Component "oceanTheme" is missing its same-stem source file oceanTheme.tsx. Fix: oceanTheme.doc.mjs has type: 'theme', so it is not a component; move components/ocean/ to themes/ocean/ and set \`themes: './themes'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['components/ocean', 'themes/ocean']],+ write: {+ [MANIFEST]: manifest({components: './components', themes: './themes'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves the components out of a components root that is the package root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './', docs: './docs'}),+ 'Button.doc.mjs': componentDoc('Button'),+ 'Button.tsx': componentSource('Button'),+ 'docs/guide.doc.mjs': topic('guide'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ `Component "guide" is missing its same-stem source file guide.tsx. Fix: guide.doc.mjs has type: 'generic', so it is not a component, and the components root is the package root, which reads every doc in the package; create components/, move the components into it, and set \`components: './components'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [+ ['Button.doc.mjs', 'components/Button.doc.mjs'],+ ['Button.tsx', 'components/Button.tsx'],+ ],+ write: {+ [MANIFEST]: manifest({components: './components', docs: './docs'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });+});++describe('component fixes never leave another root reading the new files', () => {+ it('moves the components out of a folder another root also reads before a doc is added', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './src', docs: './src'}),+ 'src/Good.doc.mjs': componentDoc('Good'),+ 'src/Good.tsx': componentSource('Good'),+ 'src/Helper.tsx': componentSource('Helper'),+ });++ const message = only(await issuesOf(dir), 'source_without_component_doc');+ expect(message).toBe(+ `Component source "Helper.tsx" has no same-stem metadata file Helper.doc.mjs, so Astryx ignores it. Fix: add Helper.doc.mjs beside it with type: 'component'; \`astryx docs authoring component-doc\` lists its fields. The docs root is also src/; move the components there into components/ and set \`components: './components'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [+ ['src/Good.doc.mjs', 'components/Good.doc.mjs'],+ ['src/Good.tsx', 'components/Good.tsx'],+ ['src/Helper.tsx', 'components/Helper.tsx'],+ ],+ write: {+ [MANIFEST]: manifest({components: './components', docs: './src'}),+ 'components/Helper.doc.mjs': componentDoc('Helper'),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('never moves the components into a components/ that holds a source without a doc', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './', docs: './docs'}),+ 'Button.doc.mjs': componentDoc('Button'),+ 'Button.tsx': componentSource('Button'),+ 'docs/guide.doc.mjs': topic('guide'),+ 'components/Helper.tsx': componentSource('Helper'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ `Component "guide" is missing its same-stem source file guide.tsx. Fix: guide.doc.mjs has type: 'generic', so it is not a component, and the components root is the package root, which reads every doc in the package; move the components into a folder that holds only components, and set \`components\` to that folder in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [+ ['Button.doc.mjs', 'ui/Button.doc.mjs'],+ ['Button.tsx', 'ui/Button.tsx'],+ ],+ write: {[MANIFEST]: manifest({components: './ui', docs: './docs'})},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });+});++describe('source_without_component_doc fixes hold when followed', () => {+ it('adds the named doc, which resolves the warning', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ 'components/Widget.tsx': componentSource('Widget'),+ });++ const message = only(await issuesOf(dir), 'source_without_component_doc');+ expect(message).toBe(+ 'Component source "Widget.tsx" has no same-stem metadata file Widget.doc.mjs, so Astryx ignores it. Fix: add Widget.doc.mjs beside it with type: \'component\'; `astryx docs authoring component-doc` lists its fields.',+ );++ const fixed = follow(dir, {+ write: {'components/Widget.doc.mjs': componentDoc('Widget')},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('never asks for a doc that is already there but hidden', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ 'components/Secret.doc.mjs':+ "export default {\n type: 'component',\n name: 'Secret',\n hidden: true,\n};\n",+ 'components/Secret.tsx': componentSource('Secret'),+ });++ expect(await issuesOf(dir)).toEqual([]);+ });+});++describe('codemod fixes hold when followed', () => {+ it('moves a stray codemod into a version folder, and renames a mis-named one', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({codemods: './codemods'}),+ 'codemods/forgotten.mjs': codemod,+ 'codemods/v1/rename.mjs': codemod,+ });++ const issues = await issuesOf(dir);+ expect(only(issues, 'codemod_outside_version')).toBe(+ 'Codemod file "codemods/forgotten.mjs" is outside a version folder, so upgrade will never load it. Fix: move it into the folder named for the version it migrates to, for example codemods/1.2.0/forgotten.mjs.',+ );+ expect(only(issues, 'invalid_codemod_version')).toBe(+ 'Codemod folder "v1" is not an exact semver version such as 1.2.0. Fix: rename it to the exact version its codemods migrate to.',+ );++ const fixed = follow(dir, {+ move: [+ ['codemods/forgotten.mjs', 'codemods/1.2.0/forgotten.mjs'],+ ['codemods/v1', 'codemods/1.0.0'],+ ],+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('never offers the manifest as a codemod when the codemods root is the package root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({codemods: './', components: './components'}),+ ...good,+ '1.2.0/rename.mjs': codemod,+ 'index.mjs': 'export const version = 1;\n',+ });++ const issues = await issuesOf(dir);+ expect(issues.map(issue => issue.message).join('\n')).not.toContain(+ `Codemod file "${MANIFEST}"`,+ );+ const rootFix =+ "Fix: the codemods root is the package root, so everything in the package is read as a codemod or a version folder. Create codemods/, move each version folder into it, and set `codemods: './codemods'` in astryx.integration.mjs.";+ expect(only(issues, 'codemod_outside_version')).toBe(+ `Codemod file "index.mjs" is outside a version folder, so upgrade will never load it. ${rootFix} If it is a codemod, move it into the folder named for the version it migrates to, for example codemods/1.2.0/index.mjs.`,+ );+ expect(only(issues, 'invalid_codemod_version')).toBe(+ `Codemod folder "components" is not an exact semver version such as 1.2.0. ${rootFix}`,+ );++ // index.mjs is the package entry, not a codemod, so it stays.+ const fixed = follow(dir, {+ mkdir: ['codemods'],+ move: [['1.2.0', 'codemods/1.2.0']],+ write: {+ [MANIFEST]: manifest({+ codemods: './codemods',+ components: './components',+ }),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('gives codemods their own folder when the codemods root holds another root', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({+ codemods: './src',+ components: './src/components',+ }),+ 'src/components/Good.doc.mjs': componentDoc('Good'),+ 'src/components/Good.tsx': componentSource('Good'),+ 'src/1.2.0/rename.mjs': codemod,+ });++ const message = only(await issuesOf(dir), 'invalid_codemod_version');+ expect(message).toBe(+ 'Codemod folder "components" is not an exact semver version such as 1.2.0. Fix: the codemods root src/ also holds the components root src/components/. Create codemods/, move each version folder into it, and set `codemods: \'./codemods\'` in astryx.integration.mjs.',+ );++ const fixed = follow(dir, {+ mkdir: ['codemods'],+ move: [['src/1.2.0', 'codemods/1.2.0']],+ write: {+ [MANIFEST]: manifest({+ codemods: './codemods',+ components: './src/components',+ }),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a root out of codemods/ instead of renaming it as a version', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({+ codemods: './codemods',+ components: './codemods/components',+ }),+ 'codemods/components/Good.doc.mjs': componentDoc('Good'),+ 'codemods/components/Good.tsx': componentSource('Good'),+ 'codemods/1.2.0/rename.mjs': codemod,+ });++ const message = only(await issuesOf(dir), 'invalid_codemod_version');+ expect(message).toBe(+ 'Codemod folder "components" is not an exact semver version such as 1.2.0. Fix: it holds the components root codemods/components/; move that root out of codemods/ and update `components` in astryx.integration.mjs.',+ );++ const fixed = follow(dir, {+ move: [['codemods/components', 'components']],+ write: {+ [MANIFEST]: manifest({+ codemods: './codemods',+ components: './components',+ }),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });+ it('picks a new folder for codemods when codemods/ already holds something else', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({codemods: './', components: './components'}),+ ...good,+ '1.2.0/rename.mjs': codemod,+ 'codemods/notes.mjs': 'export const notes = 1;\n',+ });++ const issues = await issuesOf(dir);+ const rootFix =+ 'Fix: the codemods root is the package root, so everything in the package is read as a codemod or a version folder. Move each version folder into a new folder of their own, and set `codemods` to that folder in astryx.integration.mjs.';+ expect(+ issues+ .filter(issue => issue.code === 'invalid_codemod_version')+ .map(issue => issue.message),+ ).toEqual([+ `Codemod folder "codemods" is not an exact semver version such as 1.2.0. ${rootFix}`,+ `Codemod folder "components" is not an exact semver version such as 1.2.0. ${rootFix}`,+ ]);++ const fixed = follow(dir, {+ move: [['1.2.0', 'migrations/1.2.0']],+ write: {+ [MANIFEST]: manifest({+ codemods: './migrations',+ components: './components',+ }),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves contribution metadata out of the codemods root instead of into a version', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({codemods: './codemods'}),+ 'codemods/1.2.0/rename.mjs': codemod,+ 'codemods/guide.doc.mjs': topic('guide'),+ });++ const message = only(await issuesOf(dir), 'codemod_outside_version');+ expect(message).toBe(+ `Codemod file "codemods/guide.doc.mjs" is outside a version folder, so upgrade will never load it. Fix: guide.doc.mjs has type: 'generic', so it is not a codemod; move it into docs/ and set \`docs: './docs'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [['codemods/guide.doc.mjs', 'docs/guide.doc.mjs']],+ write: {[MANIFEST]: manifest({codemods: './codemods', docs: './docs'})},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('names a theme source whose descriptor is a .doc.ts file', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({codemods: './codemods'}),+ 'codemods/1.2.0/rename.mjs': codemod,+ 'codemods/oceanTheme.doc.ts': themeDoc('ocean'),+ 'codemods/oceanTheme.ts': themeSource('oceanTheme'),+ });++ const issues = (await issuesOf(dir)).filter(+ issue => issue.code === 'codemod_outside_version',+ );+ const move =+ "move oceanTheme.doc.ts and oceanTheme.ts (with any local files it imports) into themes/ocean/ and set `themes: './themes'` in astryx.integration.mjs. Also rename oceanTheme.doc.ts to oceanTheme.doc.mjs: a theme descriptor is a .doc.mjs file.";+ expect(issues.map(issue => issue.message)).toEqual([+ `Codemod file "codemods/oceanTheme.doc.ts" is outside a version folder, so upgrade will never load it. Fix: oceanTheme.doc.ts has type: 'theme', so it is not a codemod; ${move}`,+ `Codemod file "codemods/oceanTheme.ts" is outside a version folder, so upgrade will never load it. Fix: oceanTheme.ts is the source of oceanTheme.doc.ts, which has type: 'theme', so neither is a codemod; ${move}`,+ ]);++ const fixed = follow(dir, {+ move: [+ ['codemods/oceanTheme.doc.ts', 'themes/ocean/oceanTheme.doc.mjs'],+ ['codemods/oceanTheme.ts', 'themes/ocean/oceanTheme.ts'],+ ],+ write: {+ [MANIFEST]: manifest({codemods: './codemods', themes: './themes'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a file a theme imports out of the codemods root with the theme', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({codemods: './codemods'}),+ 'codemods/1.2.0/rename.mjs': codemod,+ 'codemods/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'codemods/oceanTheme.ts': `import {tokens} from './oceanTokens';\nexport const oceanTheme = {tokens};\n`,+ 'codemods/oceanTokens.ts': 'export const tokens = {};\n',+ });++ const [tokens] = (await issuesOf(dir)).filter(issue =>+ issue.message.includes('"codemods/oceanTokens.ts"'),+ );+ expect(tokens.message).toBe(+ `Codemod file "codemods/oceanTokens.ts" is outside a version folder, so upgrade will never load it. Fix: oceanTokens.ts is imported by oceanTheme.ts, the source of oceanTheme.doc.mjs, which has type: 'theme', so none of them is a codemod; move oceanTheme.doc.mjs and oceanTheme.ts (with any local files it imports) into themes/ocean/ and set \`themes: './themes'\` in astryx.integration.mjs.`,+ );++ const fixed = follow(dir, {+ move: [+ ['codemods/oceanTheme.doc.mjs', 'themes/ocean/oceanTheme.doc.mjs'],+ ['codemods/oceanTheme.ts', 'themes/ocean/oceanTheme.ts'],+ ['codemods/oceanTokens.ts', 'themes/ocean/oceanTokens.ts'],+ ],+ write: {+ [MANIFEST]: manifest({codemods: './codemods', themes: './themes'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('moves a theme source out of the codemods root with its descriptor', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({codemods: './codemods'}),+ 'codemods/1.2.0/rename.mjs': codemod,+ 'codemods/oceanTheme.doc.mjs': themeDoc('ocean'),+ 'codemods/oceanTheme.ts': themeSource('oceanTheme'),+ });++ const issues = (await issuesOf(dir)).filter(+ issue => issue.code === 'codemod_outside_version',+ );+ const move =+ "move oceanTheme.doc.mjs and oceanTheme.ts (with any local files it imports) into themes/ocean/ and set `themes: './themes'` in astryx.integration.mjs.";+ expect(issues.map(issue => issue.message)).toEqual([+ `Codemod file "codemods/oceanTheme.doc.mjs" is outside a version folder, so upgrade will never load it. Fix: oceanTheme.doc.mjs has type: 'theme', so it is not a codemod; ${move}`,+ `Codemod file "codemods/oceanTheme.ts" is outside a version folder, so upgrade will never load it. Fix: oceanTheme.ts is the source of oceanTheme.doc.mjs, which has type: 'theme', so neither is a codemod; ${move}`,+ ]);++ const fixed = follow(dir, {+ move: [+ ['codemods/oceanTheme.doc.mjs', 'themes/ocean/oceanTheme.doc.mjs'],+ ['codemods/oceanTheme.ts', 'themes/ocean/oceanTheme.ts'],+ ],+ write: {+ [MANIFEST]: manifest({codemods: './codemods', themes: './themes'}),+ },+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });+});diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex f4574a4c85..3a4c99f155 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -33,8 +33,19 @@import * as fs from 'node:fs';import * as path from 'node:path';-import jscodeshift from 'jscodeshift';import {assertWithin} from '../../foundation/fs/path-safety.mjs';+import {+ THEME_SLUG_RE,+ unreadThemeFolders,+} from '../../foundation/discovery/theme-discovery.mjs';+import {+ createFixContext,+ DOC_CANDIDATE_RE,+ pathIsInside,+ stampOf,+ TEMPLATE_CANDIDATE_RE,+ unreachableFix,+} from '../../foundation/integrations/contribution-fixes.mjs';import {findManifestPaths,loadManifest,@@ -90,106 +101,35 @@ const UNREACHABLE_SKIP_DIRS = new Set(['.next','out',]);-const DOC_CANDIDATE_RE = /\.doc\.(?:ts|mjs|js)$/u;-const TEMPLATE_CANDIDATE_RE = /\.template\.(?:ts|mjs|js)$/u;-const STATIC_DOC_TYPES = new Set(['component', 'generic', 'page', 'block']);-const STATIC_TEMPLATE_TYPES = new Set(['page', 'block']);-const j = jscodeshift.withParser('tsx');--/** @param {any} node @returns {any} */-function unwrapStaticExpression(node) {- let current = node;- while (- current &&- [- 'TSSatisfiesExpression',- 'TSAsExpression',- 'TypeCastExpression',- 'ParenthesizedExpression',- ].includes(current.type)- ) {- current = current.expression;- }- if (current?.type === 'CallExpression' && current.arguments.length > 0) {- current = unwrapStaticExpression(current.arguments[0]);- }- return current;-}--/** @param {any} property @param {string} name */-function staticPropertyNamed(property, name) {- if (- !property ||- !['ObjectProperty', 'Property'].includes(property.type) ||- property.computed- ) {- return false;- }- return (- (property.key?.type === 'Identifier' && property.key.name === name) ||- (['Literal', 'StringLiteral'].includes(property.key?.type) &&- property.key.value === name)- );-}-/**- * Identify contribution metadata without importing it. Doctor scans files that- * the manifest does not declare, so executing those files would run code the- * package never asked Astryx to load.- *- * @param {string} file- * @param {boolean} templateOnly+ * A warning for each folder under the themes root that holds modules but is+ * not read as a theme. Either branch of its fix leaves nothing to warn about:+ * the folder becomes a theme, or a dot-folder discovery skips.+ * @param {string} packageDir+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} loaded+ * @returns {Issue[]}*/-function isStaticContributionMetadata(file, templateOnly) {- let ast;- try {- ast = j(fs.readFileSync(file, 'utf-8'));- } catch {- return false;- }- /** @type {any[]} */- const candidates = [];- ast- .find(j.ExportDefaultDeclaration)- .forEach((/** @type {any} */ exportPath) => {- candidates.push(exportPath.value.declaration);- });- ast- .find(j.ExportNamedDeclaration)- .forEach((/** @type {any} */ exportPath) => {- const declaration = exportPath.value.declaration;- if (declaration?.type !== 'VariableDeclaration') return;- for (const declarator of declaration.declarations) {- if (- declarator.id?.type === 'Identifier' &&- declarator.id.name === 'docs'- ) {- candidates.push(declarator.init);- }- }- });-- const allowedTypes = templateOnly ? STATIC_TEMPLATE_TYPES : STATIC_DOC_TYPES;- for (const candidate of candidates) {- const object = unwrapStaticExpression(candidate);- if (object?.type !== 'ObjectExpression') continue;- const typeProperty = object.properties.find((/** @type {any} */ property) =>- staticPropertyNamed(property, 'type'),- );- const value = unwrapStaticExpression(typeProperty?.value);- if (- ['Literal', 'StringLiteral'].includes(value?.type) &&- allowedTypes.has(value.value)- ) {- return true;+function unreadThemeFolderIssues(packageDir, loaded) {+ const themes = /** @type {string} */ (loaded.themes);+ return unreadThemeFolders(themes, {+ packageDir,+ packageName: loaded.name,+ }).map(folder => {+ const name = path.basename(folder);+ const shown = `${path.relative(packageDir, folder).split(path.sep).join('/')}/`;+ const hide = `rename it to .${name} so Astryx skips it`;+ let fix;+ if (THEME_SLUG_RE.test(name)) {+ const stem = `${name.replace(/-([a-z0-9])/gu, (_, character) => character.toUpperCase())}Theme`;+ fix = `if it is a theme, add ${stem}.ts and ${stem}.doc.mjs to it (\`astryx integration add theme ${name}\` writes both) and move its code into ${stem}.ts; if not, ${hide}.`;+ } else {+ fix = `${hide}; a theme folder needs a lower-kebab name.`;}- }- return false;-}--/** @param {string} candidate @param {string} root */-function pathIsInside(candidate, root) {- return candidate === root || candidate.startsWith(`${root}${path.sep}`);+ return warning(+ 'unread_theme_folder',+ `Folder "${shown}" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: ${fix}`,+ );+ });}/**@@ -214,6 +154,7 @@ async function findUnreachableContributionIssues(packageDir, loaded) {);/** @type {Issue[]} */const issues = [];+ const context = createFixContext(packageDir, loaded);let scanned = 0;let truncated = false;@@ -237,13 +178,18 @@ async function findUnreachableContributionIssues(packageDir, loaded) {truncated = true;return;}- const isTemplate = TEMPLATE_CANDIDATE_RE.test(entry.name);- if (!isTemplate && !DOC_CANDIDATE_RE.test(entry.name)) continue;- if (!isStaticContributionMetadata(full, isTemplate)) continue;+ if (+ !TEMPLATE_CANDIDATE_RE.test(entry.name) &&+ !DOC_CANDIDATE_RE.test(entry.name)+ ) {+ continue;+ }+ const stamp = stampOf(context, full);+ if (stamp == null) continue;issues.push(warning('unreachable_contribution',- `Found contribution metadata "${path.relative(packageDir, full)}" outside every declared integration root, so it contributes nothing. Move it under the matching root or update the manifest root.`,+ `Found contribution metadata "${path.relative(packageDir, full)}" outside every declared integration root, so it contributes nothing. ${unreachableFix(context, full, stamp)}`,),);}@@ -366,6 +312,8 @@ async function validateAtPackageDir(// Roots + contribution checks are shared with validateLoadedIntegration so// the everyday-command nudge runs the exact same validators.issues.push(...(await validateLoadedIntegration(loaded)));+ if (loaded.themes)+ issues.push(...unreadThemeFolderIssues(packageDir, loaded));if (scanUnreachable) {issues.push(...(await findUnreachableContributionIssues(packageDir, loaded)),diff --git a/packages/cli/api/integration/validate-integration.test.mjs b/packages/cli/api/integration/validate-integration.test.mjsindex 5a3b4ddf18..075a357c39 100644--- a/packages/cli/api/integration/validate-integration.test.mjs+++ b/packages/cli/api/integration/validate-integration.test.mjs@@ -193,6 +193,39 @@ describe('validate-integration API', () => {expect(byCode(result.issues, 'invalid_codemod')).toHaveLength(1);});+ it('names a broken codemod of an installed package by its path inside the package', async () => {+ const consumer = path.join(tmpDir, 'consumer');+ fs.mkdirSync(consumer, {recursive: true});+ fs.writeFileSync(+ path.join(consumer, 'package.json'),+ JSON.stringify({name: 'consumer'}),+ );+ const pkgDir = path.join(consumer, 'node_modules', '@acme', 'kit');+ writePackage(pkgDir, {+ name: '@acme/kit',+ manifest: `export default { codemods: './codemods' };\n`,+ });+ fs.mkdirSync(path.join(pkgDir, 'codemods', '1.1.0'), {recursive: true});+ fs.writeFileSync(+ path.join(pkgDir, 'codemods', '1.1.0', 'no-default.mjs'),+ 'export const nope = 1;\n',+ );+ fs.writeFileSync(+ path.join(pkgDir, 'codemods', 'stray.mjs'),+ `export default {type: 'code', title: 'Stray', transform: file => file.source};\n`,+ );++ const result = await validateInstalledIntegration('@acme/kit', consumer);++ const [broken] = byCode(result.issues, 'invalid_codemod');+ expect(broken.message).toContain('(codemods/1.1.0/no-default.mjs)');+ const [stray] = byCode(result.issues, 'codemod_outside_version');+ expect(stray.message).toContain('"codemods/stray.mjs"');+ for (const issue of result.issues) {+ expect(issue.message).not.toContain(tmpDir);+ }+ });+it('flags a broken template as invalid_template error', async () => {const pkgDir = path.join(tmpDir, 'pkg');writePackage(pkgDir, {@@ -210,33 +243,24 @@ describe('validate-integration API', () => {expect(byCode(result.issues, 'invalid_template')).toHaveLength(1);});- it('reports no errors for a valid source-theme catalog', async () => {+ it('reports no errors for a valid source-theme descriptor', async () => {const pkgDir = path.join(tmpDir, 'pkg');writePackage(pkgDir, {- manifest: `export default { themes: './themes' };\n`,+ manifest: `export default { themes: './themes' };+`,});const themeDir = path.join(pkgDir, 'themes', 'ocean');fs.mkdirSync(themeDir, {recursive: true});fs.writeFileSync(- path.join(pkgDir, 'themes', 'manifest.json'),- JSON.stringify({- version: 1,- themes: [- {- slug: 'ocean',- displayName: 'Ocean',- description: 'Blue and calm.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts'],- },- ],- }),+ path.join(themeDir, 'oceanTheme.doc.mjs'),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Blue and calm.', maintained: true};+`,);fs.writeFileSync(path.join(themeDir, 'oceanTheme.ts'),- `export const oceanTheme = {};\n`,+ `export const oceanTheme = {};+`,);const result = await validateLocalIntegration(pkgDir);@@ -244,13 +268,17 @@ describe('validate-integration API', () => {expect(summarizeIssues(result.issues).errors).toBe(0);});- it('flags an unreadable source-theme catalog as invalid_theme', async () => {+ it('flags an obsolete source-theme catalog as invalid_theme', async () => {const pkgDir = path.join(tmpDir, 'pkg');writePackage(pkgDir, {- manifest: `export default { themes: './themes' };\n`,+ manifest: `export default { themes: './themes' };+`,});fs.mkdirSync(path.join(pkgDir, 'themes'), {recursive: true});- fs.writeFileSync(path.join(pkgDir, 'themes', 'manifest.json'), '{not-json');+ fs.writeFileSync(+ path.join(pkgDir, 'themes', 'manifest.json'),+ '{"version":1}',+ );const result = await validateLocalIntegration(pkgDir);expect(byCode(result.issues, 'invalid_theme')).toHaveLength(1);@@ -275,6 +303,11 @@ describe('validate-integration API', () => {message: expect.stringContaining('InvisibleWidget.doc.mjs'),}),]);+ expect(+ byCode(result.issues, 'source_without_component_doc')[0].message,+ ).toContain(+ "Fix: add InvisibleWidget.doc.mjs beside it with type: 'component'",+ );});it('reports codemods outside semver folders and invalid folder names', async () => {@@ -290,8 +323,12 @@ describe('validate-integration API', () => {const result = await validateLocalIntegration(pkgDir);- expect(byCode(result.issues, 'codemod_outside_version')).toHaveLength(1);- expect(byCode(result.issues, 'invalid_codemod_version')).toHaveLength(1);+ const [stray] = byCode(result.issues, 'codemod_outside_version');+ expect(stray.message).toContain('"codemods/forgotten.mjs"');+ expect(stray.message).toContain('codemods/1.2.0/forgotten.mjs');+ expect(stray.message).not.toContain(tmpDir);+ const [folder] = byCode(result.issues, 'invalid_codemod_version');+ expect(folder.message).toContain('Fix: rename it');});it('warns about valid contribution metadata outside every declared root', async () => {@@ -333,6 +370,31 @@ describe('validate-integration API', () => {const unreachable = byCode(result.issues, 'unreachable_contribution');expect(unreachable).toHaveLength(1);expect(unreachable[0].message).toContain('src/orphan.doc.mjs');+ // No docs root is declared, but src/ also holds a .doc.mjs that is not a+ // topic, which a docs root at src/ would read too; so the fix moves it.+ expect(unreachable[0].message).toContain(+ "Fix: move it into docs/ and set `docs: './docs'` in astryx.integration.mjs.",+ );+ });++ it('names the root that reads misplaced metadata when one is declared', async () => {+ const pkgDir = path.join(tmpDir, 'pkg');+ writePackage(pkgDir, {+ manifest: `export default { templates: './templates' };\n`,+ });+ fs.mkdirSync(path.join(pkgDir, 'templates'));+ fs.mkdirSync(path.join(pkgDir, 'src', 'blocks'), {recursive: true});+ fs.writeFileSync(+ path.join(pkgDir, 'src', 'blocks', 'Carousel.doc.mjs'),+ `export default {type: 'block', name: 'Carousel', displayName: 'Carousel', aspectRatio: 1};\n`,+ );++ const result = await validateLocalIntegration(pkgDir);++ const [issue] = byCode(result.issues, 'unreachable_contribution');+ expect(issue.message).toContain(+ "Fix: move it under templates/ (the templates root), or set `templates: './src/blocks'` in astryx.integration.mjs.",+ );});it('never executes unreachable metadata while diagnosing it', async () => {diff --git a/packages/cli/api/integration/validate-unread-theme-folders.test.mjs b/packages/cli/api/integration/validate-unread-theme-folders.test.mjsnew file mode 100644index 0000000000..4f549defb5--- /dev/null+++ b/packages/cli/api/integration/validate-unread-theme-folders.test.mjs@@ -0,0 +1,110 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `doctor integration validate` warns about a folder under the themes+ * root that holds modules but is not read as a theme, and both branches of+ * its fix leave nothing to warn about.+ *+ * @input a local integration package with a themes root+ * @output the unread_theme_folder warnings validation reports+ * @position packages/cli/api/integration — validation regression tests+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {validateLocalIntegration} from './validate-integration.mjs';+import {integrationAddTheme} from './add-theme.mjs';++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-unread-theme-'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/kit', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/** @param {Record<string, string>} files paths under themes/ */+function writeThemes(files) {+ for (const [file, contents] of Object.entries(files)) {+ const target = path.join(tmpDir, 'themes', file);+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.writeFileSync(target, contents);+ }+}++const OCEAN = {+ 'ocean/oceanTheme.doc.mjs':+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Blue.', maintained: true};\n",+ 'ocean/oceanTheme.ts':+ "import {blue} from '@acme/kit/themes/shared/palette';\nexport const oceanTheme = {blue};\n",+ 'shared/palette.ts': 'export const blue = 1;\n',+};++async function unread() {+ const {issues} = await validateLocalIntegration(tmpDir);+ return issues.filter(issue => issue.code === 'unread_theme_folder');+}++describe('unread theme folders', () => {+ it('warns about each folder that looks like a theme but is not read as one', async () => {+ writeThemes({+ ...OCEAN,+ 'sand/sand.ts': 'export const sand = {};\n',+ 'sand/sand.doc.ts': "export default {type: 'theme', name: 'sand'};\n",+ 'reef/index.ts': 'export const reefTheme = {};\n',+ 'Tide_Pool/index.ts': 'export const tide = {};\n',+ 'fonts/inter.woff2': 'x',+ 'utils/format.ts': 'export const format = String;\n',+ '.cache/index.ts': 'export {};\n',+ });+ const issues = await unread();+ expect(issues.map(issue => issue.severity)).toEqual([+ 'warning',+ 'warning',+ 'warning',+ ]);+ expect(issues.map(issue => issue.message)).toEqual([+ 'Folder "themes/Tide_Pool/" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: rename it to .Tide_Pool so Astryx skips it; a theme folder needs a lower-kebab name.',+ 'Folder "themes/reef/" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: if it is a theme, add reefTheme.ts and reefTheme.doc.mjs to it (`astryx integration add theme reef` writes both) and move its code into reefTheme.ts; if not, rename it to .reef so Astryx skips it.',+ 'Folder "themes/sand/" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: if it is a theme, add sandTheme.ts and sandTheme.doc.mjs to it (`astryx integration add theme sand` writes both) and move its code into sandTheme.ts; if not, rename it to .sand so Astryx skips it.',+ ]);+ });++ it('does not warn about a helper folder a module imports by a relative path', async () => {+ writeThemes({+ ...OCEAN,+ 'index.ts':+ "export * from './ocean/oceanTheme';\nexport * from './util';\n",+ 'util/index.ts': 'export const util = 1;\n',+ });+ expect(await unread()).toEqual([]);+ });++ it('holds when either branch of the fix is followed', async () => {+ writeThemes({+ ...OCEAN,+ 'sand/sand.ts': 'export const sand = {};\n',+ 'reef/index.ts': 'export const reefTheme = {};\n',+ 'Tide_Pool/index.ts': 'export const tide = {};\n',+ });+ await integrationAddTheme('sand', {cwd: tmpDir});+ await integrationAddTheme('reef', {cwd: tmpDir});+ fs.renameSync(+ path.join(tmpDir, 'themes', 'Tide_Pool'),+ path.join(tmpDir, 'themes', '.Tide_Pool'),+ );+ const {issues} = await validateLocalIntegration(tmpDir);+ expect(issues).toEqual([]);+ });+});diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjsindex 037a89148e..b5230e0123 100644--- a/packages/cli/api/integration/validateIntegration.doc.mjs+++ b/packages/cli/api/integration/validateIntegration.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'validateIntegration',+ namespace: 'cli/api',displayName: 'validateIntegration()',summary:'Validate a single Astryx integration package and report its issues.',diff --git a/packages/cli/api/json/assertResponse.doc.mjs b/packages/cli/api/json/assertResponse.doc.mjsindex 255819ba70..bfb102645f 100644--- a/packages/cli/api/json/assertResponse.doc.mjs+++ b/packages/cli/api/json/assertResponse.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'assertResponse',+ namespace: 'cli/api',displayName: 'assertResponse()',summary:'Parse and assert one expected response type, throwing on an error or a mismatch.',diff --git a/packages/cli/api/json/isError.doc.mjs b/packages/cli/api/json/isError.doc.mjsindex 866279eec3..a9f0bb7c14 100644--- a/packages/cli/api/json/isError.doc.mjs+++ b/packages/cli/api/json/isError.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'isError',+ namespace: 'cli/api',displayName: 'isError()',summary: 'Did the CLI return an error envelope?',description:diff --git a/packages/cli/api/json/parseResponse.doc.mjs b/packages/cli/api/json/parseResponse.doc.mjsindex 975007ec5e..caf5c29579 100644--- a/packages/cli/api/json/parseResponse.doc.mjs+++ b/packages/cli/api/json/parseResponse.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'parseResponse',+ namespace: 'cli/api',displayName: 'parseResponse()',summary: 'Parse `astryx --json` stdout into the structural response envelope.',description:diff --git a/packages/cli/api/layout/layoutCheck.doc.mjs b/packages/cli/api/layout/layoutCheck.doc.mjsindex 947950198d..c284854804 100644--- a/packages/cli/api/layout/layoutCheck.doc.mjs+++ b/packages/cli/api/layout/layoutCheck.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'layoutCheck',+ namespace: 'cli/api',displayName: 'layoutCheck()',summary: 'Validate a layout expression without expanding it.',description:diff --git a/packages/cli/api/layout/layoutExpand.doc.mjs b/packages/cli/api/layout/layoutExpand.doc.mjsindex da55852bb9..806c9daf59 100644--- a/packages/cli/api/layout/layoutExpand.doc.mjs+++ b/packages/cli/api/layout/layoutExpand.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'layoutExpand',+ namespace: 'cli/api',displayName: 'layoutExpand()',summary: 'Expand a validated layout expression into XDS TSX.',description:diff --git a/packages/cli/api/layout/layoutGrammar.doc.mjs b/packages/cli/api/layout/layoutGrammar.doc.mjsindex a92c7df4cb..b68fe9d628 100644--- a/packages/cli/api/layout/layoutGrammar.doc.mjs+++ b/packages/cli/api/layout/layoutGrammar.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'layoutGrammar',+ namespace: 'cli/api',displayName: 'layoutGrammar()',summary: 'Return the XLE/XLO grammar cheatsheet for this install.',description:diff --git a/packages/cli/api/search/search.doc.mjs b/packages/cli/api/search/search.doc.mjsindex 04e53efa66..5fe6fef367 100644--- a/packages/cli/api/search/search.doc.mjs+++ b/packages/cli/api/search/search.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'search',+ namespace: 'cli/api',displayName: 'search()',summary:'Unified ranked search across components, hooks, docs, and templates.',diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex 1e8da9ba38..06ae9d9142 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -50,7 +50,7 @@* queries they have nothing to do with.*/-import {pathToFileURL} from 'node:url';+import {readDocView} from '../../foundation/doc-compiler/read.mjs';import {findCoreDir} from '../../foundation/fs/paths.mjs';import {discoverComponents,@@ -528,16 +528,26 @@ export function scoreCandidate(}/**- * Load a doc module's `docs`/`doc` export, swallowing errors.+ * A component or hook doc, compiled, or null when it cannot be read.* @param {string} docPath* @param {string} [exportName]+ * @param {'components' | 'hooks'} [root]* @returns {Promise<any>}*/-async function loadModuleDoc(docPath, exportName = 'docs') {+async function loadModuleDoc(+ docPath,+ exportName = 'docs',+ root = 'components',+) {try {- const mod = await import(pathToFileURL(docPath).href);// Support both the stamped default export and the legacy named export.- return mod?.default ?? mod[exportName] ?? null;+ return (+ (await readDocView(docPath, {+ root,+ loader: 'native',+ exports: ['default', exportName],+ })) ?? null+ );} catch {return null;}@@ -701,7 +711,7 @@ async function gatherHooks(coreDir) {let description = '';let importPath = '@astryxdesign/core/hooks';if (docPath) {- const doc = await loadModuleDoc(docPath);+ const doc = await loadModuleDoc(docPath, 'docs', 'hooks');if (doc) {keywords = Array.isArray(doc.keywords) ? doc.keywords : [];description = doc.usage?.description || doc.description || '';diff --git a/packages/cli/api/swizzle/swizzle.doc.mjs b/packages/cli/api/swizzle/swizzle.doc.mjsindex ffb4a5f5cf..49993f08cc 100644--- a/packages/cli/api/swizzle/swizzle.doc.mjs+++ b/packages/cli/api/swizzle/swizzle.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'swizzle',+ namespace: 'cli/api',displayName: 'swizzle()',summary: "Eject a component's source into your project for customization.",description:diff --git a/packages/cli/api/template/template-suffix.test.mjs b/packages/cli/api/template/template-suffix.test.mjsindex 21fe948a42..5808a7c77e 100644--- a/packages/cli/api/template/template-suffix.test.mjs+++ b/packages/cli/api/template/template-suffix.test.mjs@@ -1,25 +1,20 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file The canonical `.template.{ts,mjs,js}` suffix is discovered identically- * to the legacy `.doc.{ts,mjs,js}` suffix.+ * @file The canonical `.doc.{mjs,ts,js}` suffix is discovered identically+ * to the released `.template.{ts,mjs,js}` compatibility suffix.*- * Template-spec files are named for what they are: a scaffoldable TEMPLATE- * stamped with `type: 'page' | 'block'`. The `.doc.*` suffix was- * inherited from the component-doc convention and is still accepted during the- * transition. These tests stand up integration templates and external blocks in- * both families and assert byte-for-byte-equivalent discovery + scaffolding.+ * New authoring writes `.doc.mjs`, the canonical typed descriptor. Stable+ * 0.6.0 already accepted `.template.*`, so these tests+ * keep that family as a compatibility input and assert equivalent discovery ++ * scaffolding.*/import {afterEach, beforeEach, describe, expect, it} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';import * as os from 'node:os';-import {- template,- findShowcase,- findRelatedBlocks,-} from './template.mjs';+import {template, findShowcase, findRelatedBlocks} from './template.mjs';let tmpDir;let originalCwd;@@ -82,8 +77,8 @@ afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});-describe('integration templates: .template.* discovered like legacy .doc.*', () => {- for (const suffix of ['.template.ts', '.template.mjs', '.doc.mjs']) {+describe('integration templates: canonical .doc.* plus released .template.* compatibility', () => {+ for (const suffix of ['.doc.mjs', '.doc.ts', '.template.mjs']) {it(`discovers + lists a page template authored as ${suffix}`, async () => {const pkgDir = installWidgets(tmpDir);writeTemplate(pkgDir, 'pricing', {kind: 'page', suffix});@@ -124,7 +119,7 @@ describe('integration templates: .template.* discovered like legacy .doc.*', ()});}- it('treats a .template.ts and a legacy .doc.mjs identically (same shape)', async () => {+ it('treats canonical .doc.mjs and released .template.ts identically (same shape)', async () => {const pkgDir = installWidgets(tmpDir);writeTemplate(pkgDir, 'gauge', {kind: 'block', suffix: '.template.ts'});writeTemplate(pkgDir, 'chip', {kind: 'block', suffix: '.doc.mjs'});@@ -143,12 +138,33 @@ describe('integration templates: .template.* discovered like legacy .doc.*', ()expect(gauge.type).toBe(chip.type);expect(gauge.package).toBe(chip.package);});+ it('lists both same-stem specs and reads the id as ambiguous', async () => {+ for (const [first, second] of [+ ['.doc.mjs', '.template.ts'],+ ['.doc.ts', '.doc.mjs'],+ ]) {+ const pkgDir = installWidgets(tmpDir);+ fs.rmSync(path.join(pkgDir, 'templates'), {recursive: true, force: true});+ writeTemplate(pkgDir, 'pricing', {kind: 'page', suffix: first});+ writeTemplate(pkgDir, 'pricing', {kind: 'page', suffix: second});++ const result = await template(undefined, {list: true, cwd: tmpDir});+ expect(+ result.data.filter(entry => entry.id === 'pricing'),+ `${first} + ${second}`,+ ).toHaveLength(2);+ await expect(+ template('pricing', {cwd: tmpDir}),+ `${first} + ${second}`,+ ).rejects.toMatchObject({code: 'ERR_AMBIGUOUS_TEMPLATE'});+ }+ });});-describe('external showcase blocks: .template.* discovered like legacy .doc.*', () => {+describe('external showcase blocks: canonical .doc.* plus released .template.* compatibility', () => {/*** Create a consumer whose @test/ext package contributes two showcase blocks,- * one authored as `Foo.template.ts` and one as legacy `Bar.doc.mjs`.+ * one authored with released `Foo.template.ts` and one with canonical `Bar.doc.mjs`.*/function makeShowcaseFixture() {// Symlink the real core package (needed by findCoreDir during discovery).@@ -166,7 +182,7 @@ describe('external showcase blocks: .template.* discovered like legacy .doc.*',const extDir = path.join(tmpDir, 'node_modules', '@test', 'ext');const blocksDir = path.join(extDir, 'blocks', 'components');- // Foo showcase — canonical .template.ts (stamped type: 'block' default export).+ // Foo showcase — released .template.ts compatibility input.const fooDir = path.join(blocksDir, 'Foo');fs.mkdirSync(fooDir, {recursive: true});fs.writeFileSync(@@ -185,7 +201,7 @@ describe('external showcase blocks: .template.* discovered like legacy .doc.*',"'use client';\nexport default function FooShowcase() { return <div>Foo</div>; }",);- // Bar showcase — legacy .doc.mjs (export const doc).+ // Bar showcase — canonical .doc.mjs (historical named export).const barDir = path.join(blocksDir, 'Bar');fs.mkdirSync(barDir, {recursive: true});fs.writeFileSync(@@ -209,7 +225,11 @@ describe('external showcase blocks: .template.* discovered like legacy .doc.*',path.join(extDir, 'package.json'),JSON.stringify({name: '@test/ext',- astryx: {docs: './src', category: 'Common', blocks: './blocks/components'},+ astryx: {+ docs: './src',+ category: 'Common',+ blocks: './blocks/components',+ },}),);fs.mkdirSync(path.join(extDir, 'src'), {recursive: true});@@ -223,7 +243,7 @@ describe('external showcase blocks: .template.* discovered like legacy .doc.*',expect(result.filePath).toContain('FooShowcase.tsx');});- it('findShowcase resolves a legacy .doc.mjs external block by componentsUsed', async () => {+ it('findShowcase resolves a canonical .doc.mjs external block by componentsUsed', async () => {makeShowcaseFixture();const result = await findShowcase('Bar', tmpDir);expect(result).not.toBeNull();diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjsindex 3ca91bee76..76d6d8112f 100644--- a/packages/cli/api/template/template.doc.mjs+++ b/packages/cli/api/template/template.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'template',+ namespace: 'cli/api',displayName: 'template()',summary: 'List, inspect, or scaffold page and block templates.',description:diff --git a/packages/cli/api/theme/_adapter.mjs b/packages/cli/api/theme/_adapter.mjsindex 294790fe1c..175532a0ad 100644--- a/packages/cli/api/theme/_adapter.mjs+++ b/packages/cli/api/theme/_adapter.mjs@@ -5,20 +5,19 @@** `listThemes()` intentionally keeps its historical synchronous, bundled-only* contract. Project-aware callers use `listAvailableThemes()`, which asks- * Project for the bundled catalog plus every installed integration catalog.+ * Project for the bundled themes plus every installed integration theme root.*/import {Project} from '../../foundation/config/project.mjs';import {BUNDLED_THEME_PACKAGE,- MANIFEST_PATH,THEMES_DIR,discoverBundledThemes,} from '../../foundation/discovery/theme-discovery.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';-export {BUNDLED_THEME_PACKAGE, MANIFEST_PATH, THEMES_DIR};+export {BUNDLED_THEME_PACKAGE, THEMES_DIR};/*** A bundled theme entry kept for the historical public `listThemes()` helper.@@ -55,7 +54,7 @@ function availableBundledThemes() {/*** Load available themes with any package-owned integration issues found while* discovering them. The issue set lets a package-scoped lookup distinguish an- * absent theme from an installed package whose catalog is broken.+ * absent theme from an installed package whose theme descriptors are broken.* @param {string} cwd* @returns {Promise<{themes: import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[], issues: Array<import('../../foundation/integrations/issue').AstryxIntegrationIssue & {package: string}>}>}*/@@ -71,7 +70,7 @@ async function availableThemeState(cwd) {/*** Bundled themes plus source themes from integrations installed in `cwd`.- * A project/config load failure degrades to the bundled catalog, preserving the+ * A project/config load failure degrades to the bundled set, preserving the* command's historical usefulness outside a configured project.* @param {string} [cwd]* @returns {Promise<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]>}diff --git a/packages/cli/api/theme/add/add.binary.test.mjs b/packages/cli/api/theme/add/add.binary.test.mjsindex 032063b580..7462bc1109 100644--- a/packages/cli/api/theme/add/add.binary.test.mjs+++ b/packages/cli/api/theme/add/add.binary.test.mjs@@ -37,21 +37,10 @@ beforeEach(() => {"export default {themes: './themes'};\n",);fs.writeFileSync(- path.join(packageDir, 'themes', 'manifest.json'),- JSON.stringify({- version: 1,- themes: [- {- slug: 'ocean',- displayName: 'Ocean',- description: 'Integration theme that ships a font.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts', 'fonts/ocean.woff2'],- },- ],- }),+ path.join(themeDir, 'oceanTheme.doc.mjs'),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Integration theme that ships a font.', maintained: true};+`,);fs.writeFileSync(path.join(themeDir, 'oceanTheme.ts'),@@ -64,14 +53,18 @@ afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});-describe('themeAdd copies every listed file', () => {+describe('themeAdd copies every file of the theme', () => {it('copies a binary file byte for byte', async () => {const result = await themeAdd('ocean', {cwd: tmpDir,package: '@acme/themes',});- expect(result.data.files).toEqual(['oceanTheme.ts', 'fonts/ocean.woff2']);+ expect(result.data.files).toEqual([+ 'oceanTheme.ts',+ 'fonts/ocean.woff2',+ 'oceanTheme.doc.mjs',+ ]);const copied = fs.readFileSync(path.join(tmpDir, 'src', 'themes', 'ocean', 'fonts', 'ocean.woff2'),);diff --git a/packages/cli/api/theme/add/add.test.mjs b/packages/cli/api/theme/add/add.test.mjsindex 5aa2a31e44..575ebef54b 100644--- a/packages/cli/api/theme/add/add.test.mjs+++ b/packages/cli/api/theme/add/add.test.mjs@@ -30,7 +30,20 @@ describe('themeAdd (api/theme/add)', () => {expect(result.data.slug).toBe('neutral');expect(result.data.package).toBe('@astryxdesign/cli');expect(result.data.outputDir).toBe(path.join('src', 'themes', 'neutral'));- expect(result.data.files.length).toBeGreaterThan(0);+ // Exactly what the bundle has always copied, in that order: the CLI's own+ // descriptor stays behind.+ expect(result.data.files).toEqual([+ 'neutralTheme.ts',+ 'icons.tsx',+ 'neutralPalettes.ts',+ 'neutralPalettes.generated.ts',+ 'neutralPaletteRefs.generated.ts',+ 'neutralPalettes.generated.receipt.json',+ 'palette.config.json',+ ]);+ expect(+ fs.readdirSync(path.join(tmpDir, 'src', 'themes', 'neutral')).sort(),+ ).toEqual([...result.data.files].sort());for (const f of result.data.files) {expect(fs.existsSync(path.join(tmpDir, 'src', 'themes', 'neutral', f)),diff --git a/packages/cli/api/theme/generateTonalPalette.doc.mjs b/packages/cli/api/theme/generateTonalPalette.doc.mjsindex b15bd6d708..d33c478b82 100644--- a/packages/cli/api/theme/generateTonalPalette.doc.mjs+++ b/packages/cli/api/theme/generateTonalPalette.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'generateTonalPalette',+ namespace: 'cli/api',displayName: 'generateTonalPalette()',summary: 'Generate candidate tonal palette data without filesystem effects.',description:diff --git a/packages/cli/api/theme/integration-themes.test.mjs b/packages/cli/api/theme/integration-themes.test.mjsindex 9320177a97..c9fbd88733 100644--- a/packages/cli/api/theme/integration-themes.test.mjs+++ b/packages/cli/api/theme/integration-themes.test.mjs@@ -7,18 +7,14 @@ import {themeAdd} from './add/add.mjs';let tmpDir;-function installThemeIntegration(- packageName,- slug,- source = 'export const oceanTheme = {};\n',- extraFiles = {},-) {+function installThemeIntegration(packageName, slug, source, extraFiles = {}) {const packageDir = path.join(tmpDir,'node_modules',...packageName.split('/'),);const themeDir = path.join(packageDir, 'themes', slug);+ const stem = `${slug.replace(/-([a-z0-9])/gu, (_, character) => character.toUpperCase())}Theme`;fs.mkdirSync(themeDir, {recursive: true});fs.writeFileSync(path.join(packageDir, 'package.json'),@@ -26,26 +22,21 @@ function installThemeIntegration();fs.writeFileSync(path.join(packageDir, 'astryx.integration.mjs'),- `export default {themes: './themes'};\n`,+ `export default {themes: './themes'};+`,);fs.writeFileSync(- path.join(packageDir, 'themes', 'manifest.json'),- JSON.stringify({- version: 1,- themes: [- {- slug,- displayName: slug === 'neutral' ? 'Neutral Plus' : 'Ocean',- description: 'Integration-owned theme.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts', ...Object.keys(extraFiles)],- },- ],- }),+ path.join(themeDir, `${stem}.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {type: 'theme', name: '${slug}', displayName: '${slug === 'neutral' ? 'Neutral Plus' : 'Ocean'}', description: 'Integration-owned theme.', maintained: true};+`,+ );+ fs.writeFileSync(+ path.join(themeDir, `${stem}.ts`),+ source ??+ `export const ${stem} = {};+`,);- fs.writeFileSync(path.join(themeDir, 'oceanTheme.ts'), source);for (const [relativePath, contents] of Object.entries(extraFiles)) {const file = path.join(themeDir, relativePath);fs.mkdirSync(path.dirname(file), {recursive: true});@@ -85,23 +76,43 @@ describe('themeAdd with integration themes', () => {).toContain('oceanTheme');});- it('copies nested files listed by an integration theme catalog', async () => {+ it('copies the complete nested integration theme directory', async () => {installThemeIntegration('@acme/themes','ocean',"import {oceanBlue} from './tokens/colors';\nexport const oceanTheme = {oceanBlue};\n",- {'tokens/colors.ts': "export const oceanBlue = '#0064e0';\n"},+ {+ 'tokens/colors.ts': "export const oceanBlue = '#0064e0';\n",+ 'receipts/palette.json': '{"version":1}\n',+ },);const result = await themeAdd('ocean', {cwd: tmpDir});- expect(result.data.files).toEqual(['oceanTheme.ts', 'tokens/colors.ts']);+ expect(result.data.files).toEqual([+ 'oceanTheme.ts',+ 'oceanTheme.doc.mjs',+ 'receipts/palette.json',+ 'tokens/colors.ts',+ ]);+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.doc.mjs'),+ 'utf-8',+ ),+ ).toContain("type: 'theme'");expect(fs.readFileSync(path.join(tmpDir, 'src', 'themes', 'ocean', 'tokens', 'colors.ts'),'utf-8',),).toContain('oceanBlue');+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'receipts', 'palette.json'),+ 'utf-8',+ ),+ ).toBe('{"version":1}\n');});it('rejects a nested destination symlink that escapes the project', async () => {@@ -146,7 +157,7 @@ describe('themeAdd with integration themes', () => {expect(result.data.package).toBe('@acme/themes');});- it('reports a selected installed package with a corrupted theme catalog', async () => {+ it('reports a selected installed package with a corrupted theme directory', async () => {installThemeIntegration('@acme/themes','ocean',@@ -170,7 +181,7 @@ describe('themeAdd with integration themes', () => {themeAdd('ocean', {cwd: tmpDir, package: '@acme/themes'}),).rejects.toMatchObject({code: 'ERR_THEME_INVALID',- message: expect.stringContaining('tokens/colors.ts'),+ message: expect.stringContaining('./tokens/colors'),});});diff --git a/packages/cli/api/theme/list/list.test.mjs b/packages/cli/api/theme/list/list.test.mjsindex 97a6ac8aee..25dd497816 100644--- a/packages/cli/api/theme/list/list.test.mjs+++ b/packages/cli/api/theme/list/list.test.mjs@@ -9,8 +9,13 @@ import {BUNDLED_THEME_PACKAGE} from '../../../foundation/discovery/theme-discovelet tmpDir;function installThemeIntegration(packageName = '@acme/themes', slug = 'ocean') {- const packageDir = path.join(tmpDir, 'node_modules', ...packageName.split('/'));+ const packageDir = path.join(+ tmpDir,+ 'node_modules',+ ...packageName.split('/'),+ );const themeDir = path.join(packageDir, 'themes', slug);+ const stem = `${slug.replace(/-([a-z0-9])/gu, (_, character) => character.toUpperCase())}Theme`;fs.mkdirSync(themeDir, {recursive: true});fs.writeFileSync(path.join(packageDir, 'package.json'),@@ -18,28 +23,19 @@ function installThemeIntegration(packageName = '@acme/themes', slug = 'ocean') {);fs.writeFileSync(path.join(packageDir, 'astryx.integration.mjs'),- `export default {themes: './themes'};\n`,+ `export default {themes: './themes'};+`,);fs.writeFileSync(- path.join(packageDir, 'themes', 'manifest.json'),- JSON.stringify({- version: 1,- themes: [- {- slug,- displayName: 'Ocean',- description: 'Blue and calm.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts'],- },- ],- }),+ path.join(themeDir, `${stem}.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {type: 'theme', name: '${slug}', displayName: 'Ocean', description: 'Blue and calm.', maintained: true};+`,);fs.writeFileSync(- path.join(themeDir, 'oceanTheme.ts'),- 'export const oceanTheme = {};\n',+ path.join(themeDir, `${stem}.ts`),+ `export const ${stem} = {};+`,);}@@ -47,7 +43,10 @@ beforeEach(() => {tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-theme-list-'));fs.writeFileSync(path.join(tmpDir, 'package.json'),- JSON.stringify({name: 'consumer', dependencies: {'@acme/themes': '^1.0.0'}}),+ JSON.stringify({+ name: 'consumer',+ dependencies: {'@acme/themes': '^1.0.0'},+ }),);});diff --git a/packages/cli/api/theme/listThemes.doc.mjs b/packages/cli/api/theme/listThemes.doc.mjsindex ae639c83a1..07c7e8f9b1 100644--- a/packages/cli/api/theme/listThemes.doc.mjs+++ b/packages/cli/api/theme/listThemes.doc.mjs@@ -9,25 +9,26 @@ export const doc = {type: 'function',kind: 'api',name: 'listThemes',+ namespace: 'cli/api',displayName: 'listThemes()',- summary: 'Read the CLI bundled-theme manifest.',+ summary: 'Read the CLI bundled-theme descriptors.',description:- 'Reads templates/themes/manifest.json and returns its raw entries synchronously. This low-level helper keeps its historical bundled-only contract; project-aware themeList() and themeAdd() also discover source themes from installed integrations.',+ 'Reads the typed same-stem descriptors under templates/themes and returns normalized entries synchronously. This low-level helper keeps its historical bundled-only contract; project-aware themeList() and themeAdd() also discover source themes from installed integrations.',importPath: '@astryxdesign/cli/api',signature: 'listThemes(): BundledTheme[]',- keywords: ['theme', 'themes', 'manifest', 'bundled', 'adapter', 'list'],+ keywords: ['theme', 'themes', 'descriptor', 'bundled', 'adapter', 'list'],params: [],returns: [{type: 'BundledTheme[]',description:- 'The bundled manifest entries: slug, displayName, description, maintained, entry, exportName, and files.',+ 'The normalized bundled descriptor entries: slug, displayName, description, maintained, entry, exportName, and files.',},],throws: [{code: 'ERR_NO_SOURCE',- when: 'the bundled catalog is missing, invalid, or references missing source files',+ when: 'the bundled descriptors are missing, invalid, or have missing source files',},],examples: [diff --git a/packages/cli/api/theme/themeAdd.doc.mjs b/packages/cli/api/theme/themeAdd.doc.mjsindex 4ba6e0af35..18606793aa 100644--- a/packages/cli/api/theme/themeAdd.doc.mjs+++ b/packages/cli/api/theme/themeAdd.doc.mjs@@ -9,10 +9,11 @@ export const doc = {type: 'function',kind: 'api',name: 'themeAdd',+ namespace: 'cli/api',displayName: 'themeAdd()',summary: 'Copy an available theme into a project as editable source.',description:- 'Resolves a theme from the CLI bundle or an installed integration and copies every catalog-listed source file into the consumer project. Writes are staged and existing files require explicit overwrite. Duplicate slugs fail closed until the caller selects an owner package.',+ "Resolves a theme from the CLI bundle or an installed integration and copies it into the consumer project: a bundled theme's source files, or an integration theme's complete directory with its descriptor. Writes are staged and existing files require explicit overwrite. Duplicate slugs fail closed until the caller selects an owner package.",importPath: '@astryxdesign/cli/api',signature:'themeAdd(slug: string, options?: {targetPath?: string, overwrite?: boolean, cwd?: string, package?: string}): Promise<ThemeAddResponse>',@@ -70,10 +71,10 @@ export const doc = {{code: 'ERR_AMBIGUOUS_THEME', when: 'more than one package owns the slug'},{code: 'ERR_THEME_INVALID',- when: 'the selected installed package has a blocking integration or theme-catalog error',+ when: 'the selected installed package has a blocking integration or theme-descriptor error',},{code: 'ERR_PATH_TRAVERSAL', when: 'the target path escapes cwd'},- {code: 'ERR_NO_SOURCE', when: 'a catalog-listed source file is missing'},+ {code: 'ERR_NO_SOURCE', when: 'a theme file to copy is missing'},{code: 'ERR_FILE_EXISTS',when: 'a destination exists and overwrite is not set',diff --git a/packages/cli/api/theme/themeBuild.doc.mjs b/packages/cli/api/theme/themeBuild.doc.mjsindex b294ebaac6..e3bf88f27e 100644--- a/packages/cli/api/theme/themeBuild.doc.mjs+++ b/packages/cli/api/theme/themeBuild.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'themeBuild',+ namespace: 'cli/api',displayName: 'themeBuild()',summary: 'Compile a defineTheme file to CSS + JS + type declarations.',description:diff --git a/packages/cli/api/theme/themeList.doc.mjs b/packages/cli/api/theme/themeList.doc.mjsindex c2100012f0..65e54a501a 100644--- a/packages/cli/api/theme/themeList.doc.mjs+++ b/packages/cli/api/theme/themeList.doc.mjs@@ -9,10 +9,11 @@ export const doc = {type: 'function',kind: 'api',name: 'themeList',+ namespace: 'cli/api',displayName: 'themeList()',summary: 'List themes bundled with this CLI build.',description:- 'Projects the bundled-theme manifest into a synchronous theme.list envelope. This preserves the original programmatic API contract. The CLI command uses themeListAvailable() so installed integrations also appear.',+ 'Projects the bundled typed theme descriptors into a synchronous theme.list envelope. This preserves the original programmatic API contract. The CLI command uses themeListAvailable() so installed integrations also appear.',importPath: '@astryxdesign/cli/api',signature: 'themeList(): ThemeListResponse',keywords: ['theme', 'list', 'themes', 'bundled', 'available'],@@ -27,9 +28,11 @@ export const doc = {throws: [{code: 'ERR_NO_SOURCE',- when: 'the bundled-theme manifest cannot be read or parsed',+ when: 'the bundled theme descriptors cannot be read or parsed',},],- examples: [{label: 'List bundled themes', code: 'const {data} = themeList();'}],+ examples: [+ {label: 'List bundled themes', code: 'const {data} = themeList();'},+ ],related: ['themeListAvailable', 'themeAdd', 'listThemes'],};diff --git a/packages/cli/api/theme/themeListAvailable.doc.mjs b/packages/cli/api/theme/themeListAvailable.doc.mjsindex 30192ff63b..b3cdca0311 100644--- a/packages/cli/api/theme/themeListAvailable.doc.mjs+++ b/packages/cli/api/theme/themeListAvailable.doc.mjs@@ -9,10 +9,11 @@ export const doc = {type: 'function',kind: 'api',name: 'themeListAvailable',+ namespace: 'cli/api',displayName: 'themeListAvailable()',summary: 'List bundled and installed integration themes.',description:- 'Loads Project for the requested directory, combines the CLI bundle with source themes from installed integrations, and projects each entry with its owner package. An unreadable project configuration degrades to the bundled catalog.',+ 'Loads Project for the requested directory, combines the CLI bundle with source themes from installed integrations, and projects each entry with its owner package. An unreadable project configuration degrades to the bundled descriptors.',importPath: '@astryxdesign/cli/api',signature:'themeListAvailable(options?: {cwd?: string, package?: string}): Promise<ThemeListResponse>',@@ -21,7 +22,8 @@ export const doc = {{name: 'options.cwd',type: 'string',- description: 'Project directory whose installed integrations contribute themes.',+ description:+ 'Project directory whose installed integrations contribute themes.',},{name: 'options.package',@@ -39,7 +41,7 @@ export const doc = {throws: [{code: 'ERR_NO_SOURCE',- when: 'the CLI bundled-theme manifest cannot be read or parsed',+ when: 'the CLI bundled-theme descriptors cannot be read or parsed',},],examples: [diff --git a/packages/cli/api/theme/themePaletteGenerate.doc.mjs b/packages/cli/api/theme/themePaletteGenerate.doc.mjsindex 154fa2c457..2d6344f0b7 100644--- a/packages/cli/api/theme/themePaletteGenerate.doc.mjs+++ b/packages/cli/api/theme/themePaletteGenerate.doc.mjs@@ -5,6 +5,7 @@ export const doc = {type: 'function',kind: 'api',name: 'themePaletteGenerate',+ namespace: 'cli/api',displayName: 'themePaletteGenerate()',summary: 'Generate an author-reviewable palette candidate from JSON input.',description:diff --git a/packages/cli/api/theme/themeTargets.doc.mjs b/packages/cli/api/theme/themeTargets.doc.mjsindex 2e2a403130..d280abec24 100644--- a/packages/cli/api/theme/themeTargets.doc.mjs+++ b/packages/cli/api/theme/themeTargets.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'themeTargets',+ namespace: 'cli/api',displayName: 'themeTargets()',summary: 'List every component theming target a theme can override.',description:diff --git a/packages/cli/api/theme/themeTemplate.doc.mjs b/packages/cli/api/theme/themeTemplate.doc.mjsindex ac1f49d83b..292b3b8f16 100644--- a/packages/cli/api/theme/themeTemplate.doc.mjs+++ b/packages/cli/api/theme/themeTemplate.doc.mjs@@ -12,6 +12,7 @@ export const doc = {type: 'function',kind: 'api',name: 'themeTemplate',+ namespace: 'cli/api',displayName: 'themeTemplate()',summary: 'Write the annotated theme template into a project.',description:diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjsindex b6c386f869..a063493c5e 100644--- a/packages/cli/api/upgrade/_adapter.mjs+++ b/packages/cli/api/upgrade/_adapter.mjs@@ -19,7 +19,10 @@ import * as path from 'node:path';import {execFile} from 'node:child_process';import {promisify} from 'node:util';import {ensureJscodeshift} from '../../assets/codemods/ensure-jscodeshift.mjs';-import {getTransformsBetween, latestVersion} from '../../assets/codemods/registry.mjs';+import {+ getTransformsBetween,+ latestVersion,+} from '../../assets/codemods/registry.mjs';import {runCodemods} from '../../assets/codemods/runner.mjs';import {discoverIntegrationCodemods,@@ -32,17 +35,15 @@ import {renderAgentDocsBlock,} from '../../foundation/agent-docs/agent-docs.mjs';import {formatCliCommand} from '../../foundation/env/package-manager.mjs';-import {Project} from '../../foundation/config/project.mjs';-import {- loadIntegrations,- markProviderConflicts,-} from '../../foundation/integrations/integrations.mjs';+import {Project, providerLedgerOf} from '../../foundation/config/project.mjs';+import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';+import {resolveProviders} from '../../foundation/integrations/provider-resolution.mjs';import {warnOnIntegrationIssues} from '../../foundation/integrations/integration-warnings.mjs';import {logger} from '../logger.mjs';// Re-exported for the run leaf's lightweight agent-docs inspection path// (config_fixable short-circuit, where the full render cannot load config).-export { inspectAgentDocs };+export {inspectAgentDocs};const execFileAsync = promisify(execFile);@@ -291,7 +292,13 @@ export async function collectAllCodemods() {);for (const {version, transforms} of manifests) {for (const {name, meta, optional} of transforms) {- codemods.push({name, title: meta.title, version, pr: meta.pr, optional: !!optional});+ codemods.push({+ name,+ title: meta.title,+ version,+ pr: meta.pr,+ optional: !!optional,+ });}}return codemods;@@ -322,33 +329,35 @@ export async function ensureCodemodDeps({installDeps} = {}) {* Run the CORE registry codemods. Runs BEFORE the config is loaded so a core* CONFIG codemod can repair a config the strict loader would otherwise reject.* @param {CoreVersionManifest[]} versionManifests- * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>}} options+ * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>, root?: string}} options*/-export async function runCoreCodemods(versionManifests, {apply, path: srcPath, codemod, skipCodemods}) {+export async function runCoreCodemods(+ versionManifests,+ {apply, path: srcPath, codemod, skipCodemods, root},+) {return runCodemods(versionManifests, {apply,path: srcPath,codemod,skipCodemods,silent: logger.silent,+ root,});}-/**- * One installed package at one version; two specs that reach it share this.- * @param {{name: string, version?: string}} integration- * @returns {string}- */-function packageIdentity(integration) {- return `${integration.name}\u0000${integration.version ?? ''}`;-}-/*** Load the consumer project's config + integrations. Throws on invalid config;* the run leaf decides between the config_fixable preview and a hard abort.+ *+ * Provider identity is resolved by the same resolver Project uses, on top of+ * Project's ledger, under the codemod policy: a package that lists itself runs+ * its installed copy's released codemods, never the work in progress being+ * authored, and autolinked and local packages claim provider IDs without+ * running codemods.+ ** @param {string} cwd* @param {string[]} [extraIntegrationSpecs] explicit `--integration` specs- * @returns {Promise<{postCodemodHooks: import('../../authoring/config/type').PostCodemodHook[], integrations: import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]}>}+ * @returns {Promise<{postCodemodHooks: import('../../authoring/config/type').PostCodemodHook[], integrations: import('../../foundation/integrations/integrations.mjs').LoadedIntegration[], ledger: import('../../foundation/integrations/provider-resolution.mjs').ProviderLedger}>}*/export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {// The CLI debug preflight may already have imported this config before core@@ -360,23 +369,38 @@ export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {// Configured packages come from Project, which has already resolved provider// identity over configured, autolinked, and local packages. Loading them// again here would let upgrade run codemods from a package Project set aside.- const configured = project.loadedIntegrations.filter(- integration =>- !integration.__autolinked && configuredSpecs.has(integration.__spec),- );+ // Autolinked packages and the package being authored join only as claimants:+ // every other command uses them for their provider IDs, but upgrade has+ // never run their codemods.+ const candidates = project.loadedIntegrations.flatMap(integration => {+ const source =+ !integration.__autolinked && configuredSpecs.has(integration.__spec)+ ? /** @type {const} */ ('configured')+ : integration.__autolinked+ ? /** @type {const} */ ('autolinked')+ : integration.__local+ ? /** @type {const} */ ('local')+ : null;+ return source == null+ ? []+ : [{source, integration, spec: integration.__spec}];+ });// A package that lists itself runs its installed copy's released codemods,- // never the work in progress being authored, so that copy stands in for it.+ // never the work in progress being authored; the resolver puts that copy in+ // its place. Naming the package being authored with --integration asks for+ // the installed copy too.const local = project.loadedIntegrations.find(integration => integration.__local,);- const selfListed = local != null && configured.includes(local);- if (local != null && selfListed && project.configPath) {- const installed = await loadIntegrations([local.__spec], {- cwd: path.dirname(project.configPath),- resolveProviders: false,- });- configured.splice(configured.indexOf(local), 1, ...installed);- }+ const selfListed =+ local != null && !local.__autolinked && configuredSpecs.has(local.__spec);+ const installed =+ local != null && selfListed && project.configPath+ ? await loadIntegrations([local.__spec], {+ cwd: path.dirname(project.configPath),+ resolveProviders: false,+ })+ : [];const extraSpecs = uniqueFiles(extraIntegrationSpecs ?? []).filter(spec => !configuredSpecs.has(spec),);@@ -384,38 +408,23 @@ export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {extraSpecs.length === 0? []: await loadIntegrations(extraSpecs, {resolveProviders: false});- // Naming the package being authored with --integration asks for its- // installed copy too, so the local package must not claim against it.- const localStandsIn =- local != null &&- (selfListed || extras.some(extra => extra.name === local.name));- // Autolinked packages and the package being authored join the pass only as- // claimants: every other command uses them for their provider IDs, but- // upgrade has never run their codemods and still does not. An extra that- // names one of them opts it in, so the extra stands in for that claimant.- const extraIdentities = new Set(extras.map(packageIdentity));- const claimantsOnly = project.loadedIntegrations.filter(- integration =>- (integration.__autolinked || (integration.__local && !localStandsIn)) &&- !extraIdentities.has(packageIdentity(integration)),- );- const resolved = markProviderConflicts([- ...configured,- ...claimantsOnly,- ...extras,- ]);- // Claimants leave by package directory, not object identity: the pass can- // return one as a new conflict entry, and upgrade must not warn that a- // package every other command uses contributes nothing.- const claimantDirs = new Set(- claimantsOnly.map(integration => integration.__packageDir),- );- const integrations = resolved.filter(- integration =>- integration.__packageDir == null ||- !claimantDirs.has(integration.__packageDir),+ const {integrations, ledger} = resolveProviders(+ [+ ...candidates,+ ...installed.map(integration => ({+ source: /** @type {const} */ ('installed'),+ integration,+ spec: integration.__spec,+ })),+ ...extras.map(integration => ({+ source: /** @type {const} */ ('extra'),+ integration,+ spec: integration.__spec,+ })),+ ],+ {codemods: true, prior: providerLedgerOf(project)},);- return {postCodemodHooks, integrations};+ return {postCodemodHooks, integrations, ledger};}/**@@ -450,7 +459,10 @@ export async function selectIntegrationCodemodsFor(integrations, from, to) {try {const byVersion = await discoverIntegrationCodemods([integration]);for (const [version, rawList] of byVersion) {- const list = /** @type {Array<import('../../authoring/codemod/type').CodemodEntry>} */ (/** @type {unknown} */ (rawList));+ const list =+ /** @type {Array<import('../../authoring/codemod/type').CodemodEntry>} */ (+ /** @type {unknown} */ (rawList)+ );const existing = integrationCodemodsByVersion.get(version);if (existing) existing.push(...list);else integrationCodemodsByVersion.set(version, [...list]);@@ -469,7 +481,10 @@ export async function selectIntegrationCodemodsFor(integrations, from, to) {* @param {Array<{version: string, codemods: import('../../authoring/codemod/type').CodemodEntry[]}>} versionGroups* @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>}} options*/-export async function runIntegrationCodemodsStep(versionGroups, {apply, path: srcPath, codemod, skipCodemods}) {+export async function runIntegrationCodemodsStep(+ versionGroups,+ {apply, path: srcPath, codemod, skipCodemods},+) {const jscodeshift = (await import('jscodeshift')).default;return runIntegrationCodemods(versionGroups, {apply,diff --git a/packages/cli/api/upgrade/provider-agreement.test.mjs b/packages/cli/api/upgrade/provider-agreement.test.mjsnew file mode 100644index 0000000000..b8e2a1c091--- /dev/null+++ b/packages/cli/api/upgrade/provider-agreement.test.mjs@@ -0,0 +1,152 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Where `upgrade` and Project still disagree on a provider ID's winner.+ *+ * Both repros are `it.fails`: each asserts the agreeing result, and fails+ * today. `upgrade` lets an `--integration` extra of the same name@version stand+ * in for an autolinked package, from any directory, and orders that extra with+ * the extras. So another extra can take the provider ID in `upgrade` while+ * every other command gives it to the autolinked package. The provider ledger+ * property test carves out exactly this shape.+ *+ * Fixtures live under a repo-local temp dir, not /tmp, because Vite refuses to+ * dynamically import a module from outside the project root.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {loadProjectContext} from './_adapter.mjs';+import {Project, providerLedgerOf} from '../../foundation/config/project.mjs';++let tmpDir;+let originalCwd;++beforeEach(() => {+ originalCwd = process.cwd();+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-upgrade-agreement-'),+ );+ process.chdir(tmpDir);+});++afterEach(() => {+ process.chdir(originalCwd);+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/**+ * Install a package under node_modules/<dir>.+ * @param {string} dir+ * @param {{name: string, version: string}} pkg+ * @param {string} manifest manifest module source+ */+function install(dir, pkg, manifest) {+ const pkgDir = path.join(tmpDir, 'node_modules', ...dir.split('/'));+ fs.mkdirSync(pkgDir, {recursive: true});+ fs.writeFileSync(path.join(pkgDir, 'package.json'), JSON.stringify(pkg));+ fs.writeFileSync(path.join(pkgDir, 'astryx.integration.mjs'), manifest);+}++/** An autolinked `@acme/a` and an `@acme/other` that claims its provider ID. */+function autolinkedWithRival() {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer', dependencies: {'@acme/a': '1.0.0'}}),+ );+ install(+ '@acme/a',+ {name: '@acme/a', version: '1.0.0'},+ 'export default {};\n',+ );+ install(+ '@acme/other',+ {name: '@acme/other', version: '1.0.0'},+ "export default {providerId: '@acme/a'};\n",+ );+}++/**+ * The package each resolution lets contribute under a provider ID.+ * @param {Map<string, any>} ledger+ * @param {string} providerId+ */+function winnerOf(ledger, providerId) {+ return [...ledger.values()].find(+ entry => entry.outcome === 'contributes' && entry.providerId === providerId,+ )?.key;+}++/** @param {Array<import('../../foundation/integrations/integrations.mjs').LoadedIntegration>} integrations */+function claims(integrations) {+ return integrations.map(integration => [+ integration.name,+ integration.__providerConflict?.claimedBy ?? null,+ ]);+}++describe('upgrade and Project on an autolinked package named with --integration', () => {+ it('agree when the autolinked package is named first', async () => {+ autolinkedWithRival();+ const project = await Project.load(tmpDir, {fresh: true});+ const upgrade = await loadProjectContext(tmpDir, [+ '@acme/a',+ '@acme/other',+ ]);++ expect(claims(upgrade.integrations)).toEqual([+ ['@acme/a', null],+ ['@acme/other', '@acme/a'],+ ]);+ expect(winnerOf(upgrade.ledger, '@acme/a')).toBe(+ winnerOf(providerLedgerOf(project), '@acme/a'),+ );+ });++ it.fails(+ 'agree when an extra that claims its ID is named first',+ async () => {+ autolinkedWithRival();+ const project = await Project.load(tmpDir, {fresh: true});+ // Today upgrade runs @acme/other and reports @acme/a, which every other+ // command uses, as contributing nothing.+ const upgrade = await loadProjectContext(tmpDir, [+ '@acme/other',+ '@acme/a',+ ]);++ expect(winnerOf(upgrade.ledger, '@acme/a')).toBe(+ winnerOf(providerLedgerOf(project), '@acme/a'),+ );+ expect(claims(upgrade.integrations)).toEqual([+ ['@acme/other', '@acme/a'],+ ['@acme/a', null],+ ]);+ },+ );++ it.fails(+ 'agree when a copy of it in another directory is named',+ async () => {+ autolinkedWithRival();+ // The same name@version in another directory, with a manifest that fails.+ install(+ '@acme/a-copy',+ {name: '@acme/a', version: '1.0.0'},+ "throw new Error('broken copy');\n",+ );+ const project = await Project.load(tmpDir, {fresh: true});+ // Today the broken copy stands in for @acme/a by name@version, so upgrade+ // has no claimant left for the ID and @acme/other takes it.+ const upgrade = await loadProjectContext(tmpDir, [+ '@acme/a-copy',+ '@acme/other',+ ]);++ expect(winnerOf(upgrade.ledger, '@acme/a')).toBe(+ winnerOf(providerLedgerOf(project), '@acme/a'),+ );+ },+ );+});diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjsindex d7a04c3af4..42dfb60398 100644--- a/packages/cli/api/upgrade/run/run.mjs+++ b/packages/cli/api/upgrade/run/run.mjs@@ -171,6 +171,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {path: path_,codemod: options.codemod,skipCodemods,+ root: cwd,});const coreResult = codemodResult && 'totalFilesChanged' in codemodResult ? codemodResult : null;diff --git a/packages/cli/api/upgrade/upgrade.doc.mjs b/packages/cli/api/upgrade/upgrade.doc.mjsindex f1c5477d7d..e38cc96023 100644--- a/packages/cli/api/upgrade/upgrade.doc.mjs+++ b/packages/cli/api/upgrade/upgrade.doc.mjs@@ -11,6 +11,7 @@ export const doc = {type: 'function',kind: 'api',name: 'upgrade',+ namespace: 'cli/api',displayName: 'upgrade()',summary: 'Run version migrations and reconcile copied compositions.',description:diff --git a/packages/cli/assets/codemods/integration-discovery.mjs b/packages/cli/assets/codemods/integration-discovery.mjsindex df2c8fbb62..c4534f8963 100644--- a/packages/cli/assets/codemods/integration-discovery.mjs+++ b/packages/cli/assets/codemods/integration-discovery.mjs@@ -106,7 +106,7 @@ function collectCodemodFiles(versionDir) {/*** Discover file-based codemods contributed by configured integrations.*- * @param {Array<{name?: string, codemods?: string, __spec?: string}>} loadedIntegrations+ * @param {Array<{name?: string, codemods?: string, __spec?: string, __packageDir?: string}>} loadedIntegrations* @returns {Promise<Map<string, Array<{id: string, type: 'code'|'config', codemod: object, package: string}>>>}* Map keyed by version string; each value is the list of discovered codemods* for that version (across all integrations).@@ -145,7 +145,13 @@ export async function discoverIntegrationCodemods(loadedIntegrations = []) {const seenInVersion = new Set();for (const {id, file} of files) {- const label = `Integration "${pkgLabel}" codemod ${version}/${id} (${file})`;+ const shown = integration.__packageDir+ ? path+ .relative(integration.__packageDir, file)+ .split(path.sep)+ .join('/')+ : file;+ const label = `Integration "${pkgLabel}" codemod ${version}/${id} (${shown})`;if (seenInVersion.has(id)) {throw new Error(diff --git a/packages/cli/assets/codemods/integration-discovery.test.mjs b/packages/cli/assets/codemods/integration-discovery.test.mjsindex 7c245bdec2..34f8db8a6f 100644--- a/packages/cli/assets/codemods/integration-discovery.test.mjs+++ b/packages/cli/assets/codemods/integration-discovery.test.mjs@@ -163,6 +163,21 @@ describe('integration codemod discovery', () => {).rejects.toThrow(/is invalid/i);});+ it('names a broken codemod by its path inside the package', async () => {+ scaffold({+ '1.1.0/no-default.mjs': `export const nope = 1;\n`,+ });+ const project = await Project.load(tmpDir);+ const failure = await discoverIntegrationCodemods(+ project.loadedIntegrations,+ ).then(+ () => null,+ error => error,+ );+ expect(failure?.message).toContain('(codemods/1.1.0/no-default.mjs)');+ expect(failure?.message).not.toContain(tmpDir);+ });+it('fails discovery when default export is not a codemod envelope', async () => {scaffold({'0.2.0/bad.mjs': `export default { title: 'x', transform: () => null };\n`,diff --git a/packages/cli/assets/codemods/runner.mjs b/packages/cli/assets/codemods/runner.mjsindex afdf58c026..0e27d78c20 100644--- a/packages/cli/assets/codemods/runner.mjs+++ b/packages/cli/assets/codemods/runner.mjs@@ -194,6 +194,89 @@ function toUnifiedEntry(transformEntry, version) {};}+/**+ * What a core PROJECT codemod plans: whole files to write and delete under the+ * project root, or the problems that stop it. Paths in `writes` and `deletes`+ * are absolute; `problems` name package-relative files.+ *+ * @typedef {object} ProjectCodemodPlan+ * @property {Array<{path: string, contents: string}>} writes+ * @property {string[]} deletes+ * @property {Array<{file: string, message: string}>} problems+ */++/**+ * Run one core PROJECT codemod (`meta.codemodType === 'project'`): instead of+ * rewriting the files it is handed, it reads the project and plans whole-file+ * writes and deletions, which this applies (or previews) as one unit. A plan+ * that names a problem changes nothing. Core-only: integration codemods keep+ * the file contract.+ *+ * @param {{name: string, transform: unknown}} transformEntry+ * @param {{apply: boolean, root: string, log: {success: (m: string) => void, warn: (m: string) => void, error: (m: string) => void}}} options+ * @returns {Promise<{filesChanged: number, writtenFiles: string[], errors: Array<{file: string, codemod: string, error: string}>}>}+ */+async function runProjectCodemod({name, transform}, {apply, root, log}) {+ /** @param {string} file */+ const rel = file => path.relative(root, file).split(path.sep).join('/');+ /** @type {ProjectCodemodPlan} */+ let plan;+ try {+ plan = await /** @type {(root: string) => Promise<ProjectCodemodPlan>} */ (+ transform+ )(root);+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ log.error(` ✗ ${message}`);+ return {+ filesChanged: 0,+ writtenFiles: [],+ errors: [{file: '.', codemod: name, error: message}],+ };+ }+ if (plan.problems.length > 0) {+ for (const {file, message} of plan.problems) {+ log.error(` ✗ ${file} — ${message}`);+ }+ return {+ filesChanged: 0,+ writtenFiles: [],+ errors: plan.problems.map(({file, message}) => ({+ file,+ codemod: name,+ error: message,+ })),+ };+ }+ /** @type {string[]} */+ const writtenFiles = [];+ for (const write of plan.writes) {+ if (apply) {+ fs.mkdirSync(path.dirname(write.path), {recursive: true});+ fs.writeFileSync(write.path, write.contents, 'utf-8');+ writtenFiles.push(write.path);+ log.success(` ✓ ${rel(write.path)}`);+ } else {+ log.warn(` ~ ${rel(write.path)} (would write)`);+ }+ }+ // Deletions go last, so a failed write leaves a state a rerun completes.+ for (const file of plan.deletes) {+ if (apply) {+ fs.rmSync(file);+ writtenFiles.push(file);+ log.success(` ✓ ${rel(file)} (removed)`);+ } else {+ log.warn(` ~ ${rel(file)} (would remove)`);+ }+ }+ return {+ filesChanged: plan.writes.length + plan.deletes.length,+ writtenFiles,+ errors: [],+ };+}+/*** Run codemods against source files.*@@ -204,11 +287,19 @@ function toUnifiedEntry(transformEntry, version) {* @param {string|undefined} options.codemod - Run only this specific transform* @param {Set<string>} [options.skipCodemods] - Transform names to exclude* @param {boolean} [options.silent] - Suppress all human-facing output (for --json)+ * @param {string} [options.root] - Project root a project codemod reads (default: the process cwd)* @returns {Promise<{totalFilesChanged: number, totalTransformsApplied: number, totalValidationBlocked: number, writtenFiles: string[], errors: Array<{file: string, codemod: string, error: string}>, skippedOptional: Array<{name: string, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, version: string}>} | {ok: false, reason: string, resolvedPath: string}>}*/export async function runCodemods(versionManifests,- {apply, path: srcPath, codemod, skipCodemods, silent = false},+ {+ apply,+ path: srcPath,+ codemod,+ skipCodemods,+ silent = false,+ root = process.cwd(),+ },) {// No-op stub object so silent mode skips log output entirely without// littering the body with `if (!silent)` guards.@@ -221,11 +312,14 @@ export async function runCodemods(const resolvedPath = path.resolve(srcPath);- // Config codemods target the consumer's astryx.config.* and never read- // source files, so a missing --path should not block them. Only hard-fail- // on a missing source path when there is at least one CODE codemod to run.+ // Config and project codemods never read the files under --path, so a+ // missing --path should not block them. Only hard-fail on a missing source+ // path when there is at least one CODE codemod to run.const hasCodeCodemod = versionManifests.some(({transforms}) =>- transforms.some(t => t.meta?.codemodType !== 'config'),+ transforms.some(+ t =>+ t.meta?.codemodType !== 'config' && t.meta?.codemodType !== 'project',+ ),);const sourcePathExists = fs.existsSync(resolvedPath);@@ -290,6 +384,22 @@ export async function runCodemods(// `(file, api)` contract and targets the consumer's astryx.config.*.// A core entry signals "config" via `meta.codemodType === 'config'`// (see toUnifiedEntry).+ if (meta?.codemodType === 'project') {+ const result = await runProjectCodemod(transformEntry, {+ apply,+ root,+ log,+ });+ if (result.errors.length > 0) {+ errors.push(...result.errors);+ } else if (result.filesChanged > 0) {+ totalFilesChanged += result.filesChanged;+ totalTransformsApplied += 1;+ writtenFiles.push(...result.writtenFiles);+ }+ continue;+ }+if (meta?.codemodType === 'config') {const result = runConfigCodemod(toUnifiedEntry(transformEntry, version), {apply,diff --git a/packages/cli/assets/codemods/transforms/next/__tests__/migrate-theme-catalog-to-descriptors.test.mjs b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-theme-catalog-to-descriptors.test.mjsnew file mode 100644index 0000000000..9efee8b0d6--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-theme-catalog-to-descriptors.test.mjs@@ -0,0 +1,216 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import manifest from '../index.mjs';+import migrate from '../migrate-theme-catalog-to-descriptors.mjs';+import {runCodemods} from '../../../runner.mjs';+import {discoverThemeDirectory} from '../../../../../foundation/discovery/theme-discovery.mjs';++let root;++beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-catalog-'));+});++afterEach(() => {+ fs.rmSync(root, {recursive: true, force: true});+});++/** A catalog entry exactly as `astryx integration add theme <slug>` wrote it in 0.6. */+function entry(slug, overrides = {}) {+ const identifier = slug.replace(/-([a-z0-9])/gu, (_, c) => c.toUpperCase());+ const displayName = slug+ .split('-')+ .map(part => part[0].toUpperCase() + part.slice(1))+ .join(' ');+ return {+ slug,+ displayName,+ description: `${displayName} theme.`,+ maintained: true,+ entry: `${identifier}Theme.ts`,+ exportName: `${identifier}Theme`,+ files: [`${identifier}Theme.ts`],+ ...overrides,+ };+}++/** @param {ReturnType<typeof entry>[]} themes */+function writeKit(themes, {sources = true} = {}) {+ fs.writeFileSync(+ path.join(root, 'package.json'),+ '{"name":"@acme/kit","version":"1.0.0"}\n',+ );+ fs.writeFileSync(+ path.join(root, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+ for (const theme of themes) {+ const source = path.join(root, 'themes', theme.slug, theme.entry);+ fs.mkdirSync(path.dirname(source), {recursive: true});+ if (sources) {+ fs.writeFileSync(+ source,+ `import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const ${theme.exportName} = defineTheme({\n name: '${theme.slug}',\n});\n`,+ );+ }+ }+ fs.mkdirSync(path.join(root, 'themes'), {recursive: true});+ fs.writeFileSync(+ path.join(root, 'themes', 'manifest.json'),+ `${JSON.stringify({version: 1, themes}, null, 2)}\n`,+ );+}++const catalog = () => path.join(root, 'themes', 'manifest.json');++/** @param {boolean} apply @param {string} [srcPath] */+const run = (apply, srcPath = root) =>+ runCodemods([{version: 'next', transforms: manifest}], {+ apply,+ path: srcPath,+ codemod: undefined,+ silent: true,+ root,+ });++describe('migrate-theme-catalog-to-descriptors', () => {+ it('is staged for the next release as a project codemod', () => {+ expect(manifest.map(t => [t.name, t.meta.codemodType])).toEqual([+ ['migrate-theme-catalog-to-descriptors', 'project'],+ ]);+ });++ it('writes one typed descriptor per catalog theme and removes the catalog', async () => {+ writeKit([+ entry('ocean'),+ entry('deep-sea', {+ displayName: "Deep 'Sea'",+ description: 'Line one\nline two \\ done.',+ maintained: false,+ }),+ ]);++ const result = await run(true);++ expect(result).toMatchObject({errors: [], totalFilesChanged: 3});+ expect(fs.existsSync(catalog())).toBe(false);+ expect(+ fs.readFileSync(+ path.join(root, 'themes/ocean/oceanTheme.doc.mjs'),+ 'utf-8',+ ),+ ).toBe(+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {\n type: 'theme',\n name: 'ocean',\n displayName: 'Ocean',\n description: 'Ocean theme.',\n maintained: true,\n};\n",+ );+ const themes = discoverThemeDirectory(+ path.join(root, 'themes'),+ '@acme/kit',+ );+ expect(+ themes.map(({slug, displayName, description, maintained}) => ({+ slug,+ displayName,+ description,+ maintained,+ })),+ ).toEqual([+ {+ slug: 'deep-sea',+ displayName: "Deep 'Sea'",+ description: 'Line one\nline two \\ done.',+ maintained: false,+ },+ {+ slug: 'ocean',+ displayName: 'Ocean',+ description: 'Ocean theme.',+ maintained: true,+ },+ ]);+ });++ it('previews without writing, even with no source folder', async () => {+ writeKit([entry('ocean')]);++ const result = await run(false, path.join(root, 'src'));++ expect(result).toMatchObject({+ errors: [],+ totalFilesChanged: 2,+ writtenFiles: [],+ });+ expect(fs.existsSync(catalog())).toBe(true);+ expect(+ fs.existsSync(path.join(root, 'themes/ocean/oceanTheme.doc.mjs')),+ ).toBe(false);+ });++ it('keeps a descriptor that already exists and still removes the catalog', async () => {+ writeKit([entry('ocean'), entry('reef')]);+ const kept = path.join(root, 'themes/ocean/oceanTheme.doc.mjs');+ fs.writeFileSync(+ kept,+ "export default {type: 'theme', name: 'ocean', displayName: 'Mine', description: '', maintained: true};\n",+ );++ const result = await run(true);++ expect(result.errors).toEqual([]);+ expect(fs.readFileSync(kept, 'utf-8')).toContain("displayName: 'Mine'");+ expect(+ fs.existsSync(path.join(root, 'themes/reef/reefTheme.doc.mjs')),+ ).toBe(true);+ expect(fs.existsSync(catalog())).toBe(false);+ });++ it('changes nothing and names each entry that cannot convert', async () => {+ writeKit([+ entry('ocean'),+ entry('sea', {exportName: 'oceanBlue'}),+ entry('nested', {+ entry: 'src/nestedTheme.ts',+ files: ['src/nestedTheme.ts'],+ }),+ ]);+ fs.rmSync(path.join(root, 'themes/ocean/oceanTheme.ts'));+ const before = fs.readFileSync(catalog(), 'utf-8');++ const result = await run(true);++ expect(result.errors.map(e => [e.file, e.error])).toEqual([+ ['themes/ocean', 'holds no oceanTheme.ts for theme "ocean".'],+ [+ 'themes/manifest.json',+ 'theme "sea" exports "oceanBlue" from seaTheme.ts; a descriptor takes the export name from the file name, so rename the export or the file to match.',+ ],+ [+ 'themes/manifest.json',+ 'theme "nested" has entry "src/nestedTheme.ts"; a descriptor sits beside a .ts, .tsx, .mjs, or .js source directly in themes/nested/.',+ ],+ ]);+ expect(fs.readFileSync(catalog(), 'utf-8')).toBe(before);+ expect(fs.existsSync(path.join(root, 'themes/sea/seaTheme.doc.mjs'))).toBe(+ false,+ );+ });++ it('leaves a package with no catalog to convert alone', async () => {+ const empty = {writes: [], deletes: [], problems: []};+ await expect(migrate(root)).resolves.toEqual(empty);+ fs.writeFileSync(+ path.join(root, 'astryx.integration.mjs'),+ 'export default {};\n',+ );+ await expect(migrate(root)).resolves.toEqual(empty);+ fs.writeFileSync(+ path.join(root, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+ fs.mkdirSync(path.join(root, 'themes'));+ await expect(migrate(root)).resolves.toEqual(empty);+ });+});diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjsindex 2af3bdfcf0..66ba03012e 100644--- a/packages/cli/assets/codemods/transforms/next/index.mjs+++ b/packages/cli/assets/codemods/transforms/next/index.mjs@@ -7,4 +7,14 @@* this file into the resolved version folder.*/-export default [];+import migrateThemeCatalogToDescriptors, {+ meta as migrateThemeCatalogToDescriptorsMeta,+} from './migrate-theme-catalog-to-descriptors.mjs';++export default [+ {+ name: 'migrate-theme-catalog-to-descriptors',+ transform: migrateThemeCatalogToDescriptors,+ meta: migrateThemeCatalogToDescriptorsMeta,+ },+];diff --git a/packages/cli/assets/codemods/transforms/next/migrate-theme-catalog-to-descriptors.mjs b/packages/cli/assets/codemods/transforms/next/migrate-theme-catalog-to-descriptors.mjsnew file mode 100644index 0000000000..8ed43263ae--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/migrate-theme-catalog-to-descriptors.mjs@@ -0,0 +1,141 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Give each integration theme a typed descriptor instead of the+ * `manifest.json` theme catalog.+ *+ * Astryx 0.6 scaffolded integration themes into one catalog,+ * `<themes root>/manifest.json`. Each theme now carries a strongly typed+ * same-stem `.doc.mjs` descriptor, and a themes root that still holds the+ * catalog is refused. This project codemod reads the package's integration+ * manifest, plans one descriptor per catalog entry beside that theme's source,+ * and removes the catalog. When any entry cannot convert, it plans nothing and+ * names the entry, so the package is never left half converted.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {loadManifestObject} from '../../../../foundation/integrations/integrations.mjs';+import {findLocalIntegrationManifestOrNull} from '../../../../foundation/integrations/manifest-writer.mjs';+import {themeDescriptorSource} from '../../../../foundation/integrations/theme-descriptor.mjs';++export const meta = {+ title:+ 'Give each integration theme a typed descriptor instead of the manifest.json catalog',+ description:+ 'Writes <name>Theme.doc.mjs beside each theme the catalog lists, then removes the catalog.',+ codemodType: 'project',+};++const SLUG = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;+const SOURCE = /\.(?:ts|tsx|mjs|js)$/u;++/**+ * @param {string} root the package directory+ * @returns {Promise<import('../../runner.mjs').ProjectCodemodPlan>}+ */+export default async function migrateThemeCatalogToDescriptors(root) {+ /** @type {import('../../runner.mjs').ProjectCodemodPlan} */+ const plan = {writes: [], deletes: [], problems: []};+ /** @param {string} file @returns {string} */+ const rel = file => path.relative(root, file).split(path.sep).join('/');+ /** @param {string} file @param {string} message */+ const problem = (file, message) => plan.problems.push({file, message});++ const manifestFile = findLocalIntegrationManifestOrNull(root);+ if (!manifestFile) return plan;+ const manifest = await loadManifestObject(+ manifestFile,+ `Integration manifest ${path.basename(manifestFile)}`,+ {fresh: true},+ );+ if (typeof manifest.themes !== 'string') return plan;+ const themesRoot = path.resolve(root, manifest.themes);+ const fromRoot = path.relative(root, themesRoot);+ if (fromRoot.startsWith('..') || path.isAbsolute(fromRoot)) return plan;+ const catalogFile = path.join(themesRoot, 'manifest.json');+ if (!fs.existsSync(catalogFile)) return plan;+ const catalogPath = rel(catalogFile);++ let catalog;+ try {+ catalog = JSON.parse(fs.readFileSync(catalogFile, 'utf-8'));+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ problem(catalogPath, `is not valid JSON (${reason}).`);+ return plan;+ }+ if (+ !catalog ||+ typeof catalog !== 'object' ||+ catalog.version !== 1 ||+ !Array.isArray(catalog.themes)+ ) {+ problem(catalogPath, 'is not a version 1 theme catalog.');+ return plan;+ }++ for (const [index, entry] of catalog.themes.entries()) {+ const slug = entry?.slug;+ if (typeof slug !== 'string' || !SLUG.test(slug)) {+ problem(+ catalogPath,+ `themes[${index}] has no lowercase kebab-case slug; fix the entry or add that theme's descriptor by hand.`,+ );+ continue;+ }+ const themeDir = path.join(themesRoot, slug);+ const source = entry.entry;+ if (+ typeof source !== 'string' ||+ !SOURCE.test(source) ||+ source !== path.basename(source)+ ) {+ problem(+ catalogPath,+ `theme "${slug}" has entry ${JSON.stringify(source)}; a descriptor sits beside a .ts, .tsx, .mjs, or .js source directly in ${rel(themeDir)}/.`,+ );+ continue;+ }+ const stem = source.replace(SOURCE, '');+ if (entry.exportName !== stem) {+ problem(+ catalogPath,+ `theme "${slug}" exports ${JSON.stringify(entry.exportName)} from ${source}; a descriptor takes the export name from the file name, so rename the export or the file to match.`,+ );+ continue;+ }+ if (typeof entry.displayName !== 'string' || !entry.displayName.trim()) {+ problem(catalogPath, `theme "${slug}" has no displayName.`);+ continue;+ }+ if (typeof entry.description !== 'string') {+ problem(catalogPath, `theme "${slug}" has no description string.`);+ continue;+ }+ if (typeof entry.maintained !== 'boolean') {+ problem(catalogPath, `theme "${slug}" has no maintained flag.`);+ continue;+ }+ if (!fs.existsSync(path.join(themeDir, source))) {+ problem(rel(themeDir), `holds no ${source} for theme "${slug}".`);+ continue;+ }+ const descriptor = path.join(themeDir, `${stem}.doc.mjs`);+ if (fs.existsSync(descriptor)) continue;+ plan.writes.push({+ path: descriptor,+ contents: themeDescriptorSource({+ type: 'theme',+ name: slug,+ displayName: entry.displayName,+ description: entry.description,+ maintained: entry.maintained,+ }),+ });+ }+ if (plan.problems.length > 0)+ return {writes: [], deletes: [], problems: plan.problems};+ plan.deletes.push(catalogFile);+ return plan;+}diff --git a/packages/cli/assets/docs/cli-integrations.doc.mjs b/packages/cli/assets/docs/cli-integrations.doc.mjsindex 7f82d81771..6d319489b1 100644--- a/packages/cli/assets/docs/cli-integrations.doc.mjs+++ b/packages/cli/assets/docs/cli-integrations.doc.mjs@@ -84,7 +84,7 @@ export const docs = {content: [{type: 'prose',- text: 'A useful theme package usually ships more than colors. Start with the source theme, author the palette request at `themes/ocean/palette.config.json`, then add the guides its consumers need. The `integration add` commands keep the package manifest in sync; add palette outputs to the theme catalog after generation.',+ text: 'A useful theme package usually ships more than colors. Start with the source theme, author the palette request at `themes/ocean/palette.config.json`, then add the guides its consumers need. The `integration add` commands keep the package manifest in sync. Palette outputs live inside the theme directory, which ships as one unit, so there is nothing to register after generation.',},{type: 'code',@@ -94,7 +94,7 @@ export const docs = {},{type: 'prose',- text: "Edit the generated theme and guide files before publishing. The shown palette command writes `themes/ocean/tokens/ocean.palette.ts` and its sibling `themes/ocean/tokens/ocean.palette.receipt.json`. The TypeScript candidate directly exports `black`, `white`, and `palette`; import what the theme uses from `./tokens/ocean.palette`. Keep the request at `themes/ocean/palette.config.json`, and list the theme source, request, candidate, and receipt in the catalog entry's `files` array. Add any optional wrapper, refs, icon, or preview modules only when you author them, and list each one too. `integration pack --check` runs the real package lifecycle and compares local discovery with the npm tarball, so a missing source file or files allowlist entry fails before a consumer sees it.",+ text: 'Edit the generated theme descriptor, source, and guide files before publishing. The shown palette command writes `themes/ocean/tokens/ocean.palette.ts` and its sibling `themes/ocean/tokens/ocean.palette.receipt.json`, a reproducibility receipt. The TypeScript candidate directly exports `black`, `white`, and `palette`; import what the theme uses from `./tokens/ocean.palette`. Keep the request at `themes/ocean/palette.config.json`. The whole theme directory is copied and packed as one unit, so an optional wrapper, refs, icon, or preview module you add inside it ships with the theme. `integration pack --check` runs the real package lifecycle and compares local discovery with the npm tarball, so a missing source or descriptor fails before a consumer sees it.',},{type: 'code',@@ -104,7 +104,7 @@ export const docs = {},{type: 'prose',- text: 'The package must be a direct dependency for automatic discovery. No `astryx.config` entry is needed unless the app must control integration order. `theme add` copies every file listed by the selected catalog entry, including nested token modules, and refuses to overwrite existing project files.',+ text: "The package must be a direct dependency for automatic discovery. No `astryx.config` entry is needed unless the app must control integration order. `theme add` copies the selected theme's complete directory, including its typed `.doc.mjs`, nested token modules, and receipts, and refuses to overwrite existing project files.",},],},@@ -119,7 +119,7 @@ export const docs = {{type: 'code',lang: 'text',- code: "Kind Metadata suffix type stamp Source file\n──────── ───────────────────────── ───────────── ──────────────────────\nComponent Name.doc.{ts,mjs,js} 'component' Name.tsx (same stem)\nTemplate Name.template.{ts,mjs,js} 'page'/'block' Name.tsx (same stem)\nDoc topic topic.doc.{ts,mjs,js} 'generic' (none — docs are prose)\nCodemod <version>/<id>.{ts,mjs,js} 'code'/'config' (the codemod IS the source)\nTheme manifest.json entry — <slug>/<entry>.ts",+ code: "Kind Metadata file type stamp Source file\n──────── ───────────────────────── ───────────── ──────────────────────\nComponent Name.doc.mjs 'component' Name.tsx (same stem)\nTemplate Name.doc.mjs 'page'/'block' Name.tsx (same stem)\nDoc topic topic.doc.mjs 'generic' (none — docs are prose)\nCodemod <version>/<id>.{ts,mjs,js} 'code'/'config' (the codemod IS the source)\nTheme <slug>/nameTheme.doc.mjs 'theme' <slug>/nameTheme.ts (same stem)\n\nReleased .doc.js files, template .doc.ts files, and .template.{ts,mjs,js}\ntemplates still load. A component or topic .doc.ts loads only from a package\nlinked from outside node_modules; installed, it is listed but cannot be read.",},{type: 'prose',@@ -152,7 +152,7 @@ export const docs = {content: [{type: 'prose',- text: "Export your components from your library however you like, and consumers still import them from your package. For each component the CLI should document, ship a `.doc.{ts,mjs,js}` file with the same stem, for example `AcmeCarousel.tsx` alongside `AcmeCarousel.doc.ts`. The doc file must default-export an object with `type: 'component'` — not `'generic'` (that is for reference docs) and not `'page'`/`'block'` (those are for templates).",+ text: "Export your components from your library however you like, and consumers still import them from your package. For each component the CLI should document, ship a strongly typed `.doc.mjs` file with the same stem, for example `AcmeCarousel.tsx` alongside `AcmeCarousel.doc.mjs`. The doc file must default-export an object with `type: 'component'` — not `'generic'` (that is for reference docs) and not `'page'`/`'block'` (those are for templates). Released `.doc.js` docs remain readable for compatibility. A `.doc.ts` component doc reads only when the package is linked from outside node_modules, not once it is installed. New authoring uses `.doc.mjs`.",},{type: 'prose',@@ -161,7 +161,7 @@ export const docs = {{type: 'code',lang: 'typescript',- code: "// AcmeCarousel.doc.ts\nexport default {\n type: 'component',\n name: 'AcmeCarousel',\n description: 'A carousel that cycles through slides.',\n // props, usage, examples, ...\n} satisfies import('@astryxdesign/cli/authoring').ComponentDoc;",+ code: "// AcmeCarousel.doc.mjs\n/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */\nexport default {\n type: 'component',\n name: 'AcmeCarousel',\n displayName: 'Acme Carousel',\n usage: {description: 'A carousel that cycles through slides.'},\n props: [],\n};",},],},@@ -171,7 +171,7 @@ export const docs = {content: [{type: 'prose',- text: "Templates are usually not exported from the package directly. Instead, consumers browse them through the CLI and materialize them into their app. Define a template as a plain object with `type: 'page'` (full pages) or `type: 'block'` (smaller chunks) as its default export in a `.template.{ts,mjs,js}` file next to the source, for example `AcmeLandingPage.tsx` and `AcmeLandingPage.template.ts`. Do not use the `.doc.{ts,mjs,js}` suffix — that is for component docs and reference docs.",+ text: "Templates are usually not exported from the package directly. Instead, consumers browse them through the CLI and materialize them into their app. Define a template as a strongly typed plain object stamped with `type: 'page'` (full pages) or `type: 'block'` (smaller chunks) in a same-stem `.doc.mjs`, for example `AcmeLandingPage.tsx` and `AcmeLandingPage.doc.mjs`. Released `.template.*` files remain readable for compatibility.",},{type: 'prose',@@ -180,7 +180,7 @@ export const docs = {{type: 'code',lang: 'typescript',- code: "// AcmeLandingPage.template.ts\nexport default {\n type: 'page',\n // name, description, preview, ...\n};",+ code: "// AcmeLandingPage.doc.mjs\n/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */\nexport default {\n type: 'page',\n name: 'acme-landing-page',\n displayName: 'Acme Landing Page',\n description: 'A complete product landing page.',\n};",},{type: 'prose',@@ -194,12 +194,12 @@ export const docs = {content: [{type: 'prose',- text: "Point the integration file's `docs` field at a directory of reference docs and every `{topic}.doc.{ts,mjs,js}` under it becomes a topic the CLI serves: `astryx docs` lists it, `astryx docs <topic>` prints it, `astryx search` indexes it, and `astryx init` names it in the agent block. A topic is a plain object with `type: 'generic'` as its default export — not `'component'` (that is for component docs with a same-stem source file). This is the same shape core's own topics use.",+ text: "Point the integration file's `docs` field at a directory of reference docs and every strongly typed `{topic}.doc.mjs` under it becomes a topic the CLI serves: `astryx docs` lists it, `astryx docs <topic>` prints it, `astryx search` indexes it, and `astryx init` names it in the agent block. A topic is a plain object stamped `type: 'generic'` — not `'component'` (that is for component docs with a same-stem source file) — the same shape core's own topics use.",},{type: 'code',lang: 'typescript',- code: "// docs/deploying.doc.ts\nexport default {\n type: 'generic',\n name: 'deploying',\n title: 'Deploying',\n description: 'Ship an app built with Acme widgets.',\n category: 'guide',\n sections: [\n {title: 'Overview', content: [{type: 'prose', text: '...'}]},\n ],\n};",+ code: "// docs/deploying.doc.mjs\n/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */\nexport default {\n type: 'generic',\n name: 'deploying',\n title: 'Deploying',\n description: 'Ship an app built with Acme widgets.',\n category: 'guide',\n sections: [\n {title: 'Overview', content: [{type: 'prose', text: '...'}]},\n ],\n};",},{type: 'prose',@@ -212,7 +212,7 @@ export const docs = {},{type: 'prose',- text: "`extends: 'x'` merges onto a topic instead of owning it: a section with the same key as one in the base (its `id`, or the key its title derives) or the same title replaces that section, and a section the base does not have is appended. Reach for it to correct or add to a topic you do not want to fork: a fork of someone else's guide stops receiving their fixes the day you write it.",+ text: "`extends: 'x'` merges onto a topic instead of owning it: a section with the same key as one in the base (its `id`, or the key its title derives) or the same title replaces that section, and a section the base does not have is appended. The topic keeps its own title and description; only `replaces` renames it. Reach for it to correct or add to a topic you do not want to fork: a fork of someone else's guide stops receiving their fixes the day you write it.",},{type: 'list',@@ -233,38 +233,25 @@ export const docs = {content: [{type: 'prose',- text: "A theme contribution is editable `defineTheme` source, not compiled CSS. Add `themes: './themes'` to `astryx.integration.*`, place the source under one directory per slug, and list it in `themes/manifest.json`. If package.json has a `files` allowlist, include both the integration manifest and the themes root; packages with no allowlist already publish both. Do not add an `exports` map only for theme discovery.",+ text: "A theme contribution is editable `defineTheme` source, not compiled CSS. Add `themes: './themes'` to `astryx.integration.*`. Give each lower-kebab slug its own directory containing a theme source and mandatory same-stem, strongly typed `.doc.mjs`. If package.json has a `files` allowlist, include both the integration manifest and the themes root; packages with no allowlist already publish both. Do not add an `exports` map only for theme discovery.",},{type: 'code',lang: 'text',- code: 'themes/\n manifest.json\n ocean/\n oceanTheme.ts\n palette.config.json\n tokens/\n ocean.palette.ts\n ocean.palette.receipt.json',+ code: 'themes/\n ocean/\n oceanTheme.ts\n oceanTheme.doc.mjs\n palette.config.json\n tokens/\n ocean.palette.ts\n ocean.palette.receipt.json',},{type: 'prose',- text: 'The root catalog `manifest.json` must be `{ "version": 1, "themes": [...] }`. Each entry in the `themes` array requires every field shown below — omitting any one is a hard validation error:',- },- {- type: 'list',- style: 'unordered',- items: [- '`slug` — lowercase kebab-case starting with a letter (e.g. `"ocean"`). Must be unique within the catalog.',- '`displayName` — human-readable label (e.g. `"Ocean"`).',- '`description` — string description of the theme.',- '`maintained` — boolean indicating active maintenance.',- '`entry` — source file relative to `themes/<slug>/` (e.g. `"oceanTheme.ts"`).',- '`exportName` — a valid JS identifier naming the runtime export in the entry file (e.g. `"oceanTheme"`). Astryx parses the source without executing it and rejects missing or type-only exports.',- '`files` — non-empty array of filenames relative to `themes/<slug>/`. Must include the entry file and every local static import the entry source uses. Astryx validates that every listed file exists on disk and that every local import in the entry names a file in this list.',- ],+ text: '`ThemeDoc` owns `name` (the slug), `displayName`, `description`, and `maintained`. The descriptor/source stem supplies the source entry and required named runtime export. Astryx parses the source without executing it, confines every local static import and re-export to the theme directory, copies that complete directory, and rejects missing or type-only exports.',},{type: 'code',- lang: 'json',- code: '{\n "version": 1,\n "themes": [{\n "slug": "ocean",\n "displayName": "Ocean",\n "description": "Ocean theme with OKLCH palettes.",\n "maintained": true,\n "entry": "oceanTheme.ts",\n "exportName": "oceanTheme",\n "files": [\n "oceanTheme.ts",\n "palette.config.json",\n "tokens/ocean.palette.ts",\n "tokens/ocean.palette.receipt.json"\n ]\n }]\n}',+ lang: 'javascript',+ code: "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {\n type: 'theme',\n name: 'ocean',\n displayName: 'Ocean',\n description: 'Ocean theme.',\n maintained: true,\n};",},{type: 'prose',- text: 'The generated candidate is already importable: it exports `black`, `white`, `palette`, and a default palette value. Import it directly from `./tokens/ocean.palette`. A wrapper or palette-refs module is optional application code, not generator output; list it only if you create it.',+ text: 'The generated palette candidate is already importable: it exports `black`, `white`, `palette`, and a default palette value. Import it directly from `./tokens/ocean.palette`. A wrapper or palette-refs module is optional application code, not generator output.',},{type: 'prose',diff --git a/packages/cli/assets/docs/cli.doc.mjs b/packages/cli/assets/docs/cli.doc.mjsnew file mode 100644index 0000000000..afa9ec2b40--- /dev/null+++ b/packages/cli/assets/docs/cli.doc.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs cli`: every command, API function, output schema, and+ * enum the CLI documents, one section each.+ *+ * Built from the docs whose `namespace` is `cli/commands` or `cli/api`, so it+ * cannot drift from the commands and functions it describes. `astryx doctor`+ * names a CLI doc with no namespace, or one no topic reads.+ */++import {buildCliTopic} from '../../foundation/discovery/cli-self-docs.mjs';++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = await buildCliTopic();diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjsindex c6bc8fc403..553a907e4d 100644--- a/packages/cli/assets/docs/theme.doc.mjs+++ b/packages/cli/assets/docs/theme.doc.mjs@@ -152,7 +152,7 @@ function App() {},{type: 'prose',- text: 'The copy is editable project source, not a reference back into node_modules. Every file named by the theme catalog comes with it, including nested token or palette modules. A second add refuses to overwrite those files unless you pass `--overwrite`.',+ text: 'The copy is editable project source, not a reference back into node_modules. The complete theme directory comes with it, including its typed `.doc.mjs`, nested token and palette modules, and receipts. A second add refuses to overwrite those files unless you pass `--overwrite`.',},],},diff --git a/packages/cli/assets/templates/themes/butter/butterTheme.doc.mjs b/packages/cli/assets/templates/themes/butter/butterTheme.doc.mjsnew file mode 100644index 0000000000..2c667adbd1--- /dev/null+++ b/packages/cli/assets/templates/themes/butter/butterTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'butter',+ displayName: 'Butter',+ description:+ 'Warm, creamy yellows with a friendly blue accent. Playful enough for consumer surfaces, soft enough to stay readable.',+ maintained: false,+};diff --git a/packages/cli/assets/templates/themes/chocolate/chocolateTheme.doc.mjs b/packages/cli/assets/templates/themes/chocolate/chocolateTheme.doc.mjsnew file mode 100644index 0000000000..ca24f2aa7d--- /dev/null+++ b/packages/cli/assets/templates/themes/chocolate/chocolateTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'chocolate',+ displayName: 'Chocolate',+ description:+ 'Warm chocolate theme for Astryx — rich brown palette with Fraunces headings, Albert Sans body, and Lucide icons',+ maintained: false,+};diff --git a/packages/cli/assets/templates/themes/gothic/gothicTheme.doc.mjs b/packages/cli/assets/templates/themes/gothic/gothicTheme.doc.mjsnew file mode 100644index 0000000000..ce4e9161e0--- /dev/null+++ b/packages/cli/assets/templates/themes/gothic/gothicTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'gothic',+ displayName: 'Gothic',+ description:+ 'Deep blue-grays and a signature display serif. Dramatic and editorial, for surfaces that want to be remembered.',+ maintained: false,+};diff --git a/packages/cli/assets/templates/themes/manifest.json b/packages/cli/assets/templates/themes/manifest.jsondeleted file mode 100644index 282e69a975..0000000000--- a/packages/cli/assets/templates/themes/manifest.json+++ /dev/null@@ -1,77 +0,0 @@-{- "version": 1,- "generatedBy": "scripts/generate-cli-themes.mjs",- "themes": [- {- "slug": "butter",- "displayName": "Butter",- "description": "Warm, creamy yellows with a friendly blue accent. Playful enough for consumer surfaces, soft enough to stay readable.",- "maintained": false,- "entry": "butterTheme.ts",- "exportName": "butterTheme",- "files": ["butterTheme.ts", "icons.tsx"]- },- {- "slug": "chocolate",- "displayName": "Chocolate",- "description": "Warm chocolate theme for Astryx — rich brown palette with Fraunces headings, Albert Sans body, and Lucide icons",- "maintained": false,- "entry": "chocolateTheme.ts",- "exportName": "chocolateTheme",- "files": ["chocolateTheme.ts", "icons.tsx"]- },- {- "slug": "gothic",- "displayName": "Gothic",- "description": "Deep blue-grays and a signature display serif. Dramatic and editorial, for surfaces that want to be remembered.",- "maintained": false,- "entry": "gothicTheme.ts",- "exportName": "gothicTheme",- "files": ["gothicTheme.ts", "icons.tsx"]- },- {- "slug": "matcha",- "displayName": "Matcha",- "description": "Earthy greens with a calm, organic feel. Naturalistic and grounded, great for wellness or content-first apps.",- "maintained": false,- "entry": "matchaTheme.ts",- "exportName": "matchaTheme",- "files": ["matchaTheme.ts", "icons.tsx"]- },- {- "slug": "neutral",- "displayName": "Neutral",- "description": "Restrained warm grays. Minimal and quiet, so the content stays the focus.",- "maintained": true,- "entry": "neutralTheme.ts",- "exportName": "neutralTheme",- "files": [- "neutralTheme.ts",- "icons.tsx",- "neutralPalettes.ts",- "neutralPalettes.generated.ts",- "neutralPaletteRefs.generated.ts",- "neutralPalettes.generated.receipt.json",- "palette.config.json"- ]- },- {- "slug": "stone",- "displayName": "Stone",- "description": "Warm stone and slate, earthy and understated, with just enough character to feel handcrafted.",- "maintained": false,- "entry": "stoneTheme.ts",- "exportName": "stoneTheme",- "files": ["stoneTheme.ts", "icons.tsx"]- },- {- "slug": "y2k",- "displayName": "Y2K",- "description": "Hot pinks, lime greens, and Poppins. Bubbly, playful, and unmistakably retro.",- "maintained": false,- "entry": "y2kTheme.ts",- "exportName": "y2kTheme",- "files": ["y2kTheme.ts", "icons.tsx"]- }- ]-}diff --git a/packages/cli/assets/templates/themes/matcha/matchaTheme.doc.mjs b/packages/cli/assets/templates/themes/matcha/matchaTheme.doc.mjsnew file mode 100644index 0000000000..0944d4161a--- /dev/null+++ b/packages/cli/assets/templates/themes/matcha/matchaTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'matcha',+ displayName: 'Matcha',+ description:+ 'Earthy greens with a calm, organic feel. Naturalistic and grounded, great for wellness or content-first apps.',+ maintained: false,+};diff --git a/packages/cli/assets/templates/themes/neutral/neutralTheme.doc.mjs b/packages/cli/assets/templates/themes/neutral/neutralTheme.doc.mjsnew file mode 100644index 0000000000..0d0a291685--- /dev/null+++ b/packages/cli/assets/templates/themes/neutral/neutralTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'neutral',+ displayName: 'Neutral',+ description:+ 'Restrained warm grays. Minimal and quiet, so the content stays the focus.',+ maintained: true,+};diff --git a/packages/cli/assets/templates/themes/stone/stoneTheme.doc.mjs b/packages/cli/assets/templates/themes/stone/stoneTheme.doc.mjsnew file mode 100644index 0000000000..1969201e57--- /dev/null+++ b/packages/cli/assets/templates/themes/stone/stoneTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'stone',+ displayName: 'Stone',+ description:+ 'Warm stone and slate, earthy and understated, with just enough character to feel handcrafted.',+ maintained: false,+};diff --git a/packages/cli/assets/templates/themes/y2k/y2kTheme.doc.mjs b/packages/cli/assets/templates/themes/y2k/y2kTheme.doc.mjsnew file mode 100644index 0000000000..f4cecf6a99--- /dev/null+++ b/packages/cli/assets/templates/themes/y2k/y2kTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'y2k',+ displayName: 'Y2K',+ description:+ 'Hot pinks, lime greens, and Poppins. Bubbly, playful, and unmistakably retro.',+ maintained: false,+};diff --git a/packages/cli/authoring/codemod/codemod.doc.mjs b/packages/cli/authoring/codemod/codemod.doc.mjsindex 2cdc8cbe9e..195c210de2 100644--- a/packages/cli/authoring/codemod/codemod.doc.mjs+++ b/packages/cli/authoring/codemod/codemod.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'schema',name: 'codemod',displayName: 'Astryx Codemod',- namespace: 'cli',+ namespace: 'authoring',description:'A codemod module the CLI runs during `astryx upgrade`. Default-export a ' +"plain object with a `type` discriminant: 'code' rewrites source files, " +diff --git a/packages/cli/authoring/config/config.doc.mjs b/packages/cli/authoring/config/config.doc.mjsindex 00080c9389..5cca18c4e0 100644--- a/packages/cli/authoring/config/config.doc.mjs+++ b/packages/cli/authoring/config/config.doc.mjs@@ -11,7 +11,7 @@ export const doc = {type: 'schema',name: 'config',displayName: 'Astryx Config',- namespace: 'cli',+ namespace: 'authoring',description:'The optional astryx.config.* file at your project root. Declares which ' +'integrations to load, where to route issue links, post-codemod hooks, local ' +diff --git a/packages/cli/authoring/debug/debug.doc.mjs b/packages/cli/authoring/debug/debug.doc.mjsnew file mode 100644index 0000000000..fe993d601f--- /dev/null+++ b/packages/cli/authoring/debug/debug.doc.mjs@@ -0,0 +1,182 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SchemaDoc for DebugEvent, the record of one CLI run.+ * @input The DebugEvent type beside it (`type.ts`), which `parse.mjs` reads.+ * @output The `debug-event` section of `astryx docs authoring`.+ * @position packages/cli/authoring/debug — schema documentation+ */++/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */+export const doc = {+ type: 'schema',+ name: 'debug-event',+ displayName: 'DebugEvent',+ namespace: 'authoring',+ description:+ 'One recorded CLI run: what a `debug` handler receives, whether it is set in astryx.config or exported by an integration manifest. There is exactly one event per run, and every field is present by the time a handler sees it.',+ appliesTo: 'The argument of a `debug` handler',+ fields: [+ {+ name: 'schemaVersion',+ type: 'DebugSchemaVersion',+ description:+ 'Version of the recorded shape: 1, 2, or 3. A field that changes meaning gets a new version, so switch on this.',+ required: true,+ },+ {+ name: 'id',+ type: 'string',+ description: 'Unique per run. Deduplicate on it.',+ required: true,+ },+ {+ name: 'startedAt',+ type: 'string',+ description: 'When the run started, as ISO 8601.',+ required: true,+ },+ {+ name: 'endedAt',+ type: 'string',+ description: 'When the run ended, as ISO 8601.',+ required: true,+ },+ {+ name: 'durationMs',+ type: 'number',+ description: 'How long the run took, in milliseconds.',+ required: true,+ },+ {+ name: 'command',+ type: 'string',+ description:+ 'The full command name. Empty when astryx ran without a command.',+ required: true,+ example: "'theme build'",+ },+ {+ name: 'commandPath',+ type: 'string[]',+ description: 'The command name split into segments.',+ required: true,+ example: "['theme', 'build']",+ },+ {+ name: 'argv',+ type: 'string[]',+ description: 'The arguments after the binary, scrubbed.',+ required: true,+ },+ {+ name: 'args',+ type: 'Record<string, unknown>',+ description: 'Positional arguments, keyed by their declared names.',+ required: true,+ },+ {+ name: 'options',+ type: 'Record<string, unknown>',+ description: 'The command options, as the CLI resolved them.',+ required: true,+ },+ {+ name: 'optionSources',+ type: 'Record<string, DebugOptionSource>',+ description:+ "Where each option value came from: 'cli', 'default', 'env', 'config', or 'implied'. The keys match `options`.",+ required: true,+ },+ {+ name: 'globalOptions',+ type: 'Record<string, unknown>',+ description: 'The root flags, such as --json, --detail, and --lang.',+ required: true,+ },+ {+ name: 'outcome',+ type: 'DebugOutcome',+ description:+ "How the run ended: 'ok', 'error', 'parse-error', 'fatal', 'rejected', or 'incomplete'.",+ required: true,+ },+ {+ name: 'exitCode',+ type: 'number',+ description:+ 'The process exit code. When a signal ended the run, 128 plus the signal number.',+ required: true,+ },+ {+ name: 'signal',+ type: 'string',+ description:+ "The signal that ended the run, such as 'SIGINT'. Null otherwise.",+ required: true,+ },+ {+ name: 'error',+ type: 'DebugEventError',+ description:+ 'The failure: `name`, `message`, `code`, and `stack`. Branch on `code`, never on `message`. Null when nothing failed.',+ required: true,+ },+ {+ name: 'output',+ type: 'DebugEventOutput',+ description:+ 'What the run answered with: JSON mode, the envelope types, the result count and kind, and the stdout and stderr it printed, scrubbed and cut at the capture limit.',+ required: true,+ },+ {+ name: 'env',+ type: 'DebugEventEnv',+ description:+ 'Runtime facts: the CLI and Node versions, platform, CI, package manager, and whether a person, an AI agent, or automation ran the command. It never holds a hostname, a user name, or a raw session ID.',+ required: true,+ },+ {+ name: 'project',+ type: 'DebugEventProject',+ description:+ 'The project the command ran in, as flags and counts. It never holds package names.',+ required: true,+ },+ {+ name: 'redacted',+ type: 'boolean',+ description:+ 'Whether the values in the record were scrubbed. It is true on every event a handler receives. When it is false, treat the log as sensitive.',+ required: true,+ },+ ],+ examples: [+ {+ label: 'Keep a local log of the runs that failed',+ code:+ "import {appendFileSync} from 'node:fs';\n\n" ++ 'export default {\n' ++ ' debug: event => {\n' ++ " if (event.outcome !== 'ok') {\n" ++ " appendFileSync('failed-runs.ndjson', JSON.stringify(event) + '\\n');\n" ++ ' }\n' ++ ' },\n' ++ '};',+ },+ ],+ notes: [+ {+ type: 'prose',+ text: 'The shape only grows: fields are added, never removed or given a new meaning. When a meaning must change, `schemaVersion` gets a new value. In version 3, a null `output.resultKind` means the run never reached an answer, so do not count it together with a version 1 or 2 null.',+ },+ {+ type: 'prose',+ text: 'The handler runs synchronously as the process exits, so a promise it returns is never awaited. It gets a copy of the event, and anything it throws is ignored.',+ },+ {+ type: 'prose',+ text: 'Import DebugEventOutput, DebugEventEnv, DebugEventProject, and DebugEventError from @astryxdesign/cli/authoring for the fields of `output`, `env`, `project`, and `error`.',+ },+ ],+};diff --git a/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs b/packages/cli/authoring/doctypes/base/graph-fields.doc.mjsindex 3cdb701199..f6b7b1dbce 100644--- a/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs+++ b/packages/cli/authoring/doctypes/base/graph-fields.doc.mjs@@ -56,7 +56,7 @@ export const doc = {notes: [{type: 'prose',- text: 'Unknown fields: `component`, `function`, `generic`, `schema`, `command` and `enum` docs accept a field they do not know, and nothing reads it, so a doc written for a newer CLI still loads here. `page`, `block` and `namespace` docs refuse one. Sections and content blocks refuse one in every doc.',+ text: 'Unknown fields: `component`, `function`, `generic`, `schema`, `command` and `enum` docs accept a field they do not know, and nothing reads it, so a doc written for a newer CLI still loads here. `page`, `block` and `namespace` docs refuse one, as do `theme` descriptors. Sections and content blocks refuse one in every doc.',},],};diff --git a/packages/cli/authoring/doctypes/command/command.doc.mjs b/packages/cli/authoring/doctypes/command/command.doc.mjsindex 247a5982a6..79f6b78006 100644--- a/packages/cli/authoring/doctypes/command/command.doc.mjs+++ b/packages/cli/authoring/doctypes/command/command.doc.mjs@@ -54,7 +54,7 @@ export const doc = {name: 'namespace',type: 'string',description:- "Docs namespace path. Defaults to 'cli' when applied by the docs index.",+ "The `astryx docs` topic that reads this doc. The CLI's commands use 'cli/commands' (the section `commands-<name>` of the `cli` topic). Every command doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads.",},{name: 'aliases',diff --git a/packages/cli/authoring/doctypes/command/type.ts b/packages/cli/authoring/doctypes/command/type.tsindex 507dd625b3..738e2f758e 100644--- a/packages/cli/authoring/doctypes/command/type.ts+++ b/packages/cli/authoring/doctypes/command/type.ts@@ -65,7 +65,7 @@ export interface CommandDoc extends AuthoredDocGraphFields {summary: string;/** Longer help body / when-to-use. */description?: string;- /** Docs namespace path. Defaults to 'cli' when applied by the docs index. */+ /** The `astryx docs` topic that reads this doc. The CLI's commands use 'cli/commands' (the section `commands-<name>` of the `cli` topic). Every command doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads. */namespace?: string;/** Alternate slugs that also resolve to this doc. */aliases?: string[];diff --git a/packages/cli/authoring/doctypes/component/type.ts b/packages/cli/authoring/doctypes/component/type.tsindex 1578351ba2..0957e38e1c 100644--- a/packages/cli/authoring/doctypes/component/type.ts+++ b/packages/cli/authoring/doctypes/component/type.ts@@ -146,10 +146,10 @@ export interface ComponentBaseDoc extends AuthoredDocGraphFields {/*** The documentation type for a component directory's {Name}.doc.mjs file.*- * Every .doc.mjs must export a single `docs` constant of this type:+ * Every new .doc.mjs default-exports a stamped object of this type:** /\*\* \@type \{import('@astryxdesign/cli/authoring').ComponentDoc\} *\/- * export const docs = \{ ... \};+ * export default \{ type: 'component', ... \};** Use SingleComponentDoc (with `props`) for single-component directories.* Use MultiComponentDoc (with `components`) for multi-component directories.diff --git a/packages/cli/authoring/doctypes/doctypes-new.test.mjs b/packages/cli/authoring/doctypes/doctypes-new.test.mjsindex 2b57659a13..6b4f533f79 100644--- a/packages/cli/authoring/doctypes/doctypes-new.test.mjs+++ b/packages/cli/authoring/doctypes/doctypes-new.test.mjs@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Tests for the new authoring doc-types (schema/command/enum) and the+ * @file Tests for the new authoring doc-types (schema/command/enum/theme) and the* generalized `function` doc (hooks + CLI/API functions sharing the schema).*/@@ -12,6 +12,7 @@ import {parseCommand,parseEnum,parseFunction,+ parseTheme,} from '../index.mjs';describe('SchemaDoc', () => {@@ -22,13 +23,21 @@ describe('SchemaDoc', () => {description: 'Project config.',appliesTo: 'astryx.config.{ts,mjs,js}',fields: [- {name: 'integrations', type: 'string[]', description: 'Packages to load.'},+ {+ name: 'integrations',+ type: 'string[]',+ description: 'Packages to load.',+ },{name: 'hooks',type: 'object',description: 'Lifecycle hooks.',fields: [- {name: 'hooks.postCodemod', type: 'PostCodemodHook[]', description: 'Runs after codemods.'},+ {+ name: 'hooks.postCodemod',+ type: 'PostCodemodHook[]',+ description: 'Runs after codemods.',+ },],},],@@ -63,8 +72,16 @@ describe('CommandDoc', () => {fn: 'search',args: [{name: 'query', param: 'query', required: true}],options: [- {flag: '--type <domain>', param: 'options.type', choices: ['component', 'hook']},- {flag: '--json', cliOnly: true, description: 'Emit the typed JSON envelope.'},+ {+ flag: '--type <domain>',+ param: 'options.type',+ choices: ['component', 'hook'],+ },+ {+ flag: '--json',+ cliOnly: true,+ description: 'Emit the typed JSON envelope.',+ },],examples: [{label: 'Terminal', cli: 'astryx search button --json'}],exitCodes: [{code: 1, when: 'invalid --type'}],@@ -90,6 +107,29 @@ describe('EnumDoc', () => {});});+describe('ThemeDoc', () => {+ const doc = {+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: 'Cool blue surfaces with crisp contrast.',+ maintained: true,+ };++ it('accepts a complete theme descriptor and dispatches through parseDoc', () => {+ expect(parseTheme(doc)).toEqual(doc);+ expect(parseDoc(doc)).toEqual(doc);+ });++ it('rejects non-kebab identity and missing required metadata', () => {+ expect(() => parseTheme({...doc, name: 'OceanTheme'})).toThrow(+ /lowercase kebab-case/,+ );+ const {maintained: _maintained, ...missingMaintained} = doc;+ expect(() => parseTheme(missingMaintained)).toThrow(/maintained/);+ });+});+describe('generalized FunctionDoc', () => {it('accepts an API function whose returns are envelope entries (no field name)', () => {const apiFn = {@@ -98,7 +138,9 @@ describe('generalized FunctionDoc', () => {name: 'search',displayName: 'search()',importPath: '@astryxdesign/cli/api',- params: [{name: 'query', type: 'string', description: 'Term.', required: true}],+ params: [+ {name: 'query', type: 'string', description: 'Term.', required: true},+ ],returns: [{type: 'search', description: 'query + ranked results[]'}],throws: [{code: 'ERR_INVALID_ARGUMENT', when: 'empty query'}],};diff --git a/packages/cli/authoring/doctypes/enum/enum.doc.mjs b/packages/cli/authoring/doctypes/enum/enum.doc.mjsindex 65cfa95ac4..257198617e 100644--- a/packages/cli/authoring/doctypes/enum/enum.doc.mjs+++ b/packages/cli/authoring/doctypes/enum/enum.doc.mjs@@ -49,7 +49,7 @@ export const doc = {name: 'namespace',type: 'string',description:- "Docs namespace path. Defaults to 'cli' when applied by the docs index.",+ "The `astryx docs` topic that reads this doc. The CLI's enums use 'cli/api' (the section `api-<name>` of the `cli` topic). Every enum doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads.",},{name: 'aliases',diff --git a/packages/cli/authoring/doctypes/enum/type.ts b/packages/cli/authoring/doctypes/enum/type.tsindex 931cbed1e0..4d5005ee59 100644--- a/packages/cli/authoring/doctypes/enum/type.ts+++ b/packages/cli/authoring/doctypes/enum/type.ts@@ -32,7 +32,7 @@ export interface EnumDoc extends AuthoredDocGraphFields {displayName: string;/** One-line summary shown in listings. */description: string;- /** Docs namespace path. Defaults to 'cli' when applied by the docs index. */+ /** The `astryx docs` topic that reads this doc. The CLI's enums use 'cli/api' (the section `api-<name>` of the `cli` topic). Every enum doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads. */namespace?: string;/** Alternate slugs that also resolve to this doc. */aliases?: string[];diff --git a/packages/cli/authoring/doctypes/function/function.doc.mjs b/packages/cli/authoring/doctypes/function/function.doc.mjsindex 81ab9dd60b..ad0a853cd6 100644--- a/packages/cli/authoring/doctypes/function/function.doc.mjs+++ b/packages/cli/authoring/doctypes/function/function.doc.mjs@@ -57,7 +57,7 @@ export const doc = {name: 'namespace',type: 'string',description:- "Docs namespace path. Defaults (e.g. 'cli/api') applied by the docs index.",+ "The `astryx docs` topic that reads this doc. The CLI's API functions use 'cli/api' (the section `api-<name>` of the `cli` topic). Every function doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads.",},{name: 'aliases',diff --git a/packages/cli/authoring/doctypes/function/type.ts b/packages/cli/authoring/doctypes/function/type.tsindex d33b4e7e29..09860b787e 100644--- a/packages/cli/authoring/doctypes/function/type.ts+++ b/packages/cli/authoring/doctypes/function/type.ts@@ -62,7 +62,7 @@ export interface FunctionDoc extends AuthoredDocGraphFields {summary?: string;/** Longer description. */description?: string;- /** Docs namespace path. Defaults (e.g. 'cli/api') applied by the docs index. */+ /** The `astryx docs` topic that reads this doc. The CLI's API functions use 'cli/api' (the section `api-<name>` of the `cli` topic). Every function doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads. */namespace?: string;/** Alternate slugs that also resolve to this doc. */aliases?: string[];diff --git a/packages/cli/authoring/doctypes/hook/type.ts b/packages/cli/authoring/doctypes/hook/type.tsindex 50b4b453e0..c20c394b41 100644--- a/packages/cli/authoring/doctypes/hook/type.ts+++ b/packages/cli/authoring/doctypes/hook/type.ts@@ -23,10 +23,10 @@ import type {* Standalone hooks (e.g. useMediaQuery, useFocusTrap, useOverflow) get* their own {hookName}.doc.mjs file and use this type.*- * Every hook .doc.mjs must export a single `docs` constant:+ * Every new hook .doc.mjs default-exports a stamped object:** /\*\* @type {import('@astryxdesign/cli/authoring').HookDoc} \*\/- * export const docs = { ... };+ * export default { type: 'function', ... };*/export interface HookDoc extends AuthoredDocGraphFields {/** Doc-kind discriminant for the stamped default-export formatdiff --git a/packages/cli/authoring/doctypes/load-contract.test.mjs b/packages/cli/authoring/doctypes/load-contract.test.mjsindex c806c689fe..aecc61b9da 100644--- a/packages/cli/authoring/doctypes/load-contract.test.mjs+++ b/packages/cli/authoring/doctypes/load-contract.test.mjs@@ -49,7 +49,7 @@ const EXAMPLES = Object.fromEntries(describe('load check vs published type', () => {it('locks every doc kind', () => {- const source = ['_schema.mjs', 'template/parse.mjs']+ const source = ['_schema.mjs', 'template/parse.mjs', 'theme/parse.mjs'].map(file => fs.readFileSync(path.join(HERE, file), 'utf8')).join('\n');expect(Object.keys(LOCKS).sort()).toEqual([...KINDS].sort());@@ -57,6 +57,7 @@ describe('load check vs published type', () => {...Object.values(LOCKS),'_AuthoredDocKindDriftLock','_HookDocIsFunctionDocLock',+ '_ThemeDocDriftLock',];for (const lock of locks) {expect(source, `${lock} is missing`).toMatch(diff --git a/packages/cli/authoring/doctypes/parse.mjs b/packages/cli/authoring/doctypes/parse.mjsindex 2238eff23c..838c149d0e 100644--- a/packages/cli/authoring/doctypes/parse.mjs+++ b/packages/cli/authoring/doctypes/parse.mjs@@ -4,8 +4,8 @@* @file The doc load boundary. `parseDoc` validates an unknown loaded doc value* into its typed shape (or throws a readable error), dispatching on the stamped* `type` and falling back to legacy shape-sniffing for unstamped docs. Its- * acceptance set matches the old permissive `ComponentDocSchema` exactly, so- * every existing `.doc.*` keeps loading unchanged.+ * acceptance set preserves the old permissive `ComponentDocSchema` while new+ * stamped kinds, including `theme`, use their sealed parser.*/import {parseComponent} from './component/parse.mjs';@@ -16,6 +16,7 @@ import {parseSchema} from './schema/parse.mjs';import {parseCommand} from './command/parse.mjs';import {parseEnum} from './enum/parse.mjs';import {parseNamespace} from './namespace/parse.mjs';+import {parseTheme} from './theme/parse.mjs';import {parseLegacyDoc} from './legacy.mjs';/** @typedef {import('./types.js').ComponentDoc} ComponentDoc */@@ -27,6 +28,7 @@ import {parseLegacyDoc} from './legacy.mjs';/** @typedef {import('./types.js').CommandDoc} CommandDoc *//** @typedef {import('./types.js').EnumDoc} EnumDoc *//** @typedef {import('./types.js').NamespaceDoc} NamespaceDoc */+/** @typedef {import('./types.js').ThemeDoc} ThemeDoc *//*** Validate an unknown loaded doc value into its typed shape, or throw.@@ -36,7 +38,7 @@ import {parseLegacyDoc} from './legacy.mjs';** @param {unknown} input* @param {string} [label]- * @returns {ComponentDoc | HookDoc | FunctionDoc | ReferenceDoc | TemplateDoc | SchemaDoc | CommandDoc | EnumDoc | NamespaceDoc}+ * @returns {ComponentDoc | HookDoc | FunctionDoc | ReferenceDoc | TemplateDoc | SchemaDoc | CommandDoc | EnumDoc | NamespaceDoc | ThemeDoc}*/export function parseDoc(input, label = 'doc') {const type =@@ -62,6 +64,8 @@ export function parseDoc(input, label = 'doc') {return parseEnum(input, label);case 'namespace':return parseNamespace(input, label);+ case 'theme':+ return parseTheme(input, label);case undefined:return parseLegacyDoc(input, label);default:diff --git a/packages/cli/authoring/doctypes/reference/reference.doc.mjs b/packages/cli/authoring/doctypes/reference/reference.doc.mjsindex 73beacec6e..dba70a005d 100644--- a/packages/cli/authoring/doctypes/reference/reference.doc.mjs+++ b/packages/cli/authoring/doctypes/reference/reference.doc.mjs@@ -62,7 +62,7 @@ export const doc = {name: 'extends',type: 'string',description:- 'Name of an existing topic this doc merges onto, section by section: a section whose title matches one in the base replaces it, a section the base does not have is appended. For correcting or adding to a topic rather than owning it. Exclusive with `replaces`.',+ "Name of an existing topic this doc merges onto, section by section: a section whose title matches one in the base replaces it, a section the base does not have is appended. The topic keeps the base's title and description. For correcting or adding to a topic rather than owning it. Exclusive with `replaces`.",example: "'theme'",},{diff --git a/packages/cli/authoring/doctypes/reference/type.ts b/packages/cli/authoring/doctypes/reference/type.tsindex 14dc63eb99..e6e8a70b7a 100644--- a/packages/cli/authoring/doctypes/reference/type.ts+++ b/packages/cli/authoring/doctypes/reference/type.ts@@ -93,10 +93,10 @@ export type ReferenceContentBlock =* they aren't tied to a specific component — just drop a .doc.mjs file* in the docs/ directory and it shows up in `astryx docs`.*- * Every reference .doc.mjs must export a single `docs` constant:+ * Every new reference .doc.mjs default-exports a stamped object:** /** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} *\/- * export const docs = { ... };+ * export default { type: 'generic', ... };*/export interface ReferenceDoc extends AuthoredDocGraphFields {/** Doc-kind discriminant for the stamped default-export formatdiff --git a/packages/cli/authoring/doctypes/schema/schema.doc.mjs b/packages/cli/authoring/doctypes/schema/schema.doc.mjsindex 8810929835..9f56ec63be 100644--- a/packages/cli/authoring/doctypes/schema/schema.doc.mjs+++ b/packages/cli/authoring/doctypes/schema/schema.doc.mjs@@ -49,7 +49,7 @@ export const doc = {name: 'namespace',type: 'string',description:- "Docs namespace path (e.g. 'cli' | 'authoring'). Defaults are applied by the docs index; set explicitly to place the schema.",+ "The `astryx docs` topic that reads this doc: 'authoring' for a file an author writes (a section of `astryx docs authoring`), or 'cli/api' for a shape the CLI returns (the section `api-<name>` of the `cli` topic). Every schema doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads.",},{name: 'aliases',diff --git a/packages/cli/authoring/doctypes/schema/type.ts b/packages/cli/authoring/doctypes/schema/type.tsindex a38bddc8cd..269bf86354 100644--- a/packages/cli/authoring/doctypes/schema/type.ts+++ b/packages/cli/authoring/doctypes/schema/type.ts@@ -47,8 +47,7 @@ export interface SchemaDoc extends AuthoredDocGraphFields {displayName: string;/** One-line summary shown in listings. */description: string;- /** Docs namespace path (e.g. 'cli' | 'authoring'). Defaults are applied by- * the docs index; set explicitly to place the schema. */+ /** The `astryx docs` topic that reads this doc: 'authoring' for a file an author writes (a section of `astryx docs authoring`), or 'cli/api' for a shape the CLI returns (the section `api-<name>` of the `cli` topic). Every schema doc the CLI ships declares one, and `astryx doctor` fails on one that is missing or that no topic reads. */namespace?: string;/** Alternate slugs that also resolve to this doc (back-compat). */aliases?: string[];diff --git a/packages/cli/authoring/doctypes/template/template.doc.mjs b/packages/cli/authoring/doctypes/template/template.doc.mjsindex b9f6c05a43..d5f08bad8d 100644--- a/packages/cli/authoring/doctypes/template/template.doc.mjs+++ b/packages/cli/authoring/doctypes/template/template.doc.mjs@@ -18,7 +18,7 @@ export const doc = {"(type: 'page') for full page templates and BlockTemplateDoc (type: 'block') for " +'editable compositions. A block can stand alone or use `exampleFor` to attach ' +'to one component; `isShowcase` requires that component ownership.',- appliesTo: '<Name>.template.mjs',+ appliesTo: '<Name>.doc.mjs',fields: [{name: 'type',@@ -123,7 +123,7 @@ export const doc = {{label: 'Page template',code: `/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */-export const doc = {+export default {type: 'page',name: 'Dashboard',displayName: 'Dashboard',@@ -135,7 +135,7 @@ export const doc = {{label: 'Block template (component example)',code: `/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */-export const doc = {+export default {type: 'block',name: 'ButtonGroupExample',displayName: 'Button Group Example',diff --git a/packages/cli/authoring/doctypes/theme/parse.mjs b/packages/cli/authoring/doctypes/theme/parse.mjsnew file mode 100644index 0000000000..dbf2d84614--- /dev/null+++ b/packages/cli/authoring/doctypes/theme/parse.mjs@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Theme doc parser (stamped `type: 'theme'`). Zod is sealed here;+ * theme discovery calls `parseTheme` at the descriptor load boundary.+ *+ * @input an unknown loaded or statically extracted theme descriptor+ * @output a validated ThemeDoc or a readable schema error+ * @position packages/cli/authoring/doctypes/theme — descriptor load boundary+ */++import {z} from 'zod';+import {formatZodError} from '../../_shared/errors.mjs';++/** @typedef {import('./type.js').ThemeDoc} ThemeDoc */++/** @param {string} field */+const nonBlank = field =>+ z.string().refine(value => value.trim() !== '', {+ message: `${field} must not be blank`,+ abort: true,+ });++const themeDocSchema = z+ .object({+ type: z.literal('theme'),+ name: nonBlank('name').regex(+ /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,+ 'name must be lowercase kebab-case starting with a letter',+ ),+ displayName: nonBlank('displayName'),+ // Blank is allowed, as the released catalog allowed it.+ description: z.string(),+ maintained: z.boolean(),+ })+ .strict();++/** Zod skips `__proto__` when it looks for unknown keys. */+const PROTO_KEY_ISSUE = {+ code: /** @type {const} */ ('unrecognized_keys'),+ keys: ['__proto__'],+ path: [],+ message: 'Unrecognized key: "__proto__"',+};++/**+ * Compile-time drift lock: the sealed schema must infer exactly ThemeDoc.+ *+ * @typedef {import('../../_shared/contract.js').Expect<+ * import('../../_shared/contract.js').Equal<+ * z.infer<typeof themeDocSchema>,+ * ThemeDoc+ * >+ * >} _ThemeDocDriftLock+ */++/**+ * Validate an unknown value as a theme descriptor, or throw.+ *+ * @param {unknown} input+ * @param {string} [label]+ * @returns {ThemeDoc}+ */+export function parseTheme(input, label = 'theme') {+ const result = themeDocSchema.safeParse(input);+ const protoKey =+ input !== null &&+ typeof input === 'object' &&+ Object.hasOwn(input, '__proto__');+ if (result.success && !protoKey) return result.data;+ const issues = [+ ...(result.error?.issues ?? []),+ ...(protoKey ? [PROTO_KEY_ISSUE] : []),+ ];+ throw new Error(formatZodError(label, new z.ZodError(issues)));+}diff --git a/packages/cli/authoring/doctypes/theme/theme.doc.mjs b/packages/cli/authoring/doctypes/theme/theme.doc.mjsnew file mode 100644index 0000000000..4a4dad3d02--- /dev/null+++ b/packages/cli/authoring/doctypes/theme/theme.doc.mjs@@ -0,0 +1,79 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SchemaDoc for the ThemeDoc authoring type.+ * @position packages/cli/authoring/doctypes/theme — doc-type documentation+ */++/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */+export const doc = {+ type: 'schema',+ name: 'theme-doc',+ displayName: 'ThemeDoc',+ namespace: 'authoring',+ description:+ 'The strongly typed descriptor for one integration or CLI-bundled source theme.',+ appliesTo: '<theme-source-stem>.doc.mjs',+ fields: [+ {+ name: 'type',+ type: "'theme'",+ description: 'Doc-kind discriminant.',+ required: true,+ },+ {+ name: 'name',+ type: 'string',+ description:+ 'Lower-kebab CLI theme identity. Must match the descriptor parent directory.',+ required: true,+ example: "'ocean'",+ },+ {+ name: 'displayName',+ type: 'string',+ description: 'Human-readable name shown by theme listings.',+ required: true,+ example: "'Ocean'",+ },+ {+ name: 'description',+ type: 'string',+ description: 'One-line summary shown by theme listings.',+ required: true,+ },+ {+ name: 'maintained',+ type: 'boolean',+ description: 'Whether the owning package actively maintains this theme.',+ required: true,+ },+ ],+ examples: [+ {+ label: 'A theme descriptor beside oceanTheme.ts',+ code: `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: 'Cool blue surfaces with crisp contrast.',+ maintained: true,+};`,+ },+ ],+ notes: [+ {+ type: 'prose',+ text: 'ThemeDoc is static metadata. Default-export one object with literal string and boolean fields; discovery validates it without executing the descriptor or theme source.',+ },+ {+ type: 'prose',+ text: 'The descriptor and source share one stem. For oceanTheme.doc.mjs, discovery requires exactly one oceanTheme source module and a named oceanTheme runtime export.',+ },+ {+ type: 'prose',+ text: 'The parent theme directory, including this descriptor, is the complete copy and pack boundary. Nested source, palettes, assets, and receipts need no second file list.',+ },+ ],+};diff --git a/packages/cli/authoring/doctypes/theme/type.ts b/packages/cli/authoring/doctypes/theme/type.tsnew file mode 100644index 0000000000..97e973c39b--- /dev/null+++ b/packages/cli/authoring/doctypes/theme/type.ts@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Theme contribution descriptor type.+ *+ * A theme descriptor is a strongly typed `.doc.mjs` beside its same-stem theme+ * source. The shared stem identifies the source entry and required named runtime+ * export. The lower-kebab parent directory and `name` identify the CLI theme.+ *+ * @input metadata authored beside one source theme+ * @output the public ThemeDoc contract+ * @position packages/cli/authoring/doctypes/theme — theme descriptor vocabulary+ */++/**+ * The descriptor for one source theme contributed by an integration or bundled+ * with the CLI.+ *+ * @example+ * ```+ * /** @type {import('@astryxdesign/cli/authoring').ThemeDoc} *\/+ * export default {+ * type: 'theme',+ * name: 'ocean',+ * displayName: 'Ocean',+ * description: 'Cool blue surfaces with crisp contrast.',+ * maintained: true,+ * };+ * ```+ */+export interface ThemeDoc {+ /** Doc-kind discriminant. */+ type: 'theme';+ /** Stable CLI identity. Must be lower-kebab and match the parent directory. */+ name: string;+ /** Human-readable name shown by theme listings. */+ displayName: string;+ /** One-line summary shown by theme listings. */+ description: string;+ /** Whether the owning package actively maintains this theme. */+ maintained: boolean;+}diff --git a/packages/cli/authoring/doctypes/types.ts b/packages/cli/authoring/doctypes/types.tsindex c21f8a048d..6165f4cdd9 100644--- a/packages/cli/authoring/doctypes/types.ts+++ b/packages/cli/authoring/doctypes/types.ts@@ -3,7 +3,7 @@/*** @file Doc-type vocabulary barrel. Each kind's types live in one `type.ts`* under its folder (`base/` shared leaves, then `component/`, `hook/`,- * `reference/`, `template/`); this re-exports them as the full doc vocabulary+ * `reference/`, `template/`, `theme/`); this re-exports them as the full doc vocabulary* behind `@astryxdesign/cli/authoring`.*/@@ -17,3 +17,4 @@ export type * from './template/type.js';export type * from './schema/type.js';export type * from './command/type.js';export type * from './enum/type.js';+export type * from './theme/type.js';diff --git a/packages/cli/authoring/gap-report/gap-report.doc.mjs b/packages/cli/authoring/gap-report/gap-report.doc.mjsnew file mode 100644index 0000000000..387f520157--- /dev/null+++ b/packages/cli/authoring/gap-report/gap-report.doc.mjs@@ -0,0 +1,183 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SchemaDoc for GapReportHandler, the handler `astryx gap-report` calls.+ * @input The GapReportHandler type beside it (`type.ts`), which `parse.mjs`+ * validates.+ * @output The `gap-report-handler` section of `astryx docs authoring`.+ * @position packages/cli/authoring/gap-report — schema documentation+ */++/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */+export const doc = {+ type: 'schema',+ name: 'gap-report-handler',+ displayName: 'GapReportHandler',+ namespace: 'authoring',+ description:+ 'A handler for `astryx gap-report`: a plain object with an `audience` and a `handle` function. Set it as `gapReport` in astryx.config, or export it as `gapReport` from an integration manifest. Every handler runs: the project handler first, then each integration handler in config order.',+ appliesTo:+ '`gapReport` in astryx.config.*, or the `gapReport` named export of astryx.integration.*',+ fields: [+ {+ name: 'audience',+ type: "'internal' | 'public'",+ description:+ 'Whether the destination is internal to your organization or public. A public handler runs only when the caller agrees; an internal handler always runs.',+ required: true,+ },+ {+ name: 'handle',+ type: '(report: GapReport, context: GapReportHandlerContext) => GapReportHandlerReceipt | Promise<GapReportHandlerReceipt>',+ description:+ 'Gets the report and returns a receipt. It can be async, and the CLI waits at most 30 seconds for it. A throw, a timeout, or an invalid receipt is a failed delivery, and the other handlers still run.',+ required: true,+ fields: [+ {+ name: 'report',+ type: 'GapReport',+ description: 'The report. Each handler gets its own copy.',+ required: true,+ fields: [+ {+ name: 'report.schemaVersion',+ type: '1',+ description: 'Version of the report shape.',+ required: true,+ },+ {+ name: 'report.component',+ type: 'string',+ description: 'The component the gap is about.',+ required: true,+ },+ {+ name: 'report.category',+ type: 'GapReportCategory',+ description:+ "The kind of gap: 'missing_component', 'missing_variant', 'layout_gap', 'styling_gap', 'a11y_gap', 'api_friction', 'docs_gap', or 'other'.",+ required: true,+ },+ {+ name: 'report.categoryLabel',+ type: 'string',+ description: 'A readable name for the category.',+ required: true,+ },+ {+ name: 'report.intention',+ type: 'string',+ description: 'What the caller was trying to do.',+ required: true,+ },+ {+ name: 'report.detail',+ type: 'string',+ description: 'More detail, when the caller gave some.',+ },+ {+ name: 'report.source',+ type: 'DebugInvocationSource',+ description:+ "Who sent the report: 'human', 'ai', 'automation', or 'unknown'.",+ required: true,+ },+ {+ name: 'report.timestamp',+ type: 'string',+ description: 'When the report was sent, as ISO 8601.',+ required: true,+ },+ {+ name: 'report.target',+ type: 'GapReportTarget',+ description: 'The package the report is about.',+ required: true,+ fields: [+ {+ name: 'report.target.package',+ type: 'string',+ description: 'The package name.',+ required: true,+ },+ {+ name: 'report.target.version',+ type: 'string',+ description:+ 'The installed version. Null when it is not known.',+ required: true,+ },+ {+ name: 'report.target.issuesUrl',+ type: 'string',+ description:+ 'Where the package takes issues. Null when it does not say.',+ required: true,+ },+ ],+ },+ ],+ },+ {+ name: 'context',+ type: 'GapReportHandlerContext',+ description: 'The context of this call.',+ required: true,+ fields: [+ {+ name: 'context.signal',+ type: 'AbortSignal',+ description: 'Aborted when the handler runs past 30 seconds.',+ required: true,+ },+ ],+ },+ ],+ },+ ],+ examples: [+ {+ label: 'A project handler in astryx.config',+ code:+ 'export default {\n' ++ ' gapReport: {\n' ++ " audience: 'internal',\n" ++ ' async handle(report, {signal}) {\n' ++ ' const url = await fileIssue(report, {signal});\n' ++ " return {status: 'filed', url};\n" ++ ' },\n' ++ ' },\n' ++ '};',+ },+ ],+ notes: [+ {+ type: 'table',+ headers: ['Receipt field', 'Type', 'Required', 'Description'],+ rows: [+ [+ 'status',+ "'filed' | 'routed_only' | 'skipped'",+ 'yes',+ "'filed': the handler created or queued the report. 'routed_only': it points to a place to file the report, and must return `url`. 'skipped': it chose not to act, for example on a duplicate.",+ ],+ [+ 'url',+ 'string',+ 'no',+ 'An http or https URL. Required when status is routed_only.',+ ],+ [+ 'message',+ 'string',+ 'no',+ 'A readable message of at most 2000 characters.',+ ],+ ],+ },+ {+ type: 'prose',+ text: 'The receipt is strict: an unknown field, a URL that is not http or https, or a filed or routed_only receipt with neither `url` nor `message` is invalid.',+ },+ ],+};diff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.tsindex 81f6142043..4ea443bfec 100644--- a/packages/cli/authoring/index.d.ts+++ b/packages/cli/authoring/index.d.ts@@ -23,15 +23,16 @@// ═══════════════════════════════════════════════════════════════════════// AUTHOR THESE — each is the default export of one authored file.// ═══════════════════════════════════════════════════════════════════════-export type {ComponentDoc} from './doctypes/types.js'; // Button.doc.{ts,mjs}-export type {HookDoc} from './doctypes/types.js'; // useToast.doc.{ts,mjs}+export type {ComponentDoc} from './doctypes/types.js'; // Button.doc.mjs+export type {HookDoc} from './doctypes/types.js'; // useToast.doc.mjsexport type {FunctionDoc} from './doctypes/types.js'; // search.doc.mjs (hook | api)-export type {ReferenceDoc} from './doctypes/types.js'; // theming.doc.{ts,mjs}-export type {TemplateDoc} from './doctypes/types.js'; // Foo.template.{ts,mjs}+export type {ReferenceDoc} from './doctypes/types.js'; // theming.doc.mjs+export type {TemplateDoc} from './doctypes/types.js'; // Foo.doc.mjsexport type {SchemaDoc} from './doctypes/types.js'; // config.doc.mjs (object shape)export type {CommandDoc} from './doctypes/types.js'; // search.doc.mjs (CLI command)export type {EnumDoc} from './doctypes/types.js'; // error-codes.doc.mjs (vocabulary)export type {NamespaceDoc} from './doctypes/types.js'; // cli.doc.mjs (hierarchy)+export type {ThemeDoc} from './doctypes/types.js'; // oceanTheme.doc.mjsexport type {AstryxConfig} from './config/type.js'; // astryx.config.{ts,mjs}export type {DebugEvent} from './debug/type.js'; // one recorded CLI runexport type {AstryxIntegration} from './integration/type.js'; // astryx.integration.{ts,mjs}@@ -58,6 +59,7 @@ export {parseSchema} from './doctypes/schema/parse.mjs';export {parseCommand} from './doctypes/command/parse.mjs';export {parseEnum} from './doctypes/enum/parse.mjs';export {parseNamespace} from './doctypes/namespace/parse.mjs';+export {parseTheme} from './doctypes/theme/parse.mjs';export {parseLegacyDoc} from './doctypes/legacy.mjs';export {parseConfig} from './config/parse.mjs';export {parseIntegration} from './integration/parse.mjs';diff --git a/packages/cli/authoring/index.mjs b/packages/cli/authoring/index.mjsindex d3207309fd..8c4ae8ffcf 100644--- a/packages/cli/authoring/index.mjs+++ b/packages/cli/authoring/index.mjs@@ -11,7 +11,7 @@* `type` directly.** Types (config, integration, codemod, and the doc vocabulary —- * component/hook/reference/template) are re-exported via `./index.ts`.+ * component/hook/reference/template/theme) are re-exported via `./index.ts`.*/export {parseConfig} from './config/parse.mjs';@@ -32,4 +32,5 @@ export {parseSchema} from './doctypes/schema/parse.mjs';export {parseCommand} from './doctypes/command/parse.mjs';export {parseEnum} from './doctypes/enum/parse.mjs';export {parseNamespace} from './doctypes/namespace/parse.mjs';+export {parseTheme} from './doctypes/theme/parse.mjs';export {parseLegacyDoc} from './doctypes/legacy.mjs';diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjsindex 85997cc2e3..c6c8e5845a 100644--- a/packages/cli/authoring/integration/integration.doc.mjs+++ b/packages/cli/authoring/integration/integration.doc.mjs@@ -11,7 +11,7 @@ export const doc = {type: 'schema',name: 'integration',displayName: 'Astryx Integration',- namespace: 'cli',+ namespace: 'authoring',description:'The astryx.integration.* manifest that sits beside an integration ' +"package's package.json. It can preserve a stable provider identity across a package rename, " +@@ -57,7 +57,7 @@ export const doc = {name: 'themes',type: 'string',description:- 'Relative path to a source-theme catalog root containing manifest.json plus one directory per theme slug. Installed themes appear in `astryx theme list` and can be copied with `astryx theme add`.',+ 'Relative path to a source-theme root with one directory per theme slug. Each directory contains a source module and mandatory same-stem, strongly typed .doc.mjs descriptor. Installed themes appear in `astryx theme list` and can be copied with `astryx theme add`.',example: "'./themes'",},{diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.tsindex 1e96a7e5be..aaf813d5c3 100644--- a/packages/cli/authoring/integration/type.ts+++ b/packages/cli/authoring/integration/type.ts@@ -34,15 +34,9 @@ export interface AstryxIntegration {* serves from `astryx docs`, alongside the built-in ones. A topic may also* `replace` or `extend` a built-in topic; see the ReferenceDoc type. */docs?: string;- /** Relative path to the source-theme catalog root (resolved to absolute).- * The root contains `manifest.json` plus one directory per theme slug.- * `manifest.json` is `{ "version": 1, "themes": [...] }` where each- * entry requires `slug`, `displayName`, `description` (string),- * `maintained` (boolean), `entry` (source file relative to `themes/<slug>/`),- * `exportName` (a valid JS identifier naming the runtime export), and- * `files` (non-empty array of filenames relative to `themes/<slug>/`).- * Every file listed must exist on disk; the entry file must also appear- * in `files`. */+ /** Relative path to the source-theme root (resolved to absolute). Each+ * lower-kebab theme directory contains a source module and mandatory+ * same-stem, strongly typed `.doc.mjs` descriptor. */themes?: string;/** Static package guidance appended to the CLI-owned managed agent block. */agentDocs?: {diff --git a/packages/cli/clients/cli/__tests__/cliManifest.test.ts b/packages/cli/clients/cli/__tests__/cliManifest.test.tsindex 78f1ce01f8..4dafb629a2 100644--- a/packages/cli/clients/cli/__tests__/cliManifest.test.ts+++ b/packages/cli/clients/cli/__tests__/cliManifest.test.ts@@ -3,37 +3,35 @@import fs from 'fs';import path from 'path';import {describe, it, expect} from 'vitest';--describe('@astryxdesign/cli Theme Manifest & Template Validation', () => {- const manifestPath = path.resolve(- 'packages/cli/assets/templates/themes/manifest.json',- );-- it('validates theme manifest existence and structure', () => {- expect(fs.existsSync(manifestPath)).toBe(true);- const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));-- expect(manifest.version).toBe(1);- expect(Array.isArray(manifest.themes)).toBe(true);- expect(manifest.themes.length).toBeGreaterThan(0);- });-- it('verifies all referenced theme files exist', () => {- const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));- const themesDir = path.dirname(manifestPath);-- for (const theme of manifest.themes) {- expect(theme.slug).toBeDefined();- expect(theme.displayName).toBeDefined();- expect(theme.entry).toBeDefined();-- const entryPath = path.join(themesDir, theme.slug, theme.entry);- expect(fs.existsSync(entryPath)).toBe(true);-+import {discoverBundledThemes} from '../../../foundation/discovery/theme-discovery.mjs';++describe('@astryxdesign/cli bundled theme descriptor validation', () => {+ it('discovers typed descriptors and their same-stem source files', () => {+ const themes = discoverBundledThemes();+ expect(themes.length).toBeGreaterThan(0);++ for (const theme of themes) {+ expect(theme.slug).toBeTruthy();+ expect(theme.displayName).toBeTruthy();+ expect(theme.docPath).toBe(+ path.join(+ theme.sourceDir,+ `${path.basename(theme.entry, path.extname(theme.entry))}.doc.mjs`,+ ),+ );+ expect(fs.existsSync(theme.docPath)).toBe(true);+ expect(fs.existsSync(path.join(theme.sourceDir, theme.entry))).toBe(true);for (const file of theme.files) {- const filePath = path.join(themesDir, theme.slug, file);- expect(fs.existsSync(filePath)).toBe(true);+ expect(fs.existsSync(path.join(theme.sourceDir, file))).toBe(true);}}});++ it('does not ship the obsolete central theme catalog', () => {+ expect(+ fs.existsSync(+ path.resolve('packages/cli/assets/templates/themes/manifest.json'),+ ),+ ).toBe(false);+ });});diff --git a/packages/cli/clients/cli/commands/blog.doc.mjs b/packages/cli/clients/cli/commands/blog.doc.mjsindex 2edace9db7..ab1e560f36 100644--- a/packages/cli/clients/cli/commands/blog.doc.mjs+++ b/packages/cli/clients/cli/commands/blog.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'blog',displayName: 'astryx blog',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Read the Astryx blog from the published feed',description:'Reads the design-system blog over its published RSS feed (never the source ' +diff --git a/packages/cli/clients/cli/commands/build.doc.mjs b/packages/cli/clients/cli/commands/build.doc.mjsindex 9f881637d6..f1fc56ad0c 100644--- a/packages/cli/clients/cli/commands/build.doc.mjs+++ b/packages/cli/clients/cli/commands/build.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'build',displayName: 'astryx build',- namespace: 'cli',+ namespace: 'cli/commands',summary:'Build a page: composition kit for an idea, or the workflow playbook (no args)',description:diff --git a/packages/cli/clients/cli/commands/component.doc.mjs b/packages/cli/clients/cli/commands/component.doc.mjsindex 09bde5b5ec..1fe7bf266f 100644--- a/packages/cli/clients/cli/commands/component.doc.mjs+++ b/packages/cli/clients/cli/commands/component.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'component',displayName: 'astryx component',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'List components or print component docs',description:'Resolves a component by name across core and integration packages and prints ' +diff --git a/packages/cli/clients/cli/commands/discover.doc.mjs b/packages/cli/clients/cli/commands/discover.doc.mjsindex a39605ead9..8f5869bd70 100644--- a/packages/cli/clients/cli/commands/discover.doc.mjs+++ b/packages/cli/clients/cli/commands/discover.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'discover',displayName: 'astryx discover',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Discover external packages and components',description:'Explores components contributed by configured external packages and integrations. ' +diff --git a/packages/cli/clients/cli/commands/docs.doc.mjs b/packages/cli/clients/cli/commands/docs.doc.mjsindex 0be2c9097f..c5a592aeb9 100644--- a/packages/cli/clients/cli/commands/docs.doc.mjs+++ b/packages/cli/clients/cli/commands/docs.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'docs',displayName: 'astryx docs',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Print reference docs',description:'Reads the reference docs: with no topic it lists every topic; a topic prints that ' +diff --git a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjsindex b69977782e..5da6624615 100644--- a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs@@ -7,7 +7,7 @@ export const doc = {type: 'command',name: 'doctor integration components',displayName: 'astryx doctor integration components',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Warn when integration component names conflict with Core',description:'Compares one local or installed integration with Core component names. A ' +diff --git a/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjsindex 95d98f9968..1b12790bd4 100644--- a/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs@@ -7,7 +7,7 @@ export const doc = {type: 'command',name: 'doctor integration docs',displayName: 'astryx doctor integration docs',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Classify integration doc overlaps with Core topics',description:'Reports intentional Core topic replacements and extensions as information. ' +diff --git a/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjsindex 0425f9c957..d44a5e4a8a 100644--- a/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs@@ -9,7 +9,7 @@ export const doc = {type: 'command',name: 'doctor integration templates',displayName: 'astryx doctor integration templates',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Warn when integration template ids conflict with Core',description:'Compares one local or installed integration with the built-in Core page and ' +diff --git a/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjsindex c1d79e19e0..327ce515ab 100644--- a/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjs@@ -9,7 +9,7 @@ export const doc = {type: 'command',name: 'doctor integration validate',displayName: 'astryx doctor integration validate',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Validate an integration manifest and its contributions',description:'Validates one integration at a time: the local package rooted at cwd, or an ' +diff --git a/packages/cli/clients/cli/commands/doctor-integration.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration.doc.mjsindex dec0a1eb65..30e722b97f 100644--- a/packages/cli/clients/cli/commands/doctor-integration.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration.doc.mjs@@ -9,7 +9,7 @@ export const doc = {type: 'command',name: 'doctor integration',displayName: 'astryx doctor integration',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Check an integration package while authoring it',description:'The integration-authoring diagnostics group. Validate a manifest and all ' +diff --git a/packages/cli/clients/cli/commands/doctor-integration.test.mjs b/packages/cli/clients/cli/commands/doctor-integration.test.mjsindex 3e9fd64bb6..10b021391b 100644--- a/packages/cli/clients/cli/commands/doctor-integration.test.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration.test.mjs@@ -44,7 +44,7 @@ function writeIntegration({const stem = path.join(tmpDir, 'templates', id);fs.mkdirSync(path.dirname(stem), {recursive: true});fs.writeFileSync(- `${stem}.template.mjs`,+ `${stem}.doc.mjs`,`export default {type: 'page', name: ${JSON.stringify(name)}, description: 'fixture'};\n`,);fs.writeFileSync(@@ -124,7 +124,12 @@ describe('doctor integration — command', () => {return true;});- await createProgram().parseAsync(['node', 'astryx', 'doctor', 'integration']);+ await createProgram().parseAsync([+ 'node',+ 'astryx',+ 'doctor',+ 'integration',+ ]);const output = writes.join('');expect(output).toContain('validate [package]');@@ -136,7 +141,9 @@ describe('doctor integration — command', () => {it('explains the optional package argument in every leaf help', () => {const program = createProgram();- const doctor = program.commands.find(command => command.name() === 'doctor');+ const doctor = program.commands.find(+ command => command.name() === 'doctor',+ );const integration = doctor?.commands.find(command => command.name() === 'integration',);@@ -152,7 +159,10 @@ describe('doctor integration — command', () => {});it('templates explains how to check an installed package when no local manifest exists', async () => {- fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({name: 'plain'}));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'plain'}),+ );process.chdir(tmpDir);await createProgram().parseAsync([@@ -278,9 +288,7 @@ describe('doctor integration — command', () => {const output = logCalls.join('\n');expect(output).toContain('[warn]');expect(output).toContain(core.name);- expect(output).toContain(- `component ${core.name} --package @acme/widgets`,- );+ expect(output).toContain(`component ${core.name} --package @acme/widgets`);expect(process.exitCode).toBeUndefined();});diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjsindex 3c6953128b..30dda6904c 100644--- a/packages/cli/clients/cli/commands/doctor.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'doctor',displayName: 'astryx doctor',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Diagnose Astryx projects and integration packages',description:'Runs read-only project health diagnostics by default: Node version, @astryxdesign/core ' +diff --git a/packages/cli/clients/cli/commands/gap-report.doc.mjs b/packages/cli/clients/cli/commands/gap-report.doc.mjsindex 38e0405df8..e74414e2f4 100644--- a/packages/cli/clients/cli/commands/gap-report.doc.mjs+++ b/packages/cli/clients/cli/commands/gap-report.doc.mjs@@ -10,7 +10,7 @@ export const doc = {type: 'command',name: 'gap-report',displayName: 'astryx gap-report',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Route a design-system gap to its owning package',description:'Reports a missing component, variant, layout, styling, accessibility, API, or documentation capability. The command selects an explicit package first, then a unique component owner, then Core. The report fans out to every effective handler: project config first, then each loaded integration in config order. Public handlers require --confirm-public per handler; internal handlers always run. A handler failure is isolated and does not prevent later handlers.',diff --git a/packages/cli/clients/cli/commands/hook.doc.mjs b/packages/cli/clients/cli/commands/hook.doc.mjsindex f30c013955..4013ee700a 100644--- a/packages/cli/clients/cli/commands/hook.doc.mjs+++ b/packages/cli/clients/cli/commands/hook.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'hook',displayName: 'astryx hook',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'List hooks or print hook docs',description:'Resolves a hook by name and prints its authored doc, or lists the catalog grouped ' +diff --git a/packages/cli/clients/cli/commands/init.doc.mjs b/packages/cli/clients/cli/commands/init.doc.mjsindex 9382349cc7..cfa0954283 100644--- a/packages/cli/clients/cli/commands/init.doc.mjs+++ b/packages/cli/clients/cli/commands/init.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'init',displayName: 'astryx init',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Initialize the design system in your project',description:'Non-interactive project setup (no prompts, so it behaves the same for humans, ' +diff --git a/packages/cli/clients/cli/commands/integration-add.controls.test.mjs b/packages/cli/clients/cli/commands/integration-add.controls.test.mjsindex 7f66f07d67..218696c5fb 100644--- a/packages/cli/clients/cli/commands/integration-add.controls.test.mjs+++ b/packages/cli/clients/cli/commands/integration-add.controls.test.mjs@@ -126,7 +126,7 @@ describe('integration add control definitions', () => {);expect(page.status).toBe(0);expect(- fs.readFileSync(path.join(tmpDir, 'templates', 'acme-page.template.mjs'), 'utf-8'),+ fs.readFileSync(path.join(tmpDir, 'templates', 'acme-page.doc.mjs'), 'utf-8'),).toContain("type: 'page'");});});diff --git a/packages/cli/clients/cli/commands/integration-add.doc.mjs b/packages/cli/clients/cli/commands/integration-add.doc.mjsindex 060ff9a69f..c326ff192b 100644--- a/packages/cli/clients/cli/commands/integration-add.doc.mjs+++ b/packages/cli/clients/cli/commands/integration-add.doc.mjs@@ -5,7 +5,7 @@ export const doc = {type: 'command',name: 'integration add',displayName: 'astryx integration add',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Add one working contribution to an integration package',description:'Writes the complete minimum shape the selected contribution needs, creates the integration manifest on first use, declares the root only after a valid contribution exists, and verifies the result through the same discovery contract the packed-package check uses.',diff --git a/packages/cli/clients/cli/commands/integration-pack.doc.mjs b/packages/cli/clients/cli/commands/integration-pack.doc.mjsindex 77120fe33e..460b36f719 100644--- a/packages/cli/clients/cli/commands/integration-pack.doc.mjs+++ b/packages/cli/clients/cli/commands/integration-pack.doc.mjs@@ -5,7 +5,7 @@ export const doc = {type: 'command',name: 'integration pack',displayName: 'astryx integration pack',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Prove the packed integration is what consumers receive',description:'Runs the package lifecycle, packs with npm, checks every required contribution file against the real tarball, extracts it into a scratch consumer, and compares the local and packed contribution inventories through one shared contract.',diff --git a/packages/cli/clients/cli/commands/integration-real-world.test.mjs b/packages/cli/clients/cli/commands/integration-real-world.test.mjsindex a730cb0042..4f5a887246 100644--- a/packages/cli/clients/cli/commands/integration-real-world.test.mjs+++ b/packages/cli/clients/cli/commands/integration-real-world.test.mjs@@ -201,13 +201,6 @@ export const oceanTheme = defineTheme({});`,);- const catalogFile = path.join(providerDir, 'themes', 'manifest.json');- const catalog = JSON.parse(fs.readFileSync(catalogFile, 'utf-8'));- catalog.themes[0].files.push(- 'tokens/ocean.palette.ts',- 'tokens/ocean.palette.receipt.json',- );- writeJson(catalogFile, catalog);const providerPackage = JSON.parse(fs.readFileSync(path.join(providerDir, 'package.json'), 'utf-8'),@@ -464,8 +457,9 @@ export const oceanTheme = defineTheme({outputDir: target,files: ['oceanTheme.ts',- 'tokens/ocean.palette.ts',+ 'oceanTheme.doc.mjs','tokens/ocean.palette.receipt.json',+ 'tokens/ocean.palette.ts',],},});@@ -612,7 +606,7 @@ export const oceanTheme = defineTheme({expect(corruptedInstall.status).not.toBe(0);expect(parseEnvelope(corruptedInstall.stdout)).toMatchObject({code: 'ERR_THEME_INVALID',- error: expect.stringContaining('ocean.palette.ts'),+ error: expect.stringContaining('./tokens/ocean.palette'),});}, 120_000);});diff --git a/packages/cli/clients/cli/commands/integration.doc.mjs b/packages/cli/clients/cli/commands/integration.doc.mjsindex 681c9199f8..d7eec724ad 100644--- a/packages/cli/clients/cli/commands/integration.doc.mjs+++ b/packages/cli/clients/cli/commands/integration.doc.mjs@@ -5,7 +5,7 @@ export const doc = {type: 'command',name: 'integration',displayName: 'astryx integration',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Author and verify an Astryx integration package',description:'Add contributions that are valid on arrival, then prove the packed package exposes the same contributions a consumer will receive.',diff --git a/packages/cli/clients/cli/commands/layout-check.doc.mjs b/packages/cli/clients/cli/commands/layout-check.doc.mjsindex 600b7790bf..c21672548d 100644--- a/packages/cli/clients/cli/commands/layout-check.doc.mjs+++ b/packages/cli/clients/cli/commands/layout-check.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'layout check',displayName: 'astryx layout check',- namespace: 'cli',+ namespace: 'cli/commands',summary:'Validate a layout expression and echo canonical compact/outline forms',description:diff --git a/packages/cli/clients/cli/commands/layout-expand.doc.mjs b/packages/cli/clients/cli/commands/layout-expand.doc.mjsindex d01035e929..d164e43160 100644--- a/packages/cli/clients/cli/commands/layout-expand.doc.mjs+++ b/packages/cli/clients/cli/commands/layout-expand.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'layout expand',displayName: 'astryx layout expand',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Expand a layout expression into validated XDS TSX',description:'Parses and validates a compressed XLE/XLO expression, then expands it into ' +diff --git a/packages/cli/clients/cli/commands/layout-grammar.doc.mjs b/packages/cli/clients/cli/commands/layout-grammar.doc.mjsindex 5b4ec7a50c..ea056e75e2 100644--- a/packages/cli/clients/cli/commands/layout-grammar.doc.mjs+++ b/packages/cli/clients/cli/commands/layout-grammar.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'layout grammar',displayName: 'astryx layout grammar',- namespace: 'cli',+ namespace: 'cli/commands',summary:'Print the XLE/XLO cheatsheet (alias table generated from this branch)',description:diff --git a/packages/cli/clients/cli/commands/layout.doc.mjs b/packages/cli/clients/cli/commands/layout.doc.mjsindex 64fb9d8ae1..2ee3ba0ab2 100644--- a/packages/cli/clients/cli/commands/layout.doc.mjs+++ b/packages/cli/clients/cli/commands/layout.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'layout',displayName: 'astryx layout',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Generate XDS layouts from compressed expressions (XLE/XLO)',description:'The layout command group. Running astryx layout with no subcommand prints the ' +diff --git a/packages/cli/clients/cli/commands/manifest.doc.mjs b/packages/cli/clients/cli/commands/manifest.doc.mjsindex d4b6477eec..99f1c6c630 100644--- a/packages/cli/clients/cli/commands/manifest.doc.mjs+++ b/packages/cli/clients/cli/commands/manifest.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'manifest',displayName: 'astryx manifest',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Print the full CLI capability manifest (use with --json).',description:'Emits the complete CLI surface: every command with its arguments, options, ' +diff --git a/packages/cli/clients/cli/commands/search.doc.mjs b/packages/cli/clients/cli/commands/search.doc.mjsindex ff46f6c32e..e567f5b9b6 100644--- a/packages/cli/clients/cli/commands/search.doc.mjs+++ b/packages/cli/clients/cli/commands/search.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'search',displayName: 'astryx search',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Search components, hooks, docs, and templates in one ranked list',description:'Terminal front-end to search(): prints one ranked, greppable list across ' +diff --git a/packages/cli/clients/cli/commands/swizzle.doc.mjs b/packages/cli/clients/cli/commands/swizzle.doc.mjsindex 0a5c8a606f..f324b811a4 100644--- a/packages/cli/clients/cli/commands/swizzle.doc.mjs+++ b/packages/cli/clients/cli/commands/swizzle.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'swizzle',displayName: 'astryx swizzle',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Copy component source for customization',description:"Ejects a component's source from the resolved @astryxdesign/core (or its owning " +diff --git a/packages/cli/clients/cli/commands/template.doc.mjs b/packages/cli/clients/cli/commands/template.doc.mjsindex f13d8697b5..b843f80797 100644--- a/packages/cli/clients/cli/commands/template.doc.mjs+++ b/packages/cli/clients/cli/commands/template.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'template',displayName: 'astryx template',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Inject a page or block template',description:'One entry point for the template family: with no name it lists the discovered ' +diff --git a/packages/cli/clients/cli/commands/theme-add.doc.mjs b/packages/cli/clients/cli/commands/theme-add.doc.mjsindex 62d6d58ee1..ff0afae2fb 100644--- a/packages/cli/clients/cli/commands/theme-add.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-add.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'theme add',displayName: 'astryx theme add',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Scaffold a theme into your project as editable source',description:"Copies a bundled or installed integration theme's source into your project so you own it. " +@@ -49,7 +49,7 @@ export const doc = {{code: 0, when: 'success'},{code: 1,- when: 'unknown or ambiguous theme, a path escape, a missing catalog file, or an existing file without --overwrite',+ when: 'unknown or ambiguous theme, a path escape, a missing descriptor or source, or an existing file without --overwrite',},],related: ['theme list', 'theme build'],diff --git a/packages/cli/clients/cli/commands/theme-build.doc.mjs b/packages/cli/clients/cli/commands/theme-build.doc.mjsindex 27de8b3e5c..d008038fd4 100644--- a/packages/cli/clients/cli/commands/theme-build.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-build.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'theme build',displayName: 'astryx theme build',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Compile standalone themes or one keyed theme family',description:'Compiles defineTheme() sources through the same theme pipeline into scoped CSS, ' +diff --git a/packages/cli/clients/cli/commands/theme-list.doc.mjs b/packages/cli/clients/cli/commands/theme-list.doc.mjsindex 7d67e0f503..949ddb49e6 100644--- a/packages/cli/clients/cli/commands/theme-list.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-list.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'theme list',displayName: 'astryx theme list',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'List themes available to add',description:'Lists themes bundled with this CLI and source themes contributed by installed integrations, ' +@@ -37,7 +37,7 @@ export const doc = {{code: 0, when: 'success'},{code: 1,- when: 'the bundled-theme manifest or an installed theme catalog cannot be read',+ when: 'a bundled or installed theme descriptor cannot be read',},],related: ['theme add', 'theme build'],diff --git a/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs b/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjsindex ec492a1dcb..bcbeecc4f0 100644--- a/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs@@ -5,7 +5,7 @@ export const doc = {type: 'command',name: 'theme palette generate',displayName: 'astryx theme palette generate',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Generate an OKLCH palette candidate for human review',description:'Reads an explicit JSON request and runs the versioned astryx-oklch-v1 recipe. ' +@@ -21,8 +21,8 @@ export const doc = {'JSON is also supported. Existing author-owned files are left untouched unless --overwrite is explicit. ' +'When used in a theme integration, keep the palette request under the theme slug, ' +'write the candidate and receipt under that same slug, import the candidate from the theme source, ' +- "and list all three paths in the theme catalog entry's `files` array " +- 'so `astryx theme add` copies them into the consumer project.',+ 'and keep all three inside the theme directory: `astryx theme add` copies that whole ' ++ 'directory into the consumer project, so nothing else has to list them.',fn: 'themePaletteGenerate',args: [{name: 'config', param: 'configPath', required: true}],options: [diff --git a/packages/cli/clients/cli/commands/theme-palette.doc.mjs b/packages/cli/clients/cli/commands/theme-palette.doc.mjsindex e88366d299..2ed11b54a9 100644--- a/packages/cli/clients/cli/commands/theme-palette.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-palette.doc.mjs@@ -5,7 +5,7 @@ export const doc = {type: 'command',name: 'theme palette',displayName: 'astryx theme palette',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Create and work with theme-owned color palettes',description:'Palette authoring tools. The initial generate command creates reviewable candidates. ' +diff --git a/packages/cli/clients/cli/commands/theme-targets.doc.mjs b/packages/cli/clients/cli/commands/theme-targets.doc.mjsindex d8670b2f1e..0bc5ef2a55 100644--- a/packages/cli/clients/cli/commands/theme-targets.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-targets.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'theme targets',displayName: 'astryx theme targets',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'List the component theming targets a theme can override',description:'Prints every `defineTheme` components key across the system: the stable class it paints, ' +diff --git a/packages/cli/clients/cli/commands/theme-template.doc.mjs b/packages/cli/clients/cli/commands/theme-template.doc.mjsindex 57189ffabd..67889d8ec6 100644--- a/packages/cli/clients/cli/commands/theme-template.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-template.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'command',name: 'theme template',displayName: 'astryx theme template',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Write the annotated theme template into your project',description:'Writes theme.template.ts: the annotated reference for the whole theme surface, covering every ' +diff --git a/packages/cli/clients/cli/commands/theme.doc.mjs b/packages/cli/clients/cli/commands/theme.doc.mjsindex bfbda085e9..476b04c606 100644--- a/packages/cli/clients/cli/commands/theme.doc.mjs+++ b/packages/cli/clients/cli/commands/theme.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'theme',displayName: 'astryx theme',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Theme tools: build, export, and manage themes',description:'The theme command group. Running astryx theme with no subcommand prints the ' +diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjsindex 49c0a9958f..1c42c9b623 100644--- a/packages/cli/clients/cli/commands/upgrade.doc.mjs+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'command',name: 'upgrade',displayName: 'astryx upgrade',- namespace: 'cli',+ namespace: 'cli/commands',summary: 'Migrate versions and update ShadCN-copied compositions',description:'Migrates project source from a previous Astryx version to the installed one by ' +diff --git a/packages/cli/clients/cli/lib/hook-format.mjs b/packages/cli/clients/cli/lib/hook-format.mjsindex 540f24a20c..491579d3c1 100644--- a/packages/cli/clients/cli/lib/hook-format.mjs+++ b/packages/cli/clients/cli/lib/hook-format.mjs@@ -9,7 +9,10 @@* - Brief: signature line with import hint, description, key params*/-import {discoverHooks, findHookDoc} from '../../../foundation/discovery/hook-discovery.mjs';+import {+ discoverHooks,+ findHookDoc,+} from '../../../foundation/discovery/hook-discovery.mjs';import {loadDocs} from '../../../foundation/discovery/component-loader.mjs';import {formatAccessibility, mdCell} from './component-format.mjs';@@ -23,7 +26,9 @@ function buildSignature(docs) {const name = docs.name;// Build params string — only top-level params (skip options.foo nested params)- const topParams = (docs.params || []).filter((/** @type {any} */ p) => !p.name.includes('.'));+ const topParams = (docs.params || []).filter(+ (/** @type {any} */ p) => !p.name.includes('.'),+ );const paramStr = topParams.map((/** @type {any} */ p) => {const opt = p.required ? '' : '?';@@ -150,7 +155,9 @@ export function formatHookCompact(docs, importPath) {const imp = importPath || docs.importPath;if (imp) {sections.push('## Import\n');- sections.push(`\`\`\`tsx\nimport { ${docs.name} } from '${imp}';\n\`\`\`\n`);+ sections.push(+ `\`\`\`tsx\nimport { ${docs.name} } from '${imp}';\n\`\`\`\n`,+ );}// Best Practices (matches component compact)@@ -228,7 +235,9 @@ export function formatHookBrief(docs) {// Key params (matches component brief 'prop, prop' line)const paramNames = (docs.params || []).filter((/** @type {any} */ p) => !p.name.includes('.'))- .map((/** @type {any} */ p) => p.required ? `${p.name}: ${p.type.split('|')[0].trim()}` : p.name);+ .map((/** @type {any} */ p) =>+ p.required ? `${p.name}: ${p.type.split('|')[0].trim()}` : p.name,+ );if (paramNames.length > 0) {output.push(` ${paramNames.join(', ')}`);}@@ -253,7 +262,7 @@ export async function formatHookBriefAll(coreDir) {const docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- const docs = await loadDocs(docPath);+ const docs = await loadDocs(docPath, {root: 'hooks'});output.push(formatHookBrief(docs));} catch {output.push(`${hookName}\n (no docs)\n`);diff --git a/packages/cli/foundation/config/project-themes.test.mjs b/packages/cli/foundation/config/project-themes.test.mjsindex 310bbefe6f..de024a2c40 100644--- a/packages/cli/foundation/config/project-themes.test.mjs+++ b/packages/cli/foundation/config/project-themes.test.mjs@@ -15,6 +15,7 @@ function installThemeIntegration(packageName, slug) {...packageName.split('/'),);const themeDir = path.join(packageDir, 'themes', slug);+ const stem = `${slug.replace(/-([a-z0-9])/gu, (_, character) => character.toUpperCase())}Theme`;fs.mkdirSync(themeDir, {recursive: true});fs.writeFileSync(path.join(packageDir, 'package.json'),@@ -22,28 +23,19 @@ function installThemeIntegration(packageName, slug) {);fs.writeFileSync(path.join(packageDir, 'astryx.integration.mjs'),- `export default {themes: './themes'};\n`,+ `export default {themes: './themes'};+`,);fs.writeFileSync(- path.join(packageDir, 'themes', 'manifest.json'),- JSON.stringify({- version: 1,- themes: [- {- slug,- displayName: 'Ocean',- description: 'Blue and calm.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts'],- },- ],- }),+ path.join(themeDir, `${stem}.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {type: 'theme', name: '${slug}', displayName: 'Ocean', description: 'Blue and calm.', maintained: true};+`,);fs.writeFileSync(- path.join(themeDir, 'oceanTheme.ts'),- `export const oceanTheme = {};\n`,+ path.join(themeDir, `${stem}.ts`),+ `export const ${stem} = {};+`,);}@@ -99,7 +91,7 @@ describe('Project themes', () => {]);});- it('records an invalid integration theme catalog as an issue', async () => {+ it('records an invalid integration theme descriptor as an issue', async () => {installThemeIntegration('@acme/themes', 'ocean');fs.rmSync(path.join(diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 980d8771ca..8da8794695 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -15,7 +15,9 @@* async). It does what loadConfig did — find the config sibling-of* package.json, import + validate it, load the configured integrations —* plus autolink the installed ones no config names, and self-resolve the- * package being authored when it carries a manifest. Discovery is LAZY.+ * package being authored when it carries a manifest. Provider identity is+ * resolved once over all three (see integrations/provider-resolution), and+ * the ledger is kept for {@link providerLedgerOf}. Discovery is LAZY.* - Discovery methods (components/templates/codemods/docs/themes) are MEMOIZED per* instance (via the pluggable cache) and orchestrate the EXISTING discovery* functions — Project never reimplements discovery.@@ -38,10 +40,10 @@ import {parseConfig} from '../../authoring/config/parse.mjs';import {loadIntegrations,loadLocalIntegration,- markProviderConflicts,resolvePackageDir,} from '../integrations/integrations.mjs';-import {autolinkIntegrations} from '../integrations/autolink.mjs';+import {loadAutolinkCandidates} from '../integrations/autolink.mjs';+import {resolveProviders} from '../integrations/provider-resolution.mjs';import {setProject as setDebugProject,setEventHandler as setDebugEventHandler,@@ -297,6 +299,24 @@ export function findConfigPath(startDir = process.cwd()) {return present.length === 1 ? present[0] : null;}+/**+ * The provider ledger each loaded Project resolved, kept off the class so it+ * is not part of the Project API.+ * @type {WeakMap<Project, import('../integrations/provider-resolution.mjs').ProviderLedger>}+ */+const PROVIDER_LEDGERS = new WeakMap();++/**+ * The provider ledger a Project resolved at load: one outcome for every+ * package directory configured, autolinked, or authored. Internal: upgrade+ * resolves on top of it, and tests account for every candidate with it.+ * @param {Project} project+ * @returns {import('../integrations/provider-resolution.mjs').ProviderLedger}+ */+export function providerLedgerOf(project) {+ return PROVIDER_LEDGERS.get(project) ?? new Map();+}+/*** The single API for reading resolved project configuration. Construct via the* async {@link Project.load} factory.@@ -402,17 +422,14 @@ export class Project {// This runs whether or not a config exists, because the projects it reaches// are overwhelmingly the ones with no astryx.config at all: a scaffold adds// the dependency and writes no config, and the integration then contributes- // nothing for want of a line nobody knew to write. Appended AFTER the+ // nothing for want of a line nobody knew to write. Resolved AFTER the// configured ones so an explicit entry keeps its position and its// precedence in every discovery order.- loadedIntegrations = [- ...loadedIntegrations,- ...(await autolinkIntegrations({- projectDir,- loaded: loadedIntegrations,- fresh,- })),- ];+ const autolinked = await loadAutolinkCandidates({+ projectDir,+ loaded: loadedIntegrations,+ fresh,+ });// The package being authored is the one package that cannot install itself.// When it carries a manifest, resolve its working bytes directly so every@@ -420,17 +437,27 @@ export class Project {// replaces the same installed package in place, preserving configured// precedence while making the source being edited authoritative.const localIntegration = await loadLocalIntegrationSafely(projectDir, fresh);- if (localIntegration) {- const existing = loadedIntegrations.findIndex(- integration => integration.name === localIntegration.name,- );- if (existing === -1) loadedIntegrations.push(localIntegration);- else loadedIntegrations[existing] = localIntegration;- }// Autolinked and local packages can claim a provider ID that a configured// package already holds, so identity is resolved once over the final set.- loadedIntegrations = markProviderConflicts(loadedIntegrations);+ const resolution = resolveProviders([+ ...loadedIntegrations.map(integration => ({+ source: /** @type {const} */ ('configured'),+ integration,+ spec: integration.__spec,+ })),+ ...autolinked,+ ...(localIntegration+ ? [+ {+ source: /** @type {const} */ ('local'),+ integration: localIntegration,+ spec: localIntegration.__spec,+ },+ ]+ : []),+ ]);+ loadedIntegrations = resolution.integrations;// The debug recorder resolves its settings synchronously, long before any// command gets here, so this is where a project's `debug` block gets a@@ -461,7 +488,7 @@ export class Project {// Never let recording break config loading.}- return new Project({+ const project = new Project({cwd,configPath,config,@@ -470,6 +497,8 @@ export class Project {cache: resolvedCache,hash,});+ PROVIDER_LEDGERS.set(project, resolution.ledger);+ return project;}/**diff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjsindex 98abe649ed..fabe68d597 100644--- a/packages/cli/foundation/config/project.test.mjs+++ b/packages/cli/foundation/config/project.test.mjs@@ -163,7 +163,7 @@ function scaffoldLocalPackage({name = '@acme/local'} = {}) {fs.mkdirSync(path.join(tmpDir, 'templates'));fs.writeFileSync(- path.join(tmpDir, 'templates', 'local-page.template.mjs'),+ path.join(tmpDir, 'templates', 'local-page.doc.mjs'),`export default {type: 'page', name: 'Local page', description: 'Local page.'};\n`,);fs.writeFileSync(@@ -181,21 +181,8 @@ function scaffoldLocalPackage({name = '@acme/local'} = {}) {fs.mkdirSync(path.join(tmpDir, 'themes', 'ocean'), {recursive: true});fs.writeFileSync(- path.join(tmpDir, 'themes', 'manifest.json'),- JSON.stringify({- version: 1,- themes: [- {- slug: 'ocean',- displayName: 'Ocean',- description: 'Ocean theme.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts'],- },- ],- }),+ path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.doc.mjs'),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Ocean theme.', maintained: true};\n`,);fs.writeFileSync(path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),diff --git a/packages/cli/foundation/discovery/authoring-self-docs.mjs b/packages/cli/foundation/discovery/authoring-self-docs.mjsindex 43f1aa22ef..543cfa1603 100644--- a/packages/cli/foundation/discovery/authoring-self-docs.mjs+++ b/packages/cli/foundation/discovery/authoring-self-docs.mjs@@ -17,8 +17,8 @@import * as fs from 'node:fs';import * as path from 'node:path';-import {pathToFileURL} from 'node:url';import {CLI_ROOT} from '../fs/paths.mjs';+import {readDocView} from '../doc-compiler/read.mjs';import {DOC_OUTPUT_BUDGET_BYTES,oversizedDocSections,@@ -31,6 +31,8 @@ export const AUTHORING_ROOT = path.join(CLI_ROOT, 'authoring');export const AUTHORING_SELF_DOCS = ['integration/integration.doc.mjs','config/config.doc.mjs',+ 'debug/debug.doc.mjs',+ 'gap-report/gap-report.doc.mjs','codemod/codemod.doc.mjs','identity/identity.doc.mjs','doctypes/base/graph-fields.doc.mjs',@@ -43,6 +45,7 @@ export const AUTHORING_SELF_DOCS = ['doctypes/reference/reference.doc.mjs','doctypes/schema/schema.doc.mjs','doctypes/template/template.doc.mjs',+ 'doctypes/theme/theme.doc.mjs',];/** Blocks a self-doc note may carry that a topic section can render. */@@ -59,7 +62,8 @@ export function discoverAuthoringSelfDocSources(root = AUTHORING_ROOT) {/** @param {string} dir */const walk = dir => {for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {- if (entry.name === 'node_modules' || entry.name.startsWith('__')) continue;+ if (entry.name === 'node_modules' || entry.name.startsWith('__'))+ continue;const full = path.join(dir, entry.name);if (entry.isDirectory()) walk(full);else if (entry.name.endsWith('.doc.mjs')) {@@ -86,9 +90,14 @@ export async function loadAuthoringSelfDocs(const failed = [];for (const source of sources) {try {- const mod = await import(pathToFileURL(path.join(root, source)).href);- const doc = mod.doc ?? mod.docs ?? mod.default;- if (typeof doc?.name !== 'string' || typeof doc?.description !== 'string') {+ const doc = await readDocView(path.join(root, source), {+ root: 'self-docs',+ loader: 'native',+ });+ if (+ typeof doc?.name !== 'string' ||+ typeof doc?.description !== 'string'+ ) {throw new Error('exports no doc with a name and a description');}loaded.push({source, doc});@@ -129,7 +138,7 @@ function fieldRows(fields) {* @param {any} doc* @returns {import('../../authoring/doctypes/reference/type').ReferenceSection}*/-function selfDocSection(doc) {+export function selfDocSection(doc) {/** @type {any[]} */const content = [{type: 'prose', text: doc.description}];if (doc.appliesTo) {@@ -144,7 +153,8 @@ function selfDocSection(doc) {});}for (const example of doc.examples ?? []) {- if (typeof example?.code !== 'string' || example.code.trim() === '') continue;+ if (typeof example?.code !== 'string' || example.code.trim() === '')+ continue;content.push({type: 'code',lang: example.lang ?? 'js',diff --git a/packages/cli/foundation/discovery/authoring-surface.mjs b/packages/cli/foundation/discovery/authoring-surface.mjsnew file mode 100644index 0000000000..a63108cdfb--- /dev/null+++ b/packages/cli/foundation/discovery/authoring-surface.mjs@@ -0,0 +1,525 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The public type surface of `@astryxdesign/cli/authoring`, and whether+ * a reader of `astryx docs authoring` can reach the doc for each type in it.+ *+ * @input authoring/index.d.ts and the type modules it re-exports, parsed with+ * jscodeshift and never imported or type-checked (consumer installs have no+ * TypeScript); the self-docs on disk and in AUTHORING_SELF_DOCS; and the+ * section keys `astryx docs authoring --index` lists.+ * @output {@link tracePublicAuthoringTypes}: each exported type and the module+ * that declares it. {@link auditAuthoringSurface}: each module whose exported+ * types a reader cannot reach and why, each export that cannot be traced,+ * and each registered self-doc that documents nothing the surface exports.+ * @position Read by Doctor's authoring-docs check. A type's doc is the self-doc+ * beside the module that declares it, so a new public type needs a+ * `*.doc.mjs` in its folder, listed in AUTHORING_SELF_DOCS. The barrel's+ * parsers read those types and are not a shape anyone writes, so they need+ * no section of their own.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import jscodeshift from 'jscodeshift';+import {+ AUTHORING_ROOT,+ AUTHORING_SELF_DOCS,+ buildAuthoringReferenceDoc,+ discoverAuthoringSelfDocSources,+ loadAuthoringSelfDocs,+} from './authoring-self-docs.mjs';+import {sectionKey} from './docs-section-key.mjs';++const j = jscodeshift.withParser('ts');++/** The barrel the `types` condition of `@astryxdesign/cli/authoring` names. */+export const AUTHORING_SURFACE = 'index.d.ts';++/** Modules read by parsing. Anything else is runtime JavaScript. */+const TYPE_MODULE_RE = /\.(?:ts|tsx|mts|cts)$/u;++/** A title only a declaration of that name can match. */+const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/u;++/**+ * @typedef {object} Tracer+ * @property {string} root+ * @property {Map<string, any[]>} parsed top-level statements by absolute path+ */++/**+ * @typedef {'no-self-doc' | 'unregistered' | 'failed' | 'missing-section'} UnreadableReason+ */++/**+ * @param {string} root+ * @param {string} file+ * @returns {string} `file` relative to `root`, with `/` separators+ */+function relative(root, file) {+ return path.relative(root, file).split(path.sep).join('/');+}++/**+ * @param {string} source a `/`-separated path relative to the root+ * @returns {string}+ */+function folderOf(source) {+ return path.posix.dirname(source);+}++/** @param {any} node @returns {string | undefined} */+function nameOf(node) {+ return node?.name ?? node?.value;+}++/**+ * Names a top-level statement declares, exported or not.+ * @param {any} node+ * @returns {string[]}+ */+function declaredNames(node) {+ if (node?.type === 'VariableDeclaration') {+ return node.declarations.flatMap((/** @type {any} */ d) =>+ d.id?.type === 'Identifier' ? [d.id.name] : [],+ );+ }+ return node?.id?.type === 'Identifier' ? [node.id.name] : [];+}++/**+ * @param {Tracer} t+ * @param {string} file+ * @returns {any[]}+ */+function statementsOf(t, file) {+ let body = t.parsed.get(file);+ if (!body) {+ try {+ body = j(fs.readFileSync(file, 'utf8')).get().node.program.body;+ } catch (error) {+ throw new Error(+ `${relative(t.root, file)} could not be parsed: ${error instanceof Error ? error.message : String(error)}`,+ {cause: error},+ );+ }+ t.parsed.set(/** @type {string} */ (file), /** @type {any[]} */ (body));+ }+ return /** @type {any[]} */ (body);+}++/**+ * The file a relative specifier names, resolved as TypeScript resolves an ESM+ * import in a type module: `./x.js` is `./x.ts` when that exists.+ * @param {Tracer} t+ * @param {string} from absolute path of the importing module+ * @param {string} specifier+ * @returns {string} absolute path+ * @throws {Error} for a bare specifier, one that leaves the root, or one that+ * names no file+ */+function resolveModule(t, from, specifier) {+ const base = path.resolve(path.dirname(from), specifier);+ const inside = relative(t.root, base);+ const candidates = !specifier.startsWith('.')+ ? []+ : inside === '..' || inside.startsWith('../') || path.isAbsolute(inside)+ ? []+ : /\.js$/u.test(base)+ ? [base.replace(/\.js$/u, '.ts'), base.replace(/\.js$/u, '.d.ts'), base]+ : /\.[cm]js$/u.test(base) || TYPE_MODULE_RE.test(base)+ ? [base]+ : [+ `${base}.ts`,+ `${base}.d.ts`,+ path.join(base, 'index.ts'),+ path.join(base, 'index.d.ts'),+ ];+ const found = candidates.find(file => {+ try {+ return fs.statSync(file).isFile();+ } catch {+ return false;+ }+ });+ if (found == null) {+ throw new Error(+ `${relative(t.root, from)} names "${specifier}", which is not a file in ${path.basename(t.root)}/`,+ );+ }+ return found;+}++/**+ * The module that declares what `file` exports as `name`, following+ * re-exports. A JavaScript module declares what it exports (its JSDoc+ * typedefs included), so a trace stops there.+ * @param {Tracer} t+ * @param {string} file+ * @param {string} name+ * @param {Set<string>} [seen] `file\0name` pairs already on this trace+ * @returns {string | null} absolute path, or null when `file` does not export+ * `name`+ */+function declaringModule(t, file, name, seen = new Set()) {+ if (!TYPE_MODULE_RE.test(file)) return file;+ const visit = `${file}\u0000${name}`;+ if (seen.has(visit)) return null;+ seen.add(visit);+ const body = statementsOf(t, file);+ for (const statement of body) {+ if (+ statement.type === 'ExportNamedDeclaration' &&+ declaredNames(statement.declaration).includes(name)+ ) {+ return file;+ }+ }+ for (const statement of body) {+ if (statement.type !== 'ExportNamedDeclaration' || statement.declaration)+ continue;+ for (const specifier of statement.specifiers ?? []) {+ if (nameOf(specifier.exported) !== name) continue;+ const source = statement.source?.value;+ if (specifier.type === 'ExportNamespaceSpecifier') {+ return resolveModule(t, file, source);+ }+ const local = nameOf(specifier.local) ?? name;+ const found =+ source == null+ ? localBinding(t, file, body, local, seen)+ : declaringModule(t, resolveModule(t, file, source), local, seen);+ if (found == null) {+ throw new Error(+ `${relative(t.root, file)} exports ${name}${source == null ? '' : ` from "${source}"`}, which does not declare it`,+ );+ }+ return found;+ }+ }+ for (const statement of body) {+ if (statement.type !== 'ExportAllDeclaration') continue;+ const from = resolveModule(t, file, statement.source.value);+ if (statement.exported != null) {+ if (nameOf(statement.exported) === name) return from;+ continue;+ }+ // What a JavaScript module exports cannot be listed by parsing, so a star+ // through one never answers for a type.+ if (!TYPE_MODULE_RE.test(from)) continue;+ const found = declaringModule(t, from, name, seen);+ if (found != null) return found;+ }+ return null;+}++/**+ * The module that declares a binding local to `file`: `file` itself, or the+ * one its import of that name traces to.+ * @param {Tracer} t+ * @param {string} file+ * @param {any[]} body+ * @param {string} local+ * @param {Set<string>} seen+ * @returns {string | null}+ */+function localBinding(t, file, body, local, seen) {+ for (const statement of body) {+ const declared =+ statement.type === 'ExportNamedDeclaration'+ ? statement.declaration+ : statement;+ if (declaredNames(declared).includes(local)) return file;+ if (statement.type !== 'ImportDeclaration') continue;+ for (const specifier of statement.specifiers ?? []) {+ if (nameOf(specifier.local) !== local) continue;+ const from = resolveModule(t, file, statement.source.value);+ if (specifier.type === 'ImportNamespaceSpecifier') return from;+ const imported =+ specifier.type === 'ImportDefaultSpecifier'+ ? 'default'+ : (nameOf(specifier.imported) ?? local);+ return declaringModule(t, from, imported, seen);+ }+ }+ return null;+}++/**+ * Every name a type module exports, stars included.+ * @param {Tracer} t+ * @param {string} file+ * @param {Set<string>} [seen]+ * @returns {string[]}+ * @throws {Error} when a star passes through a JavaScript module, whose types+ * cannot be listed by parsing+ */+function exportedNames(t, file, seen = new Set()) {+ /** @type {Set<string>} */+ const names = new Set();+ if (seen.has(file)) return [];+ seen.add(file);+ for (const statement of statementsOf(t, file)) {+ if (statement.type === 'ExportNamedDeclaration') {+ for (const name of declaredNames(statement.declaration)) names.add(name);+ for (const specifier of statement.specifiers ?? []) {+ const name = nameOf(specifier.exported);+ if (name != null) names.add(name);+ }+ } else if (statement.type === 'ExportAllDeclaration') {+ const from = resolveModule(t, file, statement.source.value);+ if (statement.exported != null) {+ const name = nameOf(statement.exported);+ if (name != null) names.add(name);+ } else if (TYPE_MODULE_RE.test(from)) {+ for (const name of exportedNames(t, from, seen)) {+ if (name !== 'default') names.add(name);+ }+ } else {+ throw new Error(+ `${relative(t.root, file)} re-exports every type of "${statement.source.value}", a JavaScript module whose types cannot be listed`,+ );+ }+ }+ }+ return [...names];+}++/**+ * Every type `@astryxdesign/cli/authoring` exports, in the order index.d.ts+ * lists them, each traced to the module that declares it. A value export that+ * traces to a JavaScript module (a parser) is not a type and is left out;+ * anything else that cannot be traced is reported, never dropped.+ * @param {string} [root]+ * @returns {{+ * types: {name: string, module: string}[],+ * untraced: {name: string, reason: string}[],+ * }} `module` is relative to `root`+ */+export function tracePublicAuthoringTypes(root = AUTHORING_ROOT) {+ return traceSurface({root, parsed: new Map()});+}++/**+ * @param {Tracer} t+ * @returns {ReturnType<typeof tracePublicAuthoringTypes>}+ */+function traceSurface(t) {+ const surface = path.join(t.root, AUTHORING_SURFACE);+ /** @type {{name: string, module: string}[]} */+ const types = [];+ /** @type {{name: string, reason: string}[]} */+ const untraced = [];+ /**+ * @param {string} name+ * @param {() => string | null} trace+ * @param {boolean} typeOnly exported with `export type`+ */+ const add = (name, trace, typeOnly) => {+ let module;+ try {+ module = trace();+ } catch (error) {+ untraced.push({+ name,+ reason: error instanceof Error ? error.message : String(error),+ });+ return;+ }+ if (module == null) {+ untraced.push({+ name,+ reason: `${AUTHORING_SURFACE} exports it, but no module declares it`,+ });+ } else if (typeOnly || TYPE_MODULE_RE.test(module)) {+ types.push({name, module: relative(t.root, module)});+ }+ };++ for (const statement of statementsOf(t, surface)) {+ const typeOnly = statement.exportKind === 'type';+ if (statement.type === 'ExportNamedDeclaration') {+ for (const name of declaredNames(statement.declaration)) {+ add(name, () => surface, true);+ }+ for (const specifier of statement.specifiers ?? []) {+ const name = nameOf(specifier.exported) ?? '(unnamed)';+ add(+ name,+ () => declaringModule(t, surface, name),+ typeOnly || specifier.exportKind === 'type',+ );+ }+ } else if (statement.type === 'ExportAllDeclaration') {+ const source = statement.source.value;+ if (statement.exported != null) {+ const name = nameOf(statement.exported) ?? '(unnamed)';+ add(name, () => resolveModule(t, surface, source), typeOnly);+ continue;+ }+ let names;+ try {+ const from = resolveModule(t, surface, source);+ if (!TYPE_MODULE_RE.test(from)) {+ throw new Error(+ `${AUTHORING_SURFACE} re-exports everything "${source}" exports, and what a JavaScript module exports cannot be listed`,+ );+ }+ names = exportedNames(t, from);+ } catch (error) {+ untraced.push({+ name: `* from "${source}"`,+ reason: error instanceof Error ? error.message : String(error),+ });+ continue;+ }+ for (const name of names) {+ if (name === 'default') continue;+ add(name, () => declaringModule(t, surface, name), typeOnly);+ }+ }+ }+ return {types, untraced};+}++/**+ * Whether an authored type module in `folder` (relative to the root) declares+ * `name`. Declaration files are skipped: beside a self-doc they are generated+ * from the JavaScript next to them, declare no authored type, and use syntax+ * the parser reads only in declaration mode.+ * @param {Tracer} t+ * @param {string} folder+ * @param {string} name+ * @returns {boolean}+ */+function declaredIn(t, folder, name) {+ const dir = path.join(t.root, folder);+ let entries;+ try {+ entries = fs.readdirSync(dir, {withFileTypes: true});+ } catch {+ return false;+ }+ return entries.some(+ entry =>+ entry.isFile() &&+ TYPE_MODULE_RE.test(entry.name) &&+ !/\.d\.[cm]?ts$|\.test\.[cm]?tsx?$/u.test(entry.name) &&+ statementsOf(t, path.join(dir, entry.name)).some(statement =>+ declaredNames(+ statement.type === 'ExportNamedDeclaration'+ ? statement.declaration+ : statement,+ ).includes(name),+ ),+ );+}++/**+ * What stands between each type `@astryxdesign/cli/authoring` exports and a+ * reader of `astryx docs authoring`. A type is readable when a self-doc beside+ * the module that declares it is listed in AUTHORING_SELF_DOCS, loads, and+ * renders a section the topic's index lists. A registered self-doc must+ * document something public: a public type declared beside it, and, when its+ * title is the name of a type declared beside it, that type.+ * @param {{root?: string, sources?: string[], topicKeys?: Set<string> | null}} [options]+ * `topicKeys` are the keys `astryx docs authoring --index` lists; null skips+ * that comparison.+ * @returns {Promise<{+ * types: number,+ * unreadable: {module: string, names: string[], reason: UnreadableReason, source?: string, key?: string}[],+ * untraced: {name: string, reason: string}[],+ * unmatched: {source: string, key?: string, subject?: string}[],+ * }>}+ */+export async function auditAuthoringSurface({+ root = AUTHORING_ROOT,+ sources = AUTHORING_SELF_DOCS,+ topicKeys = null,+} = {}) {+ /** @type {Tracer} */+ const t = {root, parsed: new Map()};+ const {types, untraced} = traceSurface(t);++ /** @type {Map<string, string[]>} folder -> self-docs on disk in it */+ const beside = new Map();+ for (const source of discoverAuthoringSelfDocSources(root)) {+ const folder = folderOf(source);+ beside.set(folder, [...(beside.get(folder) ?? []), source]);+ }+ const registered = new Set(sources);+ const {loaded, failed} = await loadAuthoringSelfDocs(sources, root);+ const failedSources = new Set(failed.map(entry => entry.source));+ const sections = buildAuthoringReferenceDoc(+ loaded.map(entry => entry.doc),+ ).sections;+ /** @type {Map<string, string>} */+ const keyOf = new Map(+ loaded.map((entry, i) => [entry.source, sectionKey(sections[i])]),+ );++ /**+ * @param {string} source+ * @returns {UnreadableReason | null}+ */+ const blocked = source => {+ if (!registered.has(source)) return 'unregistered';+ if (failedSources.has(source) || !keyOf.has(source)) return 'failed';+ const key = /** @type {string} */ (keyOf.get(source));+ return topicKeys != null && !topicKeys.has(key) ? 'missing-section' : null;+ };++ /** @type {Map<string, string[]>} declaring module -> its public types */+ const byModule = new Map();+ for (const {name, module} of types) {+ byModule.set(module, [...(byModule.get(module) ?? []), name]);+ }+ /** @type {{module: string, names: string[], reason: UnreadableReason, source?: string, key?: string}[]} */+ const unreadable = [];+ for (const [module, names] of byModule) {+ const docs = beside.get(folderOf(module)) ?? [];+ if (docs.length === 0) {+ unreadable.push({module, names, reason: 'no-self-doc'});+ continue;+ }+ const reasons = docs.map(blocked);+ if (reasons.includes(null)) continue;+ const source = docs[0];+ const key = keyOf.get(source);+ unreadable.push({+ module,+ names,+ reason: /** @type {UnreadableReason} */ (reasons[0]),+ source,+ ...(key != null ? {key} : {}),+ });+ }++ const publicFolders = new Set(types.map(({module}) => folderOf(module)));+ const publicNames = new Set(types.map(({name}) => name));+ /** @type {Map<string, any>} */+ const docOf = new Map(loaded.map(entry => [entry.source, entry.doc]));+ /** @type {{source: string, key?: string, subject?: string}[]} */+ const unmatched = [];+ for (const source of sources) {+ const key = keyOf.get(source);+ const keyed = key != null ? {key} : {};+ const folder = folderOf(source);+ if (!publicFolders.has(folder)) {+ unmatched.push({source, ...keyed});+ continue;+ }+ const subject = docOf.get(source)?.displayName;+ if (+ typeof subject === 'string' &&+ IDENTIFIER_RE.test(subject) &&+ !publicNames.has(subject) &&+ declaredIn(t, folder, subject)+ ) {+ unmatched.push({source, ...keyed, subject});+ }+ }++ return {types: types.length, unreadable, untraced, unmatched};+}diff --git a/packages/cli/foundation/discovery/authoring-surface.test.mjs b/packages/cli/foundation/discovery/authoring-surface.test.mjsnew file mode 100644index 0000000000..1f20f7e782--- /dev/null+++ b/packages/cli/foundation/discovery/authoring-surface.test.mjs@@ -0,0 +1,392 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated tests for authoring-surface.mjs: every type this repo's+ * `@astryxdesign/cli/authoring` exports traces to a readable self-doc, and+ * each way a type loses its doc, or a self-doc loses its type, is named.+ */++import {afterEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ auditAuthoringSurface,+ tracePublicAuthoringTypes,+} from './authoring-surface.mjs';+import {docs} from '../../api/docs/docs.mjs';++const SLOW = 60_000;++/** @type {string[]} */+const roots = [];+afterEach(() => {+ while (roots.length) {+ fs.rmSync(/** @type {string} */ (roots.pop()), {+ recursive: true,+ force: true,+ });+ }+});++/**+ * A throwaway authoring tree. Kept under the working directory so its+ * self-docs import the way the real ones do.+ * @param {Record<string, string>} files+ * @returns {string}+ */+function tree(files) {+ const root = fs.mkdtempSync(path.join(process.cwd(), '.astryx-surface-'));+ roots.push(root);+ for (const [rel, content] of Object.entries(files)) {+ const abs = path.join(root, rel);+ fs.mkdirSync(path.dirname(abs), {recursive: true});+ fs.writeFileSync(abs, content);+ }+ return root;+}++/**+ * @param {string} name+ * @param {string} [displayName]+ */+const selfDoc = (name, displayName = name) =>+ `export const doc = {type: 'schema', name: '${name}', displayName: '${displayName}', description: 'About ${name}.', fields: []};\n`;++/** One public type with its self-doc beside it. */+const FOO = {+ 'index.d.ts': "export type {FooDoc} from './foo/type.js';\n",+ 'foo/type.ts': 'export interface FooDoc {\n name: string;\n}\n',+ 'foo/foo.doc.mjs': selfDoc('foo-doc', 'FooDoc'),+};++describe('the public authoring surface of this repo', () => {+ it('traces every exported type to the module that declares it, and leaves the parsers out', () => {+ const {types, untraced} = tracePublicAuthoringTypes();+ expect(untraced).toEqual([]);+ const moduleOf = Object.fromEntries(types.map(t => [t.name, t.module]));+ expect(moduleOf).toMatchObject({+ NamespaceDoc: 'doctypes/namespace/type.ts',+ ComponentDoc: 'doctypes/component/type.ts',+ WorkflowDocBlock: 'doctypes/reference/type.ts',+ CollectionDocBlock: 'doctypes/reference/type.ts',+ ReferenceDocBlock: 'doctypes/reference/type.ts',+ AuthoredDocGraphFields: 'doctypes/base/type.ts',+ DocPlacement: 'doctypes/base/type.ts',+ ProviderId: 'identity/type.ts',+ AstryxConfig: 'config/type.ts',+ DebugConfig: 'config/type.ts',+ AstryxIntegration: 'integration/type.ts',+ DebugEvent: 'debug/type.ts',+ GapReportHandler: 'gap-report/type.ts',+ });+ expect(types.filter(t => t.name.startsWith('parse'))).toEqual([]);+ expect(new Set(types.map(t => t.name)).size).toBe(types.length);+ });++ it(+ 'audits clean: every exported type has a readable doc and every self-doc documents one',+ async () => {+ const index = await docs('authoring', undefined, {index: true});+ const topicKeys = new Set(+ index.data.sections.map((/** @type {any} */ s) => s.id),+ );+ expect(await auditAuthoringSurface({topicKeys})).toEqual({+ types: tracePublicAuthoringTypes().types.length,+ unreadable: [],+ untraced: [],+ unmatched: [],+ });+ },+ SLOW,+ );+});++describe('auditAuthoringSurface', () => {+ it('passes a type whose registered self-doc sits beside its module', async () => {+ const root = tree(FOO);+ expect(+ await auditAuthoringSurface({+ root,+ sources: ['foo/foo.doc.mjs'],+ topicKeys: new Set(['foo-doc']),+ }),+ ).toEqual({types: 1, unreadable: [], untraced: [], unmatched: []});+ });++ it('names an exported type with no self-doc beside its module', async () => {+ const root = tree({+ ...FOO,+ 'index.d.ts': `${FOO['index.d.ts']}export type {BarDoc, BarField} from './bar/type.js';\n`,+ 'bar/type.ts':+ 'export interface BarDoc {}\nexport type BarField = string;\n',+ });+ const audit = await auditAuthoringSurface({+ root,+ sources: ['foo/foo.doc.mjs'],+ });+ expect(audit.unreadable).toEqual([+ {+ module: 'bar/type.ts',+ names: ['BarDoc', 'BarField'],+ reason: 'no-self-doc',+ },+ ]);+ });++ it('does not let a self-doc in a parent folder stand in for one beside the module', async () => {+ const root = tree({+ ...FOO,+ 'index.d.ts': `${FOO['index.d.ts']}export type {FooPart} from './foo/part/type.js';\n`,+ 'foo/part/type.ts': 'export interface FooPart {}\n',+ });+ const audit = await auditAuthoringSurface({+ root,+ sources: ['foo/foo.doc.mjs'],+ });+ expect(audit.unreadable).toEqual([+ {module: 'foo/part/type.ts', names: ['FooPart'], reason: 'no-self-doc'},+ ]);+ });++ it('names a self-doc that exists but is not registered', async () => {+ const audit = await auditAuthoringSurface({root: tree(FOO), sources: []});+ expect(audit.unreadable).toEqual([+ {+ module: 'foo/type.ts',+ names: ['FooDoc'],+ reason: 'unregistered',+ source: 'foo/foo.doc.mjs',+ },+ ]);+ });++ it('names a registered self-doc that does not load', async () => {+ const root = tree({...FOO, 'foo/foo.doc.mjs': 'export const doc = {;\n'});+ const audit = await auditAuthoringSurface({+ root,+ sources: ['foo/foo.doc.mjs'],+ });+ expect(audit.unreadable).toEqual([+ {+ module: 'foo/type.ts',+ names: ['FooDoc'],+ reason: 'failed',+ source: 'foo/foo.doc.mjs',+ },+ ]);+ });++ it("names a registered self-doc whose section the topic's index does not list", async () => {+ const audit = await auditAuthoringSurface({+ root: tree(FOO),+ sources: ['foo/foo.doc.mjs'],+ topicKeys: new Set(['something-else']),+ });+ expect(audit.unreadable).toEqual([+ {+ module: 'foo/type.ts',+ names: ['FooDoc'],+ reason: 'missing-section',+ source: 'foo/foo.doc.mjs',+ key: 'foo-doc',+ },+ ]);+ });++ it('names a registered self-doc that documents no exported type', async () => {+ const root = tree({+ ...FOO,+ 'bar/type.ts': 'export interface BarDoc {}\n',+ 'bar/bar.doc.mjs': selfDoc('bar-doc', 'BarDoc'),+ 'notes/notes.doc.mjs': selfDoc('notes', 'Notes'),+ });+ const audit = await auditAuthoringSurface({+ root,+ sources: ['foo/foo.doc.mjs', 'bar/bar.doc.mjs', 'notes/notes.doc.mjs'],+ });+ expect(audit.unmatched).toEqual([+ {source: 'bar/bar.doc.mjs', key: 'bar-doc'},+ {source: 'notes/notes.doc.mjs', key: 'notes'},+ ]);+ expect(audit.unreadable).toEqual([]);+ });++ it('names a self-doc titled after a type beside it that the surface does not export', async () => {+ const root = tree({+ ...FOO,+ 'index.d.ts': "export type {FooField} from './foo/type.js';\n",+ 'foo/type.ts':+ 'export interface FooDoc {}\nexport type FooField = string;\n',+ // What the declaration build writes beside a JavaScript module.+ 'foo/foo.doc.d.mts': 'export const doc: {\n name: string;\n};\n',+ });+ const audit = await auditAuthoringSurface({+ root,+ sources: ['foo/foo.doc.mjs'],+ });+ expect(audit.unmatched).toEqual([+ {source: 'foo/foo.doc.mjs', key: 'foo-doc', subject: 'FooDoc'},+ ]);+ });++ it('does not treat a title that is no declared name as a subject', async () => {+ const root = tree({+ ...FOO,+ 'foo/foo.doc.mjs': selfDoc('foo', 'Foo Doc'),+ });+ const audit = await auditAuthoringSurface({+ root,+ sources: ['foo/foo.doc.mjs'],+ });+ expect(audit.unmatched).toEqual([]);+ });++ it('follows named, renamed, star, and imported re-exports to the declaring module', () => {+ const root = tree({+ 'index.d.ts': [+ "export type {A, B as Bee} from './barrel.js';",+ "import type {C} from './c/type.js';",+ 'export type {C};',+ "export type * from './d/type.js';",+ "export type * as E from './e/type.js';",+ '',+ ].join('\n'),+ 'barrel.ts':+ "export type * from './a/type.js';\nexport type {B} from './b/type.js';\n",+ 'a/type.ts': 'export interface A {}\n',+ 'b/type.ts': 'export type B = number;\n',+ 'c/type.ts': 'export interface C {}\n',+ 'd/type.ts': 'export interface D1 {}\nexport type D2 = D1[];\n',+ 'e/type.ts': 'export interface E1 {}\n',+ });+ expect(tracePublicAuthoringTypes(root)).toEqual({+ types: [+ {name: 'A', module: 'a/type.ts'},+ {name: 'Bee', module: 'b/type.ts'},+ {name: 'C', module: 'c/type.ts'},+ {name: 'D1', module: 'd/type.ts'},+ {name: 'D2', module: 'd/type.ts'},+ {name: 'E', module: 'e/type.ts'},+ ],+ untraced: [],+ });+ });++ it('leaves out a value exported from a JavaScript module, and keeps a value-style export of a type', () => {+ const root = tree({+ 'index.d.ts':+ "export {parseFoo} from './foo/parse.mjs';\nexport {FooDoc} from './foo/type.js';\nexport type {FooShape} from './foo/parse.mjs';\n",+ 'foo/type.ts': 'export interface FooDoc {}\n',+ 'foo/parse.mjs': 'export function parseFoo(x) {\n return x;\n}\n',+ });+ expect(tracePublicAuthoringTypes(root)).toEqual({+ types: [+ {name: 'FooDoc', module: 'foo/type.ts'},+ {name: 'FooShape', module: 'foo/parse.mjs'},+ ],+ untraced: [],+ });+ });++ it('reports an export it cannot trace instead of dropping it', () => {+ const root = path.join(+ tree({+ 'authoring/index.d.ts': [+ "export type {Ghost} from './foo/type.js';",+ "export type {Lost} from './nowhere/type.js';",+ "export type {Outside} from '../elsewhere/type.js';",+ "export * from './foo/parse.mjs';",+ "export type * from './barrel.js';",+ "export type {Loop} from './loop-a.js';",+ '',+ ].join('\n'),+ 'authoring/foo/type.ts': 'export interface FooDoc {}\n',+ 'authoring/foo/parse.mjs': 'export const parseFoo = x => x;\n',+ 'authoring/barrel.ts': "export * from './foo/parse.mjs';\n",+ 'authoring/loop-a.ts': "export type {Loop} from './loop-b.js';\n",+ 'authoring/loop-b.ts': "export type {Loop} from './loop-a.js';\n",+ 'elsewhere/type.ts': 'export interface Outside {}\n',+ }),+ 'authoring',+ );+ const {types, untraced} = tracePublicAuthoringTypes(root);+ expect(types).toEqual([]);+ expect(untraced).toEqual([+ {+ name: 'Ghost',+ reason:+ 'index.d.ts exports Ghost from "./foo/type.js", which does not declare it',+ },+ {+ name: 'Lost',+ reason:+ 'index.d.ts names "./nowhere/type.js", which is not a file in authoring/',+ },+ {+ name: 'Outside',+ reason:+ 'index.d.ts names "../elsewhere/type.js", which is not a file in authoring/',+ },+ {+ name: '* from "./foo/parse.mjs"',+ reason:+ 'index.d.ts re-exports everything "./foo/parse.mjs" exports, and what a JavaScript module exports cannot be listed',+ },+ {+ name: '* from "./barrel.js"',+ reason:+ 'barrel.ts re-exports every type of "./foo/parse.mjs", a JavaScript module whose types cannot be listed',+ },+ {+ name: 'Loop',+ reason:+ 'loop-b.ts exports Loop from "./loop-a.js", which does not declare it',+ },+ ]);+ });++ it('gives a type declared in index.d.ts itself no doc, since nothing sits beside the barrel', async () => {+ const root = tree({'index.d.ts': 'export interface Loose {}\n'});+ const audit = await auditAuthoringSurface({root, sources: []});+ expect(audit.unreadable).toEqual([+ {module: 'index.d.ts', names: ['Loose'], reason: 'no-self-doc'},+ ]);+ });++ it('never executes a module it traces through', async () => {+ const marker = path.join(+ process.cwd(),+ `.astryx-surface-ran-${process.pid}`,+ );+ const root = tree({+ ...FOO,+ 'index.d.ts': `${FOO['index.d.ts']}export {parseFoo} from './foo/parse.mjs';\nexport type {Shape} from './foo/shape.mjs';\n`,+ 'foo/parse.mjs': `import * as fs from 'node:fs';\nfs.writeFileSync(${JSON.stringify(marker)}, 'ran');\nexport const parseFoo = x => x;\n`,+ 'foo/shape.mjs': `import * as fs from 'node:fs';\nfs.writeFileSync(${JSON.stringify(marker)}, 'ran');\n`,+ });+ const before = listTree(root);+ await auditAuthoringSurface({root, sources: ['foo/foo.doc.mjs']});+ expect(fs.existsSync(marker)).toBe(false);+ expect(listTree(root)).toEqual(before);+ });+});++/**+ * Every file under `root` with its contents, to prove a read left it alone.+ * @param {string} root+ * @returns {Record<string, string>}+ */+function listTree(root) {+ /** @type {Record<string, string>} */+ const out = {};+ /** @param {string} dir */+ const walk = dir => {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else out[path.relative(root, full)] = fs.readFileSync(full, 'utf8');+ }+ };+ walk(root);+ return out;+}diff --git a/packages/cli/foundation/discovery/cli-self-docs.mjs b/packages/cli/foundation/discovery/cli-self-docs.mjsnew file mode 100644index 0000000000..ab4b3a6d9a--- /dev/null+++ b/packages/cli/foundation/discovery/cli-self-docs.mjs@@ -0,0 +1,514 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The CLI's own docs, read by their `namespace`: every command, API+ * function, schema, and enum doc the CLI ships says which `astryx docs` topic+ * reads it, and the `cli` topic is built from the ones that name it.+ *+ * @input The command, function, schema, and enum docs under+ * clients/cli/commands, api, authoring, and foundation.+ * @output {@link buildCliTopic} for `astryx docs cli`, and+ * {@link auditCliSelfDocs}, which `astryx doctor` runs.+ * @position foundation/discovery — the reader for docs whose namespace starts+ * with `cli/`. The authoring topic reads the `authoring` namespace from its+ * own list (authoring-self-docs.mjs).+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {CLI_ROOT} from '../fs/paths.mjs';+import {readDocView} from '../doc-compiler/read.mjs';+import {AUTHORING_SELF_DOCS, selfDocSection} from './authoring-self-docs.mjs';+import {+ DOC_OUTPUT_BUDGET_BYTES,+ oversizedDocSections,+} from './docs-output-budget.mjs';+import {sectionKeyProblems} from './docs-section-key.mjs';++/** The directories, relative to the CLI root, that hold the CLI's own docs. */+export const CLI_SELF_DOC_DIRS = [+ 'clients/cli/commands',+ 'api',+ 'authoring',+ 'foundation',+];++/** The doc kinds that declare a namespace. */+const NAMESPACED_KINDS = new Set(['command', 'function', 'schema', 'enum']);++/**+ * Every namespace a CLI doc may declare, and the topic that reads it. A doc in+ * a `cli/` namespace is the section `<key prefix>-<name>` of `astryx docs cli`;+ * a doc in `authoring` is a section of `astryx docs authoring`.+ * @type {Record<string, {topic: string, keyPrefix?: string}>}+ */+export const CLI_DOC_NAMESPACES = {+ 'cli/commands': {topic: 'cli', keyPrefix: 'commands'},+ 'cli/api': {topic: 'cli', keyPrefix: 'api'},+ authoring: {topic: 'authoring'},+};++/** Blocks a doc's notes may carry that a topic section can render. */+const TOPIC_BLOCKS = new Set(['prose', 'list', 'code', 'heading', 'table']);++/** Section order within the `cli` topic: commands, then the API by kind. */+const KIND_ORDER = ['command', 'function', 'schema', 'enum'];++/**+ * Every `*.doc.mjs` under the CLI's doc directories, relative to `root` and+ * sorted. Fixture, test, and dependency directories are skipped.+ * @param {string} [root]+ * @returns {string[]}+ */+export function discoverCliSelfDocSources(root = CLI_ROOT) {+ /** @type {string[]} */+ const found = [];+ /** @param {string} dir */+ const walk = dir => {+ if (!fs.existsSync(dir)) return;+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ if (+ entry.name === 'node_modules' ||+ entry.name.startsWith('__') ||+ entry.name.startsWith('.')+ ) {+ continue;+ }+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else if (entry.name.endsWith('.doc.mjs')) {+ found.push(path.relative(root, full).split(path.sep).join('/'));+ }+ }+ };+ for (const dir of CLI_SELF_DOC_DIRS) walk(path.join(root, dir));+ return found.sort();+}++/**+ * Read each doc through the compiler and keep the kinds that declare a+ * namespace. One that fails is reported, never thrown, so one bad file cannot+ * take the rest of the topic down with it.+ * @param {string[]} [sources]+ * @param {string} [root]+ * @returns {Promise<{loaded: {source: string, doc: any}[], failed: {source: string, error: string}[]}>}+ */+export async function loadCliSelfDocs(+ sources = discoverCliSelfDocSources(),+ root = CLI_ROOT,+) {+ const loaded = [];+ const failed = [];+ for (const source of sources) {+ try {+ const doc = await readDocView(path.join(root, source), {+ root: 'self-docs',+ loader: 'native',+ });+ if (!NAMESPACED_KINDS.has(doc?.type)) continue;+ if (typeof doc.name !== 'string' || doc.name === '') {+ throw new Error('exports no doc with a name');+ }+ loaded.push({source, doc});+ } catch (error) {+ failed.push({+ source,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ return {loaded, failed};+}++/**+ * A name as a section-key segment: lowercase words joined by hyphens.+ * `integrationPackCheck` and `integration pack` both read naturally.+ * @param {string} name+ * @returns {string}+ */+export function keySegment(name) {+ return name+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+}++/**+ * The section key a doc is read by in `astryx docs cli`, or null when its+ * namespace is not one of the topic's.+ * @param {any} doc+ * @returns {string | null}+ */+export function cliSectionKey(doc) {+ const prefix = CLI_DOC_NAMESPACES[doc?.namespace]?.keyPrefix;+ if (prefix == null) return null;+ return `${prefix}-${keySegment(String(doc.name))}`;+}++/** @param {unknown} value */+function defaultText(value) {+ if (value === undefined || value === false || value === '') return null;+ if (Array.isArray(value)) return value.length > 0 ? value.join(' ') : null;+ return String(value);+}++/**+ * @param {any} cmd+ * @returns {string}+ */+function usage(cmd) {+ const args = (cmd.args ?? []).map((/** @type {any} */ arg) => {+ const name = arg.variadic ? `${arg.name}...` : arg.name;+ return arg.required ? `<${name}>` : `[${name}]`;+ });+ return ['astryx', cmd.name, ...args].join(' ');+}++/**+ * The text for a command option or argument: its own, or else the text of the+ * API parameter it maps to, as `--help` shows.+ * @param {{description?: string, param?: string}} entry+ * @param {any} fn the FunctionDoc the command calls, if any+ * @returns {string}+ */+function entryText(entry, fn) {+ if (typeof entry.description === 'string' && entry.description !== '') {+ return entry.description;+ }+ const param = (fn?.params ?? []).find(+ (/** @type {any} */ p) => p.name === entry.param,+ );+ return typeof param?.description === 'string' ? param.description : '';+}++/**+ * `text`, ending in a full stop when more text follows it in the same cell.+ * @param {string} text+ * @param {boolean} more+ */+function sentence(text, more) {+ return more && text !== '' && !/[.!?:]$/.test(text) ? `${text}.` : text;+}++/** @param {any[]} notes */+function noteBlocks(notes) {+ return (notes ?? []).filter(note => TOPIC_BLOCKS.has(note?.type));+}++/**+ * One command doc as a section of `astryx docs cli`.+ * @param {any} cmd+ * @param {{functions: Map<string, any>, commands: Set<string>}} index+ */+function commandSection(cmd, index) {+ const fn = cmd.fn == null ? undefined : index.functions.get(cmd.fn);+ /** @type {any[]} */+ const content = [{type: 'prose', text: cmd.summary}];+ if (cmd.description) content.push({type: 'prose', text: cmd.description});+ content.push({type: 'code', lang: 'bash', code: usage(cmd)});+ const args = cmd.args ?? [];+ if (args.length > 0) {+ content.push({+ type: 'table',+ headers: ['Argument', 'Description'],+ rows: args.map((/** @type {any} */ arg) => [+ `\`${arg.name}\``,+ entryText(arg, fn),+ ]),+ });+ }+ const options = cmd.options ?? [];+ if (options.length > 0) {+ content.push({+ type: 'table',+ headers: ['Option', 'Description'],+ rows: options.map((/** @type {any} */ option) => {+ const extra = [+ option.choices?.length+ ? `One of: ${option.choices.map((/** @type {string} */ c) => `\`${c}\``).join(', ')}.`+ : null,+ defaultText(option.default) == null+ ? null+ : `Default: \`${defaultText(option.default)}\`.`,+ ].filter(Boolean);+ return [+ `\`${option.flag}\``,+ [sentence(entryText(option, fn), extra.length > 0), ...extra]+ .filter(Boolean)+ .join(' '),+ ];+ }),+ });+ }+ const examples = (cmd.examples ?? []).flatMap((/** @type {any} */ e) =>+ e.label ? [`# ${e.label}`, e.cli] : [e.cli],+ );+ if (examples.length > 0) {+ content.push({type: 'code', lang: 'bash', code: examples.join('\n')});+ }+ const exitCodes = cmd.exitCodes ?? [];+ if (exitCodes.length > 0) {+ content.push({+ type: 'table',+ headers: ['Exit code', 'When'],+ rows: exitCodes.map((/** @type {any} */ e) => [String(e.code), e.when]),+ });+ }+ const subcommands = (cmd.subcommands ?? []).filter(+ (/** @type {string} */ sub) => index.commands.has(`${cmd.name} ${sub}`),+ );+ if (subcommands.length > 0) {+ content.push({+ type: 'list',+ style: 'unordered',+ items: subcommands.map(+ (/** @type {string} */ sub) =>+ `\`astryx ${cmd.name} ${sub}\`: \`astryx docs cli commands-${keySegment(`${cmd.name} ${sub}`)}\``,+ ),+ });+ }+ if (fn != null) {+ content.push({+ type: 'prose',+ text: `It runs \`${fn.name}()\` from \`${fn.importPath}\`. Read it with \`astryx docs cli ${cliSectionKey(fn)}\`.`,+ });+ }+ content.push(...noteBlocks(cmd.notes));+ return {+ id: cliSectionKey(cmd),+ title: cmd.displayName ?? `astryx ${cmd.name}`,+ content,+ };+}++/**+ * One API function doc as a section of `astryx docs cli`.+ * @param {any} fn+ * @param {{functions: Map<string, any>, commands: Set<string>}} index+ */+function functionSection(fn, index) {+ /** @type {any[]} */+ const content = [{type: 'prose', text: fn.summary ?? fn.description ?? ''}];+ if (fn.summary && fn.description) {+ content.push({type: 'prose', text: fn.description});+ }+ if (fn.signature) {+ content.push({type: 'code', lang: 'ts', code: fn.signature});+ }+ if (fn.importPath) {+ content.push({type: 'prose', text: `Import it from \`${fn.importPath}\`.`});+ }+ const params = fn.params ?? [];+ if (params.length > 0) {+ content.push({+ type: 'table',+ headers: ['Parameter', 'Type', 'Description'],+ rows: params.map((/** @type {any} */ p) => [+ `\`${p.name}\``,+ `\`${p.type ?? ''}\``,+ p.description ?? '',+ ]),+ });+ }+ const returns = fn.returns ?? [];+ if (returns.length > 0) {+ content.push({+ type: 'table',+ headers: ['Returns', 'Description'],+ rows: returns.map((/** @type {any} */ r) => [+ `\`${r.name ? `${r.name}: ` : ''}${r.type}\``,+ r.description ?? '',+ ]),+ });+ }+ const throws = fn.throws ?? [];+ if (throws.length > 0) {+ content.push({+ type: 'table',+ headers: ['Throws', 'When'],+ rows: throws.map((/** @type {any} */ t) => [`\`${t.code}\``, t.when]),+ });+ }+ for (const example of fn.examples ?? []) {+ if (typeof example?.code !== 'string' || example.code.trim() === '') {+ continue;+ }+ content.push({+ type: 'code',+ lang: 'ts',+ ...(example.label ? {label: example.label} : {}),+ code: example.code,+ });+ }+ if (fn.command != null && index.commands.has(fn.command)) {+ content.push({+ type: 'prose',+ text: `\`astryx ${fn.command}\` runs it. Read it with \`astryx docs cli commands-${keySegment(fn.command)}\`.`,+ });+ }+ return {+ id: cliSectionKey(fn),+ title: fn.displayName ?? `${fn.name}()`,+ content,+ };+}++/**+ * One enum doc as a section of `astryx docs cli`.+ * @param {any} doc+ */+function enumSection(doc) {+ return {+ id: cliSectionKey(doc),+ title: doc.displayName ?? doc.name,+ content: [+ {type: 'prose', text: doc.description},+ {+ type: 'table',+ headers: ['Value', 'Meaning'],+ rows: (doc.members ?? []).map((/** @type {any} */ m) => [+ `\`${m.value}\``,+ m.deprecated+ ? `${m.description} Deprecated: ${m.deprecated}`+ : m.description,+ ]),+ },+ ],+ };+}++/**+ * The docs a `cli/` namespace names, in reading order: commands by name (a+ * group before its subcommands), then API functions, schemas, and enums.+ * @param {any[]} docs+ * @returns {any[]}+ */+function cliDocsInOrder(docs) {+ return docs+ .filter(doc => CLI_DOC_NAMESPACES[doc.namespace]?.topic === 'cli')+ .sort(+ (a, b) =>+ KIND_ORDER.indexOf(a.type) - KIND_ORDER.indexOf(b.type) ||+ (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),+ );+}++/**+ * The `cli` topic: one section per doc whose namespace is `cli/…`.+ * @param {any[]} docs every loaded CLI doc; the ones in other namespaces are+ * left out+ * @returns {import('../../authoring/doctypes/reference/type').ReferenceDoc}+ */+export function buildCliReferenceDoc(docs) {+ const ordered = cliDocsInOrder(docs);+ const index = {+ functions: new Map(+ ordered.filter(d => d.type === 'function').map(d => [d.name, d]),+ ),+ commands: new Set(+ ordered.filter(d => d.type === 'command').map(d => d.name),+ ),+ };+ return /** @type {any} */ ({+ name: 'cli',+ title: 'CLI Reference',+ category: 'guide',+ description:+ 'Every command and API function of the CLI, with the JSON output envelope, error codes, and response types, read from the docs the CLI ships.',+ sections: ordered.map(doc =>+ doc.type === 'command'+ ? commandSection(doc, index)+ : doc.type === 'function'+ ? functionSection(doc, index)+ : doc.type === 'enum'+ ? enumSection(doc)+ : {...selfDocSection(doc), id: cliSectionKey(doc)},+ ),+ });+}++/**+ * The `cli` topic from every CLI doc that loads. One that fails is left out+ * here and reported by {@link auditCliSelfDocs}.+ * @returns {Promise<import('../../authoring/doctypes/reference/type').ReferenceDoc>}+ */+export async function buildCliTopic() {+ const {loaded} = await loadCliSelfDocs();+ return buildCliReferenceDoc(loaded.map(entry => entry.doc));+}++/**+ * What stands between a CLI doc and a reader: a missing namespace, one no+ * topic reads, one that disagrees with the authoring topic's list, a doc that+ * fails to load, and a `cli` section that clashes or is too large.+ * @param {{root?: string, sources?: string[], budget?: number, authoringSources?: string[]}} [options]+ * @returns {Promise<{+ * docs: number,+ * sections: number,+ * authoring: number,+ * missing: string[],+ * unknown: {source: string, namespace: string}[],+ * misfiled: {source: string, message: string}[],+ * failed: {source: string, error: string}[],+ * keyProblems: string[],+ * oversized: {key: string, title: string, bytes: number}[],+ * }>}+ */+export async function auditCliSelfDocs({+ root = CLI_ROOT,+ sources,+ budget = DOC_OUTPUT_BUDGET_BYTES,+ authoringSources = AUTHORING_SELF_DOCS,+} = {}) {+ const {loaded, failed} = await loadCliSelfDocs(+ sources ?? discoverCliSelfDocSources(root),+ root,+ );+ const listed = new Set(authoringSources.map(source => `authoring/${source}`));+ /** @type {string[]} */+ const missing = [];+ /** @type {{source: string, namespace: string}[]} */+ const unknown = [];+ /** @type {{source: string, message: string}[]} */+ const misfiled = [];+ let authoring = 0;+ for (const {source, doc} of loaded) {+ const namespace = doc.namespace;+ if (typeof namespace !== 'string' || namespace === '') {+ missing.push(source);+ continue;+ }+ if (!Object.hasOwn(CLI_DOC_NAMESPACES, namespace)) {+ unknown.push({source, namespace});+ continue;+ }+ const inAuthoring = listed.has(source);+ if (namespace === 'authoring') {+ if (inAuthoring) authoring++;+ else {+ misfiled.push({+ source,+ message: `${source} has namespace "authoring", but \`astryx docs authoring\` does not list it`,+ });+ }+ } else if (inAuthoring) {+ misfiled.push({+ source,+ message: `${source} is read in \`astryx docs authoring\`, but its namespace is "${namespace}"`,+ });+ }+ }+ const topic = buildCliReferenceDoc(loaded.map(entry => entry.doc));+ return {+ docs: loaded.length,+ sections: topic.sections.length,+ authoring,+ missing,+ unknown,+ misfiled,+ failed,+ keyProblems: sectionKeyProblems(topic.sections),+ oversized: oversizedDocSections(topic.sections, budget),+ };+}diff --git a/packages/cli/foundation/discovery/cli-self-docs.test.mjs b/packages/cli/foundation/discovery/cli-self-docs.test.mjsnew file mode 100644index 0000000000..90994dcd15--- /dev/null+++ b/packages/cli/foundation/discovery/cli-self-docs.test.mjs@@ -0,0 +1,437 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tests for the CLI docs reader. Every command, API function, schema, and+ * enum doc this package ships is readable in the topic its namespace names.+ * Each way one can fail to be is reported: no namespace, a namespace no topic+ * reads, a clash with the authoring topic's list, a doc that does not load, and+ * two `cli` sections with one key.+ *+ * @input This package's own docs, and fixture doc trees written under the+ * working directory.+ * @output Assertions on the audit, the `cli` topic, and reads through `docs()`.+ * @position packages/cli/foundation/discovery — tests for cli-self-docs.mjs.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {afterAll, describe, expect, it} from 'vitest';+import {+ CLI_DOC_NAMESPACES,+ auditCliSelfDocs,+ buildCliReferenceDoc,+ buildCliTopic,+ cliSectionKey,+ discoverCliSelfDocSources,+ keySegment,+ loadCliSelfDocs,+} from './cli-self-docs.mjs';+import * as api from '../../api/index.mjs';++const SLOW = 60_000;++/** @type {string[]} */+const tmpRoots = [];+afterAll(() => {+ for (const root of tmpRoots) fs.rmSync(root, {recursive: true, force: true});+});++/** Write `files` (relative path -> content) under a fresh directory. */+function writeTree(/** @type {Record<string, string>} */ files) {+ const root = fs.mkdtempSync(path.join(process.cwd(), '.astryx-cli-docs-'));+ tmpRoots.push(root);+ for (const [rel, content] of Object.entries(files)) {+ const file = path.join(root, rel);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, content);+ }+ return root;+}++const docModule = (/** @type {any} */ doc) =>+ `export const doc = ${JSON.stringify(doc, null, 2)};\n`;++const command = (/** @type {string} */ name, extra = {}) => ({+ type: 'command',+ name,+ displayName: `astryx ${name}`,+ namespace: 'cli/commands',+ summary: `Do ${name}`,+ ...extra,+});++const fn = (/** @type {string} */ name, extra = {}) => ({+ type: 'function',+ kind: 'api',+ name,+ displayName: `${name}()`,+ namespace: 'cli/api',+ summary: `The ${name} function.`,+ importPath: '@astryxdesign/cli/api',+ params: [],+ returns: [{type: name, description: 'The result.'}],+ ...extra,+});++const enumDoc = (/** @type {string} */ name, extra = {}) => ({+ type: 'enum',+ name,+ displayName: name,+ namespace: 'cli/api',+ description: `The ${name}.`,+ members: [{value: 'A', description: 'The a.'}],+ ...extra,+});++const schema = (/** @type {string} */ name, extra = {}) => ({+ type: 'schema',+ name,+ displayName: name,+ namespace: 'authoring',+ description: `The ${name} file.`,+ fields: [{name: 'x', type: 'string', description: 'The x.'}],+ ...extra,+});++/** Audit a fixture tree with nothing in the authoring topic's list. */+const audit = (/** @type {string} */ root, authoringSources = []) =>+ auditCliSelfDocs({root, authoringSources});++describe('the CLI docs this package ships', () => {+ it(+ 'each declare a namespace a topic reads, and none fails, clashes, or overflows',+ async () => {+ const result = await auditCliSelfDocs();+ expect({+ missing: result.missing,+ unknown: result.unknown,+ misfiled: result.misfiled,+ failed: result.failed,+ keyProblems: result.keyProblems,+ oversized: result.oversized,+ }).toEqual({+ missing: [],+ unknown: [],+ misfiled: [],+ failed: [],+ keyProblems: [],+ oversized: [],+ });+ expect(result.docs).toBeGreaterThan(0);+ expect(result.sections + result.authoring).toBe(result.docs);+ },+ SLOW,+ );++ it(+ 'give every function @astryxdesign/cli/api exports a section of astryx docs cli',+ async () => {+ const topic = await buildCliTopic();+ const keys = new Set(topic.sections.map(section => section.id));+ const exported = Object.entries(api)+ .filter(+ ([, value]) =>+ typeof value === 'function' &&+ Object.getOwnPropertyDescriptor(value, 'prototype')?.writable !==+ false,+ )+ .map(([name]) => `api-${keySegment(name)}`);+ expect(exported.length).toBeGreaterThan(0);+ expect(exported.filter(key => !keys.has(key))).toEqual([]);+ },+ SLOW,+ );++ it(+ 'give every command doc a section, keyed commands-<name>',+ async () => {+ const {loaded} = await loadCliSelfDocs();+ const commands = loaded.filter(({doc}) => doc.type === 'command');+ expect(commands.length).toBeGreaterThan(0);+ const keys = new Set(+ (await buildCliTopic()).sections.map(section => section.id),+ );+ expect(+ commands+ .map(({doc}) => `commands-${keySegment(doc.name)}`)+ .filter(key => !keys.has(key)),+ ).toEqual([]);+ },+ SLOW,+ );++ it(+ 'are read one section at a time through docs()',+ async () => {+ const search = await api.docs('cli', 'api-search');+ expect(search).toMatchObject({type: 'docs.detail.section'});+ expect(JSON.stringify(search.data)).toContain('search()');+ const command = await api.docs('cli', 'commands-integration-add');+ expect(JSON.stringify(command.data)).toContain(+ 'astryx integration add <kind> <name>',+ );+ const codes = await api.docs('cli', 'api-error-codes');+ expect(JSON.stringify(codes.data)).toContain('ERR_UNKNOWN_SECTION');+ const index = await api.docs('cli', undefined, {index: true});+ expect(index.type).toBe('docs.index');+ expect(index.data.sections.length).toBe(+ (await buildCliTopic()).sections.length,+ );+ },+ SLOW,+ );+});++describe('auditCliSelfDocs', () => {+ it('reports a doc with no namespace, and one no topic reads', async () => {+ const root = writeTree({+ 'api/alpha/alpha.doc.mjs': docModule(fn('alpha', {namespace: undefined})),+ 'clients/cli/commands/beta.doc.mjs': docModule(+ command('beta', {namespace: 'cli'}),+ ),+ 'api/gamma/gamma.doc.mjs': docModule(fn('gamma')),+ });+ const result = await audit(root);+ expect(result.missing).toEqual(['api/alpha/alpha.doc.mjs']);+ expect(result.unknown).toEqual([+ {source: 'clients/cli/commands/beta.doc.mjs', namespace: 'cli'},+ ]);+ expect(result.sections).toBe(1);+ });++ it('holds the authoring namespace to the authoring topic list', async () => {+ const root = writeTree({+ 'authoring/x/x.doc.mjs': docModule(schema('x')),+ 'authoring/y/y.doc.mjs': docModule(schema('y', {namespace: 'cli/api'})),+ 'authoring/z/z.doc.mjs': docModule(schema('z')),+ });+ const result = await audit(root, ['y/y.doc.mjs', 'z/z.doc.mjs']);+ expect(result.misfiled.map(entry => entry.message)).toEqual([+ 'authoring/x/x.doc.mjs has namespace "authoring", but `astryx docs authoring` does not list it',+ 'authoring/y/y.doc.mjs is read in `astryx docs authoring`, but its namespace is "cli/api"',+ ]);+ expect(result.authoring).toBe(1);+ });++ it('reports a doc that fails to load, and skips fixture directories', async () => {+ const root = writeTree({+ 'api/bad/bad.doc.mjs': 'throw new Error("boom");\n',+ 'api/__fixtures__/ghost.doc.mjs': docModule(fn('ghost')),+ 'foundation/.hidden/hidden.doc.mjs': docModule(fn('hidden')),+ 'foundation/codes.doc.mjs': docModule(enumDoc('codes')),+ });+ expect(discoverCliSelfDocSources(root)).toEqual([+ 'api/bad/bad.doc.mjs',+ 'foundation/codes.doc.mjs',+ ]);+ const result = await audit(root);+ expect(result.failed).toEqual([+ expect.objectContaining({+ source: 'api/bad/bad.doc.mjs',+ error: expect.stringContaining('boom'),+ }),+ ]);+ expect(result.sections).toBe(1);+ });++ it('reports two cli sections that share a key', async () => {+ const root = writeTree({+ 'api/a/fooBar.doc.mjs': docModule(fn('fooBar')),+ 'api/b/foo_bar.doc.mjs': docModule(fn('foo_bar')),+ });+ const result = await audit(root);+ expect(result.keyProblems).toHaveLength(1);+ expect(result.keyProblems[0]).toContain('api-foo-bar');+ });+});++describe('buildCliReferenceDoc', () => {+ it('keeps a command and the function it runs apart, and links them', () => {+ const topic = buildCliReferenceDoc([+ fn('docs', {command: 'docs'}),+ command('docs', {fn: 'docs'}),+ ]);+ expect(topic.sections.map(s => s.id)).toEqual([+ 'commands-docs',+ 'api-docs',+ ]);+ expect(JSON.stringify(topic.sections[0].content)).toContain(+ 'It runs `docs()` from `@astryxdesign/cli/api`. Read it with `astryx docs cli api-docs`.',+ );+ expect(JSON.stringify(topic.sections[1].content)).toContain(+ '`astryx docs` runs it. Read it with `astryx docs cli commands-docs`.',+ );+ });++ it('renders a command: usage, arguments, options, examples, exit codes, subcommands', () => {+ const topic = buildCliReferenceDoc([+ command('grp', {subcommands: ['sub', 'gone']}),+ command('grp sub', {+ description: 'The long form.',+ fn: 'grpSub',+ args: [+ {name: 'files', required: true, variadic: true, description: 'Files.'},+ ],+ options: [+ {flag: '--fast', description: 'Go fast'},+ {+ flag: '--mode <m>',+ description: 'Mode',+ choices: ['a', 'b'],+ default: 'a',+ },+ {flag: '--limit <n>', param: 'options.limit'},+ {flag: '--dry', description: 'Dry run.', default: false},+ ],+ examples: [+ {label: 'Run it', cli: 'astryx grp sub x'},+ {cli: 'astryx grp sub y'},+ ],+ exitCodes: [{code: 1, when: 'it fails'}],+ }),+ fn('grpSub', {+ params: [{name: 'options.limit', type: 'number', description: 'Max.'}],+ }),+ ]);+ const [group, sub] = topic.sections;+ expect(group.content).toContainEqual({+ type: 'list',+ style: 'unordered',+ items: ['`astryx grp sub`: `astryx docs cli commands-grp-sub`'],+ });+ expect(sub).toMatchObject({id: 'commands-grp-sub', title: 'astryx grp sub'});+ expect(sub.content).toEqual([+ {type: 'prose', text: 'Do grp sub'},+ {type: 'prose', text: 'The long form.'},+ {type: 'code', lang: 'bash', code: 'astryx grp sub <files...>'},+ {+ type: 'table',+ headers: ['Argument', 'Description'],+ rows: [['`files`', 'Files.']],+ },+ {+ type: 'table',+ headers: ['Option', 'Description'],+ rows: [+ ['`--fast`', 'Go fast'],+ ['`--mode <m>`', 'Mode. One of: `a`, `b`. Default: `a`.'],+ ['`--limit <n>`', 'Max.'],+ ['`--dry`', 'Dry run.'],+ ],+ },+ {+ type: 'code',+ lang: 'bash',+ code: '# Run it\nastryx grp sub x\nastryx grp sub y',+ },+ {+ type: 'table',+ headers: ['Exit code', 'When'],+ rows: [['1', 'it fails']],+ },+ {+ type: 'prose',+ text: 'It runs `grpSub()` from `@astryxdesign/cli/api`. Read it with `astryx docs cli api-grp-sub`.',+ },+ ]);+ });++ it('renders an API function and an enum', () => {+ const topic = buildCliReferenceDoc([+ fn('alpha', {+ description: 'Longer.',+ signature: 'alpha(x: string): Promise<Alpha>',+ params: [{name: 'x', type: 'string', description: 'The x.'}],+ throws: [{code: 'ERR_X', when: 'x is bad'}],+ examples: [{label: 'Call it', code: "await alpha('x');"}],+ }),+ enumDoc('codes', {+ members: [+ {value: 'A', description: 'The a.'},+ {value: 'B', description: 'The b.', deprecated: 'Use A.'},+ ],+ }),+ ]);+ expect(topic.sections[0].content).toEqual([+ {type: 'prose', text: 'The alpha function.'},+ {type: 'prose', text: 'Longer.'},+ {type: 'code', lang: 'ts', code: 'alpha(x: string): Promise<Alpha>'},+ {type: 'prose', text: 'Import it from `@astryxdesign/cli/api`.'},+ {+ type: 'table',+ headers: ['Parameter', 'Type', 'Description'],+ rows: [['`x`', '`string`', 'The x.']],+ },+ {+ type: 'table',+ headers: ['Returns', 'Description'],+ rows: [['`alpha`', 'The result.']],+ },+ {+ type: 'table',+ headers: ['Throws', 'When'],+ rows: [['`ERR_X`', 'x is bad']],+ },+ {type: 'code', lang: 'ts', label: 'Call it', code: "await alpha('x');"},+ ]);+ expect(topic.sections[1]).toEqual({+ id: 'api-codes',+ title: 'codes',+ content: [+ {type: 'prose', text: 'The codes.'},+ {+ type: 'table',+ headers: ['Value', 'Meaning'],+ rows: [+ ['`A`', 'The a.'],+ ['`B`', 'The b. Deprecated: Use A.'],+ ],+ },+ ],+ });+ });++ it('orders commands, then functions, schemas, and enums, and leaves other namespaces out', () => {+ const topic = buildCliReferenceDoc([+ enumDoc('codes'),+ schema('output', {namespace: 'cli/api'}),+ fn('beta'),+ schema('config'),+ command('zed'),+ fn('alpha'),+ command('abc'),+ fn('gone', {namespace: 'somewhere'}),+ ]);+ expect(topic.sections.map(s => s.id)).toEqual([+ 'commands-abc',+ 'commands-zed',+ 'api-alpha',+ 'api-beta',+ 'api-output',+ 'api-codes',+ ]);+ });+});++describe('section keys', () => {+ it('join lowercase words with hyphens, whatever the name looks like', () => {+ expect(keySegment('integrationPackCheck')).toBe('integration-pack-check');+ expect(keySegment('doctor integration validate')).toBe(+ 'doctor-integration-validate',+ );+ expect(keySegment('error-codes')).toBe('error-codes');+ expect(keySegment('isError')).toBe('is-error');+ });++ it('come from the namespace a doc declares, and only a cli one', () => {+ expect(cliSectionKey(fn('search'))).toBe('api-search');+ expect(cliSectionKey(command('theme add'))).toBe('commands-theme-add');+ expect(cliSectionKey(schema('config'))).toBeNull();+ expect(cliSectionKey(fn('x', {namespace: 'cli'}))).toBeNull();+ expect(Object.keys(CLI_DOC_NAMESPACES)).toEqual([+ 'cli/commands',+ 'cli/api',+ 'authoring',+ ]);+ });+});diff --git a/packages/cli/foundation/discovery/component-loader.mjs b/packages/cli/foundation/discovery/component-loader.mjsindex 540a1708cd..6e461dda02 100644--- a/packages/cli/foundation/discovery/component-loader.mjs+++ b/packages/cli/foundation/discovery/component-loader.mjs@@ -1,245 +1,76 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Component doc loader — load and merge translations- */--import {pathToFileURL} from 'node:url';-import {importUserModule} from '../fs/module-loader.mjs';-import {parseDoc} from '../../authoring/doctypes/parse.mjs';--/**- * Load a component doc through the shared load/validation boundary.- *- * This is the typed counterpart to {@link loadDocs}: it loads `.doc.ts` via- * jiti (and `.doc.mjs`/`.doc.js` via native import) and validates via- * `parseDoc`, which accepts BOTH formats, so this loader reads whichever the- * file uses:- * - NEW: a stamped default export (`export default {type: 'component', ...}`- * / `'function'` / `'generic'`) — the same single-export convention the- * other authoring parsers use for config/integration/template. These carry- * a stamped `type` and validate against the matching per-kind parser.- * - OLD: the legacy loose `export const docs = {...}` (no `type`), validated- * against the permissive legacy union.- * The default export wins when both are present. Throws a readable- * `formatZodError`-style message on failure. Translations (`docsZh`/- * `docsDense`) are merged exactly as {@link loadDocs} does so callers see- * identical output.+ * @file Component and hook doc loader.*- * @param {string} docPath absolute path to a `.doc.{ts,mjs,js}` file- * @param {{zh?: boolean, dense?: boolean, lang?: string}} [opts]- * @returns {Promise<object>} the validated (and optionally translated) doc+ * @input A component or hook `.doc.{ts,mjs,js}` path and the reading language+ * (`lang`, or the legacy `zh`/`dense` flags).+ * @output The module's own doc, with its translation laid over it for `lang`.+ * @position The loaders every component and hook reader calls. Both read+ * through the doc compiler (foundation/doc-compiler/read.mjs), which lowers+ * the doc on every read. The two differ only in how strict they are:+ * {@link loadComponentDoc} reports a doc that fails its kind's parser, and+ * {@link loadDocs}, which has never checked docs, still reads one.*/-export async function loadComponentDoc(- docPath,- {zh = false, dense = false, lang} = {},-) {- const mod = await importUserModule(docPath);- /** @type {any} */- const authored = mod?.default ?? mod?.docs;-- parseDoc(authored, docPath);- const docs = authored;- const locale = lang || (dense ? 'dense' : zh ? 'zh' : null);- if (!locale) return docs;+import {readDocView} from '../doc-compiler/read.mjs';- const translationKey =- locale === 'zh' ? 'docsZh' : locale === 'dense' ? 'docsDense' : null;- if (!translationKey || !mod[translationKey]) return docs;-- /** @type {any} */- const translation = mod[translationKey];- if (translation.props || translation.components?.some((/** @type {any} */ c) => c.props)) {- return overlayComponentDoc(docs, translation);- }- return mergeTranslation(docs, translation);-}+export {mergeTranslation} from '../doc-compiler/overlays.mjs';/**- * @param {any} docs- * @param {any} translation- * @returns {any}+ * @typedef {object} LoadDocOptions+ * @property {boolean} [zh] legacy flag for `lang: 'zh'`+ * @property {boolean} [dense] legacy flag for `lang: 'dense'`+ * @property {string | null} [lang] wins over the legacy flags+ * @property {'components' | 'hooks'} [root] which root reads the doc+ * (default: components)*/-export function mergeTranslation(docs, translation) {- if (!translation) return docs;-- /** @type {any} */- const merged = {...docs};-- // Merge prose into usage- if (merged.usage) {- merged.usage = {...merged.usage};- if (translation.usage?.description) merged.usage.description = translation.usage.description;- else if (translation.description) merged.usage.description = translation.description;- if (translation.usage?.bestPractices) merged.usage.bestPractices = translation.usage.bestPractices;- if (translation.usage?.accessibility) merged.usage.accessibility = translation.usage.accessibility;- }-- // Legacy top-level fields (for docsZh that are full ComponentDoc clones)- if (translation.description && !merged.usage) merged.description = translation.description;-- // Merge prop descriptions for single-component docs- if (translation.propDescriptions && merged.props) {- merged.props = merged.props.map((/** @type {any} */ prop) => {- const desc = translation.propDescriptions[prop.name];- return desc != null ? {...prop, description: desc} : prop;- });- }-- // Merge hook param descriptions (HookTranslationDoc). Params are an array of- // {name, type, description, required}; override description by name where the- // translation has an entry. Names may include dots (e.g. 'options.isActive');- // the lookup is keyed by the exact param name.- if (translation.paramDescriptions && merged.params) {- merged.params = merged.params.map((/** @type {any} */ param) => {- const desc = translation.paramDescriptions[param.name];- return desc != null ? {...param, description: desc} : param;- });- }-- // Merge hook return descriptions (HookTranslationDoc). Returns are an array- // of {name, type, description}; override description by name where present.- if (translation.returnDescriptions && merged.returns) {- merged.returns = merged.returns.map((/** @type {any} */ ret) => {- const desc = translation.returnDescriptions[ret.name];- return desc != null ? {...ret, description: desc} : ret;- });- }-- // Merge sub-component translations- if (translation.components && merged.components) {- merged.components = merged.components.map((/** @type {any} */ comp, /** @type {any} */ i) => {- const trans = translation.components.find((/** @type {any} */ t) => t.name === comp.name)- || translation.components[i];- if (!trans) return comp;-- const mergedComp = {...comp};- if (trans.description) mergedComp.description = trans.description;- if (trans.propDescriptions && comp.props) {- mergedComp.props = comp.props.map((/** @type {any} */ prop) => {- const desc = trans.propDescriptions[prop.name];- return desc != null ? {...prop, description: desc} : prop;- });- }- return mergedComp;- });- }-- return merged;-}/**- * Load the typed docs object from a .doc.mjs file.- * Supports --lang flag: 'zh' for Chinese, 'dense' for compressed format.- * Also supports legacy --zh and --dense flags.- * Translations are merged onto the base docs, keeping structure intact.- * @param {string} readmePath- * @param {{zh?: boolean, dense?: boolean, lang?: string}} [opts]- * @returns {Promise<any>}+ * The overlay a read applies: `lang`, else the legacy flags.+ * @param {LoadDocOptions} opts+ * @returns {string | null}*/-export async function loadDocs(readmePath, {zh = false, dense = false, lang} = {}) {- const mod = await import(pathToFileURL(readmePath).href);- // Support both the new stamped default export (`export default {type: 'component', …}`)- // and the legacy named export (`export const docs = {…}`). Default wins when both- // are present, matching loadComponentDoc's precedence.- const docs = mod?.default ?? mod.docs;-- // Resolve which translation to use (--lang takes priority over legacy flags)- const locale = lang || (dense ? 'dense' : zh ? 'zh' : null);- if (!locale) return docs;-- const translationKey = locale === 'zh' ? 'docsZh' : locale === 'dense' ? 'docsDense' : null;- if (!translationKey || !mod[translationKey]) return docs;-- const translation = mod[translationKey];-- // A full ComponentDoc-shaped translation (legacy docsZh shape) used to be- // returned wholesale. That made it a REPLACEMENT, not an overlay: any prop- // the translation had not caught up with simply ceased to exist —- // `component Button --zh` silently omitted `isInterruptible` and- // `isIconOnly`. A reader of the translated docs cannot discover a prop that- // is not there. Overlay it instead, so an untranslated prop falls back to- // its English entry. (Same principle as the reference-doc overlays, #2182.)- if (translation.props || translation.components?.some((/** @type {any} */ c) => c.props)) {- return overlayComponentDoc(docs, translation);- }-- // Otherwise it's a ComponentTranslationDoc — merge it onto docs- return mergeTranslation(docs, translation);+function localeOf({zh = false, dense = false, lang} = {}) {+ return lang || (dense ? 'dense' : zh ? 'zh' : null);}/**- * Overlay a full-ComponentDoc-shaped translation onto the English doc.+ * Load a component or hook doc and check it against its kind's parser.*- * Base order and completeness win; the translation supplies text for the- * entries it covers. Props are matched by name, never by position, so a- * translation that is missing entries (or lists them in another order) can no- * longer drop or misattribute one.+ * Reads `.doc.ts` through jiti and `.doc.mjs`/`.doc.js` natively. Both formats+ * load: a stamped default export (`export default {type: 'component', ...}`)+ * checked against its kind, and the legacy `export const docs = {...}` checked+ * against the permissive legacy union. The default export wins when both are+ * present. Throws the parser's readable message when the doc fails.*- * @param {any} docs Base (English) component doc.- * @param {any} translation Translated doc, possibly covering only some props.- * @returns {any} Merged doc with every base prop present.+ * @param {string} docPath absolute path to a `.doc.{ts,mjs,js}` file+ * @param {LoadDocOptions} [opts]+ * @returns {Promise<any>} the checked (and optionally translated) doc*/-function overlayComponentDoc(docs, translation) {- /** Merge one prop list: keep base entries and order, translate what's covered.- * @param {any[] | undefined} baseProps- * @param {any[] | undefined} tProps- */- const overlayProps = (baseProps, tProps) => {- if (!baseProps) return baseProps;- const byName = new Map((tProps ?? []).map((/** @type {any} */ p) => [p.name, p]));- return baseProps.map((/** @type {any} */ prop) => {- const t = byName.get(prop.name);- // Take the translated text, but never let it drop the prop's contract- // (type/default/required stay authoritative from the English doc).- return t ? {...prop, ...t, name: prop.name, type: prop.type} : prop;- });- };-- /** Preserve canonical structured guidance added after legacy full-doc translations,- * without changing established translated prose behavior.- * @param {any} baseUsage- * @param {any} translatedUsage- */- const mergeUsage = (baseUsage, translatedUsage) => {- if (!translatedUsage) return baseUsage;- return {- ...translatedUsage,- ...(translatedUsage.accessibility === undefined &&- baseUsage?.accessibility !== undefined- ? {accessibility: baseUsage.accessibility}- : null),- ...(translatedUsage.accessibilityThemeCoverage === undefined &&- baseUsage?.accessibilityThemeCoverage !== undefined- ? {accessibilityThemeCoverage: baseUsage.accessibilityThemeCoverage}- : null),- ...(translatedUsage.anatomy === undefined && baseUsage?.anatomy !== undefined- ? {anatomy: baseUsage.anatomy}- : null),- };- };-- const merged = {...docs, ...translation, usage: mergeUsage(docs.usage, translation.usage)};-- merged.props = overlayProps(docs.props, translation.props);-- if (docs.components) {- const tByName = new Map(- (translation.components ?? []).map((/** @type {any} */ c) => [c.name, c]),- );- merged.components = docs.components.map((/** @type {any} */ base) => {- const t = tByName.get(base.name);- if (!t) return base;- return {...base, ...t, usage: mergeUsage(base.usage, t.usage), props: overlayProps(base.props, t.props)};- });- }-- return merged;+export async function loadComponentDoc(docPath, opts = {}) {+ return readDocView(docPath, {+ root: opts.root ?? 'components',+ lang: localeOf(opts),+ label: docPath,+ strict: true,+ });}/**- * Find the doc file for a component, checking both top-level- * and nested directories. Prefers {Name}.doc.mjs, then README.md- * (for backward compatibility).+ * Load a component or hook doc without checking it. Supports `lang` ('zh' for+ * Chinese, 'dense' for compressed) and the legacy `zh`/`dense` flags; the+ * translation is laid over the doc, keeping its structure. A file that exports+ * no doc reads as `undefined`.+ * @param {string} readmePath+ * @param {LoadDocOptions} [opts]+ * @returns {Promise<any>}*/+export async function loadDocs(readmePath, opts = {}) {+ return readDocView(readmePath, {+ root: opts.root ?? 'components',+ lang: localeOf(opts),+ label: readmePath,+ loader: 'native',+ });+}diff --git a/packages/cli/foundation/discovery/docs-discovery.mjs b/packages/cli/foundation/discovery/docs-discovery.mjsindex ba6f3bf068..5a4298e57c 100644--- a/packages/cli/foundation/discovery/docs-discovery.mjs+++ b/packages/cli/foundation/discovery/docs-discovery.mjs@@ -32,9 +32,9 @@import * as fs from 'node:fs';import * as path from 'node:path';import {CLI_ROOT} from '../fs/paths.mjs';-import {importUserModule} from '../fs/module-loader.mjs';+import {importDocModule} from '../doc-compiler/import.mjs';import {CLI_PROVIDER_ID} from '../identity/providers.mjs';-import {parseDoc} from '../../authoring/doctypes/parse.mjs';+import {parseReadableDoc} from '../doc-compiler/parse-readable.mjs';import {sectionKey,sectionKeyProblems,@@ -117,7 +117,7 @@ export function discoverBuiltinTopics() {* @returns {Promise<unknown>} the authored doc value*/export async function loadTopicModule(file) {- const mod = await importUserModule(file);+ const mod = await importDocModule(file);const doc = mod?.docs ?? mod?.default;if (doc == null) {throw new Error(@@ -363,7 +363,7 @@ export async function discoverIntegrationDocs(integration) {for (const file of files) {let doc;try {- doc = parseDoc(await loadTopicModule(file), path.basename(file));+ doc = parseReadableDoc(await loadTopicModule(file), path.basename(file));} catch (err) {errors.push(new Error(@@ -423,8 +423,9 @@ export async function discoverIntegrationDocs(integration) {/*** Merge an extension onto a base topic: a section with a stable `id` replaces* the base section with the same `id`; legacy sections without IDs fall back to- * title matching. A section with no match is appended, and title/description- * are taken from the extension when it states them.+ * title matching. A section with no match is appended. The title and+ * description stay the base topic's: an extension adds to a topic, it never+ * renames it. A topic that `replaces` another is the one that renames.** Keyed by section TITLE rather than by position, the way the localization* overlays are — position keying grafts an overlay onto whichever section@@ -451,12 +452,7 @@ export function mergeTopic(base, overlay) {: section;}}- return {- ...base,- title: overlay.title || base.title,- description: overlay.description || base.description,- sections,- };+ return {...base, sections};}/**diff --git a/packages/cli/foundation/discovery/docs-discovery.test.mjs b/packages/cli/foundation/discovery/docs-discovery.test.mjsindex d8e4b9e5c3..d6afccb3b4 100644--- a/packages/cli/foundation/discovery/docs-discovery.test.mjs+++ b/packages/cli/foundation/discovery/docs-discovery.test.mjs@@ -505,11 +505,14 @@ describe('mergeTopic', () => {]);});- it('takes the title and description only when the overlay states them', () => {- expect(mergeTopic(base, {sections: []}).title).toBe('Theme');- expect(mergeTopic(base, {title: 'Theming', sections: []}).title).toBe(- 'Theming',- );+ it('keeps the base title and description: an extension never renames a topic', () => {+ const merged = mergeTopic(base, {+ title: 'Acme theme notes',+ description: 'Our additions.',+ sections: [],+ });+ expect(merged.title).toBe('Theme');+ expect(merged.description).toBe('Theming.');});});diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex 4bab70898b..a63750f27a 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -24,9 +24,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {createRequire} from 'node:module';-import {createJiti} from 'jiti';-import {loadModuleWithParser} from '../fs/module-loader.mjs';-import {parseTemplate} from '../../authoring/doctypes/template/parse.mjs';+import {readDocView} from '../doc-compiler/read.mjs';import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';import {CORE_PROVIDER_ID} from '../identity/providers.mjs';import {Project} from '../config/project.mjs';@@ -84,31 +82,28 @@ export function pkgOf(t) {*//**- * Canonical basename suffixes for template-spec files, in precedence order.- * A template spec is a scaffoldable TEMPLATE (a plain object stamped with a- * `type` of `'page'` or `'block'`), so `.template.*` is the descriptive family- * name.+ * Released compatibility suffixes, in precedence order. Stable 0.6.0+ * documented `.template.*`, so discovery keeps reading those files while all+ * new authoring uses `.doc.mjs`.*/const TEMPLATE_SUFFIXES = ['.template.ts', '.template.mjs', '.template.js'];/**- * Legacy basename suffixes for template-spec files, in precedence order.- * `.doc.*` was inherited from the component-doc convention before templates- * had their own name; it is still accepted during the transition window.+ * Descriptor suffixes for templates, in precedence order. New authoring always+ * emits `.doc.mjs`; the TypeScript and JavaScript variants remain readable.*/const DOC_SUFFIXES = ['.doc.ts', '.doc.mjs', '.doc.js'];/**- * The union of canonical + legacy template-spec suffixes, canonical first so- * `.template.*` wins over `.doc.*` when both stems exist. All template- * discovery matches this union so a `Foo.template.ts` file is treated exactly- * like a legacy `Foo.doc.mjs`.+ * Every template-spec suffix, in the released precedence a core page directory+ * uses to pick one file. Integration discovery never picks: every match is a+ * template, so two specs for one stem list twice and read as ambiguous.*/const ALL_TEMPLATE_SUFFIXES = [...TEMPLATE_SUFFIXES, ...DOC_SUFFIXES];/*** The template-spec suffix present on `file`, or null if none matches.- * Recognizes both the canonical `.template.*` and legacy `.doc.*` families.+ * Recognizes both the canonical `.doc.*` and released `.template.*` families.* @param {string} file* @returns {string | null}*/@@ -122,16 +117,6 @@ function matchedTemplateSuffix(file) {*/const TEMPLATE_SUFFIX_RE = /\.(template|doc)\.(ts|mjs|js)$/;-/** @type {ReturnType<typeof createJiti> | undefined} */-let jitiInstance;-/** Lazily-created jiti for loading `.ts` template specs (JSX-capable). */-function getJiti() {- if (!jitiInstance) {- jitiInstance = createJiti(import.meta.url, {jsx: true});- }- return jitiInstance;-}-/*** Load an integration template doc module and validate it against the template* envelope at the load boundary. Default export only — `.ts` via jiti,@@ -144,7 +129,13 @@ function getJiti() {* @param {string} [label]*/async function loadIntegrationDoc(file, label) {- return loadModuleWithParser(file, parseTemplate, {label});+ return readDocView(file, {+ root: 'templates',+ exports: ['default'],+ label: label ?? file,+ strict: true,+ value: 'parsed',+ });}const TEMPLATES_DIR = path.join(CLI_ROOT, 'assets', 'templates');@@ -492,12 +483,11 @@ function unsafeFixtureReference(source, at, reason) {/*** Load a template-spec module and return its metadata object. Supports both* families of suffix:- * - Legacy `.doc.*` core/external specs export `export const doc = {...}`.- * - Canonical `.template.*` specs export the stamped object (`type: 'page' |- * 'block'`) as the default export.- * Prefers the default export, falling back to the named `doc` export, so a- * `Foo.template.ts` (default export) is read identically to a legacy- * `Foo.doc.mjs` (`doc` export). `.ts` is loaded via jiti; `.mjs`/`.js` via a+ * - Canonical `.doc.*` specs may export the stamped object (`type: 'page' |+ * 'block'`) as the default export or use the historical named `doc` export.+ * - Released `.template.*` compatibility specs use the same object shape.+ * Prefers the default export, falling back to the named `doc` export. `.ts` is+ * loaded via jiti; `.mjs`/`.js` via a* native dynamic import. Returns null if the file does not exist.** @param {string} docPath absolute path to the spec file@@ -505,10 +495,7 @@ function unsafeFixtureReference(source, at, reason) {*/async function loadDocModule(docPath) {if (!fs.existsSync(docPath)) return null;- const docModule = docPath.endsWith('.ts')- ? await getJiti().import(docPath)- : await import(`file://${docPath}`);- return docModule.default ?? docModule.doc;+ return readDocView(docPath, {root: 'templates', loader: 'template'});}/**@@ -553,11 +540,11 @@ function findDocFiles(dir, pattern) {/*** Resolve the template-spec file for a core page directory: the first existing- * `template.<suffix>` in canonical-then-legacy precedence, or null.+ * metadata file in {@link ALL_TEMPLATE_SUFFIXES} precedence, or null.* @param {string} dirPath* @returns {string | null}*/-function findPageDocFile(dirPath) {+export function findPageDocFile(dirPath) {for (const suffix of ALL_TEMPLATE_SUFFIXES) {const candidate = path.join(dirPath, `template${suffix}`);if (fs.existsSync(candidate)) return candidate;@@ -733,7 +720,7 @@ export async function discoverAllWithErrors(cwd = process.cwd()) {/*** Recursively collect integration template-spec files under `root`.* Returns absolute paths to files ending in one of ALL_TEMPLATE_SUFFIXES- * (canonical `.template.*` or legacy `.doc.*`).+ * (canonical `.doc.*` or released `.template.*` compatibility files).** @param {string} root* @returns {string[]}@@ -763,7 +750,7 @@ function findIntegrationDocFiles(root) {* Discover templates contributed by configured integrations.** For each integration with a resolved `templates` root, every- * `<id>.template.{ts,mjs,js}` (or legacy `<id>.doc.{ts,mjs,js}`) file is a+ * canonical `<id>.doc.{mjs,ts,js}` (or released `<id>.template.{ts,mjs,js}`) file is a* template whose id is its path relative to the templates root with the* matched suffix stripped (kebab-case, may be nested). The doc's `type`* (page|block) decides scaffolding — there is no `/pages` vs `/blocks`diff --git a/packages/cli/foundation/discovery/template-adapter.test.mjs b/packages/cli/foundation/discovery/template-adapter.test.mjsindex 592ffe2870..3ff8f69710 100644--- a/packages/cli/foundation/discovery/template-adapter.test.mjs+++ b/packages/cli/foundation/discovery/template-adapter.test.mjs@@ -18,6 +18,7 @@ import * as os from 'node:os';import * as path from 'node:path';import {extractComponents,+ findPageDocFile,stripTemplateAssetRefs,} from './template-adapter.mjs';@@ -164,3 +165,17 @@ describe('stripTemplateAssetRefs', () => {);});});++describe('findPageDocFile', () => {+ it('keeps the released precedence when one page has two specs', () => {+ const page = fs.mkdtempSync(path.join(dir, 'page-'));+ fs.writeFileSync(path.join(page, 'template.doc.mjs'), 'export {};\n');+ fs.writeFileSync(path.join(page, 'template.doc.ts'), 'export {};\n');+ expect(findPageDocFile(page)).toBe(path.join(page, 'template.doc.ts'));++ fs.writeFileSync(path.join(page, 'template.template.mjs'), 'export {};\n');+ expect(findPageDocFile(page)).toBe(+ path.join(page, 'template.template.mjs'),+ );+ });+});diff --git a/packages/cli/foundation/discovery/theme-discovery.mjs b/packages/cli/foundation/discovery/theme-discovery.mjsindex ff1b4feba8..532e70fab1 100644--- a/packages/cli/foundation/discovery/theme-discovery.mjs+++ b/packages/cli/foundation/discovery/theme-discovery.mjs@@ -1,13 +1,15 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Theme catalog discovery shared by Project, theme list/add, and+ * @file Theme descriptor discovery shared by Project, theme list/add, and* integration validation.*- * A theme root uses the same layout as the CLI's generated bundle:- * `manifest.json` beside one directory per slug. Manifest `entry` and `files`- * paths are relative to that slug directory and are confined there before any- * caller reads or copies them.+ * A theme root contains one directory per lower-kebab slug. Each directory has+ * a theme source and mandatory same-stem `.doc.mjs`; the directory is the+ * complete copy and pack boundary. Descriptor metadata is parsed without+ * executing theme source. A dot-folder, or a folder holding neither a+ * descriptor nor a `<name>Theme` source, is not a theme. Dot entries and files+ * npm never publishes belong to no theme.** @input a bundled or integration-owned theme root* @output validated source-theme records with package ownership@@ -15,14 +17,42 @@*/import * as fs from 'node:fs';+import {createRequire} from 'node:module';import * as path from 'node:path';+import {lowerDoc} from '../doc-compiler/compile.mjs';+import {packageSource} from '../doc-compiler/source.mjs';import {CLI_ROOT} from '../fs/paths.mjs';import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';export const BUNDLED_THEME_PACKAGE = '@astryxdesign/cli';export const THEMES_DIR = path.join(CLI_ROOT, 'assets', 'templates', 'themes');-export const THEME_MANIFEST_BASENAME = 'manifest.json';-export const MANIFEST_PATH = path.join(THEMES_DIR, THEME_MANIFEST_BASENAME);+export const THEME_DOC_SUFFIX = '.doc.mjs';++const require = createRequire(import.meta.url);++/** @type {typeof import('@babel/parser') | undefined} */+let babelParser;+/** @type {any} */+let jscodeshiftApi;++/**+ * The descriptor parser, loaded when the first descriptor is read.+ * @returns {typeof import('@babel/parser')}+ */+function descriptorParser() {+ babelParser ??= require('@babel/parser');+ return /** @type {typeof import('@babel/parser')} */ (babelParser);+}++/**+ * The theme source parser, loaded when the first integration theme source is+ * checked. Bundled themes never need it.+ * @returns {any}+ */+function sourceParser() {+ jscodeshiftApi ??= require('jscodeshift');+ return jscodeshiftApi;+}/*** @typedef {object} DiscoveredTheme@@ -32,22 +62,14 @@ export const MANIFEST_PATH = path.join(THEMES_DIR, THEME_MANIFEST_BASENAME);* @property {boolean} maintained* @property {string} entry* @property {string} exportName- * @property {string[]} files+ * @property {string[]} files what `theme add` copies, relative to sourceDir,+ * entry first* @property {string} package* @property {string} sourceDir absolute directory holding this theme's files* @property {boolean} bundled+ * @property {string} docPath absolute descriptor path*/-/** @param {unknown} value @param {string} field @param {string} owner */-function requiredString(value, field, owner) {- if (typeof value !== 'string' || value.trim().length === 0) {- throw new Error(- `Theme catalog for ${owner} has an invalid ${field}; expected a non-empty string.`,- );- }- return value;-}-/*** Resolve one authored relative path without allowing POSIX or Windows escape* syntax, even when discovery runs on the other platform.@@ -75,26 +97,45 @@ function resolveThemePath(value, root, label) {}}-const THEME_MODULE_EXTENSIONS = ['.mjs', '.js', '.mts', '.ts', '.tsx', '.jsx'];+export const THEME_MODULE_EXTENSIONS = [+ '.mjs',+ '.js',+ '.mts',+ '.ts',+ '.tsx',+ '.jsx',+];++/** A theme directory's name: lower-kebab, starting with a letter. */+export const THEME_SLUG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;/**- * Resolve a local theme module only when the target is a listed file confined- * to the theme directory.* @param {unknown} specifier* @param {string} fromFile- * @param {string} themeDir- * @param {Set<string>} allowedFiles+ * @returns {string[]}*/-function resolveLocalThemeModule(specifier, fromFile, themeDir, allowedFiles) {- if (typeof specifier !== 'string' || !specifier.startsWith('.')) return null;+function localThemeModuleCandidates(specifier, fromFile) {+ if (typeof specifier !== 'string' || !specifier.startsWith('.')) return [];const base = path.resolve(path.dirname(fromFile), specifier);- const candidates = [+ return [base,...THEME_MODULE_EXTENSIONS.map(extension => `${base}${extension}`),...THEME_MODULE_EXTENSIONS.map(extension =>path.join(base, `index${extension}`),),];+}++/**+ * Resolve a local theme module only when the target is a listed file confined+ * to the theme directory.+ * @param {unknown} specifier+ * @param {string} fromFile+ * @param {string} themeDir+ * @param {Set<string>} allowedFiles+ */+function resolveLocalThemeModule(specifier, fromFile, themeDir, allowedFiles) {+ const candidates = localThemeModuleCandidates(specifier, fromFile);for (const candidate of candidates) {try {if (!fs.statSync(candidate).isFile()) continue;@@ -111,30 +152,16 @@ function resolveLocalThemeModule(specifier, fromFile, themeDir, allowedFiles) {}class ThemeModuleReferenceError extends Error {}+class ThemeRuntimeExportError extends Error {}/**- * Validate that every local static dependency is copied with the theme.+ * Every string specifier a module imports, re-exports, or imports dynamically.* @param {string} file* @param {any} jscodeshift- * @param {string} themeDir- * @param {Set<string>} allowedFiles- * @param {string} owner- * @param {string} entry- * @param {Set<string>} [seen]+ * @returns {string[]}*/-function validateThemeModuleGraph(- file,- jscodeshift,- themeDir,- allowedFiles,- owner,- entry,- seen = new Set(),-) {- if (seen.has(file)) return;- seen.add(file);-- const parser = /\.(?:ts|tsx|mts)$/u.test(file) ? 'tsx' : 'babel';+function moduleSpecifiers(file, jscodeshift) {+ const parser = /\.(?:ts|tsx|mts|cts)$/u.test(file) ? 'tsx' : 'babel';const j = jscodeshift.withParser(parser);const root = j(fs.readFileSync(file, 'utf-8'));/** @type {string[]} */@@ -170,7 +197,34 @@ function validateThemeModuleGraph(}});- for (const specifier of specifiers) {+ return specifiers;+}++/**+ * Validate that every local static dependency is copied with the theme.+ * @param {string} file+ * @param {any} jscodeshift+ * @param {string} themeDir+ * @param {Set<string>} allowedFiles+ * @param {string} owner+ * @param {string} entry+ * @param {string} descriptorPath+ * @param {Set<string>} [seen]+ */+function validateThemeModuleGraph(+ file,+ jscodeshift,+ themeDir,+ allowedFiles,+ owner,+ entry,+ descriptorPath,+ seen = new Set(),+) {+ if (seen.has(file)) return;+ seen.add(file);++ for (const specifier of moduleSpecifiers(file, jscodeshift)) {if (!specifier.startsWith('.')) continue;const target = resolveLocalThemeModule(specifier,@@ -179,8 +233,19 @@ function validateThemeModuleGraph(allowedFiles,);if (!target) {+ const referencesDescriptor = localThemeModuleCandidates(+ specifier,+ file,+ ).some(+ candidate => path.resolve(candidate) === path.resolve(descriptorPath),+ );+ if (referencesDescriptor) {+ throw new ThemeModuleReferenceError(+ `Theme entry "${entry}" from ${owner} must not import its descriptor "${path.basename(descriptorPath)}". Theme descriptors are authoring metadata, not runtime modules.`,+ );+ }throw new ThemeModuleReferenceError(- `Theme catalog for ${owner} entry "${entry}" references local module "${specifier}" that must resolve to a listed file inside the theme directory.`,+ `Theme entry "${entry}" from ${owner} references local module "${specifier}" that must resolve to a file inside the theme directory.`,);}if (THEME_MODULE_EXTENSIONS.includes(path.extname(target))) {@@ -191,6 +256,7 @@ function validateThemeModuleGraph(allowedFiles,owner,entry,+ descriptorPath,seen,);}@@ -428,223 +494,887 @@ function moduleExportsName(}/**- * Read and validate one theme catalog.- * @param {string} themeRoot absolute catalog root- * @param {string} owner package that owns the catalog- * @param {{bundled?: boolean}} [options]- * @returns {DiscoveredTheme[]}+ * An expression without the parentheses around it.+ * @param {any} node+ * @returns {any}*/-export function discoverThemeCatalog(themeRoot, owner, {bundled = false} = {}) {- if (!fs.existsSync(themeRoot) || !fs.statSync(themeRoot).isDirectory()) {- throw new Error(- `Declared themes root does not exist on disk: ${themeRoot}`,- );+function unparenthesized(node) {+ let current = node;+ while (current?.type === 'ParenthesizedExpression') {+ current = current.expression;}+ return current;+}- const manifestPath = resolveThemePath(- THEME_MANIFEST_BASENAME,- themeRoot,- 'theme catalog manifest',+/**+ * Convert one static literal used by ThemeDoc. Theme descriptors intentionally+ * contain data only so synchronous bundled-theme APIs stay synchronous.+ * @param {any} node+ * @param {string} label+ * @returns {string | boolean}+ */+function staticThemeValue(node, label) {+ if (node?.type === 'StringLiteral' || node?.type === 'BooleanLiteral') {+ return node.value;+ }+ throw new Error(+ `${label} must use static string and boolean values in its default export.`,);- if (!fs.existsSync(manifestPath) || !fs.statSync(manifestPath).isFile()) {- throw new Error(- `Theme root for ${owner} must contain ${THEME_MANIFEST_BASENAME}.`,- );+}++/**+ * How messages about a theme descriptor name it.+ * @param {string} docPath+ * @param {string} owner+ */+export function themeDescriptorLabel(docPath, owner) {+ return `Theme descriptor ${path.basename(docPath)} for ${owner}`;+}++/**+ * Read one strongly typed theme descriptor without executing it, and compile+ * it.+ * @param {string} docPath+ * @param {string} owner+ * @returns {import('../../authoring/doctypes/theme/type').ThemeDoc}+ */+function readThemeDoc(docPath, owner) {+ const label = themeDescriptorLabel(docPath, owner);+ const value = readThemeDescriptorValue(docPath, label);+ // Read statically, never executed, then compiled like every other doc.+ const {node, failed, failure} = lowerDoc({+ id: `${owner}:themes:${path.basename(docPath)}`,+ root: 'themes',+ provider: owner,+ source: packageSource(docPath),+ lang: null,+ file: {file: path.basename(docPath), doc: value},+ label,+ });+ if (!node || failed) throw failure;+ return node.doc;+}++/**+ * Descriptor reads in this process, by path and label, reused while the file+ * keeps its size and mtime.+ * @type {Map<string, {size: number, mtimeMs: number, read: {value: Record<string, string | boolean>} | {error: unknown}}>}+ */+const descriptorReads = new Map();++/**+ * The static value a theme descriptor default-exports, read from its source+ * without executing it. Throws when the file is not one static ThemeDoc+ * object.+ * @param {string} docPath+ * @param {string} label+ * @returns {Record<string, string | boolean>}+ */+export function readThemeDescriptorValue(docPath, label) {+ const {size, mtimeMs} = fs.statSync(docPath);+ const key = `${docPath}\0${label}`;+ let cached = descriptorReads.get(key);+ if (!cached || cached.size !== size || cached.mtimeMs !== mtimeMs) {+ /** @type {{value: Record<string, string | boolean>} | {error: unknown}} */+ let read;+ try {+ read = {+ value: readDescriptorSource(fs.readFileSync(docPath, 'utf-8'), label),+ };+ } catch (error) {+ read = {error};+ }+ cached = {size, mtimeMs, read};+ descriptorReads.set(key, cached);}+ if ('error' in cached.read) throw cached.read.error;+ return {...cached.read.value};+}- /** @type {unknown} */- let parsed;+/**+ * @param {string} source+ * @param {string} label+ * @returns {Record<string, string | boolean>}+ */+function readDescriptorSource(source, label) {+ /** @type {any} */+ let ast;try {- parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));+ ast = descriptorParser().parse(source, {+ sourceType: 'module',+ tokens: true,+ createParenthesizedExpressions: true,+ });} catch (error) {const message = error instanceof Error ? error.message : String(error);- throw new Error(`Theme catalog for ${owner} is unreadable: ${message}`, {- cause: error,+ throw new Error(`${label} could not be parsed: ${message}`, {cause: error});+ }++ const statements = ast.program.body;+ const defaults = statements.filter(+ (/** @type {any} */ statement) =>+ statement.type === 'ExportDefaultDeclaration',+ );+ const unsupported = statements.filter(+ (/** @type {any} */ statement) =>+ statement.type !== 'ExportDefaultDeclaration' &&+ statement.type !== 'EmptyStatement',+ );+ if (unsupported.length > 0 || ast.program.directives.length > 0) {+ throw new Error(+ `${label} must contain only its static default-exported ThemeDoc object.`,+ );+ }+ const object =+ defaults.length === 1 && unparenthesized(defaults[0].declaration);+ if (object?.type !== 'ObjectExpression') {+ throw new Error(`${label} must default-export one static ThemeDoc object.`);+ }+ if (!declaresThemeDoc(ast, defaults[0])) {+ throw new Error(+ `${label} must declare its public ThemeDoc type from @astryxdesign/cli/authoring.`,+ );+ }++ /** @type {Record<string, string | boolean>} */+ const value = {};+ for (const property of object.properties) {+ if (property.type !== 'ObjectProperty' || property.computed) {+ throw new Error(`${label} must contain only static object properties.`);+ }+ const key =+ property.key.type === 'Identifier'+ ? property.key.name+ : property.key.type === 'StringLiteral'+ ? property.key.value+ : null;+ if (key === null) {+ throw new Error(`${label} has an invalid property name.`);+ }+ if (Object.hasOwn(value, key)) {+ throw new Error(`${label} declares "${key}" more than once.`);+ }+ // Defined, not assigned, so `__proto__` stays a key the parser rejects.+ Object.defineProperty(value, key, {+ value: staticThemeValue(unparenthesized(property.value), label),+ enumerable: true,+ writable: true,+ configurable: true,});}+ return value;+}++/** `import('@astryxdesign/cli/authoring').ThemeDoc`, without whitespace. */+const THEME_DOC_TYPE =+ /^import\((['"])@astryxdesign\/cli\/authoring\1\)\.ThemeDoc$/u;++/** @param {any} comment */+function isJsdoc(comment) {+ return comment.type === 'CommentBlock' && comment.value.startsWith('*');+}++/** @param {string} ch */+const isSpace = ch => ch === ' ' || ch === '\t';++/**+ * The tags of one JSDoc comment, found the way TypeScript's JSDoc scanner+ * finds them: an `@` starts a tag at the start of a line (after the margin+ * `*`), or after a space and before a non-space, never inside a backtick span+ * of a tag's text. Each tag's text runs to the next tag, margins removed.+ * @param {string} value the comment's body, as Babel gives it+ * @returns {{name: string, text: string}[]}+ */+function jsdocTags(value) {+ const body = value.slice(1);+ /** @type {number[]} */+ const starts = [];+ let lineStart = true;+ let sawAsterisk = true;+ let inTag = false;+ let backticks = false;+ for (let index = 0; index < body.length; index++) {+ const ch = body[index];+ if (ch === '\n' || ch === '\r') {+ lineStart = true;+ sawAsterisk = false;+ backticks = false;+ continue;+ }+ if (lineStart) {+ if (isSpace(ch)) continue;+ if (ch === '*' && !sawAsterisk) {+ sawAsterisk = true;+ continue;+ }+ lineStart = false;+ if (ch === '@') {+ starts.push(index);+ inTag = true;+ continue;+ }+ }+ if (ch === '`' && inTag) {+ backticks = !backticks;+ } else if (+ ch === '@' &&+ !backticks &&+ isSpace(body[index - 1] ?? '') &&+ !/\s/u.test(body[index + 1] ?? ' ')+ ) {+ starts.push(index);+ inTag = true;+ backticks = false;+ }+ }+ return starts.map((start, position) => {+ const raw = body.slice(start + 1, starts[position + 1] ?? body.length);+ const name = /^[\w$]*/u.exec(raw)?.[0] ?? '';+ const text = raw.slice(name.length).replace(/(\r?\n)[ \t]*\*?/gu, '$1');+ return {name, text};+ });+}- if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) {- throw new Error(`Theme catalog for ${owner} must be a JSON object.`);+/**+ * The braced type at the start of a tag's text, and what follows it.+ * @param {string} text+ * @returns {{type: string, rest: string} | null}+ */+function bracedType(text) {+ const open = text.search(/\S/u);+ if (open === -1 || text[open] !== '{') return null;+ let depth = 0;+ /** @type {string | null} */+ let quote = null;+ for (let index = open; index < text.length; index++) {+ const ch = text[index];+ if (quote) {+ if (ch === quote) quote = null;+ } else if (ch === "'" || ch === '"' || ch === '`') {+ quote = ch;+ } else if (ch === '{') {+ depth++;+ } else if (ch === '}' && --depth === 0) {+ return {+ type: text.slice(open + 1, index).replace(/\s+/gu, ''),+ rest: text.slice(index + 1),+ };+ }}- const catalog = /** @type {{version?: unknown, themes?: unknown}} */ (parsed);- if (catalog.version !== 1) {- throw new Error(`Theme catalog for ${owner} must use version 1.`);+ return null;+}++/**+ * Split a type at top-level occurrences of one operator.+ * @param {string} type+ * @param {string} operator+ */+function splitType(type, operator) {+ /** @type {string[]} */+ const parts = [];+ let depth = 0;+ /** @type {string | null} */+ let quote = null;+ let last = 0;+ for (let index = 0; index < type.length; index++) {+ const ch = type[index];+ if (quote) {+ if (ch === quote) quote = null;+ } else if (ch === "'" || ch === '"' || ch === '`') {+ quote = ch;+ } else if ('([{<'.includes(ch)) {+ depth++;+ } else if (')]}>'.includes(ch)) {+ depth--;+ } else if (ch === operator && depth === 0) {+ parts.push(type.slice(last, index));+ last = index + 1;+ }}- if (!Array.isArray(catalog.themes)) {- throw new Error(`Theme catalog for ${owner} must contain a themes array.`);+ parts.push(type.slice(last));+ return parts;+}++/** @param {string} type */+function wrappedInParens(type) {+ if (!type.startsWith('(') || !type.endsWith(')')) return false;+ let depth = 0;+ for (let index = 0; index < type.length; index++) {+ if (type[index] === '(') depth++;+ else if (type[index] === ')' && --depth === 0) {+ return index === type.length - 1;+ }+ }+ return false;+}++/**+ * Whether a JSDoc type, whitespace removed, checks an object literal exactly+ * as ThemeDoc does: ThemeDoc or one of its aliases, optionally parenthesized,+ * marked `!`, `?` or `=`, joined with `null` or `undefined`, or intersected+ * with `{}`.+ * @param {string} type+ * @param {Map<string, string>} aliases alias name to the type it names+ * @param {Set<string>} [seen]+ * @returns {boolean}+ */+function isThemeDocType(type, aliases, seen = new Set()) {+ let current = type;+ for (;;) {+ if (/^[!?]/u.test(current)) current = current.slice(1);+ else if (current.endsWith('=')) current = current.slice(0, -1);+ else if (wrappedInParens(current)) current = current.slice(1, -1);+ else break;+ }+ const members = splitType(current, '|').filter(+ member => member !== 'null' && member !== 'undefined',+ );+ if (members.length !== 1) return false;+ if (members[0] !== current) return isThemeDocType(members[0], aliases, seen);+ const parts = splitType(current, '&').filter(part => part !== '{}');+ if (parts.length !== 1) return false;+ if (parts[0] !== current) return isThemeDocType(parts[0], aliases, seen);+ if (THEME_DOC_TYPE.test(current)) return true;+ const named = aliases.get(current);+ if (named === undefined || seen.has(current)) return false;+ seen.add(current);+ return isThemeDocType(named, aliases, seen);+}++const AUTHORING = String.raw`(['"])@astryxdesign\/cli\/authoring\2`;++/**+ * The type names the file's JSDoc binds with `@typedef` or `@import`, from any+ * JSDoc comment in the module, as TypeScript reads them.+ * @param {any[]} comments+ * @returns {Map<string, string>}+ */+function jsdocAliases(comments) {+ /** @type {Map<string, string>} */+ const aliases = new Map();+ const theme = "import('@astryxdesign/cli/authoring').ThemeDoc";+ for (const comment of comments.filter(isJsdoc)) {+ for (const tag of jsdocTags(comment.value)) {+ if (tag.name === 'typedef') {+ const typed = bracedType(tag.text);+ const name = typed && /^\s*([$A-Z_a-z][$\w]*)/u.exec(typed.rest)?.[1];+ if (typed && name) aliases.set(name, typed.type);+ } else if (tag.name === 'import') {+ const named = new RegExp(+ String.raw`^\s*\{([^{}]*)\}\s*from\s*${AUTHORING}`,+ 'u',+ ).exec(tag.text);+ for (const specifier of named?.[1].split(',') ?? []) {+ const match =+ /^\s*(?:type\s+)?ThemeDoc(?:\s+as\s+([$A-Z_a-z][$\w]*))?\s*$/u.exec(+ specifier,+ );+ if (match) aliases.set(match[1] ?? 'ThemeDoc', theme);+ }+ const namespace = new RegExp(+ String.raw`^\s*\*\s*as\s+([$A-Z_a-z][$\w]*)\s+from\s*${AUTHORING}`,+ 'u',+ ).exec(tag.text)?.[1];+ if (namespace) aliases.set(`${namespace}.ThemeDoc`, theme);+ }+ }+ }+ return aliases;+}++/**+ * Whether the JSDoc TypeScript reads for the default export types it as the+ * public ThemeDoc: `@type` in the last JSDoc comment between the previous+ * token and `export`, or `@type` or `@satisfies` in the last one between the+ * previous token and the opening parenthesis of a JSDoc cast of the object.+ * Line comments, strings, code spans, and JSDoc anywhere else never type it.+ * @param {any} ast parsed with tokens and parenthesized expressions+ * @param {any} exportDefault+ */+function declaresThemeDoc(ast, exportDefault) {+ const tokens = ast.tokens.filter(+ (/** @type {any} */ token) => typeof token.type !== 'string',+ );+ const comments = ast.comments ?? [];+ /** @param {number} start */+ const jsdocBefore = start => {+ const after =+ tokens.filter((/** @type {any} */ token) => token.end <= start).at(-1)+ ?.end ?? 0;+ return comments+ .filter(+ (/** @type {any} */ comment) =>+ isJsdoc(comment) && comment.start >= after && comment.end <= start,+ )+ .at(-1);+ };+ /** @type {Array<{comment: any, tags: string[]}>} */+ const attached = [+ {comment: jsdocBefore(exportDefault.start), tags: ['type']},+ ];+ for (+ let node = exportDefault.declaration;+ node.type === 'ParenthesizedExpression';+ node = node.expression+ ) {+ attached.push({+ comment: jsdocBefore(node.start),+ tags: ['type', 'satisfies'],+ });+ }+ const aliases = jsdocAliases(comments);+ return attached.some(({comment, tags}) => {+ if (!comment) return false;+ const found = jsdocTags(comment.value);+ return tags.some(name => {+ const tag = found.find(candidate => candidate.name === name);+ const typed = tag && bracedType(tag.text);+ return typed != null && isThemeDocType(typed.type, aliases);+ });+ });+}++/** A module named for the theme it exports, such as `oceanTheme.ts`. */+const THEME_SOURCE_RE = /^[$A-Z_a-z][$\w]*Theme\.(?:mjs|js|mts|ts|tsx|jsx)$/u;++/**+ * Whether an entry at any depth of a themes root is outside every theme: a dot+ * entry, or a name npm never publishes (npm-packlist's defaults).+ * @param {string} name+ */+export function isIgnoredThemeEntry(name) {+ return (+ name.startsWith('.') ||+ name === 'node_modules' ||+ name === 'CVS' ||+ name === 'npm-debug.log' ||+ name.endsWith('.orig')+ );+}++/**+ * Every entry below one folder of a theme root, without following symlinks+ * and without {@link isIgnoredThemeEntry} entries.+ * @param {string} folder+ * @returns {{files: string[], symlinks: string[]}} sorted POSIX paths+ * relative to the folder+ */+function listThemeFolder(folder) {+ /** @type {string[]} */+ const files = [];+ /** @type {string[]} */+ const symlinks = [];+ /** @param {string} directory */+ function walk(directory) {+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {+ if (isIgnoredThemeEntry(entry.name)) continue;+ const full = path.join(directory, entry.name);+ const relative = path.relative(folder, full).split(path.sep).join('/');+ if (entry.isSymbolicLink()) symlinks.push(relative);+ else if (entry.isDirectory()) walk(full);+ else if (entry.isFile()) files.push(relative);+ }+ }+ walk(folder);+ return {files: files.sort(), symlinks: symlinks.sort()};+}++/**+ * The first entry that makes a folder a theme: a `.doc.mjs` descriptor or a+ * `<name>Theme` source, at any depth, linked or not.+ * @param {{files: string[], symlinks: string[]}} listing+ * @returns {string | undefined}+ */+function themeEvidence({files, symlinks}) {+ return [...files, ...symlinks].sort().find(file => {+ const name = path.posix.basename(file);+ return name.endsWith(THEME_DOC_SUFFIX) || THEME_SOURCE_RE.test(name);+ });+}++/**+ * Whether discovery reads a folder under a theme root as a theme. Dot-folders+ * and folders with neither a descriptor nor a `<name>Theme` source are not.+ * @param {string} folder absolute path+ */+export function isThemeFolder(folder) {+ return (+ !isIgnoredThemeEntry(path.basename(folder)) &&+ themeEvidence(listThemeFolder(folder)) !== undefined+ );+}++/**+ * The files one theme folder ships: every regular file below it except+ * {@link isIgnoredThemeEntry} entries. What pack-check requires and what+ * `theme add` copies.+ * @param {string} folder absolute path+ * @returns {string[]} sorted POSIX paths relative to the folder+ */+export function listThemeFiles(folder) {+ return listThemeFolder(folder).files;+}++/** @param {string[]} files */+function quoted(files) {+ return files.map(file => `"${file}"`).join(', ');+}++/**+ * The files `theme add` has always copied after a bundled theme's entry, in+ * copy order. SYNC: scripts/generate-cli-themes.mjs bundles these.+ * @param {string} id the theme's export name without `Theme`+ */+function bundledThemeArtifacts(id) {+ return [+ 'icons.tsx',+ `${id}Palettes.ts`,+ `${id}Palettes.generated.ts`,+ `${id}PaletteRefs.generated.ts`,+ `${id}Palettes.generated.receipt.json`,+ 'palette.config.json',+ ];+}++/**+ * The files `theme add` copies, entry first. A bundled theme's descriptor is+ * the CLI's own metadata and stays behind; an integration theme copies its+ * whole directory.+ * @param {string[]} files every regular file in the theme directory, sorted+ * @param {string} entry+ * @param {string} descriptor+ * @param {string} exportName+ * @param {boolean} bundled+ */+function copiedThemeFiles(files, entry, descriptor, exportName, bundled) {+ const rest = files.filter(+ file => file !== entry && !(bundled && file === descriptor),+ );+ if (!bundled) return [entry, ...rest];+ const order = bundledThemeArtifacts(exportName.replace(/Theme$/u, ''));+ return [+ entry,+ ...order.filter(file => rest.includes(file)),+ ...rest.filter(file => !order.includes(file)),+ ];+}++/**+ * Discover and validate one theme root.+ * @param {string} themeRoot absolute root containing one directory per slug+ * @param {string} owner package that owns the root+ * @param {{bundled?: boolean}} [options] a bundled root is the CLI's own; its+ * sources are checked by the CLI's tests rather than on every read+ * @returns {DiscoveredTheme[]}+ */+export function discoverThemeDirectory(+ themeRoot,+ owner,+ {bundled = false} = {},+) {+ if (!fs.existsSync(themeRoot) || !fs.statSync(themeRoot).isDirectory()) {+ throw new Error(+ `Declared themes root does not exist on disk: ${themeRoot}`,+ );+ }+ if (fs.existsSync(path.join(themeRoot, 'manifest.json'))) {+ throw new Error(+ `Theme root for ${owner} contains manifest.json, the theme catalog Astryx 0.6 wrote; each theme now carries a strongly typed same-stem .doc.mjs descriptor instead. To convert it, run \`astryx upgrade --from 0.6.3 --path . --apply\` in the package, or add each theme's descriptor and delete manifest.json.`,+ );}/** @type {DiscoveredTheme[]} */const themes = [];const slugs = new Set();- for (const [index, raw] of catalog.themes.entries()) {- if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {- throw new Error(- `Theme catalog for ${owner} has an invalid entry at index ${index}.`,- );- }- const entry = /** @type {Record<string, unknown>} */ (raw);- const slug = requiredString(entry.slug, `themes[${index}].slug`, owner);- if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(slug)) {+ const rootEntries = fs+ .readdirSync(themeRoot, {withFileTypes: true})+ .filter(entry => !isIgnoredThemeEntry(entry.name));+ const rootDescriptor = rootEntries.find(+ entry => entry.isFile() && entry.name.endsWith(THEME_DOC_SUFFIX),+ );+ if (rootDescriptor) {+ throw new Error(+ `Theme descriptor "${rootDescriptor.name}" for ${owner} must be inside a lower-kebab theme directory.`,+ );+ }+ const rootSymlink = rootEntries.find(entry => entry.isSymbolicLink());+ if (rootSymlink) {+ throw new Error(+ `Theme root for ${owner} contains symlink "${rootSymlink.name}"; theme directories must stay inside the declared root.`,+ );+ }+ const directories = rootEntries+ .filter(entry => entry.isDirectory())+ .sort((a, b) => a.name.localeCompare(b.name));++ for (const directory of directories) {+ const slug = directory.name;+ const listing = listThemeFolder(path.join(themeRoot, slug));+ const evidence = themeEvidence(listing);+ if (evidence === undefined) continue;+ if (!THEME_SLUG_RE.test(slug)) {throw new Error(- `Theme catalog for ${owner} has invalid slug "${slug}"; use lowercase kebab-case starting with a letter.`,+ `Theme root for ${owner} has invalid directory "${slug}"; use lowercase kebab-case starting with a letter.`,);}const normalizedSlug = slug.toLowerCase();if (slugs.has(normalizedSlug)) {throw new Error(- `Theme catalog for ${owner} declares duplicate slug "${slug}".`,+ `Theme root for ${owner} declares duplicate slug "${slug}".`,);}slugs.add(normalizedSlug);- const displayName = requiredString(- entry.displayName,- `theme "${slug}" displayName`,- owner,+ const sourceDir = resolveThemePath(+ slug,+ themeRoot,+ `theme "${slug}" directory`,);- if (typeof entry.description !== 'string') {- throw new Error(- `Theme catalog for ${owner} has an invalid description for "${slug}".`,- );- }- if (typeof entry.maintained !== 'boolean') {+ const theme = `Theme "${slug}" for ${owner}`;+ if (listing.symlinks.length > 0) {throw new Error(- `Theme catalog for ${owner} has an invalid maintained flag for "${slug}".`,+ `${theme} contains symlink "${listing.symlinks[0]}"; theme files must be regular files inside the theme directory.`,);}- const entryFile = requiredString(- entry.entry,- `theme "${slug}" entry`,- owner,- );- const exportName = requiredString(- entry.exportName,- `theme "${slug}" exportName`,- owner,+ const descriptors = listing.files.filter(file =>+ file.endsWith(THEME_DOC_SUFFIX),);- if (!/^[$A-Z_a-z][$\w]*$/u.test(exportName)) {+ const docs = descriptors.filter(file => !file.includes('/'));+ if (docs.length !== 1) {+ const detail =+ docs.length > 1+ ? `: ${quoted(docs)}`+ : evidence.includes('/')+ ? `; "${evidence}" is in a subfolder`+ : ` beside "${evidence}"`;throw new Error(- `Theme catalog for ${owner} has invalid exportName "${exportName}".`,+ `${theme} must contain exactly one same-stem .doc.mjs descriptor; found ${docs.length}${detail}.`,);}- if (!Array.isArray(entry.files) || entry.files.length === 0) {+ const nested = descriptors.find(file => file.includes('/'));+ if (nested) {throw new Error(- `Theme catalog for ${owner} theme "${slug}" must list at least one file.`,+ `${theme} contains more than one .doc.mjs descriptor: "${docs[0]}" and "${nested}".`,);}- const files = entry.files.map((file, fileIndex) =>- requiredString(file, `theme "${slug}" files[${fileIndex}]`, owner),+ const docPath = resolveThemePath(+ docs[0],+ sourceDir,+ `theme "${slug}" descriptor`,);- if (new Set(files).size !== files.length) {+ const label = themeDescriptorLabel(docPath, owner);+ const exportName = docs[0].slice(0, -THEME_DOC_SUFFIX.length);+ if (!/^[$A-Z_a-z][$\w]*$/u.test(exportName)) {throw new Error(- `Theme catalog for ${owner} theme "${slug}" lists a file more than once.`,+ `${label} has stem "${exportName}", which is not a valid runtime export name.`,);}- if (!files.includes(entryFile)) {+ const sources = THEME_MODULE_EXTENSIONS.map(+ extension => `${exportName}${extension}`,+ ).filter(file => listing.files.includes(file));+ if (sources.length !== 1) {throw new Error(- `Theme catalog for ${owner} theme "${slug}" must include entry "${entryFile}" in files.`,+ `${theme} must contain exactly one same-stem source for ${docs[0]}; found ${sources.length}${sources.length > 1 ? `: ${quoted(sources)}` : ''}.`,);}- if (!/\.(?:ts|tsx|mjs|js)$/u.test(entryFile)) {++ const doc = readThemeDoc(docPath, owner);+ if (doc.name !== slug) {throw new Error(- `Theme catalog for ${owner} theme "${slug}" entry must be source code.`,+ `${label} names "${doc.name}" but its directory is "${slug}".`,);}-- const sourceDir = resolveThemePath(- slug,- themeRoot,- `theme "${slug}" directory`,+ const entry = sources[0];+ const entryPath = resolveThemePath(+ entry,+ sourceDir,+ `theme "${slug}" entry`,);- if (!fs.existsSync(sourceDir) || !fs.statSync(sourceDir).isDirectory()) {- throw new Error(- `Theme catalog for ${owner} is missing directory "${slug}".`,++ if (!bundled) {+ const allowedFiles = new Set(+ listing.files+ .map(file =>+ resolveThemePath(file, sourceDir, `theme "${slug}" file`),+ )+ .filter(file => file !== docPath),);- }- for (const file of files) {- const source = resolveThemePath(file, sourceDir, `theme "${slug}" file`);- if (!fs.existsSync(source) || !fs.statSync(source).isFile()) {+ const jscodeshift = sourceParser();+ try {+ validateThemeModuleGraph(+ entryPath,+ jscodeshift,+ sourceDir,+ allowedFiles,+ owner,+ entry,+ docPath,+ );+ if (+ !moduleExportsName(+ entryPath,+ exportName,+ jscodeshift,+ sourceDir,+ allowedFiles,+ )+ ) {+ throw new ThemeRuntimeExportError(+ `Theme "${slug}" for ${owner} entry "${entry}" does not export "${exportName}".`,+ );+ }+ } catch (error) {+ if (+ error instanceof ThemeModuleReferenceError ||+ error instanceof ThemeRuntimeExportError+ ) {+ throw error;+ }+ const message = error instanceof Error ? error.message : String(error);throw new Error(- `Theme catalog for ${owner} theme "${slug}" is missing file "${file}".`,+ `Theme "${slug}" for ${owner} entry "${entry}" could not be parsed: ${message}`,+ {cause: error},);}}themes.push({slug,- displayName,- description: entry.description,- maintained: entry.maintained,- entry: entryFile,+ displayName: doc.displayName,+ description: doc.description,+ maintained: doc.maintained,+ entry,exportName,- files,+ files: copiedThemeFiles(+ listing.files,+ entry,+ docs[0],+ exportName,+ bundled,+ ),package: owner,sourceDir,bundled,+ docPath,});}return themes;}-/** @returns {DiscoveredTheme[]} */-export function discoverBundledThemes() {- return discoverThemeCatalog(THEMES_DIR, BUNDLED_THEME_PACKAGE, {- bundled: true,+/** A JavaScript or TypeScript module. */+const MODULE_FILE_RE = /\.(?:[cm]?[jt]s|[jt]sx)$/u;++/**+ * Whether a folder's files look like an attempt at a theme: a doc file of any+ * suffix, a file named for a theme, an index module, or a module named for+ * the folder.+ * @param {string} folder+ * @param {string[]} files+ */+function looksLikeTheme(folder, files) {+ const own = path.basename(folder).toLowerCase();+ return files.some(file => {+ const name = path.posix.basename(file).toLowerCase();+ const stem = name.replace(/\.[^.]+$/u, '');+ return (+ /\.doc\.[^.]+$/u.test(name) ||+ /theme/u.test(name) ||+ (MODULE_FILE_RE.test(name) && (stem === 'index' || stem === own))+ );});}/**- * @param {import('../integrations/integrations.mjs').LoadedIntegration} integration- * @returns {Promise<DiscoveredTheme[]>}+ * Folders under a themes root that look like themes (see looksLikeTheme)+ * but that discovery does not read as themes, and that no module elsewhere+ * under the root imports, by a relative path or through the package's own+ * name. Discovery skips them silently, as the released catalog skipped+ * unlisted folders; doctor warns.+ * @param {string} themeRoot+ * @param {{packageDir?: string, packageName?: string}} [owner]+ * @returns {string[]} absolute folder paths, sorted*/-export async function discoverIntegrationThemes(integration) {- if (!integration.themes) return [];- const themes = discoverThemeCatalog(integration.themes, integration.name);- const jscodeshift = (await import('jscodeshift')).default;- for (const theme of themes) {- const allowedFiles = new Set(- theme.files.map(file =>- resolveThemePath(file, theme.sourceDir, `theme "${theme.slug}" file`),- ),- );- const entryPath = resolveThemePath(- theme.entry,- theme.sourceDir,- `theme "${theme.slug}" entry`,+export function unreadThemeFolders(themeRoot, {packageDir, packageName} = {}) {+ if (!fs.existsSync(themeRoot) || !fs.statSync(themeRoot).isDirectory()) {+ return [];+ }+ const folders = fs+ .readdirSync(themeRoot, {withFileTypes: true})+ .filter(entry => entry.isDirectory() && !isIgnoredThemeEntry(entry.name))+ .map(entry => path.join(themeRoot, entry.name))+ .sort();+ const unread = folders.filter(folder => {+ if (isThemeFolder(folder)) return false;+ const {files} = listThemeFolder(folder);+ return (+ files.some(file => MODULE_FILE_RE.test(file)) &&+ looksLikeTheme(folder, files));- let exportsName;+ });+ if (unread.length === 0) return [];++ const modules = [+ ...fs+ .readdirSync(themeRoot, {withFileTypes: true})+ .filter(+ entry =>+ entry.isFile() &&+ !isIgnoredThemeEntry(entry.name) &&+ MODULE_FILE_RE.test(entry.name),+ )+ .map(entry => path.join(themeRoot, entry.name)),+ ...folders.flatMap(folder =>+ listThemeFolder(folder)+ .files.filter(file => MODULE_FILE_RE.test(file))+ .map(file => path.join(folder, file)),+ ),+ ];+ const self = packageName ? `${packageName}/` : null;+ /** @type {string[]} */+ const imported = [];+ for (const file of modules) {+ let specifiers;try {- validateThemeModuleGraph(- entryPath,- jscodeshift,- theme.sourceDir,- allowedFiles,- theme.package,- theme.entry,- );- exportsName = moduleExportsName(- entryPath,- theme.exportName,- jscodeshift,- theme.sourceDir,- allowedFiles,- );- } catch (error) {- if (error instanceof ThemeModuleReferenceError) throw error;- const message = error instanceof Error ? error.message : String(error);- throw new Error(- `Theme catalog for ${theme.package} entry "${theme.entry}" could not be parsed: ${message}`,- {cause: error},- );+ specifiers = moduleSpecifiers(file, sourceParser());+ } catch {+ continue;}- if (!exportsName) {- throw new Error(- `Theme catalog for ${theme.package} entry "${theme.entry}" does not export "${theme.exportName}".`,- );+ for (const specifier of specifiers) {+ if (specifier.startsWith('.')) {+ imported.push(path.resolve(path.dirname(file), specifier));+ } else if (self && packageDir && specifier.startsWith(self)) {+ imported.push(path.resolve(packageDir, specifier.slice(self.length)));+ }}}- return themes;+ return unread.filter(+ folder =>+ !imported.some(+ target => target === folder || target.startsWith(folder + path.sep),+ ),+ );+}++/** @type {DiscoveredTheme[] | null} */+let bundledThemeCache = null;++/** @returns {DiscoveredTheme[]} */+export function discoverBundledThemes() {+ bundledThemeCache ??= discoverThemeDirectory(+ THEMES_DIR,+ BUNDLED_THEME_PACKAGE,+ {bundled: true},+ );+ return bundledThemeCache.map(theme => ({...theme, files: [...theme.files]}));+}++/**+ * @param {import('../integrations/integrations.mjs').LoadedIntegration} integration+ * @returns {Promise<DiscoveredTheme[]>}+ */+export async function discoverIntegrationThemes(integration) {+ if (!integration.themes) return [];+ return discoverThemeDirectory(integration.themes, integration.name);}diff --git a/packages/cli/foundation/discovery/theme-discovery.test.mjs b/packages/cli/foundation/discovery/theme-discovery.test.mjsindex 42fad05962..975bcfb3ac 100644--- a/packages/cli/foundation/discovery/theme-discovery.test.mjs+++ b/packages/cli/foundation/discovery/theme-discovery.test.mjs@@ -1,6 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import {execFileSync} from 'node:child_process';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -8,75 +9,98 @@ import {BUNDLED_THEME_PACKAGE,discoverBundledThemes,discoverIntegrationThemes,- discoverThemeCatalog,+ discoverThemeDirectory,} from './theme-discovery.mjs';let tmpDir;-function writeCatalog(entries) {- fs.mkdirSync(tmpDir, {recursive: true});- for (const entry of entries) {- const themeDir = path.join(tmpDir, entry.slug);- fs.mkdirSync(themeDir, {recursive: true});- for (const file of entry.files) {- const target = path.join(themeDir, file);- fs.mkdirSync(path.dirname(target), {recursive: true});- fs.writeFileSync(target, `export const ${entry.exportName} = {};\n`);- }- }+/** @param {Record<string, unknown>} doc */+function descriptorSource(doc) {+ return `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default ${JSON.stringify(doc, null, 2)};\n`;+}++/**+ * @param {{slug?: string, stem?: string, extension?: string, source?: string,+ * doc?: Record<string, unknown>, files?: Record<string, string>}} [options]+ */+function writeTheme({+ slug = 'ocean',+ stem = 'oceanTheme',+ extension = '.ts',+ source = `export const ${stem} = {};\n`,+ doc = {},+ files = {},+} = {}) {+ const themeDir = path.join(tmpDir, slug);+ fs.mkdirSync(themeDir, {recursive: true});+ fs.writeFileSync(path.join(themeDir, `${stem}${extension}`), source);fs.writeFileSync(- path.join(tmpDir, 'manifest.json'),- JSON.stringify({version: 1, themes: entries}),+ path.join(themeDir, `${stem}.doc.mjs`),+ descriptorSource({+ type: 'theme',+ name: slug,+ displayName: 'Ocean',+ description: 'Blue and calm.',+ maintained: true,+ ...doc,+ }),);+ for (const [file, contents] of Object.entries(files)) {+ const target = path.join(themeDir, file);+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.writeFileSync(target, contents);+ }+ return themeDir;}-const ocean = {- slug: 'ocean',- displayName: 'Ocean',- description: 'Blue and calm.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts'],-};-beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-catalog-'));+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-descriptor-'));});afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});-describe('theme catalog discovery', () => {- it('reads the existing bundled catalog with package ownership', () => {+describe('theme descriptor discovery', () => {+ it('reads bundled descriptors with package ownership', () => {const themes = discoverBundledThemes();expect(themes.length).toBeGreaterThan(0);expect(themes.every(theme => theme.package === BUNDLED_THEME_PACKAGE)).toBe(true,);expect(themes.every(theme => theme.bundled)).toBe(true);+ expect(+ themes.filter(theme => theme.maintained).map(theme => theme.slug),+ ).toEqual(['neutral']);+ expect(themes.every(theme => theme.docPath.endsWith('.doc.mjs'))).toBe(+ true,+ );});- it('reads the canonical manifest-plus-slug-directory shape', () => {- writeCatalog([ocean]);- expect(discoverThemeCatalog(tmpDir, '@acme/themes')).toEqual([+ it('derives source entry and runtime export from the shared stem', () => {+ writeTheme();+ expect(discoverThemeDirectory(tmpDir, '@acme/themes')).toEqual([expect.objectContaining({- ...ocean,+ slug: 'ocean',+ displayName: 'Ocean',+ description: 'Blue and calm.',+ maintained: true,+ entry: 'oceanTheme.ts',+ exportName: 'oceanTheme',+ files: ['oceanTheme.ts', 'oceanTheme.doc.mjs'],package: '@acme/themes',sourceDir: path.join(tmpDir, 'ocean'),+ docPath: path.join(tmpDir, 'ocean', 'oceanTheme.doc.mjs'),bundled: false,}),]);});- it('parses a named runtime export without executing the entry', async () => {- writeCatalog([ocean]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "throw new Error('theme source executed');\nexport const oceanTheme = {};\n",- );-+ it('parses source without executing it', async () => {+ writeTheme({+ source:+ "throw new Error('theme source executed');\nexport const oceanTheme = {};\n",+ });await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),).resolves.toEqual([@@ -84,39 +108,50 @@ describe('theme catalog discovery', () => {]);});- it('rejects an entry that does not export the catalog name', async () => {- writeCatalog([ocean]);+ it('rejects an untyped descriptor', () => {+ const themeDir = writeTheme();fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- 'export const anotherTheme = {};\n',+ path.join(themeDir, 'oceanTheme.doc.mjs'),+ "export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: '', maintained: true};\n",);-- await expect(- discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).rejects.toThrow(- 'Theme catalog for @acme/themes entry "oceanTheme.ts" does not export "oceanTheme".',+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /must declare its public ThemeDoc type/u,);});- it('rejects a type-only export of the catalog name', async () => {- writeCatalog([ocean]);+ it('rejects a descriptor module with executable statements', () => {+ const themeDir = writeTheme();fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- 'export type oceanTheme = {};\n',+ path.join(themeDir, 'oceanTheme.doc.mjs'),+ `throw new Error('descriptor executed');\n${descriptorSource({+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: 'Blue and calm.',+ maintained: true,+ })}`,+ );+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /only its static default-exported ThemeDoc object/u,);+ });+ it('rejects an entry that does not export its inferred runtime name', async () => {+ writeTheme({source: 'export const anotherTheme = {};\n'});await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),).rejects.toThrow(/does not export "oceanTheme"/u);});- it('rejects an unbound source-less export specifier', async () => {- writeCatalog([ocean]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- 'export {oceanTheme};\n',- );+ it('rejects a type-only export of its inferred runtime name', async () => {+ writeTheme({source: 'export type oceanTheme = {};\n'});+ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).rejects.toThrow(/does not export "oceanTheme"/u);+ });+ it('rejects an unbound source-less export specifier', async () => {+ writeTheme({source: 'export {oceanTheme};\n'});await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),).rejects.toThrow(@@ -125,251 +160,610 @@ describe('theme catalog discovery', () => {});it('accepts a source-less export backed by a local runtime declaration', async () => {- writeCatalog([ocean]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- 'const oceanTheme = {};\nexport {oceanTheme};\n',- );+ writeTheme({source: 'const oceanTheme = {};\nexport {oceanTheme};\n'});+ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toHaveLength(1);+ });+ it('follows imported aliases and local re-exports without execution', async () => {+ writeTheme({+ source:+ "import {theme as oceanTheme} from './tokens/theme';\nexport {oceanTheme};\n",+ files: {+ 'tokens/theme.ts':+ "throw new Error('nested source executed');\nexport const theme = {};\n",+ },+ });await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),).resolves.toEqual([- expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),+ expect.objectContaining({+ files: ['oceanTheme.ts', 'oceanTheme.doc.mjs', 'tokens/theme.ts'],+ }),]);});- it('accepts a source-less export backed by a listed imported alias', async () => {- writeCatalog([{...ocean, files: ['oceanTheme.ts', 'theme.ts']}]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "import {theme as oceanTheme} from './theme';\nexport {oceanTheme};\n",- );- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'theme.ts'),- 'export const theme = {};\n',- );-+ it('follows a default re-export', async () => {+ writeTheme({+ source: "export {default as oceanTheme} from './theme';\n",+ files: {'theme.ts': 'export default {};\n'},+ });await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).resolves.toEqual([- expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),- ]);+ ).resolves.toHaveLength(1);});- it('accepts a source-less export backed by a bare package import', async () => {- writeCatalog([ocean]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "import {defineTheme as oceanTheme} from '@astryxdesign/core/theme';\nexport {oceanTheme};\n",- );+ it('follows an export-all barrel', async () => {+ writeTheme({+ source: "export * from './theme';\n",+ files: {'theme.ts': 'export const oceanTheme = {};\n'},+ });+ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toHaveLength(1);+ });+ it('accepts a runtime binding imported from a package', async () => {+ writeTheme({+ source:+ "import {defineTheme as oceanTheme} from '@astryxdesign/core/theme';\nexport {oceanTheme};\n",+ });await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).resolves.toEqual([- expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),- ]);+ ).resolves.toHaveLength(1);});- it('follows a listed default re-export', async () => {- writeCatalog([{...ocean, files: ['oceanTheme.ts', 'theme.ts']}]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "export {default as oceanTheme} from './theme';\n",- );- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'theme.ts'),- 'export default {};\n',- );+ it('copies unreferenced nested authoring artifacts as part of the directory', () => {+ writeTheme({+ files: {+ 'tokens/ocean.palette.ts': 'export const palette = {};\n',+ 'receipts/palette.json': '{"version":1}\n',+ },+ });+ expect(discoverThemeDirectory(tmpDir, '@acme/themes')[0].files).toEqual([+ 'oceanTheme.ts',+ 'oceanTheme.doc.mjs',+ 'receipts/palette.json',+ 'tokens/ocean.palette.ts',+ ]);+ });+ it('rejects a theme source that imports its descriptor', async () => {+ writeTheme({+ source:+ "import metadata from './oceanTheme.doc.mjs';\nvoid metadata;\nexport const oceanTheme = {};\n",+ });await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).resolves.toEqual([- expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),- ]);+ ).rejects.toThrow(/must not import its descriptor "oceanTheme\.doc\.mjs"/u);});- it('follows local export-all barrels without executing them', async () => {- writeCatalog([{...ocean, files: ['oceanTheme.ts', 'theme.ts']}]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "export * from './theme';\n",- );+ it('rejects a local import outside the theme directory', async () => {+ writeTheme({+ source:+ "import {palette} from '../outside';\nexport const oceanTheme = {palette};\n",+ });fs.writeFileSync(- path.join(tmpDir, 'ocean', 'theme.ts'),- "throw new Error('theme source executed');\nexport const oceanTheme = {};\n",+ path.join(tmpDir, 'outside.ts'),+ 'export const palette = {};\n',);-await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).resolves.toEqual([- expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),- ]);+ ).rejects.toThrow(/must resolve to a file inside the theme directory/u);});- it('accepts a listed nested palette import without executing it', async () => {- writeCatalog([- {...ocean, files: ['oceanTheme.ts', 'tokens/ocean.palette.ts']},- ]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "import {oceanPalette} from './tokens/ocean.palette';\nexport const oceanTheme = {oceanPalette};\n",- );+ it('rejects a literal dynamic import outside the theme directory', async () => {+ writeTheme({+ extension: '.mjs',+ source: "void import('../extra.mjs');\nexport const oceanTheme = {};\n",+ });fs.writeFileSync(- path.join(tmpDir, 'ocean', 'tokens', 'ocean.palette.ts'),- "throw new Error('palette source executed');\nexport const oceanPalette = {};\n",+ path.join(tmpDir, 'extra.mjs'),+ 'export const extra = {};\n',);-await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).resolves.toEqual([- expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),- ]);+ ).rejects.toThrow(/must resolve to a file inside the theme directory/u);});- it('rejects a direct import from an unlisted theme file', async () => {- writeCatalog([ocean]);- fs.mkdirSync(path.join(tmpDir, 'ocean', 'tokens'), {recursive: true});+ it('rejects a local re-export outside the theme directory', async () => {+ writeTheme({source: "export * from '../outside';\n"});fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "import {oceanPalette} from './tokens/ocean.palette';\nexport const oceanTheme = {oceanPalette};\n",- );- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'tokens', 'ocean.palette.ts'),- 'export const oceanPalette = {};\n',+ path.join(tmpDir, 'outside.ts'),+ 'export const oceanTheme = {};\n',);-await expect(discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).rejects.toThrow(- /must resolve to a listed file inside the theme directory/u,+ ).rejects.toThrow(/must resolve to a file inside the theme directory/u);+ });++ it('rejects the obsolete central manifest even when descriptors exist', () => {+ writeTheme();+ fs.writeFileSync(path.join(tmpDir, 'manifest.json'), '{"version":1}\n');+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /the theme catalog Astryx 0\.6 wrote.*astryx upgrade --from 0\.6\.3 --path \. --apply/u,);});- it('rejects a direct import outside the theme directory', async () => {- writeCatalog([ocean]);+ it('rejects a descriptor placed at the themes root', () => {fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "import {oceanPalette} from '../outside';\nexport const oceanTheme = {oceanPalette};\n",+ path.join(tmpDir, 'oceanTheme.doc.mjs'),+ descriptorSource({+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: '',+ maintained: true,+ }),);- fs.writeFileSync(- path.join(tmpDir, 'outside.ts'),- 'export const oceanPalette = {};\n',+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /must be inside a lower-kebab theme directory/u,);+ });- await expect(- discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).rejects.toThrow(- /must resolve to a listed file inside the theme directory/u,+ it('rejects a missing descriptor', () => {+ const dir = path.join(tmpDir, 'ocean');+ fs.mkdirSync(dir);+ fs.writeFileSync(+ path.join(dir, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',+ );+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme "ocean" for @acme/themes must contain exactly one same-stem .doc.mjs descriptor; found 0 beside "oceanTheme.ts".',);});- it('rejects a literal dynamic import from an unlisted file', async () => {- const mjsTheme = {- ...ocean,- entry: 'oceanTheme.mjs',- files: ['oceanTheme.mjs'],- };- writeCatalog([mjsTheme]);+ it('rejects more than one descriptor', () => {+ const dir = writeTheme();fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.mjs'),- "void import('./extra.mjs');\nexport const oceanTheme = {};\n",+ path.join(dir, 'other.doc.mjs'),+ descriptorSource({+ type: 'theme',+ name: 'ocean',+ displayName: 'Other',+ description: '',+ maintained: false,+ }),);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'extra.mjs'),- 'export const extra = {};\n',+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme "ocean" for @acme/themes must contain exactly one same-stem .doc.mjs descriptor; found 2: "oceanTheme.doc.mjs", "other.doc.mjs".',);+ });- await expect(- discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).rejects.toThrow(- /must resolve to a listed file inside the theme directory/u,+ it('rejects missing and ambiguous same-stem source files', () => {+ const dir = writeTheme();+ fs.rmSync(path.join(dir, 'oceanTheme.ts'));+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /exactly one same-stem source.*found 0/u,);- });- it('rejects a re-export outside the theme directory', async () => {- writeCatalog([ocean]);fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "export * from '../outside';\n",+ path.join(dir, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',);fs.writeFileSync(- path.join(tmpDir, 'outside.ts'),+ path.join(dir, 'oceanTheme.mjs'),'export const oceanTheme = {};\n',);+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /exactly one same-stem source.*found 2/u,+ );+ });- await expect(- discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).rejects.toThrow(- /must resolve to a listed file inside the theme directory/u,+ it('rejects descriptor identity that differs from its directory', () => {+ writeTheme({doc: {name: 'sea'}});+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme descriptor oceanTheme.doc.mjs for @acme/themes names "sea" but its directory is "ocean".',);});- it('rejects a re-export from an unlisted theme file', async () => {- writeCatalog([ocean]);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'oceanTheme.ts'),- "export * from './theme';\n",+ it('rejects malformed descriptor fields and unknown catalog-era fields', () => {+ writeTheme({doc: {maintained: 'yes'}});+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /maintained/u,);- fs.writeFileSync(- path.join(tmpDir, 'ocean', 'theme.ts'),- 'export const oceanTheme = {};\n',++ fs.rmSync(path.join(tmpDir, 'ocean'), {recursive: true});+ writeTheme({doc: {entry: 'oceanTheme.ts'}});+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /unrecognized key|entry/iu,+ );+ });++ it('rejects invalid theme directory and source stem names', () => {+ writeTheme({slug: 'Ocean'});+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /invalid directory/u,);- await expect(- discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),- ).rejects.toThrow(- /must resolve to a listed file inside the theme directory/u,+ fs.rmSync(path.join(tmpDir, 'Ocean'), {recursive: true});+ writeTheme({stem: 'ocean-theme'});+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /not a valid runtime export name/u,);});- it('rejects duplicate slugs case-insensitively', () => {- writeCatalog([ocean, {...ocean, slug: 'OCEAN'}]);- expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(- /invalid slug|duplicate slug/u,+ it('rejects symlinks inside the copy boundary', () => {+ const dir = writeTheme();+ const outside = path.join(tmpDir, 'outside.json');+ fs.writeFileSync(outside, '{}\n');+ fs.symlinkSync(outside, path.join(dir, 'outside.json'));+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme "ocean" for @acme/themes contains symlink "outside.json"; theme files must be regular files inside the theme directory.',);});+});- it('rejects files that escape the theme directory', () => {- fs.mkdirSync(path.join(tmpDir, 'ocean'), {recursive: true});- fs.writeFileSync(- path.join(tmpDir, 'outside.ts'),- 'export const oceanTheme = {};\n',+const TYPE = "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */";+const BODY =+ "{type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Blue and calm.', maintained: true}";++/** @param {string} source the whole descriptor file */+function writeDescriptor(source) {+ const dir = writeTheme();+ fs.writeFileSync(path.join(dir, 'oceanTheme.doc.mjs'), source);+}++describe('theme descriptor type annotation', () => {+ it.each([+ ['the annotation on the export', `${TYPE}\nexport default ${BODY};\n`],+ [+ 'a header comment above the annotation',+ `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n${TYPE}\nexport default ${BODY};\n`,+ ],+ [+ 'a multi-line JSDoc block',+ `/**\n * Ocean.\n *\n * @type {import("@astryxdesign/cli/authoring").ThemeDoc}\n */\nexport default ${BODY};\n`,+ ],+ [+ 'a typedef alias',+ `/** @typedef {import('@astryxdesign/cli/authoring').ThemeDoc} ThemeDoc */\n\n/** @type {ThemeDoc} */\nexport default ${BODY};\n`,+ ],+ [+ 'a typedef alias declared after the export',+ `/** @type {Doc} */\nexport default ${BODY};\n/** @typedef {import('@astryxdesign/cli/authoring').ThemeDoc} Doc */\n`,+ ],+ [+ 'an @import of the type',+ `/** @import {ThemeDoc} from '@astryxdesign/cli/authoring' */\n/** @type {ThemeDoc} */\nexport default ${BODY};\n`,+ ],+ [+ 'a renamed @import',+ `/** @import {ComponentDoc, ThemeDoc as Doc} from '@astryxdesign/cli/authoring' */\n/** @type {Doc} */\nexport default ${BODY};\n`,+ ],+ [+ 'a namespace @import',+ `/** @import * as authoring from '@astryxdesign/cli/authoring' */\n/** @type {authoring.ThemeDoc} */\nexport default ${BODY};\n`,+ ],+ ['a JSDoc cast of the object', `export default ${TYPE} (${BODY});\n`],+ [+ 'a JSDoc cast inside outer parentheses',+ `export default (${TYPE} (${BODY}));\n`,+ ],+ [+ 'a @satisfies cast',+ `export default ${TYPE.replace('@type', '@satisfies')} (${BODY});\n`,+ ],+ ...['!T', '?T', 'T=', '(T)', 'T | null', 'undefined | T', 'T & {}'].map(+ form => [+ `the type written {${form}}`,+ `/** @type {${form.replace('T', "import('@astryxdesign/cli/authoring').ThemeDoc")}} */\nexport default ${BODY};\n`,+ ],+ ),+ [+ 'an @import with a type modifier',+ `/** @import {type ThemeDoc} from '@astryxdesign/cli/authoring' */\n/** @type {ThemeDoc} */\nexport default ${BODY};\n`,+ ],+ [+ 'a chain of typedef aliases',+ `/** @typedef {import('@astryxdesign/cli/authoring').ThemeDoc} A */\n/** @typedef {A} B */\n/** @type {B} */\nexport default ${BODY};\n`,+ ],+ ])('accepts %s', (_, source) => {+ writeDescriptor(source);+ expect(discoverThemeDirectory(tmpDir, '@acme/themes')).toHaveLength(1);+ });++ it.each([+ ['a line comment', `// ${TYPE.slice(4, -3)}\nexport default ${BODY};\n`],+ [+ 'a block comment that is not JSDoc',+ `/* ${TYPE.slice(4, -3)} */\nexport default ${BODY};\n`,+ ],+ ['an annotation after the export', `export default ${BODY};\n${TYPE}\n`],+ [+ 'an annotation inside a string value',+ `export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: "${TYPE.slice(4, -3)}", maintained: true};\n`,+ ],+ [+ 'an annotation on a property',+ `export default {\n ${TYPE}\n type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Blue.', maintained: true};\n`,+ ],+ [+ 'an unparenthesized inline annotation',+ `export default ${TYPE} ${BODY};\n`,+ ],+ [+ 'an annotation inside the parentheses',+ `export default (${TYPE} ${BODY});\n`,+ ],+ [+ 'a later JSDoc between the annotation and the export',+ `${TYPE}\n/** Ocean. */\nexport default ${BODY};\n`,+ ],+ [+ 'a typedef written as a line comment',+ `// @typedef {import('@astryxdesign/cli/authoring').ThemeDoc} ThemeDoc\n/** @type {ThemeDoc} */\nexport default ${BODY};\n`,+ ],+ [+ 'an alias of another public type',+ `/** @typedef {import('@astryxdesign/cli/authoring').ComponentDoc} ThemeDoc */\n/** @type {ThemeDoc} */\nexport default ${BODY};\n`,+ ],+ [+ 'a ThemeDoc from another module',+ `/** @type {import('@astryxdesign/core').ThemeDoc} */\nexport default ${BODY};\n`,+ ],+ [+ 'a type in a code span before the real @type {object}',+ `/** Not \`${TYPE.slice(4, -3)}\` here. @type {object} */\nexport default ${BODY};\n`,+ ],+ [+ 'a typedef in a code span',+ `/** Declare \`@typedef {import('@astryxdesign/cli/authoring').ThemeDoc} TD\` first. */\n/** @type {TD} */\nexport default ${BODY};\n`,+ ],+ [+ 'a type in a code span of a tag',+ `/**\n * @see \` ${TYPE.slice(4, -3)}\` here\n */\nexport default ${BODY};\n`,+ ],+ [+ '@import type {...}, which is not @import syntax',+ `/** @import type {ThemeDoc} from '@astryxdesign/cli/authoring' */\n/** @type {ThemeDoc} */\nexport default ${BODY};\n`,+ ],+ [+ '@satisfies on the export statement',+ `${TYPE.replace('@type', '@satisfies')}\nexport default ${BODY};\n`,+ ],+ [+ 'an annotation before default, not before the parenthesis',+ `export ${TYPE} default (${BODY});\n`,+ ],+ [+ 'a union with another type',+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc | string} */\nexport default ${BODY};\n`,+ ],+ ])('rejects %s', (_, source) => {+ writeDescriptor(source);+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme descriptor oceanTheme.doc.mjs for @acme/themes must declare its public ThemeDoc type from @astryxdesign/cli/authoring.',+ );+ });+});++describe('theme descriptor values', () => {+ it.each([+ ['displayName', {displayName: ' '}],+ ['name', {name: ' '}],+ ])('rejects a blank %s', (field, doc) => {+ writeTheme({doc});+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ `Theme descriptor oceanTheme.doc.mjs for @acme/themes is invalid: ${field}: ${field} must not be blank`,+ );+ });++ it.each(['', ' '])('accepts a blank description (%j)', description => {+ writeTheme({doc: {description}});+ expect(discoverThemeDirectory(tmpDir, '@acme/themes')[0].description).toBe(+ description,+ );+ });++ it.each(['__proto__', "'__proto__'", 'extra'])(+ 'rejects the unknown key %s',+ key => {+ writeDescriptor(+ `${TYPE}\nexport default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Blue.', maintained: true, ${key}: 'x'};\n`,+ );+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ `Theme descriptor oceanTheme.doc.mjs for @acme/themes is invalid: (root): Unrecognized key: "${key.replaceAll("'", '')}"`,+ );+ },+ );++ it('rejects a BigInt where a string belongs', () => {+ writeDescriptor(+ `${TYPE}\nexport default {type: 'theme', name: 'ocean', displayName: 10n, description: 'Blue.', maintained: true};\n`,+ );+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ /must use static string and boolean values/u,);+ });++ it('reuses a read while the file keeps its size and mtime', () => {+ const dir = writeTheme();+ const file = path.join(dir, 'oceanTheme.doc.mjs');+ const pinned = new Date('2020-01-01T00:00:00Z');+ fs.utimesSync(file, pinned, pinned);+ expect(discoverThemeDirectory(tmpDir, '@acme/themes')[0].displayName).toBe(+ 'Ocean',+ );+fs.writeFileSync(- path.join(tmpDir, 'manifest.json'),- JSON.stringify({- version: 1,- themes: [- {- ...ocean,- entry: '../outside.ts',- files: ['../outside.ts'],- },- ],- }),+ file,+ fs.readFileSync(file, 'utf-8').replace('"Ocean"', '"Coral"'),+ );+ fs.utimesSync(file, pinned, pinned);+ expect(discoverThemeDirectory(tmpDir, '@acme/themes')[0].displayName).toBe(+ 'Ocean',);- expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(- /must stay inside/u,++ const later = new Date('2020-01-01T00:00:01Z');+ fs.utimesSync(file, later, later);+ expect(discoverThemeDirectory(tmpDir, '@acme/themes')[0].displayName).toBe(+ 'Coral',);});+});- it('rejects a missing catalog file and a missing listed source', () => {- expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(- /must contain manifest\.json/u,+describe('theme folder messages', () => {+ it('names the package and file of a symlinked descriptor', () => {+ const dir = path.join(tmpDir, 'ocean');+ fs.mkdirSync(dir);+ fs.writeFileSync(+ path.join(dir, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',);+ const elsewhere = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-linked-'));+ try {+ const target = path.join(elsewhere, 'oceanTheme.doc.mjs');+ fs.writeFileSync(target, `${TYPE}\nexport default ${BODY};\n`);+ fs.symlinkSync(target, path.join(dir, 'oceanTheme.doc.mjs'));+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme "ocean" for @acme/themes contains symlink "oceanTheme.doc.mjs"; theme files must be regular files inside the theme directory.',+ );+ } finally {+ fs.rmSync(elsewhere, {recursive: true, force: true});+ }+ });++ it('names the package and both files of a nested second descriptor', () => {+ writeTheme({+ files: {'extra/otherTheme.doc.mjs': `${TYPE}\nexport default ${BODY};\n`},+ });+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme "ocean" for @acme/themes contains more than one .doc.mjs descriptor: "oceanTheme.doc.mjs" and "extra/otherTheme.doc.mjs".',+ );+ });+});++const UNPUBLISHED = [+ '.DS_Store',+ '._oceanTheme.ts',+ '.gitignore',+ '.npmignore',+ '.npmrc',+ 'oceanTheme.ts.orig',+ 'npm-debug.log',+ 'palette/.DS_Store',+ 'palette/npm-debug.log',+ '.git/HEAD',+ 'CVS/Entries',+ 'node_modules/dep/index.js',+];++describe('files a theme leaves out', () => {+ it('leaves out dot entries and files npm never publishes, at any depth', () => {+ const dir = writeTheme({files: {'palette/tokens.ts': 'export {};\n'}});+ for (const file of UNPUBLISHED) {+ fs.mkdirSync(path.dirname(path.join(dir, file)), {recursive: true});+ fs.writeFileSync(path.join(dir, file), 'x\n');+ }+ fs.symlinkSync(path.join(dir, 'palette'), path.join(dir, '.linked'));+ fs.mkdirSync(path.join(tmpDir, 'node_modules', 'dep'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, 'npm-debug.log'), 'x\n');+ expect(discoverThemeDirectory(tmpDir, '@acme/themes')[0].files).toEqual([+ 'oceanTheme.ts',+ 'oceanTheme.doc.mjs',+ 'palette/tokens.ts',+ ]);+ });+});++describe('folders under a theme root that are not themes', () => {+ it('skips dot-folders and folders with neither a descriptor nor a theme source', () => {+ writeTheme();+ const stray = {+ 'shared/palette.ts': 'export const blue = "#00f";\n',+ '.cache/state.json': '{}\n',+ '.cache/stateTheme.ts': 'export const stateTheme = {};\n',+ '__tests__/oceanTheme.test.ts': 'export {};\n',+ 'Shared_Helpers/colors.ts': 'export const red = "#f00";\n',+ };+ for (const [file, contents] of Object.entries(stray)) {+ fs.mkdirSync(path.dirname(path.join(tmpDir, file)), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, file), contents);+ }+ fs.mkdirSync(path.join(tmpDir, 'empty'));+ fs.symlinkSync(path.join(tmpDir, 'shared'), path.join(tmpDir, '.linked'));+ expect(+ discoverThemeDirectory(tmpDir, '@acme/themes').map(theme => theme.slug),+ ).toEqual(['ocean']);+ });++ it('still fails a folder with a theme source and no descriptor', () => {+ writeTheme();+ fs.mkdirSync(path.join(tmpDir, 'sand'));fs.writeFileSync(- path.join(tmpDir, 'manifest.json'),- JSON.stringify({version: 1, themes: [ocean]}),+ path.join(tmpDir, 'sand', 'sandTheme.ts'),+ 'export const sandTheme = {};\n',);- expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(- /missing directory "ocean"/u,+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme "sand" for @acme/themes must contain exactly one same-stem .doc.mjs descriptor; found 0 beside "sandTheme.ts".',+ );+ });++ it('still fails a folder whose descriptor sits in a subfolder', () => {+ writeTheme({slug: 'reef', stem: 'reefTheme', doc: {name: 'reef'}});+ fs.mkdirSync(path.join(tmpDir, 'reef', 'src'));+ for (const file of ['reefTheme.ts', 'reefTheme.doc.mjs']) {+ fs.renameSync(+ path.join(tmpDir, 'reef', file),+ path.join(tmpDir, 'reef', 'src', file),+ );+ }+ expect(() => discoverThemeDirectory(tmpDir, '@acme/themes')).toThrow(+ 'Theme "reef" for @acme/themes must contain exactly one same-stem .doc.mjs descriptor; found 0; "src/reefTheme.doc.mjs" is in a subfolder.',);});+});- it('requires the named entry to be one of the copied files', () => {- writeCatalog([{...ocean, files: ['other.ts']}]);- expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(- /must include entry/u,+describe('bundled theme files', () => {+ it('copies what the bundle has always copied, entry first, without its descriptor', () => {+ const themes = discoverBundledThemes();+ expect(themes.find(theme => theme.slug === 'neutral')?.files).toEqual([+ 'neutralTheme.ts',+ 'icons.tsx',+ 'neutralPalettes.ts',+ 'neutralPalettes.generated.ts',+ 'neutralPaletteRefs.generated.ts',+ 'neutralPalettes.generated.receipt.json',+ 'palette.config.json',+ ]);+ for (const theme of themes) {+ expect(theme.files[0]).toBe(theme.entry);+ expect(theme.files.some(file => file.endsWith('.doc.mjs'))).toBe(false);+ }+ });++ it('passes the full source check it skips at runtime', () => {+ const bundled = discoverBundledThemes();+ const checked = discoverThemeDirectory(+ path.dirname(bundled[0].sourceDir),+ BUNDLED_THEME_PACKAGE,+ );+ expect(checked.map(theme => theme.slug)).toEqual(+ bundled.map(theme => theme.slug),);});++ it('loads no parser on import and only the descriptor parser for bundled themes', () => {+ const script = `+ import {createRequire} from 'node:module';+ const cache = createRequire(import.meta.url).cache;+ const loaded = name => Object.keys(cache).some(file => file.includes('/node_modules/' + name + '/'));+ const state = () => ({babel: loaded('@babel/parser'), jscodeshift: loaded('jscodeshift')});+ const discovery = await import(${JSON.stringify(new URL('./theme-discovery.mjs', import.meta.url).href)});+ const imported = state();+ discovery.discoverBundledThemes();+ console.log(JSON.stringify({imported, bundled: state()}));+ `;+ const output = execFileSync(+ process.execPath,+ ['--input-type=module', '-e', script],+ {encoding: 'utf-8'},+ );+ expect(JSON.parse(output)).toEqual({+ imported: {babel: false, jscodeshift: false},+ bundled: {babel: true, jscodeshift: false},+ });+ });});diff --git a/packages/cli/foundation/doc-compiler/bundle.mjs b/packages/cli/foundation/doc-compiler/bundle.mjsnew file mode 100644index 0000000000..eccdfa464c--- /dev/null+++ b/packages/cli/foundation/doc-compiler/bundle.mjs@@ -0,0 +1,218 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Compiled docs bundle — every descriptor a project reads, compiled at+ * once.+ *+ * @input A loaded Project and a reading language.+ * @output A plain-JSON bundle: the schema version, the language, one compiled+ * node per descriptor (a doc topic with its extensions is one linked node),+ * and every compiler diagnostic, in one deterministic order.+ * @position The whole-project view of the compiler, for checks that need every+ * node at once; today only tests call it. Single reads stay lazy:+ * ./read.mjs and api/docs/_adapter.mjs compile only what a read touches.+ * Internal to the CLI.+ */++import {+ readThemeDescriptorValue,+ themeDescriptorLabel,+} from '../discovery/theme-discovery.mjs';+import {+ COMPILED_DOC_SCHEMA_VERSION,+ linkReferenceTopic,+ lowerReferenceTopic,+} from './compile.mjs';+import {diagnostic as rawDiagnostic, sortDiagnostics} from './diagnostics.mjs';+import {collectDocInputs} from './inputs.mjs';+import {compileDocFile, loadTopicInput} from './read.mjs';+import {packageSource, scrubPaths} from './source.mjs';++/**+ * A compiler diagnostic whose message names files by package, never by their+ * location on this machine.+ * @param {string} code+ * @param {Parameters<typeof rawDiagnostic>[1]} at+ */+function diagnostic(code, at) {+ return rawDiagnostic(code, {+ ...at,+ message: scrubPaths(at.message) || '(the error had no message)',+ });+}++/**+ * @typedef {import('./compile.mjs').CompiledDocNode} CompiledDocNode+ * @typedef {import('./compile.mjs').CompiledReferenceNode} CompiledReferenceNode+ * @typedef {import('./diagnostics.mjs').CompilerDiagnostic} CompilerDiagnostic+ */++/**+ * @typedef {object} CompiledDocsBundle+ * @property {number} schemaVersion+ * @property {string | null} lang+ * @property {Array<CompiledDocNode | CompiledReferenceNode>} nodes in the order+ * the project reads its roots+ * @property {CompilerDiagnostic[]} diagnostics sorted+ */++/**+ * Compile every descriptor the project reads.+ *+ * A problem with one descriptor withdraws that node and is reported; it never+ * stops the rest, so every node in the bundle reads back through the sealed+ * parser. A token reference that finds nothing is a warning: readers+ * print a placeholder for it, as they always have.+ *+ * @param {import('../config/project.mjs').Project} project+ * @param {{lang?: string | null}} [options]+ * @returns {Promise<CompiledDocsBundle>}+ */+export async function compileDocs(project, {lang = null} = {}) {+ const {inputs, problems} = await collectDocInputs(project);+ /** @type {CompilerDiagnostic[]} */+ const diagnostics = problems.map(problem =>+ diagnostic(problem.code, {+ provider: problem.provider,+ source: problem.source,+ message: problem.message,+ }),+ );+ const catalog = await project.docs();++ /** @type {Map<string, CompiledReferenceNode>} lowered topics by name */+ const topics = new Map();+ for (const entry of catalog.entries()) {+ const input = await loadTopicInput(entry, lang);+ const failed = [input.base, ...input.extensions].filter(+ file => 'error' in file || 'overlayError' in file,+ );+ if (failed.length > 0) {+ for (const file of failed) {+ const fromExtension = input.extensions.find(ext => ext === file);+ const path = fromExtension+ ? entry.extensions[input.extensions.indexOf(fromExtension)].path+ : entry.path;+ diagnostics.push(+ diagnostic('error' in file ? 'load_failed' : 'overlay_failed', {+ provider: fromExtension ? fromExtension.provider : entry.package,+ source: packageSource(path),+ message: `${file.file}: ${messageOf('error' in file ? file.error : file.overlayError)}`,+ }),+ );+ }+ continue;+ }+ try {+ topics.set(entry.name.toLowerCase(), lowerReferenceTopic(input));+ } catch (error) {+ diagnostics.push(+ diagnostic(+ errorCode(error) === 'not_json' ? 'not_json' : 'invalid_topic',+ {+ provider: entry.package,+ source: packageSource(entry.path),+ message: messageOf(error),+ },+ ),+ );+ }+ }+ /** @param {string} name */+ const lowerTarget = async name => {+ const target = catalog.resolve(name);+ return target ? (topics.get(target.name.toLowerCase()) ?? null) : null;+ };++ /** @type {Array<CompiledDocNode | CompiledReferenceNode>} */+ const nodes = [];+ for (const input of inputs) {+ if (input.root === 'docs') {+ if (input.role !== 'base') continue;+ const lowered = topics.get(input.name.toLowerCase());+ if (!lowered) continue;+ const linked = await linkReferenceTopic(lowered, lowerTarget);+ diagnostics.push(...unresolvedReferences(linked, input));+ nodes.push(linked);+ continue;+ }+ const result = await compileDocFile(+ input.file,+ {+ root: input.root,+ provider: input.owner,+ id: input.id,+ lang:+ input.root === 'components' || input.root === 'hooks' ? lang : null,+ check: true,+ ...(input.root === 'templates' ? {loader: 'template'} : {}),+ ...(input.root === 'themes'+ ? {+ label: themeDescriptorLabel(input.file, input.owner),+ readStatic: () =>+ readThemeDescriptorValue(+ input.file,+ themeDescriptorLabel(input.file, input.owner),+ ),+ }+ : {}),+ },+ {node: true},+ );+ diagnostics.push(...result.diagnostics);+ // A descriptor with a problem of its own withdraws its node.+ if (result.node && !result.diagnostics.some(d => d.severity === 'error')) {+ nodes.push(result.node);+ }+ }++ return {+ schemaVersion: COMPILED_DOC_SCHEMA_VERSION,+ lang,+ nodes,+ diagnostics: sortDiagnostics(diagnostics),+ };+}++/**+ * A warning for each token reference in a linked topic that finds no topic or+ * no section.+ * @param {CompiledReferenceNode} node+ * @param {import('./inputs.mjs').DocInput} input+ * @returns {CompilerDiagnostic[]}+ */+function unresolvedReferences(node, input) {+ /** @type {CompilerDiagnostic[]} */+ const found = [];+ for (const section of node.doc.sections) {+ for (const block of section.content) {+ if (block?.type !== 'token-ref') continue;+ const status = block.resolved?.status;+ if (status === 'resolved') continue;+ found.push(+ diagnostic('unresolved_reference', {+ provider: input.owner,+ source: input.source,+ field: `sections.${section.id}`,+ message:+ status === 'unknown-topic'+ ? `"${node.id}" section "${section.id}" refers to topic "${block.topic}", which this project does not have.`+ : `"${node.id}" section "${section.id}" refers to section "${block.section}" of "${block.topic}", which that topic does not have.`,+ }),+ );+ }+ }+ return found;+}++/** @param {unknown} error */+function messageOf(error) {+ return error instanceof Error ? error.message : String(error);+}++/** @param {unknown} error */+function errorCode(error) {+ return error && typeof error === 'object' && 'compilerCode' in error+ ? error.compilerCode+ : undefined;+}diff --git a/packages/cli/foundation/doc-compiler/bundle.test.mjs b/packages/cli/foundation/doc-compiler/bundle.test.mjsnew file mode 100644index 0000000000..075ab268da--- /dev/null+++ b/packages/cli/foundation/doc-compiler/bundle.test.mjs@@ -0,0 +1,255 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file compileDocs: every descriptor a project reads compiles to one node or+ * a diagnostic, and the bundle reads back through its sealed parser.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {Project} from '../config/project.mjs';+import {CLI_ROOT} from '../fs/paths.mjs';+import {compileDocs} from './bundle.mjs';+import {COMPILED_DOC_KINDS} from './compile.mjs';+import {collectDocInputs} from './inputs.mjs';+import {parseCompiledDocsBundle} from './ir.mjs';++const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');++let tmpDir;++beforeEach(() => {+ // Inside the repo, so the project finds this checkout's Core.+ tmpDir = fs.mkdtempSync(path.join(REPO_ROOT, '.astryx-doc-bundle-'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer', version: '1.0.0'}),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('compileDocs over what this repo ships', () => {+ it('compiles every descriptor, in every language, with nothing to report', async () => {+ const project = await Project.load(tmpDir);+ const {inputs} = await collectDocInputs(project);+ // One node per input, except that a topic and its extensions are one node.+ const expected = inputs.filter(+ input => input.root !== 'docs' || input.role === 'base',+ ).length;+ for (const lang of [null, 'zh', 'dense']) {+ const bundle = await compileDocs(project, {lang});+ expect(bundle.diagnostics).toEqual([]);+ expect(bundle.nodes).toHaveLength(expected);+ expect(new Set(bundle.nodes.map(node => node.kind))).toEqual(+ new Set(COMPILED_DOC_KINDS),+ );+ // Plain JSON that reads back through the sealed parser, as written.+ const copy = JSON.parse(JSON.stringify(bundle));+ expect(parseCompiledDocsBundle(copy)).toEqual(bundle);+ }+ }, 180_000);++ it('is deterministic', async () => {+ const one = await compileDocs(await Project.load(tmpDir));+ const two = await compileDocs(await Project.load(tmpDir));+ expect(JSON.stringify(two)).toBe(JSON.stringify(one));+ }, 120_000);++ it('never carries a machine path', async () => {+ const bundle = await compileDocs(await Project.load(tmpDir));+ const text = JSON.stringify(bundle);+ expect(text.includes(REPO_ROOT)).toBe(false);+ expect(text.includes(tmpDir)).toBe(false);+ }, 120_000);+});++describe('compileDocs over a broken integration', () => {+ /**+ * @param {string} rel+ * @param {string} text+ */+ function write(rel, text) {+ const file = path.join(tmpDir, 'node_modules', '@acme', 'kit', rel);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, text);+ }++ /** @param {object} fields */+ const topic = fields =>+ `export default ${JSON.stringify({+ type: 'generic',+ title: 'Acme',+ description: 'Acme notes.',+ sections: [{title: 'Acme', content: [{type: 'prose', text: 'Hi.'}]}],+ ...fields,+ })};\n`;++ beforeEach(() => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ version: '1.0.0',+ dependencies: {'@acme/kit': '^1.0.0'},+ }),+ );+ write(+ 'package.json',+ JSON.stringify({name: '@acme/kit', version: '1.0.0'}),+ );+ write(+ 'astryx.integration.mjs',+ "export default {components: './components', docs: './docs'};\n",+ );+ write(+ 'components/AcmeCard.tsx',+ 'export function AcmeCard() { return null; }\n',+ );+ write(+ 'components/AcmeCard.doc.mjs',+ "export default {type: 'component', name: 'AcmeCard', displayName: 'Acme Card', usage: {description: 'A card.'}, props: []};\n",+ );+ write('docs/acme-guide.doc.mjs', topic({name: 'acme-guide'}));+ });++ it('warns on a token reference that finds nothing, and still compiles the topic', async () => {+ write(+ 'docs/acme-guide.doc.mjs',+ topic({+ name: 'acme-guide',+ sections: [+ {+ title: 'Colors',+ content: [+ {type: 'token-ref', topic: 'no-such-topic', section: 'x'},+ {type: 'token-ref', topic: 'tokens', section: 'no-such-section'},+ ],+ },+ ],+ }),+ );+ const bundle = await compileDocs(await Project.load(tmpDir));+ const warnings = bundle.diagnostics.filter(d => d.provider === '@acme/kit');+ expect(warnings.map(d => [d.code, d.severity, d.field])).toEqual([+ ['unresolved_reference', 'warning', 'sections.colors'],+ ['unresolved_reference', 'warning', 'sections.colors'],+ ]);+ expect(+ warnings.every(d => d.source === '@acme/kit/docs/acme-guide.doc.mjs'),+ ).toBe(true);+ expect(bundle.nodes.some(node => node.id === 'acme-guide')).toBe(true);+ });++ it('reports a component doc that fails to load, and compiles the rest', async () => {+ write(+ 'components/AcmeCard.doc.mjs',+ "throw new Error('boom');\nexport default {};\n",+ );+ const project = await Project.load(tmpDir);+ const bundle = await compileDocs(project);+ const found = bundle.diagnostics.filter(d => d.provider === '@acme/kit');+ // Discovery lists the doc; compiling it fails at load, and only it.+ expect(found.map(d => [d.code, d.source])).toEqual([+ ['load_failed', '@acme/kit/components/AcmeCard.doc.mjs'],+ ]);+ expect(found[0].message).toMatch(/boom/);+ expect(bundle.nodes.some(node => node.kind === 'reference')).toBe(true);+ });++ it('withdraws a descriptor that fails its parser, and the bundle still reads back', async () => {+ write(+ 'components/AcmeCard.doc.mjs',+ "export default {type: 'component', displayName: 'No name'};\n",+ );+ const bundle = await compileDocs(await Project.load(tmpDir));+ const found = bundle.diagnostics.filter(d => d.provider === '@acme/kit');+ expect(found.map(d => d.code)).toEqual(['invalid_doc']);+ expect(+ bundle.nodes.some(node => node.id === '@acme/kit:components:AcmeCard'),+ ).toBe(false);+ expect(() =>+ parseCompiledDocsBundle(JSON.parse(JSON.stringify(bundle))),+ ).not.toThrow();+ });++ it('reports a topic value JSON cannot hold with the same code as any other doc', async () => {+ write(+ 'docs/acme-guide.doc.mjs',+ topic({name: 'acme-guide'}).replace('};', ', big: 1n};'),+ );+ const bundle = await compileDocs(await Project.load(tmpDir));+ const found = bundle.diagnostics.filter(d => d.provider === '@acme/kit');+ expect(found.map(d => d.code)).toContain('not_json');+ expect(found.map(d => d.code)).not.toContain('invalid_topic');+ // The compiler's code never reaches the error a reader throws.+ const {lowerTopic} = await import('../../api/docs/_adapter.mjs');+ const catalog = await (await Project.load(tmpDir)).docs();+ const entry = /** @type {any} */ (catalog.resolve('acme-guide'));+ const thrown = await lowerTopic(catalog, entry).catch(error => error);+ expect(thrown).toBeInstanceOf(Error);+ expect(/** @type {any} */ (thrown).code).toBeUndefined();+ });++ it('gives every extension file its own input, even two from one package', async () => {+ write('docs/theme-a.doc.mjs', topic({name: 'theme-a', extends: 'theme'}));+ write('docs/theme-b.doc.mjs', topic({name: 'theme-b', extends: 'theme'}));+ const project = await Project.load(tmpDir);+ const {problems} = await collectDocInputs(project);+ expect(problems.filter(p => p.code === 'duplicate_id')).toEqual([]);+ });++ it('names a package that has no name by its folder, never by its path', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ "export default {components: './components'};\n",+ );+ fs.mkdirSync(path.join(tmpDir, 'components', 'Local'), {recursive: true});+ fs.writeFileSync(+ path.join(tmpDir, 'components', 'Local', 'Local.tsx'),+ 'export {};\n',+ );+ fs.writeFileSync(+ path.join(tmpDir, 'components', 'Local', 'Local.doc.mjs'),+ "export default {type: 'component', name: 'Local', displayName: 'Local', usage: {description: 'd'}, props: []};\n",+ );+ const bundle = await compileDocs(await Project.load(tmpDir));+ const text = JSON.stringify(bundle);+ expect(text.includes(tmpDir)).toBe(false);+ expect(() => parseCompiledDocsBundle(JSON.parse(text))).not.toThrow();+ });++ it('reports an extension that fails to load against the extension, not its base', async () => {+ write('docs/theme-notes.doc.mjs', "throw new Error('bad extension');\n");+ // Discovery refuses an unloadable topic file, so the catalog never merges+ // it; compile the entry as the catalog would have if it had loaded.+ const project = await Project.load(tmpDir);+ const catalog = await project.docs();+ const theme = /** @type {any} */ (catalog.resolve('theme'));+ theme.extensions.push({+ package: '@acme/kit',+ path: path.join(+ tmpDir,+ 'node_modules',+ '@acme',+ 'kit',+ 'docs',+ 'theme-notes.doc.mjs',+ ),+ });+ const bundle = await compileDocs(project);+ const found = bundle.diagnostics.filter(d => d.code === 'load_failed');+ expect(found.map(d => [d.provider, d.source])).toEqual([+ ['@acme/kit', '@acme/kit/docs/theme-notes.doc.mjs'],+ ]);+ // The broken extension withdraws the topic it extends, as a docs read does.+ expect(bundle.nodes.some(node => node.id === 'theme')).toBe(false);+ });+});diff --git a/packages/cli/foundation/doc-compiler/compile.mjs b/packages/cli/foundation/doc-compiler/compile.mjsindex 1de2d28d8d..f34554a479 100644--- a/packages/cli/foundation/doc-compiler/compile.mjs+++ b/packages/cli/foundation/doc-compiler/compile.mjs@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Doc compiler — authored reference topics in, compiled nodes out.+ * @file Doc compiler — authored docs in, compiled nodes out.** @input A {@link ReferenceTopicInput}: one topic's own file and the files of* the extensions merged onto it, each already through the authored-doc parser@@ -16,9 +16,13 @@* JSON form, the one `--json` output has always shown.* @position The one step between authored docs and every docs reader. The docs* API, doctor and search read compiled nodes, and ./lenses.mjs turns them into- * response shapes. Internal to the CLI: the public way in is `docs()`.+ * response shapes. Every other doc kind (components, hooks, templates, themes,+ * and the CLI's self-docs) lowers through {@link lowerDoc}, which ./read.mjs+ * feeds. Internal to the CLI: the public way in is the docs API.*/+import {parseTemplate} from '../../authoring/doctypes/template/parse.mjs';+import {parseTheme} from '../../authoring/doctypes/theme/parse.mjs';import {mergeTopic, problemsInTopic} from '../discovery/docs-discovery.mjs';import {sectionKey,@@ -27,10 +31,53 @@ import {withSectionKeys,withSourceTitle,} from '../discovery/docs-section-key.mjs';+import {diagnostic as rawDiagnostic} from './diagnostics.mjs';+import {scrubPaths} from './source.mjs';+import {overlayAuthoredDoc} from './overlays.mjs';+import {parseReadableDoc} from './parse-readable.mjs';++/**+ * A compiler diagnostic whose message names files by package, never by their+ * location on this machine.+ * @param {string} code+ * @param {Parameters<typeof rawDiagnostic>[1]} at+ */+function diagnostic(code, at) {+ return rawDiagnostic(code, {+ ...at,+ message: scrubPaths(at.message) || '(the error had no message)',+ });+}/** Bumped whenever the shape of a compiled node changes. */export const COMPILED_DOC_SCHEMA_VERSION = 1;+/** Every kind a compiled node has: one per authored doc kind a root reads. */+export const COMPILED_DOC_KINDS = /** @type {const} */ ([+ 'component',+ 'function',+ 'reference',+ 'page',+ 'block',+ 'schema',+ 'command',+ 'enum',+ 'theme',+]);++/**+ * The roots that read docs, and the kinds each may hold. A doc without a+ * stamped `type` (the legacy form) takes its root's first kind.+ * @type {Readonly<Record<string, readonly string[]>>}+ */+export const ROOT_KINDS = Object.freeze({+ components: ['component'],+ hooks: ['function'],+ templates: ['page', 'block'],+ themes: ['theme'],+ 'self-docs': ['command', 'function', 'schema', 'enum'],+});+/*** One authored file, as discovery loaded it.* @typedef {object} AuthoredFile@@ -191,9 +238,12 @@ function asJson(value, topic) {try {return JSON.parse(JSON.stringify(value));} catch (err) {- throw new Error(- `${topic} cannot be compiled: ${err instanceof Error ? err.message : String(err)}`,- {cause: err},+ throw Object.assign(+ new Error(+ `${topic} cannot be compiled: ${err instanceof Error ? err.message : String(err)}`,+ {cause: err},+ ),+ {compilerCode: 'not_json'},);}}@@ -260,3 +310,202 @@ function applyOverlay(docs, translation) {}),};}++/**+ * @typedef {import('./diagnostics.mjs').CompilerDiagnostic} CompilerDiagnostic+ */++/**+ * One authored doc of any kind but a reference topic, as its root loaded it.+ * @typedef {object} DocFileInput+ * @property {string} id the input's id: provider, root, and name+ * @property {keyof typeof ROOT_KINDS} root+ * @property {string} provider the package that contributes it+ * @property {string} source `<package>/<path>` of the file+ * @property {string | null} lang the overlay language, or null+ * @property {AuthoredFile} file `doc` is the authored export, not a parse+ * result; `overlay` is the translation the module exports for `lang`+ * @property {string} [label] how a parse error names the file (default: its+ * file name)+ * @property {boolean} [useParsed] carry the parser's result instead of the+ * authored export, for a reader that has always read the checked value+ */++/**+ * The parser that checks a root's docs. Templates and themes have their own;+ * every other root dispatches on the stamped type.+ * @param {string} root+ * @returns {(input: unknown, label?: string) => any}+ */+export function parserFor(root) {+ if (root === 'themes') return parseTheme;+ if (root === 'templates') return parseTemplate;+ return parseReadableDoc;+}++/**+ * A compiled node for any kind but a reference topic.+ * @typedef {object} CompiledDocNode+ * @property {number} schemaVersion+ * @property {Exclude<typeof COMPILED_DOC_KINDS[number], 'reference'>} kind+ * @property {'lowered'} stage+ * @property {string} id+ * @property {string | null} lang+ * @property {{provider: string, source: string}} provenance+ * @property {any} doc the authored doc, overlaid for `lang`, as JSON carries+ * it: key order kept, `undefined` and functions dropped+ */++/**+ * The result of lowering one doc.+ *+ * `view` is the doc as readers have always read it: the authored export (or,+ * where a reader has always read it, the parser's result), with its+ * translation laid over it, not copied and not converted. Readers print from+ * the view, so nothing they print depends on JSON. `node` is the sealed,+ * JSON-only form a whole-project compile collects.+ *+ * @typedef {object} LoweredDoc+ * @property {any} [view] absent when the file could not be read+ * @property {CompiledDocNode | null} node null when not asked for, or when a+ * problem is fatal to the node+ * @property {CompilerDiagnostic[]} diagnostics+ * @property {boolean} [loadFailed] importing the file threw+ * @property {unknown} [loadFailure] what importing the file threw (any value,+ * `undefined` included)+ * @property {boolean} [missing] the file exports no doc+ * @property {null | undefined} [missingValue] the empty export, as the reader+ * picked it+ * @property {boolean} [failed] the kind's parser threw+ * @property {unknown} [failure] what the kind's parser threw+ * @property {boolean} [overlayFailed] laying the translation over threw+ * @property {unknown} [overlayFailure] what laying the translation over threw+ */++/**+ * Lower one doc of any kind but a reference topic.+ *+ * With `check`, the doc is held to its kind's parser, and a failure is+ * recorded, not fatal: readers that never checked docs keep reading it, and a+ * checked reader turns it into the error it has always thrown. A doc stamped+ * with a kind its root does not read keeps its root's kind and carries a+ * `wrong_kind` diagnostic. With `node`, the view is also carried as JSON; a+ * value JSON cannot hold withdraws the node, never the view.+ *+ * @param {DocFileInput} input+ * @param {{check?: boolean, node?: boolean}} [options]+ * @returns {LoweredDoc}+ */+export function lowerDoc(input, {check = true, node: wantNode = true} = {}) {+ const {file} = input;+ const at = {provider: input.provider, source: input.source};+ /** @type {CompilerDiagnostic[]} */+ const diagnostics = [];+ if ('error' in file) {+ diagnostics.push(+ diagnostic('load_failed', {+ ...at,+ message: `${file.file} could not be loaded: ${messageOf(file.error)}`,+ }),+ );+ return {node: null, diagnostics, loadFailed: true, loadFailure: file.error};+ }+ if (file.doc == null) {+ diagnostics.push(+ diagnostic('missing_export', {+ ...at,+ message: `${file.file} exports no doc.`,+ }),+ );+ return {node: null, diagnostics, missing: true, missingValue: file.doc};+ }+ const allowed = ROOT_KINDS[input.root];+ if (!allowed) throw new Error(`No doc root is named "${input.root}".`);+ const stamped =+ typeof file.doc === 'object' && 'type' in file.doc+ ? file.doc.type+ : undefined;+ const kindFits = stamped === undefined || allowed.includes(stamped);+ if (!kindFits) {+ diagnostics.push(+ diagnostic('wrong_kind', {+ ...at,+ message: `${file.file} is stamped type ${JSON.stringify(stamped)}, which the ${input.root} root does not read (it reads ${allowed.join(', ')}).`,+ }),+ );+ }+ /** @type {LoweredDoc} */+ const result = {node: null, diagnostics};+ let view = file.doc;+ // A theme descriptor is read statically; its parse result is the doc.+ if (check || input.root === 'themes') {+ try {+ const parsed = parserFor(input.root)(file.doc, input.label ?? file.file);+ if (input.useParsed || input.root === 'themes') view = parsed;+ } catch (error) {+ result.failed = true;+ result.failure = error;+ diagnostics.push(+ diagnostic('invalid_doc', {...at, message: messageOf(error)}),+ );+ }+ }+ if ('overlayError' in file) {+ result.overlayFailed = true;+ result.overlayFailure = file.overlayError;+ } else if (file.overlay) {+ try {+ view = overlayAuthoredDoc(view, file.overlay);+ } catch (error) {+ result.overlayFailed = true;+ result.overlayFailure = error;+ }+ }+ if (result.overlayFailed) {+ diagnostics.push(+ diagnostic('overlay_failed', {+ ...at,+ message: `${file.file}'s translation could not be applied: ${messageOf(result.overlayFailure)}`,+ }),+ );+ return result;+ }+ result.view = view;+ if (!wantNode) return result;+ let json;+ try {+ const text = JSON.stringify(view);+ if (text === undefined) throw new TypeError('the doc is not a JSON value');+ json = JSON.parse(text);+ } catch (error) {+ diagnostics.push(+ diagnostic('not_json', {+ ...at,+ message: `${file.file} cannot be compiled: ${messageOf(error)}`,+ }),+ );+ return result;+ }+ result.node = {+ schemaVersion: COMPILED_DOC_SCHEMA_VERSION,+ kind: /** @type {CompiledDocNode['kind']} */ (+ kindFits && stamped !== undefined ? stamped : allowed[0]+ ),+ stage: 'lowered',+ id: input.id,+ lang: input.lang,+ provenance: {provider: input.provider, source: input.source},+ doc: json,+ };+ return result;+}++/** @param {unknown} error */+function messageOf(error) {+ // Any value can be thrown; describing one must never throw in its place.+ try {+ return error instanceof Error ? String(error.message) : String(error);+ } catch {+ return Object.prototype.toString.call(error);+ }+}diff --git a/packages/cli/foundation/doc-compiler/diagnostics.mjs b/packages/cli/foundation/doc-compiler/diagnostics.mjsnew file mode 100644index 0000000000..c657b8ec16--- /dev/null+++ b/packages/cli/foundation/doc-compiler/diagnostics.mjs@@ -0,0 +1,277 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Compiler diagnostics — one shape for every problem the doc compiler+ * finds.+ *+ * @input A diagnostic code, the package and file it concerns, and a message.+ * @output A plain-JSON diagnostic: a stable code, the phase that found it,+ * severity, provider, source, field, message, remediation, and the scope of+ * what it invalidates. Lists sort into one deterministic order.+ * @position Shared by every compiler phase: listing inputs, loading, parsing,+ * overlaying, lowering, linking, serializing, and reading a bundle back. A+ * code fixes its phase, severity, scope, and remediation, so no phase or+ * reader can report the same problem two ways or downgrade it.+ */++/** Compiler phases, in the order a descriptor passes through them. */+export const DIAGNOSTIC_PHASES = /** @type {const} */ ([+ 'discover',+ 'load',+ 'parse',+ 'overlay',+ 'lower',+ 'link',+ 'serialize',+ 'bundle',+]);++/**+ * What a failure invalidates: the one node it concerns, or the whole+ * compilation (a bundle that cannot be read at all).+ * @typedef {'node' | 'compilation'} DiagnosticScope+ */++/**+ * @typedef {typeof DIAGNOSTIC_PHASES[number]} DiagnosticPhase+ * @typedef {'error' | 'warning'} DiagnosticSeverity+ */++/**+ * @typedef {object} CompilerDiagnostic+ * @property {string} code stable; one of {@link DIAGNOSTIC_CODES}+ * @property {DiagnosticPhase} phase+ * @property {DiagnosticSeverity} severity+ * @property {DiagnosticScope} scope+ * @property {string | null} provider the package the problem is in+ * @property {string | null} source `<package>/<path>` of the file, never a+ * machine path+ * @property {string | null} field the field or reference at fault, when known+ * @property {string} message+ * @property {string} remediation what to do about it+ */++/**+ * @typedef {object} DiagnosticRule+ * @property {DiagnosticPhase} phase+ * @property {DiagnosticSeverity} severity+ * @property {DiagnosticScope} scope+ * @property {string} remediation+ */++/** Every code the compiler emits, with the facts it fixes. */+export const DIAGNOSTIC_CODES = Object.freeze(+ /** @type {Record<string, DiagnosticRule>} */ ({+ duplicate_file: {+ phase: 'discover',+ severity: 'error',+ scope: 'node',+ remediation:+ 'Give each descriptor one reader: move it out of all but one of the roots that read it.',+ },+ duplicate_id: {+ phase: 'discover',+ severity: 'error',+ scope: 'node',+ remediation:+ 'Rename one of the descriptors, so each name in a root belongs to one file.',+ },+ load_failed: {+ phase: 'load',+ severity: 'error',+ scope: 'node',+ remediation: 'Fix the error the file throws when it is loaded.',+ },+ missing_export: {+ phase: 'load',+ severity: 'error',+ scope: 'node',+ remediation: 'Export the doc as the default export of the file.',+ },+ invalid_doc: {+ phase: 'parse',+ severity: 'error',+ scope: 'node',+ remediation:+ 'Fix the fields the message names; `astryx docs authoring` lists every field of each doc kind.',+ },+ wrong_kind: {+ phase: 'parse',+ severity: 'error',+ scope: 'node',+ remediation:+ 'Stamp the doc with a type its root reads, or move it to the root for its type.',+ },+ overlay_failed: {+ phase: 'overlay',+ severity: 'error',+ scope: 'node',+ remediation:+ 'Fix the translation file, or remove it to read the authored text.',+ },+ invalid_topic: {+ phase: 'lower',+ severity: 'error',+ scope: 'node',+ remediation:+ 'Fix the topic or the extension the message names; an extension that breaks its base withdraws the whole topic.',+ },+ unresolved_reference: {+ phase: 'link',+ severity: 'warning',+ scope: 'node',+ remediation:+ 'Point the token reference at a topic and section that exist; `astryx docs <topic> --index` lists the section keys.',+ },+ not_json: {+ phase: 'serialize',+ severity: 'error',+ scope: 'node',+ remediation:+ 'Keep a doc to plain data: no cycles, BigInt values, or objects that cannot be written as JSON.',+ },+ unsupported_schema: {+ phase: 'bundle',+ severity: 'error',+ scope: 'compilation',+ remediation: 'Compile the docs again with this CLI.',+ },+ invalid_bundle: {+ phase: 'bundle',+ severity: 'error',+ scope: 'compilation',+ remediation:+ 'Compile the docs again with this CLI; a compiled bundle is never edited by hand.',+ },+ }),+);++/**+ * @param {string} code+ * @param {object} at+ * @param {string | null} [at.provider]+ * @param {string | null} [at.source]+ * @param {string | null} [at.field]+ * @param {string} at.message+ * @returns {CompilerDiagnostic}+ */+export function diagnostic(+ code,+ {provider = null, source = null, field = null, message},+) {+ if (!Object.hasOwn(DIAGNOSTIC_CODES, code)) {+ throw new Error(`Unknown compiler diagnostic code "${code}".`);+ }+ const rule = DIAGNOSTIC_CODES[code];+ return {+ code,+ phase: rule.phase,+ severity: rule.severity,+ scope: rule.scope,+ provider,+ source,+ field,+ message,+ remediation: rule.remediation,+ };+}++/** @param {string | null} value */+const orderable = value => value ?? '\uffff';++/**+ * Diagnostics in one order, whatever order the phases found them in: by+ * source, then phase, then code, field, and message.+ * @param {CompilerDiagnostic[]} list+ * @returns {CompilerDiagnostic[]} a new array+ */+export function sortDiagnostics(list) {+ const phase = (/** @type {CompilerDiagnostic} */ d) =>+ DIAGNOSTIC_PHASES.indexOf(d.phase);+ return [...list].sort(+ (a, b) =>+ compare(orderable(a.source), orderable(b.source)) ||+ phase(a) - phase(b) ||+ compare(a.code, b.code) ||+ compare(orderable(a.field), orderable(b.field)) ||+ compare(a.message, b.message),+ );+}++/**+ * Code-point order: the same on every machine and locale.+ * @param {string} a+ * @param {string} b+ */+function compare(a, b) {+ return a < b ? -1 : a > b ? 1 : 0;+}++const DIAGNOSTIC_FIELDS = new Set([+ 'code',+ 'phase',+ 'severity',+ 'scope',+ 'provider',+ 'source',+ 'field',+ 'message',+ 'remediation',+]);++/**+ * What is wrong with a value that claims to be a diagnostic, or null. A known+ * code must carry its own phase, severity, scope, and remediation: a reader+ * never reinterprets them.+ * @param {unknown} value+ * @returns {string | null}+ */+export function diagnosticProblem(value) {+ const d = /** @type {any} */ (value);+ if (d == null || typeof d !== 'object' || Array.isArray(d)) {+ return 'expected a diagnostic object';+ }+ const unknown = Object.keys(d).filter(key => !DIAGNOSTIC_FIELDS.has(key));+ if (unknown.length > 0) return `unknown fields: ${unknown.join(', ')}`;+ if (typeof d.code !== 'string' || !Object.hasOwn(DIAGNOSTIC_CODES, d.code)) {+ return `code: ${JSON.stringify(d.code)} is not a compiler diagnostic code`;+ }+ const rule = DIAGNOSTIC_CODES[d.code];+ for (const key of /** @type {const} */ ([+ 'phase',+ 'severity',+ 'scope',+ 'remediation',+ ])) {+ if (d[key] !== rule[key]) {+ return `${key}: "${d.code}" always has ${key} ${JSON.stringify(rule[key])}`;+ }+ }+ for (const key of ['provider', 'source', 'field']) {+ if (d[key] !== null && (typeof d[key] !== 'string' || d[key] === '')) {+ return `${key}: expected text or null`;+ }+ }+ if (d.source !== null && !isPortableSource(d.source)) {+ return 'source: expected a path inside a package, not a location on one machine';+ }+ if (typeof d.message !== 'string' || d.message === '') {+ return 'message: expected text';+ }+ return null;+}++/**+ * A `<package>/<path>` that names no location on one machine: not absolute,+ * no drive letter or URL scheme, no backslash, no `..` segment.+ * @param {string} source+ * @returns {boolean}+ */+export function isPortableSource(source) {+ return (+ !source.startsWith('/') &&+ !/^[A-Za-z]:/u.test(source) &&+ !source.includes('\\') &&+ !/(^|\/)\.\.(\/|$)/u.test(source)+ );+}diff --git a/packages/cli/foundation/doc-compiler/doc-compiler.test.mjs b/packages/cli/foundation/doc-compiler/doc-compiler.test.mjsindex fa8b8bb447..47b8fe5e43 100644--- a/packages/cli/foundation/doc-compiler/doc-compiler.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-compiler.test.mjs@@ -131,6 +131,27 @@ describe('lowerReferenceTopic', () => {});});+ it('keeps the topic named as it is when extended, and renames it only when replaced', () => {+ const extended = lowerReferenceTopic(+ input(file(demo()), [extension('acme', 'Acme start.')]),+ );+ expect(extended.doc.title).toBe('demo title');+ expect(extended.doc.description).toBe('About demo.');+ const replacement = authored(+ 'acme-demo',+ [{title: 'Quick Start', content: [prose('Acme start.')]}],+ {replaces: 'demo'},+ );+ const replaced = lowerReferenceTopic({+ ...input(file(replacement)),+ id: 'demo',+ provider: '@acme/replacement',+ replaces: 'demo',+ });+ expect(replaced.doc.title).toBe('acme-demo title');+ expect(replaced.doc.description).toBe('About acme-demo.');+ });+it('applies extensions in configuration order, so the last one wins', () => {const node = lowerReferenceTopic(input(file(demo()), [@@ -544,6 +565,7 @@ describe('readers go through the compiler', () => {'lowerReferenceTopic','linkReferenceTopic','linkReferenceSection',+ 'lowerDoc',],};/** The docs adapter and leaves drive the compiler; nothing else does. */@@ -618,12 +640,17 @@ describe('readers go through the compiler', () => {return found;}+ /** Temporary folders other tests create with mkdtemp and delete mid-run. */+ const TRANSIENT_DIR = /^__[a-z][a-z_]*_[A-Za-z0-9]{6}$/;+/** @param {string} dir @returns {string[]} */const sources = dir =>fs.readdirSync(dir, {withFileTypes: true}).flatMap(entry => {const full = path.join(dir, entry.name);if (entry.isDirectory()) {- return entry.name === 'node_modules' ? [] : sources(full);+ const skip =+ entry.name === 'node_modules' || TRANSIENT_DIR.test(entry.name);+ return skip ? [] : sources(full);}return entry.name.endsWith('.mjs') && !entry.name.endsWith('.test.mjs')? [full]diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsnew file mode 100644index 0000000000..38866a9325--- /dev/null+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -0,0 +1,1642 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every module in the CLI package that runs anything but its static+ * imports of other CLI code (a doc file, a module chosen at run time, a code+ * string, a thread, or a process) is listed here, site by site, with what it+ * runs. A doc read that goes around the doc compiler (./read.mjs) is such a+ * site, so it fails this test until it is listed; so does any other new+ * site, and a listed one that is gone.+ *+ * What it claims: every ordinary way a module runs code — the shapes code+ * review sees, whatever the local names. What it does not claim: that the+ * rule cannot be evaded on purpose. Deliberate obfuscation (a method name+ * built at run time, a runner stashed behind a computed key or a getter) is+ * out of scope; this test records what the CLI does, it does not sandbox it.+ * It checks where code runs, not what a computed site loads: each entry+ * says that.+ */++import {describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {isBuiltin} from 'node:module';+import {parse} from '@babel/parser';+import babelTypes from '@babel/types';+import {CLI_ROOT} from '../fs/paths.mjs';++const {VISITOR_KEYS, isReferenced, isTSType} = babelTypes;++/**+ * Command modules build their help text from the raw exports of their own+ * self-docs, imported statically: those reads skip the compiler.+ */+const SELF_DOCS = 'its self-docs, statically: raw exports build its help text';++/**+ * Every module that runs anything but its static imports of other CLI code:+ * what it runs, and each site the scan finds in it (`×n` for a repeated one).+ * @type {Record<string, {runs: string, sites: string[]}>}+ */+const RUNNERS = {+ 'api/doctor/doctor.mjs': {+ runs: "the project's astryx.config, for the config check",+ sites: ['import(<computed>)'],+ },+ 'api/gap-report/gap-report-worker.mjs': {+ runs: "an integration's gap-report handler, in the worker thread",+ sites: ['importUserModule'],+ },+ 'api/gap-report/gap-report.mjs': {+ runs: 'the gap-report worker thread, and `gh issue create` as the GitHub fallback',+ sites: ['import(node:child_process)', 'worker_threads.Worker'],+ },+ 'api/integration/pack-check.mjs': {+ runs: '`npm pack`, `tar`, and a Node script that resolves the packed specifiers, to check a package as published',+ sites: ['child_process.spawnSync ×3'],+ },+ 'api/swizzle/_github.mjs': {+ runs: '`gh auth status`, to check the GitHub CLI is signed in',+ sites: ['child_process.execFileSync'],+ },+ 'api/theme/build/build.mjs': {+ runs: 'theme source modules, through jiti; eval for legacy theme object literals',+ sites: [+ '.evalModule() ×2',+ '.import()',+ 'createJiti ×4',+ 'eval ×2',+ 'import(<computed>)',+ ],+ },+ 'api/theme/build/core-interception.mjs': {+ runs: "@astryxdesign/core as a theme's CommonJS dependencies require it, to wrap defineTheme",+ sites: ['require(<computed>)'],+ },+ 'api/upgrade/_adapter.mjs': {+ runs: 'the commands a codemod declares as its post-codemod hooks',+ sites: ['child_process.execFile'],+ },+ 'assets/codemods/ensure-jscodeshift.mjs': {+ runs: 'the package manager, to install jscodeshift',+ sites: ['child_process.execSync'],+ },+ 'assets/codemods/integration-discovery.mjs': {+ runs: "each integration's codemods, through the codemod parser, to plan an upgrade",+ sites: ['loadModuleWithParser(..., parseCodemod)'],+ },+ 'authoring/shadcn/source-variants.mjs': {+ runs: "@babel/plugin-transform-typescript (CommonJS), to reproduce the ShadCN client's transform",+ sites: ['require(@babel/plugin-transform-typescript)'],+ },+ 'clients/cli/bin/astryx.mjs': {+ runs: "the CLI's own modules, by real path, so a linked bin finds them",+ sites: ['import(<computed>)'],+ },+ 'clients/cli/commands/blog.mjs': {+ runs: SELF_DOCS,+ sites: ['import ../../../api/blog/blog.doc.mjs', 'import ./blog.doc.mjs'],+ },+ 'clients/cli/commands/build-theme.mjs': {+ runs: `${SELF_DOCS}; and \`astryx theme build\`, a child process per theme`,+ sites: [+ 'child_process.spawn',+ 'import ../../../api/theme/themeAdd.doc.mjs',+ 'import ../../../api/theme/themeBuild.doc.mjs',+ 'import ../../../api/theme/themeListAvailable.doc.mjs',+ 'import ../../../api/theme/themePaletteGenerate.doc.mjs',+ 'import ../../../api/theme/themeTargets.doc.mjs',+ 'import ../../../api/theme/themeTemplate.doc.mjs',+ 'import ./theme-add.doc.mjs',+ 'import ./theme-build.doc.mjs',+ 'import ./theme-list.doc.mjs',+ 'import ./theme-palette-generate.doc.mjs',+ 'import ./theme-palette.doc.mjs',+ 'import ./theme-targets.doc.mjs',+ 'import ./theme-template.doc.mjs',+ 'import ./theme.doc.mjs',+ ],+ },+ 'clients/cli/commands/build.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/build/build.doc.mjs',+ 'import ./build.doc.mjs',+ ],+ },+ 'clients/cli/commands/component/index.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../../api/component/component.doc.mjs',+ 'import ../component.doc.mjs',+ ],+ },+ 'clients/cli/commands/discover.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/discover/discover.doc.mjs',+ 'import ./discover.doc.mjs',+ ],+ },+ 'clients/cli/commands/docs.mjs': {+ runs: SELF_DOCS,+ sites: ['import ../../../api/docs/docs.doc.mjs', 'import ./docs.doc.mjs'],+ },+ 'clients/cli/commands/doctor.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/doctor/doctor.doc.mjs',+ 'import ../../../api/integration/integrationComponentConflicts.doc.mjs',+ 'import ../../../api/integration/integrationDocConflicts.doc.mjs',+ 'import ../../../api/integration/integrationTemplateConflicts.doc.mjs',+ 'import ../../../api/integration/validateIntegration.doc.mjs',+ 'import ./doctor-integration-components.doc.mjs',+ 'import ./doctor-integration-docs.doc.mjs',+ 'import ./doctor-integration-templates.doc.mjs',+ 'import ./doctor-integration-validate.doc.mjs',+ 'import ./doctor-integration.doc.mjs',+ 'import ./doctor.doc.mjs',+ ],+ },+ 'clients/cli/commands/ensure-core-built.mjs': {+ runs: '`pnpm -F @astryxdesign/core build`: a test helper that builds core once for the theme-build suites',+ sites: ['child_process.execFileSync'],+ },+ 'clients/cli/commands/gap-report.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/gap-report/gap-report.doc.mjs',+ 'import ./gap-report.doc.mjs',+ ],+ },+ 'clients/cli/commands/hook/index.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../../api/hook/hook.doc.mjs',+ 'import ../hook.doc.mjs',+ ],+ },+ 'clients/cli/commands/init.mjs': {+ runs: SELF_DOCS,+ sites: ['import ../../../api/init/init.doc.mjs', 'import ./init.doc.mjs'],+ },+ 'clients/cli/commands/integration.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/integration/integrationAdd.doc.mjs',+ 'import ../../../api/integration/integrationPackCheck.doc.mjs',+ 'import ./integration-add.doc.mjs',+ 'import ./integration-pack.doc.mjs',+ 'import ./integration.doc.mjs',+ ],+ },+ 'clients/cli/commands/layout.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/layout/layoutCheck.doc.mjs',+ 'import ../../../api/layout/layoutExpand.doc.mjs',+ 'import ../../../api/layout/layoutGrammar.doc.mjs',+ 'import ./layout-check.doc.mjs',+ 'import ./layout-expand.doc.mjs',+ 'import ./layout-grammar.doc.mjs',+ 'import ./layout.doc.mjs',+ ],+ },+ 'clients/cli/commands/search.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/search/search.doc.mjs',+ 'import ./search.doc.mjs',+ ],+ },+ 'clients/cli/commands/swizzle.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/swizzle/swizzle.doc.mjs',+ 'import ./swizzle.doc.mjs',+ ],+ },+ 'clients/cli/commands/template.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/template/template.doc.mjs',+ 'import ./template.doc.mjs',+ ],+ },+ 'clients/cli/commands/upgrade.mjs': {+ runs: SELF_DOCS,+ sites: [+ 'import ../../../api/upgrade/upgrade.doc.mjs',+ 'import ./upgrade.doc.mjs',+ ],+ },+ 'clients/cli/index.mjs': {+ runs: 'the command modules, to register each command, and the manifest command doc',+ sites: ['import ./commands/manifest.doc.mjs', 'import(<computed>)'],+ },+ 'clients/cli/lib/manifest.mjs': {+ runs: 'the manifest command doc, for the exit codes the manifest reports',+ sites: ['import ../commands/manifest.doc.mjs'],+ },+ 'clients/cli/lib/resolve-theme.mjs': {+ runs: 'the configured theme (ASTRYX_THEME or package.json), by path or package name',+ sites: ['require(<computed>) ×2'],+ },+ 'foundation/config/project.mjs': {+ runs: 'astryx.config, through the config parser',+ sites: ['loadModuleWithParser(..., parseConfig)'],+ },+ 'foundation/discovery/docs-discovery.mjs': {+ runs: 'a contributed topic, for its catalog fields: name, title, description, category, and relationships',+ sites: ['importDocModule'],+ },+ 'foundation/discovery/template-adapter.mjs': {+ runs: '@babel/parser, to find the fixture references in template source',+ sites: ['require(@babel/parser)'],+ },+ 'foundation/discovery/theme-discovery.mjs': {+ runs: '@babel/parser and jscodeshift (CommonJS), each on first use, so listing bundled themes never loads jscodeshift',+ sites: ['require(@babel/parser)', 'require(jscodeshift)'],+ },+ 'foundation/doc-compiler/import.mjs': {+ runs: 'authored doc files, for the doc reader and discovery',+ sites: [+ '.import()',+ 'createJiti',+ 'import(<computed>) ×2',+ 'importUserModule',+ ],+ },+ 'foundation/doc-compiler/read.mjs': {+ runs: 'authored doc files, each one handed to the compiler, with the loader its reader has always used',+ sites: ['importDocModule', 'importNativeModule ×3', 'importTemplateModule'],+ },+ 'foundation/fs/module-loader.mjs': {+ runs: 'user modules (config, manifests, handlers, codemods): natively, through jiti, or by require for a fresh CommonJS read',+ sites: [+ '.import() ×2',+ 'createJiti ×2',+ 'import(<computed>)',+ 'require(<computed>)',+ 'require.cache',+ ],+ },+ 'foundation/fs/paths.mjs': {+ runs: "Yarn's pnpapi, under Plug'n'Play, to find an installed package",+ sites: ['require(pnpapi)'],+ },+ 'foundation/integrations/integrations.mjs': {+ runs: "each installed integration's manifest",+ sites: ['importUserModule'],+ },+ 'scripts/generate-cli-readme.mjs': {+ runs: '`astryx manifest` and the error-code and response-type docs, to write the README tables (build time, not shipped)',+ sites: ['child_process.spawnSync', 'import(<computed>)'],+ },+ 'scripts/sync-api-types.mjs': {+ runs: '`tsc`, to emit the API declarations (build time, not shipped)',+ sites: ['child_process.execFileSync'],+ },+};++/**+ * Modules that hand back whatever module or doc they are pointed at. Every+ * export is a loader except those named here, which hand back no module.+ * @type {Record<string, string[]>}+ */+const LOADER_MODULES = {+ 'foundation/doc-compiler/import.mjs': [],+ 'foundation/fs/module-loader.mjs': ['findPresentFiles'],+ // loadTopicModule hands back a topic's raw doc.+ 'foundation/discovery/docs-discovery.mjs': [+ 'BUILTIN_DOCS_PACKAGE',+ 'DocsCatalog',+ 'discoverBuiltinTopics',+ 'discoverIntegrationDocs',+ 'GRAPH_BLOCK_TYPES',+ 'GRAPH_ONLY_FIELDS',+ 'mergeTopic',+ 'problemsInTopic',+ 'withSourceTitle',+ ],+};++/**+ * Built-ins that run code. Every export counts except those named here.+ * @type {Record<string, string[]>}+ */+const RUNNER_BUILTINS = {+ child_process: [],+ cluster: [],+ inspector: [],+ 'inspector/promises': [],+ module: [+ 'builtinModules',+ 'constants',+ 'enableCompileCache',+ 'findPackageJSON',+ 'findSourceMap',+ 'flushCompileCache',+ 'getCompileCacheDir',+ 'isBuiltin',+ 'SourceMap',+ 'stripTypeScriptTypes',+ ],+ repl: [],+ test: [],+ vm: [],+ worker_threads: [+ 'BroadcastChannel',+ 'isMainThread',+ 'MessageChannel',+ 'MessagePort',+ 'parentPort',+ 'threadId',+ 'workerData',+ ],+};++/** Packages whose every export runs modules. */+const RUNNER_PACKAGES = new Set(['jiti']);++/** Globals that run code, and the objects they can be read from. */+const RUNNER_GLOBALS = new Set([+ 'eval',+ 'Function',+ 'ShadowRealm',+ 'SharedWorker',+ 'Worker',+]);+const GLOBAL_OBJECTS = new Set(['globalThis', 'global', 'self', 'window']);++/** Members of `process` that run code. */+const PROCESS_RUNNERS = new Set([+ 'binding',+ 'dlopen',+ 'execve',+ 'getBuiltinModule',+]);++/** Members of `WebAssembly` that run code. */+const WASM_RUNNERS = new Set([+ 'compile',+ 'compileStreaming',+ 'Instance',+ 'instantiate',+ 'instantiateStreaming',+ 'Module',+]);++/** URL schemes that carry code rather than name a file in this package. */+const CODE_URL = /^(?:data|blob|https?):/;++/** Methods that run code whatever they are called on: jiti's, vm's, a realm's. */+const RUNNER_METHODS = new Set([+ 'compileFunction',+ 'evalModule',+ 'import',+ 'importValue',+ 'runInContext',+ 'runInNewContext',+ 'runInThisContext',+]);++/** A doc file specifier: `x.doc.mjs`, `x.doc.ts`, `x.doc.zh.mjs`, `x.doc`. */+const DOC_FILE = /\.doc(?:\.[\w-]+)?(?:\.[cm]?[jt]sx?)?$/;++/** Syntax that only types; it never runs. */+const TYPE_ONLY = new Set([+ 'TSDeclareFunction',+ 'TSDeclareMethod',+ 'TSInterfaceDeclaration',+ 'TSTypeAliasDeclaration',+ 'TSTypeAnnotation',+ 'TSTypeParameterDeclaration',+ 'TSTypeParameterInstantiation',+]);++/** Values whose `.constructor` reaches Function in a step or two. */+const LITERALS = new Set([+ 'ArrayExpression',+ 'ArrowFunctionExpression',+ 'ClassExpression',+ 'FunctionExpression',+ 'NumericLiteral',+ 'ObjectExpression',+ 'RegExpLiteral',+ 'StringLiteral',+ 'TemplateLiteral',+]);++/** A code file Node or jiti can run. */+const CODE_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/;+/** Directories that hold no code the CLI runs as itself, by name... */+const UNSCANNED_NAMES = new Set(['node_modules', '__fixtures__', '__tests__']);+/**+ * ...and the temporary folders tests create with mkdtemp (`__<prefix>_XXXXXX`)+ * and delete while this scan runs. Any other `__*` folder is scanned.+ */+const TRANSIENT_DIR = /^__[a-z][a-z_]*_[A-Za-z0-9]{6}$/;+/** ...and by path: tests, and the authored docs and templates. */+const UNSCANNED_PATHS = new Set([+ 'assets/docs',+ 'assets/templates',+ 'test',+ 'test-utils',+]);++/** @param {string} full @returns {string} */+const relOf = full => path.relative(CLI_ROOT, full).split(path.sep).join('/');++/**+ * Every code file under `dir` the CLI can run as itself: not a test, fixture,+ * dependency, generated `.d.mts`, or file in a hidden (transient) directory.+ * @param {string} dir+ * @returns {string[]}+ */+function sources(dir) {+ return fs.readdirSync(dir, {withFileTypes: true}).flatMap(entry => {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ const skip =+ entry.name.startsWith('.') ||+ TRANSIENT_DIR.test(entry.name) ||+ UNSCANNED_NAMES.has(entry.name) ||+ UNSCANNED_PATHS.has(relOf(full));+ return skip ? [] : sources(full);+ }+ const code =+ CODE_FILE.test(entry.name) &&+ !/\.test\.[^.]+$/.test(entry.name) &&+ !entry.name.endsWith('.d.mts');+ return code ? [full] : [];+ });+}++/**+ * @param {string} source+ * @param {string} rel+ */+function parseModule(source, rel) {+ const typescript = /\.[cm]?tsx?$/.test(rel);+ /** @type {import('@babel/parser').ParserPlugin[]} */+ const plugins = typescript+ ? [['typescript', {dts: /\.d\.[cm]?ts$/.test(rel)}]]+ : [];+ if (!typescript || rel.endsWith('x')) plugins.push('jsx');+ return parse(source, {+ sourceType: rel.endsWith('.cjs') ? 'script' : 'module',+ allowReturnOutsideFunction: rel.endsWith('.cjs'),+ plugins,+ });+}++/**+ * Visit every node that runs, depth first, with its ancestors.+ * @param {any} node+ * @param {any[]} ancestors+ * @param {(node: any, ancestors: any[]) => void} visit+ */+function walk(node, ancestors, visit) {+ if (typeof node?.type !== 'string') return;+ if (TYPE_ONLY.has(node.type) || isTSType(node) || node.declare) return;+ if (node.importKind === 'type' || node.exportKind === 'type') return;+ visit(node, ancestors);+ ancestors.push(node);+ for (const key of VISITOR_KEYS[node.type] ?? []) {+ for (const child of [node[key]].flat()) walk(child, ancestors, visit);+ }+ ancestors.pop();+}++/** @param {any} node @returns {string | undefined} */+function stringValue(node) {+ if (node?.type === 'StringLiteral') return node.value;+ if (node?.type === 'TemplateLiteral' && node.expressions.length === 0) {+ return node.quasis[0].value.cooked;+ }+ return undefined;+}++/** @param {any} node @returns {string} */+const nameOf = node => (node.type === 'Identifier' ? node.name : node.value);++/** @param {any} node @returns {boolean} */+const isMember = node =>+ node?.type === 'MemberExpression' ||+ node?.type === 'OptionalMemberExpression';++/** @param {any} node @returns {boolean} */+const isCall = node =>+ node?.type === 'CallExpression' ||+ node?.type === 'OptionalCallExpression' ||+ node?.type === 'NewExpression';++/** @param {any} member @returns {string | undefined} */+const memberName = member =>+ member.computed ? stringValue(member.property) : member.property.name;++/** @param {string} specifier */+const withoutQuery = specifier => specifier.replace(/[?#].*$/, '');++/**+ * @typedef {object} Target+ * @property {'doc' | 'url' | 'unscanned' | 'loader' | 'builtin' | 'package'}+ * kind — `url`: code carried by the specifier or fetched, not a file in this+ * package; `unscanned`: a file in a part of the package this test does not+ * scan+ * @property {string} key+ */++/**+ * What an import specifier names, seen from `rel`, when it matters here.+ * @param {string} specifier+ * @param {string} rel+ * @returns {Target | null}+ */+function targetOf(specifier, rel) {+ if (CODE_URL.test(specifier)) return {kind: 'url', key: specifier};+ let file = withoutQuery(specifier);+ const local = /^(?:\.|\/|file:)/.test(file);+ if (local) {+ try {+ file = decodeURIComponent(file);+ } catch {+ // A malformed escape names no file; compare it as written.+ }+ }+ if (DOC_FILE.test(file)) return {kind: 'doc', key: specifier};+ if (isBuiltin(file)) {+ const name = file.replace(/^node:/, '');+ return Object.hasOwn(RUNNER_BUILTINS, name)+ ? {kind: 'builtin', key: name}+ : null;+ }+ if (local) {+ const resolved = file.startsWith('.')+ ? path.posix.join(path.posix.dirname(rel), file)+ : file.replace(/^file:\/\//, '');+ // Extension-free and case-free: TypeScript and case-insensitive disks+ // resolve both.+ /** @param {string} p */+ const stem = p =>+ p.toLowerCase().replace(/(?:\/index)?\.[cm]?[jt]sx?$/, '');+ const loader = Object.keys(LOADER_MODULES).find(+ mod =>+ stem(resolved) === stem(mod) ||+ stem(resolved).endsWith(`/${stem(mod)}`),+ );+ if (loader) return {kind: 'loader', key: loader};+ const unscanned =+ [...UNSCANNED_PATHS].some(dir => resolved.startsWith(`${dir}/`)) ||+ resolved+ .split('/')+ .slice(0, -1)+ .some(+ part =>+ UNSCANNED_NAMES.has(part) ||+ TRANSIENT_DIR.test(part) ||+ (part.startsWith('.') && part !== '..'),+ ) ||+ /\.test\.[^./]+$/.test(resolved);+ return unscanned ? {kind: 'unscanned', key: specifier} : null;+ }+ const pkg = file+ .split('/')+ .slice(0, file.startsWith('@') ? 2 : 1)+ .join('/');+ return RUNNER_PACKAGES.has(pkg) ? {kind: 'package', key: pkg} : null;+}++/** Targets whose every export is code this test does not read. */+const UNREAD = new Set(['doc', 'unscanned', 'url']);++/** @param {Target} target @returns {string[]} */+function inertExports(target) {+ if (target.kind === 'loader') return LOADER_MODULES[target.key];+ if (target.kind === 'builtin') return RUNNER_BUILTINS[target.key];+ return [];+}++/**+ * Every ordinary place `source` runs code outside its static imports, as+ * labels (deliberate obfuscation is out of scope, as the file header says):+ *+ * - a static import or re-export of a doc file, or of a file this test does+ * not scan;+ * - a use of a loader module's export under any local name: called, passed,+ * re-exported, or read off a namespace;+ * - `import()` of a computed specifier, a doc file, a loader module, or a+ * built-in or package that runs code;+ * - a require function, CommonJS or from createRequire, called or passed on+ * (resolving is not running);+ * - an export of jiti, or a code-running export of child_process, cluster,+ * inspector, module, repl, test, vm, or worker_threads, imported or+ * fetched with getBuiltinModule;+ * - eval, Function (also as any called `.constructor`), ShadowRealm, a+ * global Worker, `module.require`; a jiti, vm, or realm method on anything;+ * - a doc file resolved as a module.+ *+ * Names are matched without scope analysis, so a shadowing local cannot hide+ * a loader; it can only add a site.+ * @param {string} source+ * @param {string} rel path under packages/cli+ * @returns {{sites: string[], problems: string[]}}+ */+function scanModule(source, rel) {+ const program = parseModule(source, rel).program;+ /** @type {string[]} */+ const sites = [];+ /** @type {string[]} */+ const problems = [];+ /** @type {Map<string, {target: Target, imported: string | null}>} */+ const bindings = new Map();+ /** Local names holding a require function; CommonJS has `require`. */+ const requires = new Set(['require']);+ /** Local names holding the global object. */+ const globals = new Set(GLOBAL_OBJECTS);++ walk(program, [], node => {+ if (node.type === 'ImportDeclaration') {+ const target = targetOf(node.source.value, rel);+ if (!target || UNREAD.has(target.kind)) return;+ for (const specifier of node.specifiers) {+ if (specifier.importKind === 'type') continue;+ const imported =+ specifier.type === 'ImportSpecifier'+ ? nameOf(specifier.imported)+ : null;+ bindings.set(specifier.local.name, {+ target,+ imported: imported === 'default' ? null : imported,+ });+ }+ } else if (+ node.type === 'TSImportEqualsDeclaration' &&+ node.moduleReference.type === 'TSExternalModuleReference'+ ) {+ const target = targetOf(node.moduleReference.expression.value, rel);+ if (target && !UNREAD.has(target.kind)) {+ bindings.set(node.id.name, {target, imported: null});+ }+ }+ });++ /** @param {any} expr `createRequire` from `module`, under any name */+ const isCreateRequire = expr => {+ const id = isMember(expr) ? expr.object : expr;+ const binding = id?.type === 'Identifier' ? bindings.get(id.name) : null;+ if (binding?.target.kind !== 'builtin' || binding.target.key !== 'module') {+ return false;+ }+ return isMember(expr)+ ? binding.imported === null && memberName(expr) === 'createRequire'+ : binding.imported === 'createRequire';+ };+ // A name bound to a require function or to the global object stands in for+ // it, and is bound before it is used.+ walk(program, [], node => {+ const [id, value] =+ node.type === 'VariableDeclarator'+ ? [node.id, node.init]+ : node.type === 'AssignmentExpression'+ ? [node.left, node.right]+ : [];+ if (id?.type !== 'Identifier') return;+ if (isCall(value) && isCreateRequire(value.callee)) requires.add(id.name);+ if (value?.type === 'Identifier' && globals.has(value.name)) {+ globals.add(id.name);+ }+ });++ /**+ * `const {eval: e} = globalThis`: taking the member is the site, whatever+ * the local name.+ * @param {any} pattern+ * @param {ReadonlySet<string>} runners+ * @param {string} owner+ */+ const destructured = (pattern, runners, owner) => {+ if (pattern?.type !== 'ObjectPattern') return;+ for (const property of pattern.properties) {+ const name =+ property.type === 'ObjectProperty'+ ? property.computed+ ? stringValue(property.key)+ : nameOf(property.key)+ : undefined;+ if (name === undefined) sites.push(`${owner}[<computed>]`);+ else if (runners.has(name)) sites.push(name);+ }+ };++ /** @param {any} node */+ const docResolve = node => {+ const specifier = stringValue(node);+ if (specifier !== undefined && DOC_FILE.test(withoutQuery(specifier))) {+ sites.push(`resolve(${specifier})`);+ }+ };++ /** @param {any} call */+ const requireCall = call => {+ const specifier = stringValue(call.arguments[0]);+ if (+ specifier !== undefined &&+ isBuiltin(specifier) &&+ !targetOf(specifier, rel)+ ) {+ return;+ }+ sites.push(`require(${specifier ?? '<computed>'})`);+ };++ /**+ * `process.getBuiltinModule`: a built-in without an import.+ * @param {any} call+ */+ const builtinGetter = call => {+ const specifier = stringValue(call.arguments[0]);+ if (specifier === undefined) sites.push('getBuiltinModule(<computed>)');+ else if (targetOf(specifier, rel)) {+ sites.push(`getBuiltinModule(${specifier})`);+ }+ };++ /**+ * `createRequire`: a site unless the require function it makes is kept by+ * name (tracked above), only resolves, or runs right here.+ * @param {any} ref+ * @param {any[]} ancestors+ */+ const createRequireSite = (ref, ancestors) => {+ const call = ancestors.at(-1);+ const up = ancestors.at(-2);+ const kept =+ (up?.type === 'VariableDeclarator' && up.init === call) ||+ (up?.type === 'AssignmentExpression' && up.right === call);+ if (!isCall(call) || call.callee !== ref) sites.push('createRequire');+ else if (isCall(up) && up.callee === call) requireCall(up);+ else if (isMember(up) && up.object === call) {+ if (memberName(up) !== 'resolve') sites.push('createRequire');+ } else if (!kept || (up.id ?? up.left).type !== 'Identifier') {+ sites.push('createRequire');+ }+ };++ /**+ * `loadModuleWithParser`: the parser it is handed says what it loads.+ * @param {any} ref+ * @param {any[]} ancestors+ */+ const parserSite = (ref, ancestors) => {+ const call = ancestors.at(-1);+ if (!isCall(call) || call.callee !== ref) {+ sites.push('loadModuleWithParser');+ return;+ }+ const parser = call.arguments[1];+ const text = parser+ ? source.slice(parser.start, parser.end).replace(/\s+/g, ' ')+ : '';+ sites.push(`loadModuleWithParser(..., ${text})`);+ let docParser = false;+ walk(parser, [], node => {+ const name = node.type === 'Identifier' ? node.name : stringValue(node);+ docParser ||= name !== undefined && DOC_PARSERS.has(name);+ });+ if (docParser) {+ problems.push(+ `${rel}: loadModuleWithParser(..., ${text}) loads a doc outside the compiler`,+ );+ }+ };++ /**+ * @param {Target} target+ * @param {string} name the export used+ * @param {any} ref the expression that reads it+ * @param {any[]} ancestors+ */+ const exportSite = (target, name, ref, ancestors) => {+ if (inertExports(target).includes(name)) return;+ if (target.key === 'module' && name === 'createRequire') {+ createRequireSite(ref, ancestors);+ } else if (target.kind === 'loader' && name === 'loadModuleWithParser') {+ parserSite(ref, ancestors);+ } else {+ sites.push(target.kind === 'builtin' ? `${target.key}.${name}` : name);+ }+ };++ /**+ * @param {any} id an identifier that is read+ * @param {any[]} ancestors+ */+ const reference = (id, ancestors) => {+ const parent = ancestors.at(-1);+ const binding = bindings.get(id.name);+ if (binding) {+ const {target, imported} = binding;+ if (imported !== null) {+ exportSite(target, imported, id, ancestors);+ } else if (isMember(parent) && parent.object === id) {+ const name = memberName(parent);+ if (name === undefined) sites.push(`${target.key}[<computed>]`);+ else exportSite(target, name, parent, ancestors.slice(0, -1));+ } else {+ sites.push(target.key);+ }+ } else if (requires.has(id.name)) {+ if (isCall(parent) && parent.callee === id) requireCall(parent);+ else if (!isMember(parent) || parent.object !== id) sites.push('require');+ else if (memberName(parent) !== 'resolve') {+ sites.push(`require.${memberName(parent) ?? '<computed>'}`);+ }+ } else if (id.name === 'getBuiltinModule') {+ if (isCall(parent) && parent.callee === id) builtinGetter(parent);+ else sites.push('getBuiltinModule');+ } else if (+ RUNNER_GLOBALS.has(id.name) &&+ !(parent.operator === 'instanceof' && parent.right === id)+ ) {+ sites.push(id.name);+ }+ };++ walk(program, [], (node, ancestors) => {+ switch (node.type) {+ case 'VariableDeclarator':+ case 'AssignmentExpression': {+ const [id, value] =+ node.type === 'VariableDeclarator'+ ? [node.id, node.init]+ : [node.left, node.right];+ if (value?.type !== 'Identifier') return;+ if (globals.has(value.name))+ destructured(id, RUNNER_GLOBALS, value.name);+ else if (value.name === 'process') {+ destructured(id, PROCESS_RUNNERS, 'process');+ }+ return;+ }+ case 'ImportDeclaration':+ case 'ExportAllDeclaration':+ case 'ExportNamedDeclaration': {+ if (!node.source) return;+ const specifier = node.source.value;+ const target = targetOf(specifier, rel);+ if (!target) return;+ if (UNREAD.has(target.kind)) {+ const how =+ node.type === 'ImportDeclaration' ? 'import' : 'export from';+ sites.push(`${how} ${specifier}`);+ } else if (node.type === 'ExportAllDeclaration') {+ sites.push(`export * from ${specifier}`);+ } else if (node.type === 'ExportNamedDeclaration') {+ for (const s of node.specifiers) {+ if (s.exportKind === 'type') continue;+ const name = s.type === 'ExportSpecifier' ? nameOf(s.local) : '*';+ if (!inertExports(target).includes(name)) {+ sites.push(`export ${name} from ${specifier}`);+ }+ }+ }+ return;+ }+ case 'TSImportEqualsDeclaration': {+ const ref = node.moduleReference;+ if (ref.type !== 'TSExternalModuleReference') return;+ const specifier = ref.expression.value;+ const target = targetOf(specifier, rel);+ if (target && UNREAD.has(target.kind)) {+ sites.push(`import ${specifier}`);+ } else if (target && node.isExport) {+ sites.push(`export * from ${specifier}`);+ }+ return;+ }+ case 'ImportExpression':+ case 'CallExpression':+ case 'OptionalCallExpression': {+ if (node.type === 'ImportExpression' || node.callee.type === 'Import') {+ const specifier = stringValue(+ node.type === 'ImportExpression' ? node.source : node.arguments[0],+ );+ if (specifier === undefined) sites.push('import(<computed>)');+ else if (targetOf(specifier, rel)) sites.push(`import(${specifier})`);+ return;+ }+ const callee = node.callee;+ if (!isMember(callee)) return;+ const name = memberName(callee);+ const object = callee.object;+ if (name === 'constructor') sites.push('.constructor()');+ if (name === 'getBuiltinModule') builtinGetter(node);+ if (+ name === 'get' &&+ object.type === 'Identifier' &&+ object.name === 'Reflect'+ ) {+ const key = stringValue(node.arguments[1]);+ if (+ key !== undefined &&+ (RUNNER_GLOBALS.has(key) || PROCESS_RUNNERS.has(key))+ ) {+ sites.push(key);+ }+ }+ const resolver =+ object.type === 'MetaProperty' ||+ (object.type === 'Identifier' && requires.has(object.name)) ||+ (isCall(object) && isCreateRequire(object.callee));+ if (name === 'resolve' && resolver) docResolve(node.arguments[0]);+ if (+ name !== undefined &&+ RUNNER_METHODS.has(name) &&+ !(object.type === 'Identifier' && bindings.has(object.name))+ ) {+ sites.push(`.${name}()`);+ }+ return;+ }+ case 'NewExpression':+ if (node.callee.type === 'Identifier' && node.callee.name === 'URL') {+ docResolve(node.arguments[0]);+ }+ return;+ case 'MemberExpression':+ case 'OptionalMemberExpression': {+ const object = node.object;+ const name = memberName(node);+ const global =+ (object.type === 'Identifier' && globals.has(object.name)) ||+ (isMember(object) &&+ object.object.type === 'Identifier' &&+ globals.has(object.object.name));+ if (name === 'constructor' && LITERALS.has(object.type)) {+ sites.push('.constructor');+ } else if (+ WASM_RUNNERS.has(name ?? '') &&+ ((object.type === 'Identifier' && object.name === 'WebAssembly') ||+ (isMember(object) && memberName(object) === 'WebAssembly'))+ ) {+ sites.push(`WebAssembly.${name}`);+ } else if (isMember(object)) {+ return;+ } else if (object.type !== 'Identifier' || bindings.has(object.name)) {+ return;+ } else if (object.name === 'module') {+ if (name === 'require' || name === 'constructor') {+ sites.push(`module.${name}`);+ }+ } else if (object.name === 'process') {+ if (name !== 'getBuiltinModule' && PROCESS_RUNNERS.has(name ?? '')) {+ sites.push(`process.${name}`);+ }+ } else if (global) {+ if (name === undefined) sites.push(`${object.name}[<computed>]`);+ else if (RUNNER_GLOBALS.has(name)) sites.push(name);+ }+ return;+ }+ case 'Identifier': {+ const parent = ancestors.at(-1);+ if (parent?.type === 'TSImportEqualsDeclaration') return;+ if (parent && isReferenced(node, parent, ancestors.at(-2))) {+ reference(node, ancestors);+ }+ return;+ }+ }+ });++ return {sites, problems};+}++/**+ * The names a module exports.+ * @param {string} source+ * @param {string} rel+ * @returns {string[]}+ */+function exportNames(source, rel) {+ return parseModule(source, rel).program.body.flatMap(+ (/** @type {any} */ node) => {+ if (node.type === 'ExportDefaultDeclaration') return ['default'];+ if (node.type !== 'ExportNamedDeclaration') return [];+ const declaration = node.declaration;+ return [+ ...(declaration?.id ? [declaration.id.name] : []),+ ...(declaration?.declarations ?? []).map(+ (/** @type {any} */ d) => d.id.name,+ ),+ ...node.specifiers.map((/** @type {any} */ s) => nameOf(s.exported)),+ ];+ },+ );+}++/** @param {string} rel */+const read = rel => fs.readFileSync(path.join(CLI_ROOT, rel), 'utf8');++/** Every doc kind's parser: the `parse*` exports under authoring/doctypes. */+const DOC_PARSERS = new Set(+ sources(path.join(CLI_ROOT, 'authoring/doctypes')).flatMap(full =>+ exportNames(read(relOf(full)), relOf(full)).filter(name =>+ /^parse[A-Z]/.test(name),+ ),+ ),+);++/**+ * A module's sites as the list writes them: sorted, repeats counted.+ * @param {string[]} sites+ * @returns {string[]}+ */+function tally(sites) {+ /** @type {Map<string, number>} */+ const counts = new Map();+ for (const site of sites) counts.set(site, (counts.get(site) ?? 0) + 1);+ return [...counts]+ .map(([site, n]) => (n === 1 ? site : `${site} ×${n}`))+ .sort();+}++/**+ * How one module breaks the list: sites other than its entry's, or a doc+ * parser handed to a generic loader, which no entry can allow.+ * @param {string} rel+ * @param {string} source+ * @param {readonly string[]} [entry] the listed sites+ * @returns {string[]}+ */+function violations(rel, source, entry = RUNNERS[rel]?.sites ?? []) {+ const {sites, problems} = scanModule(source, rel);+ const found = tally(sites);+ const listed = [...entry].sort();+ const same = found.join('\n') === listed.join('\n');+ return same+ ? problems+ : [+ ...problems,+ `${rel} runs [${found.join(', ')}], listed [${listed.join(', ')}]`,+ ];+}++describe('every module that runs code outside its static imports is listed', () => {+ const scanned = sources(CLI_ROOT).map(relOf);++ it('lists each one with exactly the sites it has', () => {+ const found = scanned.flatMap(rel => {+ try {+ return violations(rel, read(rel));+ } catch (error) {+ return [+ `${rel} does not parse: ${/** @type {Error} */ (error).message}`,+ ];+ }+ });+ expect(found).toEqual([]);+ });++ it('lists no module that is gone', () => {+ expect(Object.keys(RUNNERS).filter(rel => !scanned.includes(rel))).toEqual(+ [],+ );+ });++ it('names only exports the loader modules still have', () => {+ const stale = Object.entries(LOADER_MODULES).flatMap(([rel, inert]) => {+ const names = exportNames(read(rel), rel);+ return inert+ .filter(name => !names.includes(name))+ .map(n => `${rel}#${n}`);+ });+ expect(stale).toEqual([]);+ });+});++/** A module the list does not name. */+const LEAF = 'api/leaf/leaf.mjs';+const MODULE_LOADER = "'../../foundation/fs/module-loader.mjs'";+const IMPORTERS = "'../../foundation/doc-compiler/import.mjs'";++/**+ * A listed module's real source, edited.+ * @param {string} rel+ * @param {(source: string) => string} edit+ */+const edited = (rel, edit) => {+ const code = edit(read(rel));+ if (code === read(rel)) throw new Error(`the edit to ${rel} changed nothing`);+ return {file: rel, code};+};++/**+ * Ways to run a doc file (or any module) that the list must catch.+ * @type {Array<{name: string, file: string, code: string}>}+ */+const BYPASSES = [+ // The 23 cases from review of the first scan.+ ['computed import(file)', 'const m = await import(file);'],+ [+ 'importUserModule(docPath)',+ `import {importUserModule} from ${MODULE_LOADER};\nawait importUserModule(docPath);`,+ ],+ [+ 'a static import of a doc file',+ "import {doc} from './Button.doc.mjs';\nconsole.log(doc);",+ ],+ [+ 'a static default import of a doc file',+ "import doc from '../../foundation/x/Button.doc.mjs';",+ ],+ [+ 'a literal dynamic import of a doc file',+ "await import('/abs/node_modules/@acme/kit/components/Foo.doc.mjs');",+ ],+ [+ 'createRequire(...)(docPath)',+ "import {createRequire} from 'node:module';\ncreateRequire(import.meta.url)(docPath);",+ ],+ [+ 'require = createRequire(...); require(docPath)',+ "import {createRequire} from 'node:module';\nconst require = createRequire(import.meta.url);\nrequire(docPath);",+ ],+ ["eval('import(docPath)')", "await eval('import(docPath)');"],+ [+ "new Function('p', 'return import(p)')",+ "await new Function('p', 'return import(p)')(docPath);",+ ],+ [+ "jiti['import'](docPath)",+ "import {createJiti} from 'jiti';\nawait createJiti(import.meta.url)['import'](docPath);",+ ],+ [+ 'a jiti instance called as require',+ "import {createJiti} from 'jiti';\nconst jiti = createJiti(import.meta.url);\njiti(docPath);",+ ],+ [+ 'loader.importUserModule(docPath) through a namespace import',+ `import * as loader from ${MODULE_LOADER};\nawait loader.importUserModule(docPath);`,+ ],+ [+ 'a renamed import of a loader',+ `import {importUserModule as load} from ${MODULE_LOADER};\nawait load(docPath);`,+ ],+ [+ 'files.map(importUserModule): a loader passed as a value',+ `import {importUserModule} from ${MODULE_LOADER};\nawait Promise.all(files.map(importUserModule));`,+ ],+ [+ 'importUserModule.call(null, docPath)',+ `import {importUserModule} from ${MODULE_LOADER};\nawait importUserModule.call(null, docPath);`,+ ],+ [+ 'a re-export of the doc importers',+ `export {importDocModule} from ${IMPORTERS};`,+ ],+ [+ 'a literal dynamic import of the doc importers',+ `const {importDocModule} = await import(${IMPORTERS});\nawait importDocModule(docPath);`,+ ],+ [+ 'loadModuleWithParser(file, parsers.parseDoc)',+ `import {loadModuleWithParser} from ${MODULE_LOADER};\nawait loadModuleWithParser(file, parsers.parseDoc);`,+ ],+ [+ 'loadModuleWithParser(file, x => parseDoc(x))',+ `import {loadModuleWithParser} from ${MODULE_LOADER};\nawait loadModuleWithParser(file, x => parseDoc(x));`,+ ],+ [+ 'new Worker(docPath)',+ "import {Worker} from 'node:worker_threads';\nnew Worker(docPath);",+ ],+ [+ 'child_process fork(docPath)',+ "import {fork} from 'node:child_process';\nfork(docPath);",+ ],+ [+ 'vm.runInThisContext(readFileSync(docPath))',+ "import vm from 'node:vm';\nimport fs from 'node:fs';\nvm.runInThisContext(fs.readFileSync(docPath, 'utf8'));",+ ],+ [+ 'import.meta.resolve of a doc file',+ "const url = import.meta.resolve('./Button.doc.mjs');",+ ],+ // The same, reached another way.+ [+ 'importUserModule.apply(null, [docPath])',+ `import {importUserModule} from ${MODULE_LOADER};\nawait importUserModule.apply(null, [docPath]);`,+ ],+ [+ 'a dynamic import of import.mjs, then m.importDocModule(docPath)',+ `const m = await import(${IMPORTERS});\nawait m.importDocModule(docPath);`,+ ],+ ['export * from import.mjs', `export * from ${IMPORTERS};`],+ [+ 'a namespace of import.mjs passed on',+ `import * as importers from ${IMPORTERS};\nexport default importers;`,+ ],+ [+ 'a computed member of a loader namespace',+ `import * as loader from ${MODULE_LOADER};\nloader[name](docPath);`,+ ],+ [+ 'a loader re-exported by a local export',+ `import {importUserModule} from ${MODULE_LOADER};\nexport {importUserModule};`,+ ],+ [+ 'a loader in an object shorthand',+ `import {importUserModule} from ${MODULE_LOADER};\nexport const api = {importUserModule};`,+ ],+ [+ 'a loader behind a block-scoped shadow',+ `import {importUserModule as load} from ${MODULE_LOADER};\nexport function f(p) {\n { const load = () => {}; }\n return load(p);\n}`,+ ],+ [+ 'a loader import with a query string',+ "import {importDocModule} from '../../foundation/doc-compiler/import.mjs?v=1';\nimportDocModule(docPath);",+ ],+ [+ 'a loader import with an escaped character',+ "import {importDocModule} from '../../foundation/doc-compiler/%69mport.mjs';\nimportDocModule(docPath);",+ ],+ [+ 'a raw topic loader from discovery',+ "import {loadTopicModule} from '../../foundation/discovery/docs-discovery.mjs';\nawait loadTopicModule(docPath);",+ ],+ ['a side-effect import of a doc file', "import './Button.doc.mjs';"],+ [+ 'a static import of a doc overlay',+ "import {docsZh} from './Button.doc.zh.mjs';",+ ],+ ['a re-export of a doc file', "export {doc} from './Button.doc.mjs';"],+ [+ 'Module.createRequire(...)(docPath) through a default import',+ "import Module from 'node:module';\nModule.createRequire(import.meta.url)(docPath);",+ ],+ [+ 'a require function passed on',+ "import {createRequire} from 'node:module';\nconst r = createRequire(import.meta.url);\nconst q = r;\nq(docPath);",+ ],+ [+ 'module.register',+ "import {register} from 'node:module';\nregister('./hooks.mjs', import.meta.url);",+ ],+ ['(0, eval)(source)', '(0, eval)(source);'],+ ['globalThis.eval(source)', 'globalThis.eval(source);'],+ ["globalThis['ev' + 'al'](source)", "globalThis['ev' + 'al'](source);"],+ [+ "Function('return import(p)') without new",+ "Function('return import(p)')();",+ ],+ [+ "import('node:child_process')",+ "const {fork} = await import('node:child_process');",+ ],+ [+ "require('worker_threads').Worker",+ "new (require('worker_threads').Worker)(docPath);",+ ],+ [+ 'a default import of child_process',+ "import cp from 'child_process';\ncp.fork(docPath);",+ ],+ ['jiti.evalModule(source)', 'jiti.evalModule(source);'],+ [+ 'process.getBuiltinModule, with no import',+ "process.getBuiltinModule('node:child_process').fork(docPath);",+ ],+ [+ 'getBuiltinModule taken off process',+ "const {getBuiltinModule} = process;\ngetBuiltinModule('node:vm');",+ ],+ ['a ShadowRealm', 'const realm = new ShadowRealm();'],+ ["a realm's importValue", "await realm.importValue(docPath, 'doc');"],+ [+ "an async function's constructor",+ "await (async () => {}).constructor('return import(p)')();",+ ],+ [+ 'node:test running files',+ "import {run} from 'node:test';\nrun({files: [docPath]});",+ ],+ [+ 'a helper from a directory the scan skips',+ "import {runCli} from '../../test-utils/run-cli.mjs';\nrunCli(docPath);",+ ],+ [+ 'a static import of a data: URL',+ "import one from 'data:text/javascript,export default 1';\nexport {one};",+ ],+ [+ 'a dynamic import of a data: URL',+ "await import('data:text/javascript,export default 1');",+ ],+ [+ 'a dynamic import over https',+ "await import('https://example.test/x.mjs');",+ ],+ ['process.dlopen', 'process.dlopen({exports: {}}, file);'],+ ['process.execve', 'process.execve(file, args);'],+ [+ 'dlopen destructured off process',+ 'const {dlopen} = process;\ndlopen({exports: {}}, file);',+ ],+ ['WebAssembly.instantiate', 'await WebAssembly.instantiate(bytes);'],+ [+ 'WebAssembly.compile through globalThis',+ 'await globalThis.WebAssembly.compile(bytes);',+ ],+ ['new WebAssembly.Module', 'new WebAssembly.Module(bytes);'],+ ['Object.constructor(source)', 'Object.constructor(source)();'],+ [+ "a function literal's constructor, taken and kept",+ 'const F = (() => {}).constructor;\nexport {F};',+ ],+ [+ '[].constructor.constructor(source)',+ '[].constructor.constructor(source)();',+ ],+ [+ "''.constructor.constructor(source)",+ "''.constructor.constructor(source)();",+ ],+ [+ "a prototype's constructor",+ 'Object.getPrototypeOf(async function () {}).constructor(source)();',+ ],+ [+ 'eval destructured off globalThis',+ 'const {eval: e} = globalThis;\ne(source);',+ ],+ [+ 'Function destructured off globalThis',+ 'const {Function: F} = globalThis;\nF(source)();',+ ],+ [+ 'eval through an alias of globalThis',+ 'const g = globalThis;\ng.eval(source);',+ ],+ [+ 'eval through a chain of aliases',+ 'const g = globalThis;\nconst h = g;\nh.eval(source);',+ ],+ [+ 'a computed destructuring off globalThis',+ "const {['ev' + 'al']: e} = globalThis;\ne(source);",+ ],+ [+ "Reflect.get(globalThis, 'eval')",+ "Reflect.get(globalThis, 'eval')(source);",+ ],+ [+ 'a module under the authored templates',+ "import helper from '../../assets/templates/x/helper.mjs';",+ ],+ [+ 'a module in a hidden directory',+ "import {load} from './.cache/load.mjs';\nload(docPath);",+ ],+ [+ 'a module in a fixtures directory',+ "import {load} from './__fixtures__/load.mjs';\nload(docPath);",+ ],+ ['a test module', "import {load} from './load.test.mjs';\nload(docPath);"],+ [+ 'the doc importers by absolute file URL',+ "import {importDocModule} from 'file:///repo/packages/cli/foundation/doc-compiler/import.mjs';\nimportDocModule(docPath);",+ ],+ [+ 'child_process imported as {default as cp}',+ "import {default as cp} from 'node:child_process';\ncp.fork(docPath);",+ ],+ [+ 'createRequire passed on',+ "import {createRequire} from 'node:module';\nconst make = createRequire;\nmake(import.meta.url)(docPath);",+ ],+].map(([name, code]) => ({name, file: LEAF, code}));++BYPASSES.push(+ {+ name: 'a require of a doc file, in CommonJS',+ file: 'api/leaf/leaf.cjs',+ code: "const {doc} = require('./Button.doc.cjs');",+ },+ {+ name: 'an import-equals of a doc file, in TypeScript',+ file: 'api/leaf/leaf.ts',+ code: "import doc = require('./Button.doc.mjs');",+ },+ {+ name: 'module.require, in CommonJS',+ file: 'api/leaf/leaf.cjs',+ code: 'module.require(docPath);',+ },+ {+ name: 'a loader module re-exported by import-equals, in TypeScript',+ file: 'api/leaf/leaf.ts',+ code: `export import loader = require(${MODULE_LOADER});`,+ },+ {+ name: 'an extension-free import of the doc importers, in TypeScript',+ file: 'api/leaf/leaf.ts',+ code: "import {importDocModule} from '../../foundation/doc-compiler/import';\nimportDocModule(docPath);",+ },+ {+ name: 'import(docPath) in a listed module',+ ...edited(+ 'foundation/config/project.mjs',+ s => `${s}\nawait import(docPath);`,+ ),+ },+ {+ name: 'a doc parser swapped into a listed loadModuleWithParser call',+ ...edited('foundation/config/project.mjs', s =>+ s.replace(+ 'loadModuleWithParser(configPath, parseConfig',+ 'loadModuleWithParser(configPath, parseDoc',+ ),+ ),+ },+ {+ name: 'a second loader call in a listed module',+ ...edited(+ 'foundation/integrations/integrations.mjs',+ s => `${s}\nawait importUserModule(docPath);`,+ ),+ },+);++/**+ * Code that runs nothing outside its static imports.+ * @type {Array<{name: string, file: string, code: string}>}+ */+const INNOCENT = [+ ['a literal import of a built-in', "await import('node:fs');"],+ ['a literal lazy import', "const m = await import('./other.mjs');"],+ [+ 'an inert loader-module export',+ `import {findPresentFiles} from ${MODULE_LOADER};\nfindPresentFiles(dir, names);`,+ ],+ [+ 'an inert export read off a loader namespace',+ `import * as loader from ${MODULE_LOADER};\nloader.findPresentFiles(dir, names);`,+ ],+ [+ 'a require function that only resolves',+ "import {createRequire} from 'node:module';\nconst require = createRequire(import.meta.url);\nrequire.resolve('pkg/package.json');",+ ],+ [+ 'createRequire(...).resolve',+ "import {createRequire} from 'node:module';\ncreateRequire(import.meta.url).resolve('pkg');",+ ],+ [+ 'a doc path as data',+ "const target = name + '.doc.mjs';\nif (file.endsWith('.doc.mjs')) files.push(target);",+ ],+ [+ 'an inert member of {default as x}',+ "import {default as threads} from 'node:worker_threads';\nthreads.parentPort.postMessage(1);",+ ],+ [+ 'the worker side of worker_threads',+ "import {parentPort, workerData} from 'node:worker_threads';\nparentPort.postMessage(workerData);",+ ],+ ['x instanceof Function', 'if (x instanceof Function) f();'],+ ['j.Function, an AST node type', 'root.find(j.Function);'],+ [+ 'a property that shares a loader name',+ 'const o = {importUserModule: 1};\nconsole.log(o.importUserModule);',+ ],+ [+ 'a read through the compiler',+ "import {readDocView} from '../../foundation/doc-compiler/read.mjs';\nawait readDocView(file, {root: 'components'});",+ ],+ [+ 'the docs catalog',+ "import {DocsCatalog} from '../../foundation/discovery/docs-discovery.mjs';\nnew DocsCatalog();",+ ],+ [+ 'an inert export of module',+ "import {builtinModules} from 'node:module';\nbuiltinModules.includes(name);",+ ],+ [+ 'a URL of a module that is not a doc',+ "const worker = new URL('./worker.mjs', import.meta.url);",+ ],+ ['a string that mentions import()', "const text = 'await import(x)';"],+ [+ 'getBuiltinModule of an inert built-in',+ "const fs = process.getBuiltinModule('node:fs');",+ ],+ ['an inert member of process', 'const dir = process.cwd();'],+ ['an inert destructuring of process', 'const {env, argv} = process;'],+ ['an inert member of globalThis', 'globalThis.crypto.randomUUID();'],+ ['WebAssembly.validate', 'WebAssembly.validate(bytes);'],+ ['a constructor read and passed on', 'patchPrototype(command.constructor);'],+ [+ "a constructor's name",+ "const kind = proto?.constructor?.name ?? 'non-plain object';",+ ],+ ['a property named constructor', 'const o = {constructor: 1};\nread(o);'],+].map(([name, code]) => ({name, file: LEAF, code}));++INNOCENT.push(+ {+ name: 'a require of a built-in, in CommonJS',+ file: 'api/leaf/leaf.cjs',+ code: "const path = require('node:path');",+ },+ {+ name: 'a type-only import of a doc file, in TypeScript',+ file: 'api/leaf/leaf.ts',+ code: "import type {Doc} from './Button.doc.mjs';\nexport type D = Doc;",+ },+ {+ name: 'a loader named in a type, in TypeScript',+ file: 'api/leaf/leaf.ts',+ code: `import {importDocModule} from ${IMPORTERS};\nlet load: typeof importDocModule | undefined;`,+ },+);++describe('the scan', () => {+ it('reads every code file but tests, fixtures, dependencies, and generated or hidden ones', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'doc-loads-'));+ const code = [+ 'a.cjs',+ 'a.cts',+ 'a.js',+ 'a.jsx',+ 'a.mjs',+ 'a.mts',+ 'a.ts',+ 'a.tsx',+ ];+ const skipped = [+ '.cache/a.mjs',+ '__fixtures__/a.mjs',+ '__tests__/a.mjs',+ 'a.d.mts',+ 'a.json',+ 'a.test.mjs',+ 'a.test.ts',+ 'node_modules/a.mjs',+ ];+ try {+ for (const file of [...code, ...skipped]) {+ fs.mkdirSync(path.dirname(path.join(dir, file)), {recursive: true});+ fs.writeFileSync(path.join(dir, file), '');+ }+ const found = sources(dir).map(full => path.relative(dir, full));+ expect(found.sort()).toEqual(code);+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });++ it.each(BYPASSES)('catches $name', ({file, code}) => {+ expect(violations(file, code)).not.toEqual([]);+ });++ it.each(INNOCENT)('passes $name', ({file, code}) => {+ expect(scanModule(code, file)).toEqual({sites: [], problems: []});+ });++ it('refuses a doc parser handed to a loader, even with the site listed', () => {+ for (const parser of ['parsers.parseDoc', 'x => parseFunction(x)']) {+ const code = `import {loadModuleWithParser} from ${MODULE_LOADER};\nloadModuleWithParser(file, ${parser});`;+ const listed = tally(scanModule(code, LEAF).sites);+ expect(violations(LEAF, code, listed)).toEqual([+ `${LEAF}: loadModuleWithParser(..., ${parser}) loads a doc outside the compiler`,+ ]);+ }+ });+});++describe('the scan walks every folder that can ship', () => {+ it('skips only test scaffolding and the temporary folders tests create', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'doc-loads-walk-'));+ try {+ for (const dir of [+ '__generated__',+ '__tests__',+ '__fixtures__',+ '__import_hint_integration_Ab12Cd',+ '.hidden',+ 'node_modules',+ ]) {+ fs.mkdirSync(path.join(root, dir));+ fs.writeFileSync(path.join(root, dir, 'run.mjs'), "eval('1');\n");+ }+ expect(+ sources(root).map(file => path.basename(path.dirname(file))),+ ).toEqual(['__generated__']);+ } finally {+ fs.rmSync(root, {recursive: true, force: true});+ }+ });+});diff --git a/packages/cli/foundation/doc-compiler/import.mjs b/packages/cli/foundation/doc-compiler/import.mjsnew file mode 100644index 0000000000..e1ca80314f--- /dev/null+++ b/packages/cli/foundation/doc-compiler/import.mjs@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Doc module importers: how the doc reader and discovery execute an+ * authored doc file.+ *+ * @input An absolute path to a `.doc.{ts,mjs,js}` (or legacy template) file.+ * @output The module's namespace object.+ * @position Called by ./read.mjs, which hands what comes back to the compiler,+ * and by discovery, which reads a contributed topic's name and relationships+ * to build the catalog. Doc files also run outside these importers: each CLI+ * command imports its own self-docs statically for its help text, and the+ * README script imports them at build time. ./doc-loads.test.mjs lists, site+ * by site, every use of these importers and every other place the CLI runs+ * anything but its static imports of other CLI code (a static doc import is+ * one); a new site fails it. It catches every ordinary way of running code,+ * whatever the local names; deliberate obfuscation is out of scope.+ */++import {pathToFileURL} from 'node:url';+import {createJiti} from 'jiti';+import {importUserModule} from '../fs/module-loader.mjs';++/** @type {ReturnType<typeof createJiti> | undefined} */+let jsxJiti;++/**+ * Import a component, hook, topic, or self-doc module: `.ts` through jiti,+ * anything else natively.+ * @param {string} file+ * @returns {Promise<any>}+ */+export function importDocModule(file) {+ return importUserModule(file);+}++/**+ * How core and external template docs have always been imported: `.ts`+ * through a JSX-aware jiti, anything else natively.+ * @param {string} file+ * @returns {Promise<any>}+ */+export function importTemplateModule(file) {+ if (file.endsWith('.ts')) {+ jsxJiti ??= createJiti(import.meta.url, {jsx: true});+ return jsxJiti.import(file);+ }+ return import(`file://${file}`);+}++/**+ * Import a module natively, by file URL: how the docs API, search, and the+ * unchecked component and hook readers have always imported docs.+ * @param {string} file+ * @returns {Promise<any>}+ */+export function importNativeModule(file) {+ return import(pathToFileURL(file).href);+}diff --git a/packages/cli/foundation/doc-compiler/inputs.mjs b/packages/cli/foundation/doc-compiler/inputs.mjsnew file mode 100644index 0000000000..73210338d6--- /dev/null+++ b/packages/cli/foundation/doc-compiler/inputs.mjs@@ -0,0 +1,286 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Compiler inputs — every authored descriptor a project reads, listed once.+ *+ * @input A loaded Project: the components, hooks, templates, themes, and doc+ * topics its discovery found, plus the CLI's own self-documentation.+ * @output One {@link DocInput} per descriptor file, in read order, and the+ * problems found while listing them: a file two roots both claim, or two+ * files under one input id.+ * @position Between discovery and the doc compiler. Discovery still decides+ * what each root contributes; this module lists that result in one shape so+ * the compiler and the completeness check read the same set. Internal to the+ * CLI: nothing here is a public type, and an input id is not a published+ * identifier.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ CORE_PACKAGE,+ findComponentReadme,+} from '../discovery/component-discovery.mjs';+import {discoverHooks, findHookDoc} from '../discovery/hook-discovery.mjs';+import {CLI_ROOT, findCoreDir} from '../fs/paths.mjs';+import {packageSource} from './source.mjs';++export {packageSource};++/** The package that owns the CLI's own self-documentation. */+const CLI_PACKAGE = '@astryxdesign/cli';++/** Where the CLI keeps self-documentation, relative to its package root. */+export const SELF_DOC_TREES = ['api', 'clients', 'authoring', 'foundation'];++/** Directories that hold test inputs, never shipped descriptors. */+const NON_DESCRIPTOR_DIRS = new Set([+ '__tests__',+ '__fixtures__',+ 'fixtures',+ 'node_modules',+]);++/**+ * @typedef {'components' | 'hooks' | 'templates' | 'themes' | 'docs' | 'self-docs'} DocRoot+ */++/**+ * One authored descriptor, as the compiler will read it.+ * @typedef {object} DocInput+ * @property {string} id `owner:root:name`, unique within a project+ * @property {DocRoot} root the kind of root that reads it+ * @property {string} name the name a reader asks for+ * @property {string} owner the package that contributes it, as discovery+ * reports it+ * @property {string} file absolute path; never leaves the CLI+ * @property {string} source `<package>/<path inside it>` for the file itself:+ * where it ships, independent of the machine it was found on+ * @property {'base' | 'extension'} [role] for a doc topic: its own file, or an+ * extension merged onto it+ * @property {false} [listed] a component doc that `component <Name>` reads but+ * the component list leaves out+ */++/**+ * @typedef {object} DocInputProblem+ * @property {'duplicate_file' | 'duplicate_id'} code+ * @property {string} provider the package of the input that was not added+ * @property {string} source `<package>/<path>` of its file+ * @property {string} message+ */++/**+ * List every descriptor the project reads.+ *+ * @param {import('../config/project.mjs').Project} project+ * @returns {Promise<{inputs: DocInput[], problems: DocInputProblem[]}>}+ */+export async function collectDocInputs(project) {+ const list = new InputList();++ for (const record of await project.components()) {+ if (record.docPath == null) continue;+ list.add('components', record.name, record.package, record.docPath);+ }++ const coreDir = findCoreDir(project.cwd);+ if (coreDir != null) {+ for (const name of Object.values(discoverHooks(coreDir)).flat()) {+ const file = findHookDoc(coreDir, name);+ if (file != null) list.add('hooks', name, CORE_PACKAGE, file);+ }+ // `component <Name>` finds a core doc by its file name even when the+ // component list, which needs a same-stem source, leaves it out.+ for (const {name, file} of unlistedCoreComponentDocs(coreDir, list)) {+ list.add('components', name, CORE_PACKAGE, file, undefined, false);+ }+ }++ // A template is looked up by its type and directory name; its display name+ // is only a title, and a showcase can share it with the block it shows.+ for (const template of /** @type {any[]} */ (await project.templates())) {+ list.add(+ 'templates',+ `${template.type}/${template.dirName}`,+ template.package ?? CORE_PACKAGE,+ template.docPath,+ );+ }++ for (const theme of await project.themes()) {+ list.add('themes', theme.slug, theme.package, theme.docPath);+ }++ for (const topic of (await project.docs()).entries()) {+ list.add('docs', topic.name, topic.package, topic.path, 'base');+ for (const extension of topic.extensions) {+ list.add(+ 'docs',+ topic.name,+ extension.package,+ extension.path,+ 'extension',+ );+ }+ }++ for (const file of selfDocFiles()) {+ const name = path+ .relative(CLI_ROOT, file)+ .split(path.sep)+ .join('/')+ .replace(/\.doc\.mjs$/u, '');+ list.add('self-docs', name, CLI_PACKAGE, file);+ }++ return {inputs: list.inputs, problems: list.problems};+}++/**+ * Core component docs outside the component list that `component <Name>`+ * still reads: every core doc, outside the hooks directory, that is not listed+ * yet and that its own file name resolves back to.+ *+ * @param {string} coreDir+ * @param {InputList} list the inputs so far+ * @returns {Array<{name: string, file: string}>}+ */+function unlistedCoreComponentDocs(coreDir, list) {+ const srcDir = path.join(coreDir, 'src');+ const hooksDir = path.join(srcDir, 'hooks');+ /** @type {Array<{name: string, file: string}>} */+ const found = [];+ /** @param {string} dir */+ const walk = dir => {+ const entries = fs+ .readdirSync(dir, {withFileTypes: true})+ .sort((a, b) => a.name.localeCompare(b.name));+ for (const entry of entries) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (full !== hooksDir && !NON_DESCRIPTOR_DIRS.has(entry.name)) {+ walk(full);+ }+ } else if (entry.isFile() && entry.name.endsWith('.doc.mjs')) {+ if (list.claims(full)) continue;+ const name = entry.name.slice(0, -'.doc.mjs'.length);+ const resolved = findComponentReadme(coreDir, name);+ if (resolved != null && realPath(resolved) === realPath(full)) {+ found.push({name, file: full});+ }+ }+ }+ };+ if (fs.existsSync(srcDir)) walk(srcDir);+ return found;+}++/**+ * Every self-documentation file the CLI ships, in path order.+ * @returns {string[]} absolute paths+ */+export function selfDocFiles() {+ /** @type {string[]} */+ const files = [];+ /** @param {string} dir */+ const walk = dir => {+ const entries = fs+ .readdirSync(dir, {withFileTypes: true})+ .sort((a, b) => a.name.localeCompare(b.name));+ for (const entry of entries) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!NON_DESCRIPTOR_DIRS.has(entry.name)) walk(full);+ } else if (entry.isFile() && entry.name.endsWith('.doc.mjs')) {+ files.push(full);+ }+ }+ };+ for (const tree of SELF_DOC_TREES) {+ const dir = path.join(CLI_ROOT, tree);+ if (fs.existsSync(dir)) walk(dir);+ }+ return files;+}++/** Collects inputs in read order and records what could not be added. */+class InputList {+ /** @type {DocInput[]} */+ inputs = [];+ /** @type {DocInputProblem[]} */+ problems = [];+ /** @type {Map<string, DocInput>} real path -> the input that claimed it */+ #byFile = new Map();+ /** @type {Map<string, DocInput>} */+ #byId = new Map();++ /**+ * @param {string} file+ * @returns {boolean} whether an input already reads this file+ */+ claims(file) {+ return this.#byFile.has(realPath(file));+ }++ /**+ * @param {DocRoot} root+ * @param {string} name+ * @param {string} owner+ * @param {string} file+ * @param {'base' | 'extension'} [role]+ * @param {false} [listed]+ */+ add(root, name, owner, file, role, listed) {+ const real = realPath(file);+ const claimed = this.#byFile.get(real);+ if (claimed != null) {+ this.problems.push({+ code: 'duplicate_file',+ provider: owner,+ source: packageSource(real),+ message: `${packageSource(real)} is read as ${root} "${name}" and as ${claimed.root} "${claimed.name}"; one descriptor must have one reader.`,+ });+ return;+ }+ // An extension is named by its file too: one package may extend a topic+ // from more than one file.+ const id =+ role === 'extension'+ ? `${owner}:${root}:${name}+${path.basename(file).replace(/\.doc\.[cm]?[jt]s$/u, '')}`+ : `${owner}:${root}:${name}`;+ const taken = this.#byId.get(id);+ if (taken != null) {+ this.problems.push({+ code: 'duplicate_id',+ provider: owner,+ source: packageSource(real),+ message: `${packageSource(real)} and ${taken.source} both read as ${root} "${name}" from ${owner}.`,+ });+ return;+ }+ /** @type {DocInput} */+ const input = {+ id,+ root,+ name,+ owner,+ file: real,+ source: packageSource(real),+ ...(role == null ? {} : {role}),+ ...(listed === false ? {listed} : {}),+ };+ this.#byFile.set(real, input);+ this.#byId.set(id, input);+ this.inputs.push(input);+ }+}++/** @param {string} file */+function realPath(file) {+ try {+ return fs.realpathSync(file);+ } catch {+ return path.resolve(file);+ }+}diff --git a/packages/cli/foundation/doc-compiler/inputs.test.mjs b/packages/cli/foundation/doc-compiler/inputs.test.mjsnew file mode 100644index 0000000000..4621086276--- /dev/null+++ b/packages/cli/foundation/doc-compiler/inputs.test.mjs@@ -0,0 +1,299 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every authored descriptor becomes exactly one compiler input.+ *+ * The repo check is the completeness oracle for what Core and the CLI ship:+ * every `.doc.mjs` under a descriptor root is read once, and nothing else is.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {Project} from '../config/project.mjs';+import {CLI_ROOT} from '../fs/paths.mjs';+import {collectDocInputs, packageSource} from './inputs.mjs';++const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');+const SKIP = new Set(['__tests__', '__fixtures__', 'fixtures', 'node_modules']);++/**+ * Every `.doc.mjs` under a directory, by real path.+ * @param {string} dir+ * @param {Set<string>} into+ */+function docFiles(dir, into) {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!SKIP.has(entry.name)) docFiles(full, into);+ } else if (entry.name.endsWith('.doc.mjs')) {+ into.add(fs.realpathSync(full));+ }+ }+ return into;+}++let tmpDir;++beforeEach(() => {+ // Inside the repo, so the project finds this checkout's Core.+ tmpDir = fs.mkdtempSync(path.join(REPO_ROOT, '.astryx-doc-inputs-'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer', version: '1.0.0'}),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('collectDocInputs over what this repo ships', () => {+ it('reads every descriptor Core and the CLI ship exactly once', async () => {+ const {inputs, problems} = await collectDocInputs(+ await Project.load(tmpDir),+ );+ expect(problems).toEqual([]);++ // What ships comes from the packages themselves, not from the module under+ // test: Core's source, and every directory the CLI's package.json ships.+ const shipped = new Set();+ docFiles(path.join(REPO_ROOT, 'packages', 'core', 'src'), shipped);+ const {files} = JSON.parse(+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf-8'),+ );+ for (const entry of files) {+ const full = path.join(CLI_ROOT, entry);+ if (fs.statSync(full).isDirectory()) docFiles(full, shipped);+ }+ const read = inputs.map(input => input.file);+ const rel = (/** @type {string} */ file) => path.relative(REPO_ROOT, file);+ expect(read.filter(file => !shipped.has(file)).map(rel)).toEqual([]);+ expect([...shipped].filter(file => !read.includes(file)).map(rel)).toEqual(+ [],+ );+ expect(new Set(read).size).toBe(read.length);+ expect(new Set(inputs.map(input => input.id)).size).toBe(inputs.length);+ }, 120_000);++ it('pins the core docs that `component <Name>` reads but the list leaves out', async () => {+ const {inputs} = await collectDocInputs(await Project.load(tmpDir));+ // Each is readable by name; listing them would change `component --list`,+ // so a new entry here is a decision, not a silent drift.+ expect(+ inputs+ .filter(input => input.listed === false)+ .map(input => input.name)+ .sort(),+ ).toEqual([+ 'Chat',+ 'ChatComposerTokenElement',+ 'Code',+ 'ContextMenuItem',+ 'Heading',+ 'Indicator',+ 'Layer',+ 'NavMenu',+ 'Resizable',+ 'SyntaxTheme',+ ]);+ });++ it('keys templates by type and directory, not by their display title', async () => {+ const {inputs} = await collectDocInputs(await Project.load(tmpDir));+ const byName = new Map(+ inputs+ .filter(input => input.root === 'templates')+ .map(input => [input.name, input]),+ );+ // A showcase shares its title with the block it shows; both stay inputs.+ expect(byName.get('block/BannerStatuses')?.source).toBe(+ '@astryxdesign/cli/assets/templates/blocks/components/Banner/BannerStatuses.doc.mjs',+ );+ expect(byName.get('block/BannerShowcase')?.source).toBe(+ '@astryxdesign/cli/assets/templates/blocks/components/Banner/BannerShowcase.doc.mjs',+ );+ });+});++describe('collectDocInputs over an integration', () => {+ /**+ * @param {string} rel+ * @param {string} text+ */+ function write(rel, text) {+ const file = path.join(tmpDir, 'node_modules', '@acme', 'kit', rel);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, text);+ }++ it('lists each descriptor once, owned by the package, with where it ships', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ version: '1.0.0',+ dependencies: {'@acme/kit': '^1.0.0'},+ }),+ );+ write(+ 'package.json',+ JSON.stringify({name: '@acme/kit', version: '1.0.0'}),+ );+ write(+ 'astryx.integration.mjs',+ "export default {components: './components', templates: './templates', docs: './docs', themes: './themes'};\n",+ );+ write(+ 'components/AcmeCard.tsx',+ 'export function AcmeCard() { return null; }\n',+ );+ write(+ 'components/AcmeCard.doc.mjs',+ "export default {type: 'component', name: 'AcmeCard', displayName: 'Acme Card', usage: {description: 'A card.'}, props: []};\n",+ );+ write(+ 'templates/hero.tsx',+ 'export default function Hero() { return null; }\n',+ );+ write(+ 'templates/hero.doc.mjs',+ "export default {type: 'block', name: 'Hero block', description: 'A hero.'};\n",+ );+ const topic = (/** @type {object} */ fields) =>+ `export default ${JSON.stringify({+ type: 'generic',+ title: 'Acme',+ description: 'Acme notes.',+ sections: [{title: 'Acme', content: [{type: 'prose', text: 'Hi.'}]}],+ ...fields,+ })};\n`;+ write('docs/acme-guide.doc.mjs', topic({name: 'acme-guide'}));+ write(+ 'docs/theme-notes.doc.mjs',+ topic({name: 'theme-notes', extends: 'theme'}),+ );+ write('themes/ocean/oceanTheme.ts', 'export const oceanTheme = {};\n');+ write(+ 'themes/ocean/oceanTheme.doc.mjs',+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Blue.', maintained: true};\n",+ );++ const project = await Project.load(tmpDir);+ expect(await project.issues()).toEqual([]);+ const {inputs, problems} = await collectDocInputs(project);+ expect(problems).toEqual([]);+ expect(+ inputs+ .filter(input => input.owner === '@acme/kit')+ .map(({id, source, role}) => ({id, source, role})),+ ).toEqual([+ {+ id: '@acme/kit:components:AcmeCard',+ source: '@acme/kit/components/AcmeCard.doc.mjs',+ role: undefined,+ },+ {+ id: '@acme/kit:templates:block/hero',+ source: '@acme/kit/templates/hero.doc.mjs',+ role: undefined,+ },+ {+ id: '@acme/kit:themes:ocean',+ source: '@acme/kit/themes/ocean/oceanTheme.doc.mjs',+ role: undefined,+ },+ {+ id: '@acme/kit:docs:theme+theme-notes',+ source: '@acme/kit/docs/theme-notes.doc.mjs',+ role: 'extension',+ },+ {+ id: '@acme/kit:docs:acme-guide',+ source: '@acme/kit/docs/acme-guide.doc.mjs',+ role: 'base',+ },+ ]);+ });+});++describe('collectDocInputs problems', () => {+ /** @param {object} overrides */+ const project = overrides =>+ /** @type {any} */ ({+ cwd: os.tmpdir(),+ components: async () => [],+ templates: async () => [],+ themes: async () => [],+ docs: async () => ({entries: () => []}),+ ...overrides,+ });++ it('reports a file two roots both claim, and reads it once', async () => {+ const file = path.join(tmpDir, 'Shared.doc.mjs');+ fs.writeFileSync(file, 'export default {};\n');+ const {inputs, problems} = await collectDocInputs(+ project({+ components: async () => [+ {name: 'Shared', package: '@acme/kit', docPath: file},+ ],+ templates: async () => [+ {+ type: 'block',+ dirName: 'shared',+ package: '@acme/kit',+ docPath: file,+ },+ ],+ }),+ );+ expect(+ inputs.filter(input => input.file === fs.realpathSync(file)),+ ).toHaveLength(1);+ expect(problems).toEqual([+ {+ code: 'duplicate_file',+ provider: '@acme/kit',+ source: expect.stringMatching(/\/Shared\.doc\.mjs$/),+ message: expect.stringContaining(+ 'is read as templates "block/shared" and as components "Shared"',+ ),+ },+ ]);+ });++ it('reports two files under one input id', async () => {+ const one = path.join(tmpDir, 'a', 'Card.doc.mjs');+ const two = path.join(tmpDir, 'b', 'Card.doc.mjs');+ for (const file of [one, two]) {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, 'export default {};\n');+ }+ const {problems} = await collectDocInputs(+ project({+ components: async () => [+ {name: 'Card', package: '@acme/kit', docPath: one},+ {name: 'Card', package: '@acme/kit', docPath: two},+ ],+ }),+ );+ expect(problems).toEqual([+ {+ code: 'duplicate_id',+ provider: '@acme/kit',+ source: expect.stringMatching(/\/Card\.doc\.mjs$/),+ message: expect.stringContaining('both read as components "Card"'),+ },+ ]);+ });+});++describe('packageSource', () => {+ it('names the package a file ships in and its path inside it', () => {+ expect(+ packageSource(path.join(CLI_ROOT, 'api', 'docs', 'docs.doc.mjs')),+ ).toBe('@astryxdesign/cli/api/docs/docs.doc.mjs');+ });+});diff --git a/packages/cli/foundation/doc-compiler/ir.mjs b/packages/cli/foundation/doc-compiler/ir.mjsindex 448ecfae4c..d9cb4d94d1 100644--- a/packages/cli/foundation/doc-compiler/ir.mjs+++ b/packages/cli/foundation/doc-compiler/ir.mjs@@ -1,13 +1,14 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file The compiled-node contract and its sealed parser.+ * @file The compiled-doc contract and its sealed parsers.*- * @input Any value that claims to be a compiled reference node — typically one- * read back from JSON.+ * @input Any value that claims to be a compiled node or a compiled docs bundle+ * — typically one read back from JSON.* @output The same value once it validates; a thrown Error naming the problems- * otherwise. An unsupported schema version fails with its own message before- * anything else is checked.+ * otherwise, carrying a compiler diagnostic (`unsupported_schema` or+ * `invalid_bundle`). An unsupported schema version fails with its own message+ * before anything else is checked.* @position The load boundary for compiled nodes that did not come straight* from ./compile.mjs in this process. The value is returned as given, not* rebuilt, so key order (which response JSON follows) survives. A node is@@ -15,7 +16,8 @@*/import {SECTION_KEY_RE} from '../discovery/docs-section-key.mjs';-import {COMPILED_DOC_SCHEMA_VERSION} from './compile.mjs';+import {COMPILED_DOC_KINDS, COMPILED_DOC_SCHEMA_VERSION} from './compile.mjs';+import {diagnostic, diagnosticProblem} from './diagnostics.mjs';const NODE_FIELDS = new Set(['schemaVersion',@@ -65,15 +67,13 @@ const isPackageName = value =>*/export function parseCompiledReferenceNode(value) {const node = /** @type {any} */ (value);- if (node?.schemaVersion !== COMPILED_DOC_SCHEMA_VERSION) {- throw new Error(- `Compiled doc schema version ${JSON.stringify(node?.schemaVersion)} is not supported; this CLI reads version ${COMPILED_DOC_SCHEMA_VERSION}. Compile the docs again with this CLI.`,- );- }+ const skew = schemaVersionProblem(node);+ if (skew) throw compiledDocError('unsupported_schema', skew);const problems = jsonProblems(node, 'node');if (problems.length === 0) problems.push(...structureProblems(node));if (problems.length > 0) {- throw new Error(+ throw compiledDocError(+ 'invalid_bundle',`Invalid compiled doc node: ${problems.slice(0, MAX_PROBLEMS).join('; ')}`,);}@@ -285,3 +285,180 @@ function resolutionProblem(resolved) {return `status: expected resolved, unknown-topic or unknown-section, got ${JSON.stringify(resolved.status)}`;}}++const DOC_NODE_FIELDS = new Set([+ 'schemaVersion',+ 'kind',+ 'stage',+ 'id',+ 'lang',+ 'provenance',+ 'doc',+]);+const BUNDLE_FIELDS = new Set([+ 'schemaVersion',+ 'lang',+ 'nodes',+ 'diagnostics',+]);++/**+ * A package-relative source, never a location on one machine.+ * @param {unknown} value+ * @returns {boolean}+ */+const isPackageSource = value =>+ isPackageName(value) &&+ !/(^|\/)\.\.(\/|$)/.test(/** @type {string} */ (value));++/**+ * An Error for a value that is not a compiled doc, carrying the diagnostic a+ * reader reports.+ * @param {'unsupported_schema' | 'invalid_bundle'} code+ * @param {string} message+ * @returns {Error & {diagnostic: import('./diagnostics.mjs').CompilerDiagnostic}}+ */+function compiledDocError(code, message) {+ const error = /** @type {Error & {diagnostic: any}} */ (new Error(message));+ error.diagnostic = diagnostic(code, {message});+ return error;+}++/**+ * @param {unknown} value+ */+function schemaVersionProblem(value) {+ const version = /** @type {any} */ (value)?.schemaVersion;+ return version === COMPILED_DOC_SCHEMA_VERSION+ ? null+ : `Compiled doc schema version ${JSON.stringify(version)} is not supported; this CLI reads version ${COMPILED_DOC_SCHEMA_VERSION}. Compile the docs again with this CLI.`;+}++/**+ * Validate a compiled node of any kind.+ * @param {unknown} value+ * @returns {import('./compile.mjs').CompiledDocNode | import('./compile.mjs').CompiledReferenceNode}+ */+export function parseCompiledDocNode(value) {+ const skew = schemaVersionProblem(value);+ if (skew) throw compiledDocError('unsupported_schema', skew);+ const problems = nodeProblems(value, 'node');+ if (problems.length > 0) {+ throw compiledDocError(+ 'invalid_bundle',+ `Invalid compiled doc node: ${problems.slice(0, MAX_PROBLEMS).join('; ')}`,+ );+ }+ return /** @type {any} */ (value);+}++/**+ * Validate a compiled docs bundle: every node, every diagnostic, and one node+ * per id.+ * @param {unknown} value+ * @returns {import('./bundle.mjs').CompiledDocsBundle}+ */+export function parseCompiledDocsBundle(value) {+ const skew = schemaVersionProblem(value);+ if (skew) throw compiledDocError('unsupported_schema', skew);+ const bundle = /** @type {any} */ (value);+ /** @type {string[]} */+ const problems = jsonProblems(bundle, 'bundle');+ if (problems.length === 0) {+ const unknown = Object.keys(bundle).filter(key => !BUNDLE_FIELDS.has(key));+ if (unknown.length > 0)+ problems.push(`unknown fields: ${unknown.join(', ')}`);+ if (bundle.lang !== null && !isText(bundle.lang)) {+ problems.push('lang: expected a language or null');+ }+ if (!Array.isArray(bundle.nodes)) {+ problems.push('nodes: expected an array');+ } else {+ const ids = new Set();+ bundle.nodes.forEach(+ (/** @type {unknown} */ node, /** @type {number} */ index) => {+ for (const problem of nodeProblems(node, `nodes[${index}]`)) {+ problems.push(problem);+ }+ const id = /** @type {any} */ (node)?.id;+ if (ids.has(id))+ problems.push(`nodes[${index}].id: "${id}" appears twice`);+ ids.add(id);+ },+ );+ }+ if (!Array.isArray(bundle.diagnostics)) {+ problems.push('diagnostics: expected an array');+ } else {+ bundle.diagnostics.forEach(+ (/** @type {unknown} */ d, /** @type {number} */ index) => {+ const problem = diagnosticProblem(d);+ if (problem) problems.push(`diagnostics[${index}]: ${problem}`);+ },+ );+ }+ }+ if (problems.length > 0) {+ throw compiledDocError(+ 'invalid_bundle',+ `Invalid compiled docs bundle: ${problems.slice(0, MAX_PROBLEMS).join('; ')}`,+ );+ }+ return bundle;+}++/**+ * Problems with one node of any kind, each prefixed with where it is.+ * @param {unknown} value+ * @param {string} at+ * @returns {string[]}+ */+function nodeProblems(value, at) {+ const node = /** @type {any} */ (value);+ if (node?.schemaVersion !== COMPILED_DOC_SCHEMA_VERSION) {+ return [`${at}.schemaVersion: expected ${COMPILED_DOC_SCHEMA_VERSION}`];+ }+ const json = jsonProblems(node, at);+ if (json.length > 0) return json;+ if (node.kind === 'reference') {+ return structureProblems(node).map(problem => `${at}: ${problem}`);+ }+ /** @type {string[]} */+ const problems = [];+ const unknown = Object.keys(node).filter(key => !DOC_NODE_FIELDS.has(key));+ if (unknown.length > 0)+ problems.push(`${at}: unknown fields: ${unknown.join(', ')}`);+ if (!COMPILED_DOC_KINDS.includes(node.kind)) {+ problems.push(+ `${at}.kind: ${JSON.stringify(node.kind)} is not a compiled doc kind`,+ );+ }+ if (node.stage !== 'lowered')+ problems.push(`${at}.stage: expected "lowered"`);+ if (!isText(node.id)) problems.push(`${at}.id: expected an id`);+ if (node.lang !== null && !isText(node.lang)) {+ problems.push(`${at}.lang: expected a language or null`);+ }+ const provenance = node.provenance;+ if (+ !isRecord(provenance) ||+ Object.keys(provenance).length !== 2 ||+ !isPackageName(provenance.provider) ||+ !isPackageSource(provenance.source)+ ) {+ problems.push(+ `${at}.provenance: expected {provider, source} naming a package and a path inside it, not a machine path`,+ );+ }+ if (!isRecord(node.doc) || !isText(node.doc.name)) {+ problems.push(`${at}.doc: expected a doc with a name`);+ } else if (+ (node.kind === 'page' || node.kind === 'block' || node.kind === 'theme') &&+ node.doc.type !== node.kind+ ) {+ problems.push(+ `${at}.doc.type: a ${node.kind} node holds a ${node.kind} doc`,+ );+ }+ return problems;+}diff --git a/packages/cli/foundation/doc-compiler/lower-doc.test.mjs b/packages/cli/foundation/doc-compiler/lower-doc.test.mjsnew file mode 100644index 0000000000..c4fe880b0c--- /dev/null+++ b/packages/cli/foundation/doc-compiler/lower-doc.test.mjs@@ -0,0 +1,492 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file lowerDoc, the compiled-node parsers, and diagnostics: every doc kind+ * lowers into one sealed node shape, and every failure has one diagnostic.+ */++import {describe, expect, it} from 'vitest';+import {+ COMPILED_DOC_KINDS,+ COMPILED_DOC_SCHEMA_VERSION,+ lowerDoc,+} from './compile.mjs';+import {+ DIAGNOSTIC_CODES,+ diagnostic,+ diagnosticProblem,+ sortDiagnostics,+} from './diagnostics.mjs';+import {parseCompiledDocNode, parseCompiledDocsBundle} from './ir.mjs';++/**+ * @param {any} doc+ * @param {object} [more]+ * @returns {any}+ */+const input = (doc, more = {}) => ({+ id: '@acme/kit:components:Card',+ root: 'components',+ provider: '@acme/kit',+ source: '@acme/kit/src/Card.doc.mjs',+ lang: null,+ file: {file: 'Card.doc.mjs', doc},+ ...more,+});++const card = {+ type: 'component',+ name: 'Card',+ displayName: 'Card',+ usage: {description: 'A card.'},+ props: [{name: 'title', type: 'string', description: 'The title.'}],+};++describe('lowerDoc', () => {+ it('lowers each root into its kind, with package provenance and JSON doc', () => {+ const cases = [+ ['components', card, 'component'],+ [+ 'components',+ {name: 'Old', description: 'Legacy.', props: []},+ 'component',+ ],+ [+ 'hooks',+ {+ type: 'function',+ kind: 'hook',+ name: 'useThing',+ displayName: 'useThing',+ description: 'Does a thing.',+ params: [],+ returns: [],+ },+ 'function',+ ],+ [+ 'templates',+ {type: 'page', name: 'Home', description: 'A page.'},+ 'page',+ ],+ [+ 'templates',+ {type: 'block', name: 'Hero', description: 'A block.'},+ 'block',+ ],+ [+ 'themes',+ {+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: 'Blue.',+ maintained: true,+ },+ 'theme',+ ],+ [+ 'self-docs',+ {type: 'enum', name: 'codes', description: 'Codes.', values: []},+ 'enum',+ ],+ ];+ for (const [root, doc, kind] of cases) {+ const {node, diagnostics} = lowerDoc(input(doc, {root}));+ expect({root, kind: node?.kind}).toEqual({root, kind});+ expect(node?.provenance).toEqual({+ provider: '@acme/kit',+ source: '@acme/kit/src/Card.doc.mjs',+ });+ expect(node?.schemaVersion).toBe(COMPILED_DOC_SCHEMA_VERSION);+ expect(() => parseCompiledDocNode(node)).not.toThrow();+ // Legacy and stamped docs parse cleanly; nothing to report.+ expect(diagnostics.filter(d => d.code !== 'invalid_doc')).toEqual([]);+ }+ });++ it('carries the authored doc as JSON: key order kept, undefined dropped', () => {+ const {node} = lowerDoc(+ input({+ ...card,+ playground: {defaults: {onOpenChange: undefined, size: 'md'}},+ }),+ );+ expect(Object.keys(node?.doc)).toEqual([+ 'type',+ 'name',+ 'displayName',+ 'usage',+ 'props',+ 'playground',+ ]);+ expect(node?.doc.playground).toEqual({defaults: {size: 'md'}});+ });++ it('lays the translation for the reading language over the doc', () => {+ const {node} = lowerDoc(+ input(card, {+ lang: 'zh',+ file: {+ file: 'Card.doc.mjs',+ doc: card,+ overlay: {+ usage: {description: '卡片。'},+ propDescriptions: {title: '标题。'},+ },+ },+ }),+ );+ expect(node?.lang).toBe('zh');+ expect(node?.doc.usage.description).toBe('卡片。');+ expect(node?.doc.props[0]).toEqual({+ name: 'title',+ type: 'string',+ description: '标题。',+ });+ });++ it('keeps a doc that fails its parser, and reports why', () => {+ const {node, diagnostics, failure} = lowerDoc(+ input({type: 'component', name: 'Card'}),+ );+ expect(node?.doc).toEqual({type: 'component', name: 'Card'});+ expect(diagnostics.map(d => d.code)).toEqual(['invalid_doc']);+ expect(failure).toBeInstanceOf(Error);+ expect(diagnostics[0].message).toBe(/** @type {Error} */ (failure).message);+ });++ it("keeps a doc of another kind, in its root's kind, and names the mismatch", () => {+ const {node, diagnostics} = lowerDoc(+ input({type: 'page', name: 'Home', description: 'A page.'}),+ );+ expect(node?.kind).toBe('component');+ expect(diagnostics.map(d => d.code)).toEqual(['wrong_kind']);+ });++ it('yields no node, and records what failed, when the file cannot be read', () => {+ const thrown = new SyntaxError('Unexpected token');+ const loaded = lowerDoc(+ input(card, {file: {file: 'Card.doc.mjs', error: thrown}}),+ );+ expect(loaded.node).toBeNull();+ expect(loaded.loadFailure).toBe(thrown);+ expect(loaded.diagnostics.map(d => d.code)).toEqual(['load_failed']);+ const empty = lowerDoc(+ input(card, {file: {file: 'Card.doc.mjs', doc: null}}),+ );+ expect(empty).toMatchObject({+ node: null,+ missing: true,+ missingValue: null,+ });+ expect(empty.diagnostics.map(d => d.code)).toEqual(['missing_export']);+ const overlaid = lowerDoc(+ input(card, {+ file: {file: 'Card.doc.mjs', doc: card, overlayError: thrown},+ }),+ );+ expect(overlaid).toMatchObject({node: null, overlayFailure: thrown});+ expect(overlaid.view).toBeUndefined();+ expect(overlaid.diagnostics.map(d => d.code)).toEqual(['overlay_failed']);+ });++ it('keeps the parse failure first when the translation also breaks', () => {+ const {failure, overlayFailure, diagnostics} = lowerDoc(+ input(+ {type: 'component', name: 'Card'},+ {+ lang: 'zh',+ file: {+ file: 'Card.doc.mjs',+ doc: {type: 'component', name: 'Card'},+ overlay: {+ get props() {+ throw new TypeError('bad translation');+ },+ },+ },+ },+ ),+ );+ expect(/** @type {Error} */ (failure).message).toMatch(+ /Card\.doc\.mjs is invalid/,+ );+ expect(overlayFailure).toBeInstanceOf(TypeError);+ expect(diagnostics.map(d => d.code)).toEqual([+ 'invalid_doc',+ 'overlay_failed',+ ]);+ });++ it('refuses a theme descriptor outside the themes root, as readers always did', () => {+ const theme = {+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: 'd',+ maintained: true,+ };+ for (const root of ['components', 'hooks', 'self-docs']) {+ const {failure} = lowerDoc(+ input(theme, {root, label: '/x/Ocean.doc.mjs'}),+ );+ expect(/** @type {Error} */ (failure).message).toBe(+ '/x/Ocean.doc.mjs has unsupported type "theme".',+ );+ }+ });++ it('hands readers the authored value, and only the node goes through JSON', () => {+ const cyclic = /** @type {any} */ ({+ ...card,+ big: 10n,+ when: new Date(0),+ fn() {},+ });+ cyclic.self = cyclic;+ cyclic.gone = undefined;+ const {view, node, diagnostics} = lowerDoc(input(cyclic));+ expect(view).toBe(cyclic);+ expect(node).toBeNull();+ expect(diagnostics.at(-1)?.code).toBe('not_json');+ expect(diagnostics.at(-1)?.message).not.toMatch(/^\//);+ const read = lowerDoc(input(cyclic), {check: false, node: false});+ expect(read).toEqual({node: null, diagnostics: [], view: cyclic});+ });++ it('never puts a machine path in a diagnostic', () => {+ const {diagnostics} = lowerDoc(+ input(+ {type: 'component', name: 'Card'},+ {label: '/home/someone/kit/Card.doc.mjs'},+ ),+ );+ expect(diagnostics[0].message).not.toContain('/home/someone');+ });++ it('refuses a value JSON cannot hold', () => {+ const cyclic = /** @type {any} */ ({...card});+ cyclic.self = cyclic;+ for (const doc of [cyclic, {...card, big: 1n}]) {+ const {node, diagnostics} = lowerDoc(input(doc));+ expect(node).toBeNull();+ expect(diagnostics.at(-1)?.code).toBe('not_json');+ }+ });++ it("carries the parser's result only when asked to", () => {+ const block = {+ type: 'block',+ name: 'Hero',+ description: 'A block.',+ extra: 1,+ };+ const authored = lowerDoc(input(block, {root: 'templates'}));+ const parsed = lowerDoc(input(block, {root: 'templates', useParsed: true}));+ expect(authored.node?.doc.extra).toBe(1);+ expect(parsed.node?.doc).toEqual(+ expect.objectContaining({type: 'block', name: 'Hero'}),+ );+ });+});++describe('diagnostics', () => {+ it('fixes phase, severity, scope, and remediation per code', () => {+ for (const [code, rule] of Object.entries(DIAGNOSTIC_CODES)) {+ const d = diagnostic(code, {message: 'x'});+ expect(d).toEqual({+ code,+ phase: rule.phase,+ severity: rule.severity,+ scope: rule.scope,+ provider: null,+ source: null,+ field: null,+ message: 'x',+ remediation: rule.remediation,+ });+ expect(diagnosticProblem(d)).toBeNull();+ }+ expect(() => diagnostic('nope', {message: 'x'})).toThrow(/Unknown/);+ for (const name of [+ 'toString',+ 'constructor',+ '__proto__',+ 'hasOwnProperty',+ ]) {+ expect(() => diagnostic(name, {message: 'x'})).toThrow(/Unknown/);+ expect(+ diagnosticProblem({+ ...diagnostic('invalid_doc', {message: 'x'}),+ code: name,+ }),+ ).toMatch(/not a compiler diagnostic code/);+ }+ });++ it('rejects a diagnostic a reader reinterpreted', () => {+ const d = diagnostic('invalid_doc', {message: 'x'});+ expect(diagnosticProblem({...d, severity: 'warning'})).toMatch(+ /always has severity/,+ );+ expect(diagnosticProblem({...d, code: 'made_up'})).toMatch(+ /not a compiler diagnostic code/,+ );+ expect(diagnosticProblem({...d, extra: 1})).toMatch(/unknown fields/);+ expect(diagnosticProblem({...d, source: ''})).toMatch(/source/);+ for (const source of [+ '/tmp/x/Card.doc.mjs',+ 'C:\\x\\Card.doc.mjs',+ '@acme/kit/../x',+ ]) {+ expect(diagnosticProblem({...d, source})).toMatch(+ /not a location on one machine/,+ );+ }+ });++ it('sorts by source, then phase, code, field, and message', () => {+ const at = (+ /** @type {string} */ code,+ /** @type {string|null} */ source,+ field = null,+ ) => diagnostic(code, {source, field, message: `${code} ${field}`});+ const list = [+ at('unresolved_reference', 'b/x', 'sections.b'),+ at('invalid_doc', 'b/x'),+ at('load_failed', 'b/x'),+ at('unresolved_reference', 'b/x', 'sections.a'),+ at('invalid_doc', null),+ at('duplicate_id', 'a/x'),+ ];+ const sorted = sortDiagnostics(list);+ expect(sorted.map(d => `${d.source}:${d.code}:${d.field}`)).toEqual([+ 'a/x:duplicate_id:null',+ 'b/x:load_failed:null',+ 'b/x:invalid_doc:null',+ 'b/x:unresolved_reference:sections.a',+ 'b/x:unresolved_reference:sections.b',+ 'null:invalid_doc:null',+ ]);+ expect(sortDiagnostics([...list].reverse())).toEqual(sorted);+ });+});++describe('parseCompiledDocNode and parseCompiledDocsBundle', () => {+ const node = () =>+ /** @type {any} */ (structuredClone(lowerDoc(input(card)).node));+ const bundle = () => ({+ schemaVersion: COMPILED_DOC_SCHEMA_VERSION,+ lang: null,+ nodes: [node()],+ diagnostics: [diagnostic('unresolved_reference', {message: 'x'})],+ });++ it('accepts a node of every kind and a bundle, as given', () => {+ const value = bundle();+ expect(parseCompiledDocsBundle(value)).toBe(value);+ expect(COMPILED_DOC_KINDS).toHaveLength(9);+ });++ it('names schema skew with its own diagnostic, before anything else', () => {+ for (const parse of [parseCompiledDocNode, parseCompiledDocsBundle]) {+ try {+ parse({schemaVersion: 99, nope: true});+ throw new Error('expected a throw');+ } catch (error) {+ expect(/** @type {any} */ (error).message).toMatch(+ /schema version 99 is not supported/,+ );+ expect(/** @type {any} */ (error).diagnostic.code).toBe(+ 'unsupported_schema',+ );+ }+ }+ });++ it.each([+ [+ 'an unknown field',+ (/** @type {any} */ n) => (n.extra = 1),+ /unknown fields: extra/,+ ],+ [+ 'an unknown kind',+ (/** @type {any} */ n) => (n.kind = 'namespace'),+ /not a compiled doc kind/,+ ],+ [+ 'a machine path as provider',+ (/** @type {any} */ n) => (n.provenance.provider = '/home/x'),+ /not a machine path/,+ ],+ [+ 'a machine path as source',+ (/** @type {any} */ n) => (n.provenance.source = 'C:\\x\\Card.doc.mjs'),+ /not a machine path/,+ ],+ [+ 'a source that climbs out of its package',+ (/** @type {any} */ n) => (n.provenance.source = '@acme/kit/../x'),+ /not a machine path/,+ ],+ [+ 'a stage other than lowered',+ (/** @type {any} */ n) => (n.stage = 'linked'),+ /stage/,+ ],+ [+ 'a doc without a name',+ (/** @type {any} */ n) => delete n.doc.name,+ /doc with a name/,+ ],+ [+ 'a page node without a page doc',+ (/** @type {any} */ n) => {+ n.kind = 'page';+ n.doc.type = 'block';+ },+ /a page node holds a page doc/,+ ],+ [+ 'a function in the doc',+ (/** @type {any} */ n) => (n.doc.render = () => null),+ /is not JSON/,+ ],+ [+ 'undefined in the doc',+ (/** @type {any} */ n) => (n.doc.gone = undefined),+ /undefined is not JSON/,+ ],+ ])('rejects %s', (_name, mutate, message) => {+ const value = node();+ mutate(value);+ expect(() => parseCompiledDocNode(value)).toThrow(message);+ try {+ parseCompiledDocNode(value);+ } catch (error) {+ expect(/** @type {any} */ (error).diagnostic.code).toBe('invalid_bundle');+ }+ });++ it('rejects a bundle with a duplicate id, a bad node, or a reinterpreted diagnostic', () => {+ const twice = bundle();+ twice.nodes.push(node());+ expect(() => parseCompiledDocsBundle(twice)).toThrow(/appears twice/);+ const bad = bundle();+ bad.nodes[0].kind = 'nope';+ expect(() => parseCompiledDocsBundle(bad)).toThrow(/nodes\[0\]\.kind/);+ const reinterpreted = bundle();+ reinterpreted.diagnostics[0] = {+ ...reinterpreted.diagnostics[0],+ severity: 'error',+ };+ expect(() => parseCompiledDocsBundle(reinterpreted)).toThrow(+ /diagnostics\[0\]/,+ );+ expect(() => parseCompiledDocsBundle({...bundle(), extra: 1})).toThrow(+ /unknown fields/,+ );+ });+});diff --git a/packages/cli/foundation/doc-compiler/overlays.mjs b/packages/cli/foundation/doc-compiler/overlays.mjsnew file mode 100644index 0000000000..06d49a262f--- /dev/null+++ b/packages/cli/foundation/doc-compiler/overlays.mjs@@ -0,0 +1,206 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Translation overlays for component and hook docs.+ *+ * @input An authored component or hook doc and the translation its module+ * exports for the reading language (`docsZh`, `docsDense`).+ * @output The doc in that language: translated text laid over the authored+ * doc, never dropping a prop, param, or field the translation has not+ * caught up with.+ * @position Used by ./compile.mjs when it lowers a component or hook doc, so+ * every reader sees one overlay rule. Reference topics overlay by section in+ * ./compile.mjs instead.+ */++/**+ * The translation a doc module exports for `lang`, or null.+ * @param {Record<string, any>} mod+ * @param {string | null} lang+ * @returns {any}+ */+export function translationFor(mod, lang) {+ const key = lang === 'zh' ? 'docsZh' : lang === 'dense' ? 'docsDense' : null;+ return key && mod?.[key] ? mod[key] : null;+}++/**+ * Lay a translation over an authored component or hook doc. A translation+ * that carries props is a full translated doc, overlaid prop by prop; any other+ * is a set of translated strings merged onto the doc.+ * @param {any} docs+ * @param {any} translation+ * @returns {any}+ */+export function overlayAuthoredDoc(docs, translation) {+ if (+ translation.props ||+ translation.components?.some((/** @type {any} */ c) => c.props)+ ) {+ return overlayComponentDoc(docs, translation);+ }+ return mergeTranslation(docs, translation);+}++/**+ * @param {any} docs+ * @param {any} translation+ * @returns {any}+ */+export function mergeTranslation(docs, translation) {+ if (!translation) return docs;++ /** @type {any} */+ const merged = {...docs};++ // Merge prose into usage+ if (merged.usage) {+ merged.usage = {...merged.usage};+ if (translation.usage?.description)+ merged.usage.description = translation.usage.description;+ else if (translation.description)+ merged.usage.description = translation.description;+ if (translation.usage?.bestPractices)+ merged.usage.bestPractices = translation.usage.bestPractices;+ if (translation.usage?.accessibility)+ merged.usage.accessibility = translation.usage.accessibility;+ }++ // Legacy top-level fields (for docsZh that are full ComponentDoc clones)+ if (translation.description && !merged.usage)+ merged.description = translation.description;++ // Merge prop descriptions for single-component docs+ if (translation.propDescriptions && merged.props) {+ merged.props = merged.props.map((/** @type {any} */ prop) => {+ const desc = translation.propDescriptions[prop.name];+ return desc != null ? {...prop, description: desc} : prop;+ });+ }++ // Merge hook param descriptions (HookTranslationDoc). Params are an array of+ // {name, type, description, required}; override description by name where the+ // translation has an entry. Names may include dots (e.g. 'options.isActive');+ // the lookup is keyed by the exact param name.+ if (translation.paramDescriptions && merged.params) {+ merged.params = merged.params.map((/** @type {any} */ param) => {+ const desc = translation.paramDescriptions[param.name];+ return desc != null ? {...param, description: desc} : param;+ });+ }++ // Merge hook return descriptions (HookTranslationDoc). Returns are an array+ // of {name, type, description}; override description by name where present.+ if (translation.returnDescriptions && merged.returns) {+ merged.returns = merged.returns.map((/** @type {any} */ ret) => {+ const desc = translation.returnDescriptions[ret.name];+ return desc != null ? {...ret, description: desc} : ret;+ });+ }++ // Merge sub-component translations+ if (translation.components && merged.components) {+ merged.components = merged.components.map(+ (/** @type {any} */ comp, /** @type {any} */ i) => {+ const trans =+ translation.components.find(+ (/** @type {any} */ t) => t.name === comp.name,+ ) || translation.components[i];+ if (!trans) return comp;++ const mergedComp = {...comp};+ if (trans.description) mergedComp.description = trans.description;+ if (trans.propDescriptions && comp.props) {+ mergedComp.props = comp.props.map((/** @type {any} */ prop) => {+ const desc = trans.propDescriptions[prop.name];+ return desc != null ? {...prop, description: desc} : prop;+ });+ }+ return mergedComp;+ },+ );+ }++ return merged;+}++/**+ * Overlay a full-ComponentDoc-shaped translation onto the English doc.+ *+ * Base order and completeness win; the translation supplies text for the+ * entries it covers. Props are matched by name, never by position, so a+ * translation that is missing entries (or lists them in another order) can no+ * longer drop or misattribute one.+ *+ * @param {any} docs Base (English) component doc.+ * @param {any} translation Translated doc, possibly covering only some props.+ * @returns {any} Merged doc with every base prop present.+ */+function overlayComponentDoc(docs, translation) {+ /** Merge one prop list: keep base entries and order, translate what's covered.+ * @param {any[] | undefined} baseProps+ * @param {any[] | undefined} tProps+ */+ const overlayProps = (baseProps, tProps) => {+ if (!baseProps) return baseProps;+ const byName = new Map(+ (tProps ?? []).map((/** @type {any} */ p) => [p.name, p]),+ );+ return baseProps.map((/** @type {any} */ prop) => {+ const t = byName.get(prop.name);+ // Take the translated text, but never let it drop the prop's contract+ // (type/default/required stay authoritative from the English doc).+ return t ? {...prop, ...t, name: prop.name, type: prop.type} : prop;+ });+ };++ /** Preserve canonical structured guidance added after legacy full-doc translations,+ * without changing established translated prose behavior.+ * @param {any} baseUsage+ * @param {any} translatedUsage+ */+ const mergeUsage = (baseUsage, translatedUsage) => {+ if (!translatedUsage) return baseUsage;+ return {+ ...translatedUsage,+ ...(translatedUsage.accessibility === undefined &&+ baseUsage?.accessibility !== undefined+ ? {accessibility: baseUsage.accessibility}+ : null),+ ...(translatedUsage.accessibilityThemeCoverage === undefined &&+ baseUsage?.accessibilityThemeCoverage !== undefined+ ? {accessibilityThemeCoverage: baseUsage.accessibilityThemeCoverage}+ : null),+ ...(translatedUsage.anatomy === undefined &&+ baseUsage?.anatomy !== undefined+ ? {anatomy: baseUsage.anatomy}+ : null),+ };+ };++ const merged = {+ ...docs,+ ...translation,+ usage: mergeUsage(docs.usage, translation.usage),+ };++ merged.props = overlayProps(docs.props, translation.props);++ if (docs.components) {+ const tByName = new Map(+ (translation.components ?? []).map((/** @type {any} */ c) => [c.name, c]),+ );+ merged.components = docs.components.map((/** @type {any} */ base) => {+ const t = tByName.get(base.name);+ if (!t) return base;+ return {+ ...base,+ ...t,+ usage: mergeUsage(base.usage, t.usage),+ props: overlayProps(base.props, t.props),+ };+ });+ }++ return merged;+}diff --git a/packages/cli/foundation/doc-compiler/parse-readable.mjs b/packages/cli/foundation/doc-compiler/parse-readable.mjsnew file mode 100644index 0000000000..882c3fde2b--- /dev/null+++ b/packages/cli/foundation/doc-compiler/parse-readable.mjs@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file parseDoc as every reader outside the themes root has always seen it.+ *+ * @input Any authored doc value and a label for messages.+ * @output The parsed doc, or the parser's error.+ * @position The public `parseDoc` also accepts theme descriptors. Component,+ * hook, self-doc, and topic readers never did: to them a theme descriptor is+ * an unsupported type, with the message they have always printed.+ */++import {parseDoc} from '../../authoring/doctypes/parse.mjs';++/**+ * @param {unknown} input+ * @param {string} [label]+ * @returns {any}+ */+export function parseReadableDoc(input, label = 'doc') {+ const type =+ input && typeof input === 'object' && 'type' in input+ ? /** @type {{type?: unknown}} */ (input).type+ : undefined;+ if (type === 'theme') {+ throw new Error(`${label} has unsupported type ${JSON.stringify(type)}.`);+ }+ return parseDoc(input, label);+}diff --git a/packages/cli/foundation/doc-compiler/read.mjs b/packages/cli/foundation/doc-compiler/read.mjsnew file mode 100644index 0000000000..a5d25655ce--- /dev/null+++ b/packages/cli/foundation/doc-compiler/read.mjs@@ -0,0 +1,320 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Doc reader — authored files in, lowered docs out, for every doc kind.+ *+ * @input A descriptor file, the root that reads it (components, hooks,+ * templates, themes, self-docs, or doc topics), the reading language, and+ * how strictly the reader checks.+ * @output The lowered doc for that file. Readers get the view they have always+ * read, lowered afresh on every read; a whole-project compile also gets the+ * sealed node, memoized per file for the life of the process. For doc+ * topics: the compiler input for a topic, with its extensions and overlays+ * loaded.+ * @position Loads authored doc files for the readers in api/ and clients/ and+ * hands each to ./compile.mjs. Each reader keeps its own loader, export+ * order, and strictness, so what it prints is what it printed before.+ * ./doc-loads.test.mjs lists, site by site, every other place the CLI runs+ * anything but its static imports of other CLI code, the doc reads that skip+ * this module among them: discovery's catalog fields, each command's+ * self-docs for its help text, and the build-time README. A new site fails+ * it. It catches every ordinary way of running code, whatever the local+ * names; deliberate obfuscation is out of scope. Internal to the CLI:+ * nothing here is public API.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ importDocModule,+ importNativeModule,+ importTemplateModule,+} from './import.mjs';+import {lowerDoc, parserFor} from './compile.mjs';+import {translationFor} from './overlays.mjs';+import {parseReadableDoc} from './parse-readable.mjs';+import {packageOf, packageSource} from './source.mjs';++/**+ * How each root's module names its doc, in precedence order: the `??` chain+ * each reader has always used, so a file that exports two docs keeps serving+ * the one it served before.+ */+export const DOC_EXPORTS = Object.freeze({+ components: ['default', 'docs'],+ hooks: ['default', 'docs'],+ templates: ['default', 'doc'],+ 'self-docs': ['doc', 'docs', 'default'],+});++/** How a reader imports a doc module. */+const LOADERS = Object.freeze({+ // jiti for `.ts`, native otherwise: the checked loaders' import.+ user: importDocModule,+ // A plain `import()`: what the unchecked readers have always used.+ native: importNativeModule,+ // jiti with JSX for `.ts`: template discovery's import.+ template: importTemplateModule,+});++/**+ * @typedef {object} ReadOptions+ * @property {'components' | 'hooks' | 'templates' | 'themes' | 'self-docs'} root+ * @property {string | null} [lang] overlay language; null reads the authored+ * text+ * @property {string} [label] how a parse error names the file (default: its+ * file name)+ * @property {string} [provider] the owning package, when the caller knows it+ * @property {string} [id] the node's id (default: provider, root, and file+ * name)+ * @property {keyof typeof LOADERS} [loader] how to import the module (default+ * `user`)+ * @property {readonly string[]} [exports] which exports name the doc, in+ * precedence order, for a reader that has always read a narrower set than its+ * root's default ({@link DOC_EXPORTS})+ * @property {() => unknown} [readStatic] for themes: the descriptor value, read+ * without executing the file+ * @property {'authored' | 'parsed'} [value] which value the view carries: the+ * authored export (default) or its parser's result, for a reader that has+ * always read the checked value+ * @property {boolean} [check] hold the doc to its kind's parser+ */++/** @type {Map<string, Promise<import('./compile.mjs').LoweredDoc>>} */+const lowered = new Map();++/**+ * Lower one descriptor file. Memoized per file and options for the life of the+ * process; a file that failed to load is tried again on the next read, as a+ * fresh import would be.+ * @param {string} file absolute path+ * @param {ReadOptions} options+ * @param {{node?: boolean}} [want] also build the sealed node+ * @returns {Promise<import('./compile.mjs').LoweredDoc>}+ */+export function compileDocFile(file, options, {node = false} = {}) {+ const lang = options.lang ?? null;+ const check = options.check === true;+ const key = JSON.stringify([+ path.resolve(file),+ options.root,+ lang,+ options.label ?? null,+ options.provider ?? null,+ options.id ?? null,+ options.loader ?? 'user',+ options.exports ?? null,+ options.value ?? 'authored',+ check,+ node,+ ]);+ let result = lowered.get(key);+ if (!result) {+ result = loadAuthored(file, options, lang).then(authored => {+ const provider = options.provider ?? packageOf(file);+ const out = lowerDoc(+ {+ id:+ options.id ?? `${provider}:${options.root}:${path.basename(file)}`,+ root: options.root,+ provider,+ source: packageSource(file),+ lang,+ file: authored,+ ...(options.label ? {label: options.label} : {}),+ ...(options.value === 'parsed' ? {useParsed: true} : {}),+ },+ {check, node},+ );+ if (out.node) deepFreeze(out.node);+ if (out.loadFailed || 'overlayError' in authored) {+ lowered.delete(key);+ }+ return out;+ });+ lowered.set(key, result);+ }+ return result;+}++/**+ * What a reader gets for one descriptor: the view it has always read.+ *+ * `strict` readers check the doc and throw what they always threw: the import+ * error, the parser's error (for an empty export too), then a failed+ * translation. Other readers skip the check, throw only what importing or+ * translating threw, and read an empty export as the empty value itself.+ * The view is shared, as the module's own export always was.+ * @param {string} file absolute path+ * @param {ReadOptions & {strict?: boolean}} options+ * @returns {Promise<any>}+ */+export async function readDocView(file, options) {+ const strict = options.strict === true;+ const lang = options.lang ?? null;+ // Lowered on every read, as the readers always loaded: Node caches the+ // module, and the translation and the check run fresh each time, so a+ // reader never shares a translated or parsed result with the next one.+ const provider = options.provider ?? packageOf(file);+ const result = lowerDoc(+ {+ id: options.id ?? `${provider}:${options.root}:${path.basename(file)}`,+ root: options.root,+ provider,+ source: packageSource(file),+ lang,+ file: await loadAuthored(file, options, lang),+ ...(options.label ? {label: options.label} : {}),+ ...(options.value === 'parsed' ? {useParsed: true} : {}),+ },+ {check: strict || options.check === true, node: false},+ );+ if (result.loadFailed) throw result.loadFailure;+ if (result.missing) {+ if (strict)+ parserFor(options.root)(result.missingValue, options.label ?? file);+ return result.missingValue;+ }+ if (strict && result.failed) throw result.failure;+ if (result.overlayFailed) throw result.overlayFailure;+ return result.view;+}++/**+ * Load one file as its root reads it: the doc its module exports and, for a+ * component or hook, the translation it exports for `lang`.+ * @param {string} file+ * @param {ReadOptions} options+ * @param {string | null} lang+ * @returns {Promise<import('./compile.mjs').AuthoredFile>}+ */+async function loadAuthored(file, options, lang) {+ const name = path.basename(file);+ if (options.root === 'themes') {+ if (!options.readStatic) {+ throw new Error(+ 'A theme descriptor is read statically; pass readStatic.',+ );+ }+ try {+ return {file: name, doc: options.readStatic()};+ } catch (error) {+ return {file: name, error};+ }+ }+ let mod;+ try {+ mod = await LOADERS[options.loader ?? 'user'](file);+ } catch (error) {+ return {file: name, error};+ }+ // `a ?? b ?? c`, exactly: the first value that is not null or undefined,+ // else the last one.+ const [first, ...rest] = options.exports ?? DOC_EXPORTS[options.root];+ let doc = mod?.[first];+ for (const key of rest) doc = doc ?? mod?.[key];+ const overlay =+ lang && (options.root === 'components' || options.root === 'hooks')+ ? translationFor(mod, lang)+ : null;+ return overlay ? {file: name, doc, overlay} : {file: name, doc};+}++/**+ * Freeze a value and everything in it.+ * @template T+ * @param {T} value+ * @returns {T}+ */+export function deepFreeze(value) {+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {+ Object.freeze(value);+ for (const child of Object.values(value)) deepFreeze(child);+ }+ return value;+}++// ── Doc topics ─────────────────────────────────────────────────────────────++/** The localized overlays a docs read can apply. */+export const OVERLAY_LANGUAGES = ['zh', 'dense'];++/**+ * Where the `lang` overlay of a doc file lives: `{topic}.doc.{lang}.mjs`.+ * @param {string} docPath+ * @param {string} lang+ * @returns {string}+ */+export function overlayPath(docPath, lang) {+ return path.join(+ path.dirname(docPath),+ `${path.basename(docPath, '.doc.mjs')}.doc.${lang}.mjs`,+ );+}++/**+ * The overlay languages a topic ships for its own file or any extension.+ * @param {import('../discovery/docs-discovery.mjs').DocsTopicEntry} entry+ * @returns {string[]}+ */+export function overlayLanguages(entry) {+ const files = [entry.path, ...entry.extensions.map(ext => ext.path)];+ return OVERLAY_LANGUAGES.filter(lang =>+ files.some(file => fs.existsSync(overlayPath(file, lang))),+ );+}++/**+ * Load one topic file and the overlay for `lang`. A failure is recorded on the+ * result, not thrown, so the compiler reports it in reading order.+ * @param {string} docPath+ * @param {string | null} lang+ * @returns {Promise<import('./compile.mjs').AuthoredFile>}+ */+export async function loadTopicFile(docPath, lang) {+ const file = path.basename(docPath);+ let doc;+ try {+ const mod = await importNativeModule(docPath);+ doc = parseReadableDoc(mod.docs ?? mod.default, file);+ } catch (error) {+ return {file, error};+ }+ if (!lang) return {file, doc};+ const translationPath = overlayPath(docPath, lang);+ if (!fs.existsSync(translationPath)) return {file, doc};+ try {+ const translationMod = await importNativeModule(translationPath);+ return {+ file,+ doc,+ overlay: translationMod.docsZh || translationMod.docsDense || null,+ };+ } catch (overlayError) {+ return {file, doc, overlayError};+ }+}++/**+ * Everything the compiler needs for one topic, read from disk.+ * @param {import('../discovery/docs-discovery.mjs').DocsTopicEntry} entry+ * @param {string | null} lang+ * @returns {Promise<import('./compile.mjs').ReferenceTopicInput>}+ */+export async function loadTopicInput(entry, lang) {+ const extensions = [];+ for (const extension of entry.extensions) {+ extensions.push({+ ...(await loadTopicFile(extension.path, lang)),+ provider: extension.package,+ });+ }+ return {+ id: entry.name,+ provider: entry.package,+ replaces: entry.replaces ?? null,+ lang,+ base: await loadTopicFile(entry.path, lang),+ extensions,+ };+}diff --git a/packages/cli/foundation/doc-compiler/read.test.mjs b/packages/cli/foundation/doc-compiler/read.test.mjsnew file mode 100644index 0000000000..8a5a7bd1a7--- /dev/null+++ b/packages/cli/foundation/doc-compiler/read.test.mjs@@ -0,0 +1,313 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file readDocView and the loaders built on it: every component and hook read+ * is the authored doc, compiled losslessly, and each reader keeps its own+ * strictness.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {pathToFileURL} from 'node:url';+import {Project} from '../config/project.mjs';+import {CLI_ROOT} from '../fs/paths.mjs';+import {loadComponentDoc, loadDocs} from '../discovery/component-loader.mjs';+import {compileDocFile, readDocView} from './read.mjs';+import {collectDocInputs} from './inputs.mjs';++const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-doc-read-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/**+ * @param {string} name+ * @param {string} text+ */+function write(name, text) {+ const file = path.join(tmpDir, name);+ fs.writeFileSync(file, text);+ return file;+}++/** Drop what JSON drops, keep key order: the compiled form of a value. */+const asJson = (/** @type {unknown} */ value) =>+ JSON.parse(JSON.stringify(value));++describe('component and hook reads over what this repo ships', () => {+ it('are the authored docs, compiled without loss', async () => {+ const dir = fs.mkdtempSync(path.join(REPO_ROOT, '.astryx-doc-read-'));+ try {+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"consumer"}');+ const {inputs} = await collectDocInputs(await Project.load(dir));+ const docs = inputs.filter(+ input => input.root === 'components' || input.root === 'hooks',+ );+ expect(docs.length).toBeGreaterThan(200);+ for (const input of docs) {+ const mod = await import(pathToFileURL(input.file).href);+ const authored = mod.default ?? mod.docs;+ const root = /** @type {'components' | 'hooks'} */ (input.root);+ // Byte-for-byte what JSON output has always printed for the doc.+ expect(JSON.stringify(await loadDocs(input.file, {root}))).toBe(+ JSON.stringify(authored),+ );+ // A checked load passes every shipped doc.+ await expect(loadComponentDoc(input.file, {root})).resolves.toEqual(+ asJson(authored),+ );+ }+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ }, 180_000);+});++describe('readDocView', () => {+ const card =+ "export default {type: 'component', name: 'Card', displayName: 'Card', usage: {description: 'A card.'}, props: []};\n";++ it('freezes the node a whole-project compile collects', async () => {+ const file = write('Card.doc.mjs', card);+ const {node} = await compileDocFile(+ file,+ {root: 'components', check: true},+ {node: true},+ );+ expect(node).not.toBeNull();+ expect(Object.isFrozen(node)).toBe(true);+ expect(Object.isFrozen(node?.doc.props)).toBe(true);+ });++ it("keeps each reader's strictness for a doc that fails its parser", async () => {+ const file = write(+ 'Bad.doc.mjs',+ "export default {type: 'component', name: 'Bad'};\n",+ );+ await expect(loadDocs(file)).resolves.toEqual({+ type: 'component',+ name: 'Bad',+ });+ await expect(loadComponentDoc(file)).rejects.toThrow(`${file} is invalid`);+ });++ it('passes on what a file throws when it is imported, unchanged', async () => {+ const file = write('Throws.doc.mjs', "throw new RangeError('no way');\n");+ for (const read of [loadDocs, loadComponentDoc]) {+ await expect(read(file)).rejects.toThrow(RangeError);+ await expect(read(file)).rejects.toThrow('no way');+ }+ });++ it("reads a file with no doc as undefined, or as its parser's error when checked", async () => {+ const file = write('Empty.doc.mjs', 'export const unrelated = 1;\n');+ await expect(loadDocs(file)).resolves.toBeUndefined();+ await expect(loadComponentDoc(file)).rejects.toThrow(`${file} is invalid`);+ });++ it('applies the translation a module exports for the reading language', async () => {+ const file = write(+ 'Card.doc.mjs',+ card + "export const docsZh = {usage: {description: '卡片。'}};\n",+ );+ expect((await loadDocs(file, {zh: true})).usage.description).toBe('卡片。');+ expect((await loadDocs(file, {lang: 'zh'})).usage.description).toBe(+ '卡片。',+ );+ expect((await loadDocs(file)).usage.description).toBe('A card.');+ expect((await loadDocs(file, {dense: true})).usage.description).toBe(+ 'A card.',+ );+ });++ it('reads a narrower set of exports when a reader always has', async () => {+ const file = write(+ 'Both.doc.mjs',+ card ++ "export const docs = {name: 'Legacy', description: 'Old.', props: []};\n",+ );+ expect((await readDocView(file, {root: 'components'})).name).toBe('Card');+ expect(+ (await readDocView(file, {root: 'components', exports: ['docs']})).name,+ ).toBe('Legacy');+ });++ it('reads each file once per process, and retries a file that failed to load', async () => {+ const file = write('Card.doc.mjs', card);+ const before = await compileDocFile(file, {root: 'components'});+ expect(await compileDocFile(file, {root: 'components'})).toBe(before);+ const broken = write('Broken.doc.mjs', 'export default {;\n');+ const failed = await compileDocFile(broken, {root: 'components'});+ expect(failed.loadFailure).toBeInstanceOf(Error);+ expect(await compileDocFile(broken, {root: 'components'})).not.toBe(failed);+ });++ it('prints what the module holds: no JSON anywhere a reader looks', async () => {+ const file = write(+ 'Odd.doc.mjs',+ `const doc = {+ type: 'component', name: 'Odd', displayName: 'Odd', usage: {description: 'd'},+ props: undefined, big: 10n, when: new Date(0), limit: Infinity,+ examples: [{title: 'x', code() { return 1; }}],+ get lazy() { throw new Error('never read'); },+};+doc.self = doc;+export default doc;+`,+ );+ const view = await loadDocs(file);+ expect(Object.keys(view)).toContain('props');+ expect(view.props).toBeUndefined();+ expect(view.big).toBe(10n);+ expect(view.when).toBeInstanceOf(Date);+ expect(view.limit).toBe(Infinity);+ expect(typeof view.examples[0].code).toBe('function');+ expect(view.self).toBe(view);+ expect(() => view.lazy).toThrow('never read');+ // A checked read of a valid doc with odd values is no different.+ const ok = write(+ 'Big.doc.mjs',+ "export default {type: 'component', name: 'Big', displayName: 'Big', usage: {description: 'd'}, props: [], playground: {seed: 10n}};\n",+ );+ expect((await loadComponentDoc(ok)).playground.seed).toBe(10n);+ });++ it("hands readers the module's own doc, as main always did", async () => {+ const file = write(+ 'Deep.doc.mjs',+ `let deep = {};+const root = deep;+for (let i = 0; i < 5000; i++) deep = deep.next = {};+const doc = new Proxy(+ {type: 'component', name: 'Deep', displayName: 'Deep', usage: {description: 'd'}, props: [], root},+ {get: (target, key) => (key === 'displayName' ? 'From the proxy' : target[key])},+);+export default doc;+`,+ );+ const mod = await import(pathToFileURL(file).href);+ const view = await loadDocs(file);+ expect(view).toBe(mod.default);+ expect(view.displayName).toBe('From the proxy');+ expect(await loadComponentDoc(file)).toBe(mod.default);+ });++ it('translates and checks afresh on every read, as main did', async () => {+ const file = write(+ 'Counted.doc.mjs',+ `let reads = 0;+export default {+ type: 'component', name: 'Counted', displayName: 'Counted', props: [],+ get usage() { reads += 1; return {description: 'read ' + reads}; },+};+export const docsZh = {get props() { throw new TypeError('bad translation'); }};+`,+ );+ const first = await loadDocs(file, {lang: 'zh'}).catch(error => error);+ const second = await loadDocs(file, {lang: 'zh'}).catch(error => error);+ expect(first).toBeInstanceOf(TypeError);+ expect(second).not.toBe(first);+ const template = write(+ 'Block.doc.mjs',+ "export default {type: 'block', name: 'Block', description: 'd', componentsUsed: ['A']};\n",+ );+ const read = () =>+ readDocView(template, {+ root: 'templates',+ exports: ['default'],+ strict: true,+ value: 'parsed',+ });+ const one = await read();+ one.componentsUsed.push('mutated');+ expect((await read()).componentsUsed).toEqual(['A']);+ });++ it('treats any thrown value as a failure, undefined included, as main did', async () => {+ const strict = write(+ 'ThrowsUndefined.doc.mjs',+ "export default {type: 'component', name: 'ThrowsUndefined', displayName: 'T', props: [], get usage() { throw undefined; }};\n",+ );+ await expect(loadComponentDoc(strict)).rejects.toBeUndefined();+ const translated = write(+ 'ZhUndefined.doc.mjs',+ "export default {type: 'component', name: 'ZhUndefined', displayName: 'Z', props: [], usage: {description: 'd'}};\nexport const docsZh = {get usage() { throw undefined; }};\n",+ );+ await expect(loadDocs(translated, {lang: 'zh'})).rejects.toBeUndefined();+ const imported = write('ImportUndefined.doc.mjs', 'throw undefined;\n');+ await expect(loadDocs(imported)).rejects.toBeUndefined();+ const bare = write(+ 'NullProto.doc.mjs',+ 'const e = Object.create(null);\ne.tag = 1;\nthrow e;\n',+ );+ const thrown = await loadDocs(bare).catch(error => error);+ expect(Object.getPrototypeOf(thrown)).toBeNull();+ expect(thrown.tag).toBe(1);+ });++ it('never lets a message that is not a path break a read', async () => {+ const file = write(+ 'Odd.doc.mjs',+ "throw new Error('Could not read file:///tmp/data/100%-coverage.json');\n",+ );+ await expect(loadDocs(file)).rejects.toThrow('100%-coverage.json');+ const empty = write('Empty.doc.mjs', "throw new Error('');\n");+ const {diagnostics} = await compileDocFile(empty, {root: 'components'});+ expect(diagnostics[0].message).not.toBe('');+ });++ it('reads an empty export as that value, and checks it as that value', async () => {+ const file = write('Null.doc.mjs', 'export default null;\n');+ await expect(+ readDocView(file, {root: 'templates', exports: ['default']}),+ ).resolves.toBeNull();+ await expect(+ readDocView(file, {+ root: 'templates',+ exports: ['default'],+ strict: true,+ label: 'Template "t"',+ }),+ ).rejects.toThrow(/received null/);+ });++ it('keeps the unchecked readers on a plain import', () => {+ // Outside vitest's own loader: a plain import cannot strip types under+ // node_modules, and the checked loader (jiti) can, as on main.+ const dir = path.join(tmpDir, 'node_modules', 'kit');+ fs.mkdirSync(dir, {recursive: true});+ const file = path.join(dir, 'Typed.doc.ts');+ fs.writeFileSync(+ file,+ "export default {name: 'Typed'} as {name: string};\n",+ );+ const loader = path.join(+ CLI_ROOT,+ 'foundation/discovery/component-loader.mjs',+ );+ const run = (/** @type {string} */ call) =>+ spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `const m = await import(${JSON.stringify(pathToFileURL(loader).href)});+try { const d = await m.${call}(${JSON.stringify(file)}); console.log('ok', d.name); }+catch (e) { console.log('threw', e.message.split('\\n')[0]); }`,+ ],+ {encoding: 'utf8'},+ ).stdout.trim();+ expect(run('loadDocs')).toMatch(/^threw .*node_modules/);+ expect(run('loadComponentDoc')).toMatch(/^(ok Typed|threw .*is invalid)/);+ });+});diff --git a/packages/cli/foundation/doc-compiler/source.mjs b/packages/cli/foundation/doc-compiler/source.mjsnew file mode 100644index 0000000000..b0232fe757--- /dev/null+++ b/packages/cli/foundation/doc-compiler/source.mjs@@ -0,0 +1,128 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Where an authored file ships: its package and its path inside it.+ *+ * @input An absolute file path.+ * @output `<package name>/<path inside the package>`, found by walking up to+ * the nearest package.json that names a package.+ * @position Used by the doc compiler for provenance and diagnostics, so no+ * compiled node or diagnostic carries a machine-specific path.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++/**+ * The nearest package a directory belongs to: the nearest package.json that+ * names a package, else the nearest package.json at all (named by its folder).+ * @typedef {{dir: string, name: string}} PackageRoot+ */++/** @type {Map<string, {named: PackageRoot | null, any: PackageRoot | null}>} */+const packageRoots = new Map();++/**+ * Where a file ships: its package's name and its path inside that package.+ * Never a location on this machine: a file outside any package is named by+ * its folder and file name.+ * @param {string} file absolute path+ * @returns {string}+ */+export function packageSource(file) {+ const {named, any} = packageRootsOf(path.dirname(path.resolve(file)));+ const root = named ?? any;+ if (root == null) {+ return `${folderName(path.dirname(path.resolve(file)))}/${path.basename(file)}`;+ }+ const inside = path+ .relative(root.dir, path.resolve(file))+ .split(path.sep)+ .join('/');+ return `${root.name}/${inside}`;+}++/**+ * The name of the package a file ships in; for a package.json with no name,+ * its folder's name; outside any package, `unknown`.+ * @param {string} file absolute path+ * @returns {string}+ */+export function packageOf(file) {+ const {named, any} = packageRootsOf(path.dirname(path.resolve(file)));+ return (named ?? any)?.name ?? 'unknown';+}++/**+ * Replace every absolute path in a message with where that file ships, so a+ * diagnostic never carries a location on this machine.+ * @param {string} message+ * @returns {string}+ */+export function scrubPaths(message) {+ return message+ .replace(/file:\/\/(\/[^\s'"`)]+)/gu, (_, file) =>+ packageSource(safeDecode(file)),+ )+ .replace(/(?<![\w:/.-])((?:\/[^\s'"`:()/]+)+)/gu, (_, file) =>+ packageSource(file),+ )+ .replace(/(?<![\w])([A-Za-z]:\\[^\s'"`:()]+)/gu, (_, file) =>+ packageSource(file),+ );+}++/** @param {string} dir */+function folderName(dir) {+ const name = path+ .basename(dir)+ .toLowerCase()+ .replace(/[^a-z0-9._~-]+/gu, '-');+ return name.replace(/^[._]+/u, '') || 'unknown';+}++/**+ * @param {string} dir+ * @returns {{named: PackageRoot | null, any: PackageRoot | null}}+ */+function packageRootsOf(dir) {+ const cached = packageRoots.get(dir);+ if (cached !== undefined) return cached;+ /** @type {PackageRoot | null} */+ let here = null;+ let named = false;+ const manifest = path.join(dir, 'package.json');+ if (fs.existsSync(manifest)) {+ here = {dir, name: folderName(dir)};+ try {+ const {name} = JSON.parse(fs.readFileSync(manifest, 'utf-8'));+ if (typeof name === 'string' && name !== '') {+ here = {dir, name};+ named = true;+ }+ } catch {+ // An unreadable package.json names no package; keep walking up.+ }+ }+ const parent = path.dirname(dir);+ const above =+ named || parent === dir ? {named: null, any: null} : packageRootsOf(parent);+ const found = named+ ? {named: here, any: here}+ : {named: above.named, any: here ?? above.any};+ packageRoots.set(dir, found);+ return found;+}++/**+ * A file URL path decoded, or as written when it is not valid percent-encoding+ * (a message may hold any text).+ * @param {string} text+ */+function safeDecode(text) {+ try {+ return decodeURI(text);+ } catch {+ return text;+ }+}diff --git a/packages/cli/foundation/integrations/autolink.mjs b/packages/cli/foundation/integrations/autolink.mjsindex 63fd1fd0fb..e2e8db3f2e 100644--- a/packages/cli/foundation/integrations/autolink.mjs+++ b/packages/cli/foundation/integrations/autolink.mjs@@ -29,8 +29,9 @@* package's own package.json `name` (see loadIntegrations), so an aliased* dependency reports the package it actually is.*- * An explicit config entry always wins: candidates already loaded from config- * are dropped before anything here is imported.+ * An explicit config entry always wins: a dependency whose directory is+ * already loaded from config is never imported again, and comes back as a+ * repeat so the provider ledger still records it.** @position lib — sits between config/project (the caller) and* integrations/integrations (the loader); contributes no discovery of its own.@@ -39,6 +40,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {findManifestPaths, loadIntegrations} from './integrations.mjs';+import {resolveProviders} from './provider-resolution.mjs';/*** package.json fields whose keys name a dependency this project installs.@@ -164,36 +166,44 @@ function realPath(target) {}/**- * Declared dependencies that ship an integration manifest and are not already- * loaded, in declaration order.- *- * A candidate must have EXACTLY ONE root manifest. Zero is the ordinary case- * (almost every dependency), and more than one is a packaging mistake the- * loader treats as a hard error — an error the project did not ask for and- * cannot fix, so an ambiguous package is passed over here rather than allowed- * to fail the load of a project that merely depends on it.+ * @typedef {object} AutolinkCandidate+ * @property {string} spec+ * @property {string} field+ * @property {string} packageDir+ * @property {string} hostDir+ * @property {boolean} [repeat] the directory is already loaded or already a+ * candidate under another dependency key; it is not loaded again+ */++/**+ * Every declared dependency that ships exactly one root manifest, in+ * declaration order, including the ones whose directory is already loaded or+ * already a candidate (`repeat`), so a caller can account for each of them.** @param {string} projectDir directory holding the project's package.json* @param {{exclude?: Iterable<string>}} [options] `exclude` — package* directories already loaded (from config); matched through symlinks- * @returns {Array<{spec: string, field: string, packageDir: string, hostDir: string}>}+ * @returns {AutolinkCandidate[]}*/-export function findAutolinkCandidates(projectDir, {exclude = []} = {}) {+export function scanAutolinkCandidates(projectDir, {exclude = []} = {}) {const taken = new Set([...exclude].map(realPath));- /** @type {Array<{spec: string, field: string, packageDir: string, hostDir: string}>} */+ /** @type {AutolinkCandidate[]} */const candidates = [];for (const {name, field} of readDeclaredDependencies(projectDir)) {const resolved = resolveInstalledPackageDir(name, projectDir);if (!resolved) continue;+ if (findManifestPaths(resolved.packageDir).length !== 1) continue;+// Two dependency keys can name one installed package — an npm alias beside// the package it aliases, or the two spellings of a package mid-rename// resolving through one store entry. Load it once.const identity = realPath(resolved.packageDir);- if (taken.has(identity)) continue;-- if (findManifestPaths(resolved.packageDir).length !== 1) continue;+ if (taken.has(identity)) {+ candidates.push({spec: name, field, ...resolved, repeat: true});+ continue;+ }taken.add(identity);candidates.push({spec: name, field, ...resolved});@@ -202,6 +212,100 @@ export function findAutolinkCandidates(projectDir, {exclude = []} = {}) {return candidates;}+/**+ * Declared dependencies that ship an integration manifest and are not already+ * loaded, in declaration order.+ *+ * A candidate must have EXACTLY ONE root manifest. Zero is the ordinary case+ * (almost every dependency), and more than one is a packaging mistake the+ * loader treats as a hard error — an error the project did not ask for and+ * cannot fix, so an ambiguous package is passed over here rather than allowed+ * to fail the load of a project that merely depends on it.+ *+ * @param {string} projectDir directory holding the project's package.json+ * @param {{exclude?: Iterable<string>}} [options] `exclude` — package+ * directories already loaded (from config); matched through symlinks+ * @returns {Array<{spec: string, field: string, packageDir: string, hostDir: string}>}+ */+export function findAutolinkCandidates(projectDir, options) {+ return scanAutolinkCandidates(projectDir, options)+ .filter(candidate => !candidate.repeat)+ .map(({spec, field, packageDir, hostDir}) => ({+ spec,+ field,+ packageDir,+ hostDir,+ }));+}++/**+ * Load every autolink candidate, each in isolation, as provider candidates for+ * {@link resolveProviders}. Nothing is filtered here: a candidate whose load+ * throws or whose manifest fails comes back with its error, and a repeated+ * directory comes back unloaded, so the resolver records each one.+ *+ * @param {object} options+ * @param {string} options.projectDir directory holding the project's package.json+ * @param {import('./integrations.mjs').LoadedIntegration[]} [options.loaded]+ * integrations already loaded from config+ * @param {boolean} [options.fresh]+ * @returns {Promise<import('./provider-resolution.mjs').ProviderCandidate[]>}+ */+export async function loadAutolinkCandidates({+ projectDir,+ loaded = [],+ fresh = false,+}) {+ const scanned = scanAutolinkCandidates(projectDir, {+ // A configured entry that never resolved to a directory has none to exclude.+ exclude: loaded.flatMap(integration =>+ typeof integration.__packageDir === 'string'+ ? [integration.__packageDir]+ : [],+ ),+ });++ /** @type {import('./provider-resolution.mjs').ProviderCandidate[]} */+ const candidates = [];+ for (const candidate of scanned) {+ const {spec, packageDir} = candidate;+ if (candidate.repeat) {+ candidates.push({source: 'autolinked', spec, packageDir, repeat: true});+ continue;+ }+ try {+ // Resolve from the directory whose node_modules actually holds the+ // package, so a hoisted dependency resolves the same way Node found it.+ const [integration] = await loadIntegrations([spec], {+ cwd: candidate.hostDir,+ fresh,+ });+ candidates.push({+ source: 'autolinked',+ spec,+ packageDir,+ ...(integration == null+ ? {}+ : {+ integration: {+ ...integration,+ __autolinked: true,+ __dependencyField: candidate.field,+ },+ }),+ });+ } catch (error) {+ candidates.push({+ source: 'autolinked',+ spec,+ packageDir,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ return candidates;+}+/*** Load every declared dependency that ships an integration manifest and is not* already loaded from config.@@ -216,6 +320,12 @@ export function findAutolinkCandidates(projectDir, {exclude = []} = {}) {* consuming project can neither fix nor silence, and which* `astryx doctor integration validate <package>` reports on demand.*+ * One package reached twice (an alias beside the package it aliases, at the+ * same version) loads once. The same name at another version is kept, so the+ * provider pass reports it instead of dropping it. Project.load does not call+ * this; it hands {@link loadAutolinkCandidates} to the resolver, whose ledger+ * records every candidate dropped here.+ ** @param {object} options* @param {string} options.projectDir directory holding the project's package.json* @param {import('./integrations.mjs').LoadedIntegration[]} [options.loaded]@@ -228,50 +338,26 @@ export async function autolinkIntegrations({loaded = [],fresh = false,}) {- const candidates = findAutolinkCandidates(projectDir, {- // A configured entry that never resolved to a directory has none to exclude.- exclude: loaded.flatMap(integration =>- typeof integration.__packageDir === 'string'- ? [integration.__packageDir]- : [],- ),- });-+ const candidates = await loadAutolinkCandidates({projectDir, loaded, fresh});+ const {ledger} = resolveProviders([+ ...loaded.map(integration => ({+ source: /** @type {const} */ ('configured'),+ integration,+ spec: integration.__spec,+ })),+ ...candidates,+ ]);/** @type {import('./integrations.mjs').LoadedIntegration[]} */const autolinked = [];- // One package reached twice (an alias beside the package it aliases, at the- // same version) loads once. The same name at another version is kept, so the- // provider-identity pass in Project.load reports it instead of dropping it.- /** @param {{name: string, version?: string}} integration */- const identity = integration =>- `${integration.name}\u0000${integration.version ?? ''}`;- const seen = new Set(loaded.map(identity));-- for (const candidate of candidates) {- /** @type {import('./integrations.mjs').LoadedIntegration|undefined} */- let integration;- try {- // Resolve from the directory whose node_modules actually holds the- // package, so a hoisted dependency resolves the same way Node found it.- [integration] = await loadIntegrations([candidate.spec], {- cwd: candidate.hostDir,- fresh,- });- } catch {- continue;+ for (const entry of ledger.values()) {+ const {candidate} = entry;+ if (+ candidate.source === 'autolinked' &&+ candidate.integration != null &&+ (entry.outcome === 'contributes' || entry.outcome === 'set-aside')+ ) {+ autolinked.push(candidate.integration);}- if (!integration || integration.__loadError) continue;- // Identity is the resolved package's own name and version, so an alias and- // the package it aliases collapse here even when they are two directories- // on disk.- if (seen.has(identity(integration))) continue;- seen.add(identity(integration));- autolinked.push({- ...integration,- __autolinked: true,- __dependencyField: candidate.field,- });}-return autolinked;}diff --git a/packages/cli/foundation/integrations/contribution-fixes.mjs b/packages/cli/foundation/integrations/contribution-fixes.mjsnew file mode 100644index 0000000000..afbe11705c--- /dev/null+++ b/packages/cli/foundation/integrations/contribution-fixes.mjs@@ -0,0 +1,1284 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The `Fix:` advice for contribution metadata that no root reads, or+ * that the wrong root reads.+ *+ * A fix must hold when followed literally. It never names a path outside the+ * package, never makes the package root a root, and names only the offending+ * file plus the same-stem source that moves with it. It offers a folder as a+ * root only when that root would read nothing but this kind of metadata,+ * overlap no other root, and orphan nothing the current root holds. Metadata+ * is read statically: nothing here runs package code.+ *+ * @input a package directory, its resolved roots, and one misplaced file+ * @output the `Fix: ...` sentence for that file+ * @position packages/cli/foundation/integrations — shared by the unreachable+ * scan in api/integration/validate-integration.mjs and the component checks+ * in validate-contributions.mjs+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import jscodeshift from 'jscodeshift';+import {isValidSemver} from '../env/semver.mjs';+import {+ isThemeFolder as readsAsTheme,+ THEME_DOC_SUFFIX,+ THEME_MODULE_EXTENSIONS,+ THEME_SLUG_RE,+} from '../discovery/theme-discovery.mjs';++/** @typedef {'components' | 'templates' | 'docs' | 'themes'} MetadataRoot */++/**+ * @typedef {object} ContributionStamp+ * @property {string} type+ * @property {string | null} name the static `name`, when it has one+ */++/**+ * @typedef {object} FixContext+ * @property {string} packageDir+ * @property {string} manifest file name of the package's manifest+ * @property {Partial<Record<MetadataRoot | 'codemods', string>>} roots+ * declared roots, absolute+ * @property {Map<string, ContributionStamp | null>} stamps+ * @property {Map<string, string[] | null>} candidates+ */++export const DOC_CANDIDATE_RE = /\.doc\.(?:ts|mjs|js)$/u;+export const TEMPLATE_CANDIDATE_RE = /\.template\.(?:ts|mjs|js)$/u;+const STATIC_DOC_TYPES = new Set([+ 'component',+ 'generic',+ 'page',+ 'block',+ 'theme',+]);+const STATIC_TEMPLATE_TYPES = new Set(['page', 'block']);+/** Stray-codemod and version-folder rules, shared with the codemod checks. */+export const CODEMOD_FILE_RE = /\.(?:ts|mjs|js)$/u;+export const CODEMOD_TEST_RE = /\.(?:test|spec|fixture)\.(?:ts|mjs|js)$/u;+export const CODEMOD_SKIP_DIRS = new Set([+ 'node_modules',+ '.git',+ '__tests__',+ '__fixtures__',+]);+/** @type {MetadataRoot[]} */+const METADATA_ROOTS = ['components', 'templates', 'docs', 'themes'];+/** Past this many entries a folder's contents count as unknown. */+const FOLDER_SCAN_LIMIT = 5_000;++/** The manifest root that reads each kind of contribution metadata. */+export const ROOT_FOR_TYPE = /** @type {Record<string, MetadataRoot>} */ ({+ component: 'components',+ generic: 'docs',+ page: 'templates',+ block: 'templates',+ theme: 'themes',+});++/** What a root holds, as a fix names it. */+const ROOT_HOLDS = /** @type {Record<MetadataRoot, string>} */ ({+ components: 'components',+ docs: 'topics',+ templates: 'templates',+ themes: 'themes',+});++const j = jscodeshift.withParser('tsx');++/** @param {any} node @returns {any} */+function unwrapStaticExpression(node) {+ let current = node;+ while (+ current &&+ [+ 'TSSatisfiesExpression',+ 'TSAsExpression',+ 'TypeCastExpression',+ 'ParenthesizedExpression',+ ].includes(current.type)+ ) {+ current = current.expression;+ }+ if (current?.type === 'CallExpression' && current.arguments.length > 0) {+ current = unwrapStaticExpression(current.arguments[0]);+ }+ return current;+}++/** @param {any} property @param {string} name */+function staticPropertyNamed(property, name) {+ if (+ !property ||+ !['ObjectProperty', 'Property'].includes(property.type) ||+ property.computed+ ) {+ return false;+ }+ return (+ (property.key?.type === 'Identifier' && property.key.name === name) ||+ (['Literal', 'StringLiteral'].includes(property.key?.type) &&+ property.key.value === name)+ );+}++/**+ * Identify contribution metadata without importing it. Doctor scans files that+ * the manifest does not declare, so executing those files would run code the+ * package never asked Astryx to load.+ *+ * @param {string} file+ * @param {boolean} templateOnly+ * @returns {ContributionStamp | null} null when it is not contribution metadata+ */+export function readContributionStamp(file, templateOnly) {+ let ast;+ try {+ ast = j(fs.readFileSync(file, 'utf-8'));+ } catch {+ return null;+ }+ /** @type {any[]} */+ const candidates = [];+ ast+ .find(j.ExportDefaultDeclaration)+ .forEach((/** @type {any} */ exportPath) => {+ candidates.push(exportPath.value.declaration);+ });+ ast+ .find(j.ExportNamedDeclaration)+ .forEach((/** @type {any} */ exportPath) => {+ const declaration = exportPath.value.declaration;+ if (declaration?.type !== 'VariableDeclaration') return;+ for (const declarator of declaration.declarations) {+ if (+ declarator.id?.type === 'Identifier' &&+ declarator.id.name === 'docs'+ ) {+ candidates.push(declarator.init);+ }+ }+ });++ const allowedTypes = templateOnly ? STATIC_TEMPLATE_TYPES : STATIC_DOC_TYPES;+ for (const candidate of candidates) {+ const object = unwrapStaticExpression(candidate);+ if (object?.type !== 'ObjectExpression') continue;+ /** @param {string} name @returns {unknown} */+ const field = name =>+ unwrapStaticExpression(+ object.properties.find((/** @type {any} */ property) =>+ staticPropertyNamed(property, name),+ )?.value,+ );+ const type = /** @type {any} */ (field('type'));+ if (+ ['Literal', 'StringLiteral'].includes(type?.type) &&+ allowedTypes.has(type.value)+ ) {+ const name = /** @type {any} */ (field('name'));+ return {+ type: type.value,+ name: typeof name?.value === 'string' ? name.value : null,+ };+ }+ }+ return null;+}++/** @param {string} candidate @param {string} root */+export function pathIsInside(candidate, root) {+ return candidate === root || candidate.startsWith(`${root}${path.sep}`);+}++/**+ * @param {string} packageDir+ * @param {{components?: string, templates?: string, codemods?: string, docs?: string, themes?: string, __manifestFile?: string}} integration+ * @returns {FixContext}+ */+export function createFixContext(packageDir, integration) {+ return {+ packageDir,+ manifest: integration.__manifestFile+ ? path.basename(integration.__manifestFile)+ : 'astryx.integration.mjs',+ roots: {+ components: integration.components,+ templates: integration.templates,+ codemods: integration.codemods,+ docs: integration.docs,+ themes: integration.themes,+ },+ stamps: new Map(),+ candidates: new Map(),+ };+}++/**+ * The static stamp of a candidate metadata file, read once per context.+ * @param {FixContext} context+ * @param {string} file+ * @returns {ContributionStamp | null}+ */+export function stampOf(context, file) {+ if (!context.stamps.has(file)) {+ context.stamps.set(+ file,+ readContributionStamp(file, TEMPLATE_CANDIDATE_RE.test(file)),+ );+ }+ return context.stamps.get(file) ?? null;+}++/** @param {FixContext} context @param {string} file */+function shown(context, file) {+ return path.relative(context.packageDir, file).split(path.sep).join('/');+}++/** @param {FixContext} context */+function declaredRoots(context) {+ return /** @type {string[]} */ (Object.values(context.roots).filter(Boolean));+}++/** @param {string} file */+function isFile(file) {+ try {+ return fs.statSync(file).isFile();+ } catch {+ return false;+ }+}++/**+ * Every doc or template file under `dir`, or null when there are too many+ * entries to know.+ * @param {FixContext} context+ * @param {string} dir+ * @returns {string[] | null}+ */+function candidatesUnder(context, dir) {+ if (context.candidates.has(dir)) {+ return context.candidates.get(dir) ?? null;+ }+ /** @type {string[] | null} */+ let found = [];+ let seen = 0;+ /** @param {string} current */+ const walk = current => {+ let entries;+ try {+ entries = fs.readdirSync(current, {withFileTypes: true});+ } catch {+ return;+ }+ for (const entry of entries) {+ if (found == null) return;+ if (entry.name === '.git') continue;+ seen += 1;+ if (seen > FOLDER_SCAN_LIMIT) {+ found = null;+ return;+ }+ const full = path.join(current, entry.name);+ if (entry.isDirectory()) {+ walk(full);+ } else if (+ entry.isFile() &&+ (DOC_CANDIDATE_RE.test(entry.name) ||+ TEMPLATE_CANDIDATE_RE.test(entry.name))+ ) {+ found.push(full);+ }+ }+ };+ walk(dir);+ context.candidates.set(dir, found);+ return found;+}++/**+ * A folder inside the package, not its root, that neither holds nor sits in a+ * declared root.+ * @param {FixContext} context+ * @param {string} dir+ */+function isFreeFolder(context, dir) {+ return (+ dir !== context.packageDir &&+ pathIsInside(dir, context.packageDir) &&+ !declaredRoots(context).some(+ root => pathIsInside(root, dir) || pathIsInside(dir, root),+ )+ );+}++/**+ * Whether `dir` is one complete theme: a slug folder whose only metadata is+ * its theme descriptor, naming that folder, beside exactly one source that+ * imports nothing outside the folder. The descriptor being fixed may lack its+ * source or import from outside; the fix asks for both.+ * @param {FixContext} context+ * @param {string} dir+ * @param {string} [fixing]+ */+function isCompleteTheme(context, dir, fixing) {+ const found = candidatesUnder(context, dir);+ if (found?.length !== 1) return false;+ const [descriptor] = found;+ const stamp = stampOf(context, descriptor);+ const slug = path.basename(dir);+ return (+ THEME_SLUG_RE.test(slug) &&+ path.dirname(descriptor) === dir &&+ descriptor.endsWith(THEME_DOC_SUFFIX) &&+ stamp?.type === 'theme' &&+ stamp.name === slug &&+ (descriptor === fixing ||+ (sourcesBeside(descriptor, 'theme').length === 1 &&+ importsOutside(descriptor)?.length === 0))+ );+}++/**+ * Whether `dir` reads cleanly as a themes root: every folder in it that+ * discovery reads as a theme is one complete theme, and no metadata sits+ * directly in it.+ * @param {FixContext} context+ * @param {string} dir+ * @param {{except?: string, ignore?: string, fixing?: string}} [options] a+ * theme folder moving out of `dir`, a descriptor moving away, and the+ * descriptor being fixed+ */+function readsAsThemesRoot(context, dir, {except, ignore, fixing} = {}) {+ if (!fs.existsSync(dir)) return true;+ if (fs.existsSync(path.join(dir, 'manifest.json'))) return false;+ let entries;+ try {+ entries = fs.readdirSync(dir, {withFileTypes: true});+ } catch {+ return false;+ }+ return entries.every(entry => {+ const full = path.join(dir, entry.name);+ if (entry.name.startsWith('.')) return true;+ if (entry.isSymbolicLink()) return false;+ if (entry.isDirectory()) {+ return (+ full === except ||+ !readsAsTheme(full) ||+ isCompleteTheme(context, full, fixing)+ );+ }+ return (+ full === ignore ||+ !(+ DOC_CANDIDATE_RE.test(entry.name) ||+ TEMPLATE_CANDIDATE_RE.test(entry.name)+ )+ );+ });+}++/**+ * Whether declaring `dir` as the `key` root reads only complete metadata of+ * that kind, overlaps no root, and stays inside the package below its root.+ * The file being fixed may lack its source; the fix asks for it.+ * @param {FixContext} context+ * @param {string} dir+ * @param {MetadataRoot} key+ * @param {string} fixing+ */+function canBeRoot(context, dir, key, fixing) {+ if (!isFreeFolder(context, dir)) return false;+ if (key === 'themes') return readsAsThemesRoot(context, dir, {fixing});+ const found = candidatesUnder(context, dir);+ if (found == null) return false;+ const complete = found.every(file => {+ const stamp = stampOf(context, file);+ return (+ stamp != null &&+ ROOT_FOR_TYPE[stamp.type] === key &&+ (file === fixing ||+ stamp.type === 'generic' ||+ sourcesBeside(file, stamp.type).length > 0)+ );+ });+ const names = found.map(file => identity(context, file, key));+ const unique = new Set(names).size === names.length;+ return (+ complete &&+ unique &&+ (key !== 'components' || uncoveredSources(dir, found).length === 0)+ );+}++/**+ * The name a root knows a contribution by, and must hold only once: a+ * component's stem, a topic's lower-cased \`name\`, a template's path without+ * its suffix. A file with no static name gets its path, which never repeats.+ * @param {FixContext} context+ * @param {string} file+ * @param {MetadataRoot} key+ */+function identity(context, file, key) {+ if (key === 'components') return docStem(file);+ if (key === 'docs')+ return stampOf(context, file)?.name?.toLowerCase() ?? file;+ return path.join(path.dirname(file), docStem(file).toLowerCase());+}++/**+ * The PascalCase \`.tsx\` files directly in a folder that no doc under it+ * covers. A components root there warns that Astryx ignores each one.+ * @param {string} dir+ * @param {string[]} found the doc and template files under it+ * @returns {string[]} their file names+ */+function uncoveredSources(dir, found) {+ const covered = new Set(+ found.filter(file => DOC_CANDIDATE_RE.test(file)).map(docStem),+ );+ try {+ return fs+ .readdirSync(dir, {withFileTypes: true})+ .filter(entry => entry.isFile() || entry.isSymbolicLink())+ .map(entry => entry.name)+ .filter(name => {+ const match = /^([A-Z][A-Za-z0-9]+)\.tsx$/u.exec(name);+ return match != null && !covered.has(match[1]);+ });+ } catch {+ return [];+ }+}++/**+ * Whether a folder holds an entry by this name, compared the way a+ * case-insensitive file system would.+ * @param {string} dir+ * @param {string} name+ */+function hasEntry(dir, name) {+ const wanted = name.toLowerCase();+ try {+ return fs.readdirSync(dir).some(entry => entry.toLowerCase() === wanted);+ } catch {+ return false;+ }+}++/**+ * What already holds the name \`file\` would take once moved to the top of+ * \`root\`, or null when the name is free.+ * @param {FixContext} context+ * @param {string} file+ * @param {ContributionStamp} stamp+ * @param {string} root+ * @returns {string | null} e.g. \`a topic named "guide" (docs/guide.doc.mjs)\`+ */+function takenIn(context, file, stamp, root) {+ const key = ROOT_FOR_TYPE[stamp.type];+ const stem = docStem(file);+ const name = identity(context, path.join(root, path.basename(file)), key);+ const same = (candidatesUnder(context, root) ?? []).find(+ other =>+ (key === 'templates' || DOC_CANDIDATE_RE.test(other)) &&+ (key === 'docs'+ ? stamp.name != null &&+ stampOf(context, other)?.name?.toLowerCase() ===+ stamp.name.toLowerCase()+ : identity(context, other, key) === name),+ );+ if (same) {+ const kind = {+ components: 'component',+ docs: 'topic',+ templates: 'template',+ }[/** @type {'components' | 'docs' | 'templates'} */ (key)];+ const called = key === 'docs' ? `"${stamp.name}"` : stem;+ return `a ${kind} named ${called} (${shown(context, same)})`;+ }+ const clash = [path.basename(file), ...sourcesBeside(file, stamp.type)].find(+ entry => hasEntry(root, entry),+ );+ return clash ? `a file named ${clash}` : null;+}++/**+ * The local modules a theme source reaches, read statically the way theme+ * discovery reads them. Null when a file in the graph cannot be parsed.+ * @param {string} entry+ * @returns {Array<{importer: string, specifier: string, target: string}> | null}+ */+function localImports(entry) {+ /** @type {Array<{importer: string, specifier: string, target: string}>} */+ const edges = [];+ const seen = new Set();+ const queue = [entry];+ while (queue.length > 0) {+ const file = /** @type {string} */ (queue.shift());+ if (seen.has(file)) continue;+ seen.add(file);+ /** @type {string[]} */+ const specifiers = [];+ try {+ const js = jscodeshift.withParser(+ /\.(?:ts|tsx|mts)$/u.test(file) ? 'tsx' : 'babel',+ );+ const ast = js(fs.readFileSync(file, 'utf-8'));+ /** @param {any} node */+ const add = node => {+ if (typeof node?.value === 'string') specifiers.push(node.value);+ };+ for (const type of [+ js.ImportDeclaration,+ js.ExportNamedDeclaration,+ js.ExportAllDeclaration,+ js.ImportExpression,+ ]) {+ ast.find(type).forEach((/** @type {any} */ found) => {+ add(found.node.source);+ });+ }+ ast.find(js.CallExpression).forEach((/** @type {any} */ call) => {+ if (call.node.callee?.type === 'Import') add(call.node.arguments?.[0]);+ });+ } catch {+ return null;+ }+ for (const specifier of specifiers) {+ if (!specifier.startsWith('.')) continue;+ const base = path.resolve(path.dirname(file), specifier);+ const target = [+ base,+ ...THEME_MODULE_EXTENSIONS.map(extension => `${base}${extension}`),+ ...THEME_MODULE_EXTENSIONS.map(extension =>+ path.join(base, `index${extension}`),+ ),+ ].find(isFile);+ if (!target) continue;+ edges.push({importer: file, specifier, target});+ if (THEME_MODULE_EXTENSIONS.includes(path.extname(target))) {+ queue.push(target);+ }+ }+ }+ return edges;+}++/**+ * A theme's imports that reach outside the folder its descriptor is in. Null+ * when unknown.+ * @param {string} file the theme descriptor+ */+function importsOutside(file) {+ const [source] = sourcesBeside(file, 'theme');+ if (!source) return [];+ const home = path.dirname(file);+ const edges = localImports(path.join(home, source));+ return edges && edges.filter(edge => !pathIsInside(edge.target, home));+}++/**+ * The sentence that brings the files a theme imports from outside its folder+ * into the folder: discovery rejects any import that leaves it. Files move+ * with the folder keep their paths; outside files are copied to its top.+ * @param {FixContext} context+ * @param {string} file the theme descriptor+ * @param {string} destination the theme folder, as the fix names it+ * @returns {string} a sentence with a leading space, or ''+ */+function themeImportNote(context, file, destination) {+ const [source] = sourcesBeside(file, 'theme');+ if (!source) return '';+ const home = path.dirname(file);+ const edges = localImports(path.join(home, source));+ if (!edges) return '';+ const copies = [+ ...new Set(+ edges+ .map(edge => edge.target)+ .filter(target => !pathIsInside(target, home)),+ ),+ ];+ if (+ copies.length === 0 ||+ copies.some(target => !pathIsInside(target, context.packageDir))+ ) {+ return '';+ }+ const why = ': a theme can import only files inside its own folder.';+ const listed = copies.map(target => shown(context, target));+ const list =+ listed.length === 1+ ? listed[0]+ : `${listed.slice(0, -1).join(', ')} and ${listed.at(-1)}`;+ const names = copies.map(target => path.basename(target).toLowerCase());+ if (+ new Set(names).size !== names.length ||+ copies.some(target => hasEntry(home, path.basename(target)))+ ) {+ return ` Also copy ${list} into ${destination} and point the imports of ${copies.length === 1 ? 'it at the copy' : 'them at the copies'}${why}`;+ }+ /** @param {string} target where a file ends up, relative to the theme folder */+ const inTheme = target =>+ (pathIsInside(target, home)+ ? path.relative(home, target)+ : path.basename(target)+ )+ .split(path.sep)+ .join('/');+ /** @type {string[]} */+ const changes = [];+ for (const {importer, specifier, target} of edges) {+ const extension = path.extname(specifier);+ let next = inTheme(target);+ if (!(extension && target.endsWith(extension))) {+ next = next.slice(0, next.length - path.extname(next).length);+ }+ next = path.posix.relative(path.posix.dirname(inTheme(importer)), next);+ if (!next.startsWith('.')) next = `./${next}`;+ const change = `of ${specifier} in ${path.basename(importer)} to ${next}`;+ if (next !== specifier && !changes.includes(change)) changes.push(change);+ }+ const changed =+ changes.length === 1+ ? `the import ${changes[0]}`+ : `the imports ${changes.slice(0, -1).join(', ')} and ${changes.at(-1)}`;+ return ` Also copy ${list} into ${destination} and change ${changed}${why}`;+}++/**+ * The same-stem sources beside a doc: a component's or template's `.tsx`, or+ * a theme's entry modules (a theme needs exactly one).+ * @param {string} file+ * @param {string} type+ * @returns {string[]} their file names+ */+function sourcesBeside(file, type) {+ if (type === 'generic') return [];+ const dir = path.dirname(file);+ const stem = docStem(file);+ const names =+ type === 'theme'+ ? THEME_MODULE_EXTENSIONS.map(extension => `${stem}${extension}`)+ : [`${stem}.tsx`];+ return names.filter(name => isFile(path.join(dir, name)));+}++/** @param {string} file */+function docStem(file) {+ return path+ .basename(file)+ .replace(DOC_CANDIDATE_RE, '')+ .replace(TEMPLATE_CANDIDATE_RE, '');+}++/**+ * The sentences asking for what the doc needs wherever it ends up: a missing+ * same-stem source, and for a theme, the descriptor's `.doc.mjs` name.+ * @param {string} file+ * @param {string} type+ * @returns {string} a sentence with a leading space, or ''+ */+function sourceNote(file, type) {+ // Theme discovery reads only `.doc.mjs` descriptors.+ const rename =+ type === 'theme' && !file.endsWith(THEME_DOC_SUFFIX)+ ? ` Also rename ${path.basename(file)} to ${docStem(file)}${THEME_DOC_SUFFIX}: a theme descriptor is a ${THEME_DOC_SUFFIX} file.`+ : '';+ if (type === 'generic' || sourcesBeside(file, type).length > 0) return rename;+ return type === 'theme'+ ? `${rename} Also add its same-stem theme source, such as ${docStem(file)}.ts, beside it.`+ : ` Also add ${docStem(file)}.tsx beside it.`;+}++/**+ * How a fix names a folder.+ * @param {FixContext} context+ * @param {string} dir+ */+function place(context, dir) {+ return dir === context.packageDir+ ? 'the package root'+ : `${shown(context, dir)}/`;+}++/** @param {string} text */+function capitalize(text) {+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;+}++/**+ * Whether codemods can move into `dir`: it is missing, or holds nothing the+ * codemod checks would read as a stray codemod or a mis-named version.+ * @param {string} dir+ */+function holdsOnlyVersions(dir) {+ if (!fs.existsSync(dir)) return true;+ try {+ return fs+ .readdirSync(dir, {withFileTypes: true})+ .every(entry =>+ entry.isDirectory()+ ? isValidSemver(entry.name) || CODEMOD_SKIP_DIRS.has(entry.name)+ : !CODEMOD_FILE_RE.test(entry.name) ||+ CODEMOD_TEST_RE.test(entry.name),+ );+ } catch {+ return false;+ }+}++/**+ * The step that gives codemods a folder of their own, and the folder it names+ * (null when codemods/ is taken and the author picks one).+ * @param {FixContext} context+ * @returns {{step: string, folder: string | null}}+ */+function ownCodemodsFolder(context) {+ const target = path.join(context.packageDir, 'codemods');+ return context.roots.codemods !== target && holdsOnlyVersions(target)+ ? {+ step: `create codemods/, move each version folder into it, and set \`codemods: './codemods'\` in ${context.manifest}`,+ folder: 'codemods',+ }+ : {+ step: `move each version folder into a new folder of their own, and set \`codemods\` to that folder in ${context.manifest}`,+ folder: null,+ };+}++/**+ * Declared roots other than codemods at or inside `dir`.+ * @param {FixContext} context+ * @param {string} dir+ * @returns {Array<{kind: MetadataRoot, root: string}>}+ */+function metadataRootsIn(context, dir) {+ /** @type {Array<{kind: MetadataRoot, root: string}>} */+ const found = [];+ for (const kind of METADATA_ROOTS) {+ const root = context.roots[kind];+ if (root && pathIsInside(root, dir)) found.push({kind, root});+ }+ return found;+}++/**+ * The fix for every codemods entry when the codemods root also holds the rest+ * of the package: it is the package root, or it holds another root. No+ * per-entry move or rename helps then.+ * @param {FixContext} context+ * @param {string} [stray] a stray file's name, which may itself be a codemod+ * @returns {string | null}+ */+export function sharedCodemodsRootFix(context, stray) {+ const root = context.roots.codemods;+ if (!root) return null;+ const {step, folder} = ownCodemodsFolder(context);+ const also =+ stray == null+ ? ''+ : ` If it is a codemod, move it into the folder named for the version it migrates to, for example ${folder ? `${folder}/1.2.0/${stray}` : `1.2.0/${stray} in that folder`}.`;+ if (root === context.packageDir) {+ return `Fix: the codemods root is the package root, so everything in the package is read as a codemod or a version folder. ${capitalize(step)}.${also}`;+ }+ // codemods/ holding another root is fixed by moving that root out.+ if (root === path.join(context.packageDir, 'codemods')) return null;+ const [held] = metadataRootsIn(context, root);+ if (!held) return null;+ const relation =+ held.root === root+ ? `is also the ${held.kind} root`+ : `also holds the ${held.kind} root ${place(context, held.root)}`;+ return `Fix: the codemods root ${place(context, root)} ${relation}. ${capitalize(step)}.${also}`;+}++/**+ * The fix for a codemods folder that holds another root, which a rename would+ * break.+ * @param {FixContext} context+ * @param {string} folder+ * @returns {string | null}+ */+export function heldRootFix(context, folder) {+ const [held] = metadataRootsIn(context, folder);+ const codemods = context.roots.codemods;+ if (!held || !codemods) return null;+ return `Fix: it holds the ${held.kind} root ${place(context, held.root)}; move that root out of ${place(context, codemods)} and update \`${held.kind}\` in ${context.manifest}.`;+}++/**+ * The step that stops another root from also reading `dir`, the folder a fix+ * puts `key` metadata in. `dir` is undefined for a folder the author picks,+ * which only a root at the package root is sure to cover.+ * @param {FixContext} context+ * @param {string | undefined} dir+ * @param {MetadataRoot} key+ * @returns {string} a sentence with a leading space, or ''+ */+function overlapNote(context, dir, key) {+ /** @param {string | undefined} root */+ const covers = root =>+ root != null &&+ (dir === undefined ? root === context.packageDir : pathIsInside(dir, root));+ const at = dir === undefined ? 'that folder' : place(context, dir);+ let note = '';+ const codemods = context.roots.codemods;+ if (covers(codemods)) {+ if (+ dir !== undefined &&+ codemods === path.join(context.packageDir, 'codemods')+ ) {+ return ` The codemods root codemods/ also reads ${at}; move ${at} out of codemods/ and set \`${key}\` to its new path in ${context.manifest}.`;+ }+ const which =+ codemods === context.packageDir+ ? 'is the package root, so it'+ : place(context, /** @type {string} */ (codemods));+ note = ` The codemods root ${which} also reads ${at}; ${ownCodemodsFolder(context).step}.`;+ }+ const own = path.join(context.packageDir, key);+ const free = !fs.existsSync(own) && isFreeFolder(context, own);+ for (const kind of METADATA_ROOTS) {+ const other = context.roots[kind];+ if (kind === key || other == null || !covers(other)) continue;+ if (other === context.packageDir) {+ note += ` The ${kind} root is the package root, so it also reads ${at}; create ${kind}/, move the ${ROOT_HOLDS[kind]} into it, and set \`${kind}: './${kind}'\` in ${context.manifest}.`;+ continue;+ }+ // Moving this root out of the outermost root clears every root around it.+ if (other === dir) {+ return free+ ? `${note} The ${kind} root is also ${at}; move the ${ROOT_HOLDS[key]} there into ${key}/ and set \`${key}: './${key}'\` in ${context.manifest}.`+ : `${note} The ${kind} root is also ${at}; move the ${ROOT_HOLDS[key]} there into a folder of their own and set \`${key}\` to that folder in ${context.manifest}.`;+ }+ return free+ ? `${note} The ${kind} root ${place(context, other)} also reads ${at}; move ${at} to ${key}/ and set \`${key}: './${key}'\` in ${context.manifest}.`+ : `${note} The ${kind} root ${place(context, other)} also reads ${at}; move ${at} out of it and set \`${key}\` to its new path in ${context.manifest}.`;+ }+ return note;+}++/**+ * @param {FixContext} context+ * @param {string} file+ * @param {ContributionStamp} stamp+ */+function themeSlug(context, file, stamp) {+ const themeDir = path.dirname(file);+ if (stamp.name) return stamp.name;+ return themeDir === context.packageDir+ ? docStem(file)+ : path.basename(themeDir);+}++/**+ * What to move for a theme: its whole folder when the folder holds only this+ * theme and does not hold the target, else the descriptor and its source.+ * @param {FixContext} context+ * @param {string} file+ * @param {string} [target] the folder it moves to+ * @returns {{what: string, folder: boolean}}+ */+function themeFiles(context, file, target) {+ const themeDir = path.dirname(file);+ if (+ themeDir !== context.packageDir &&+ (target === undefined || !pathIsInside(target, themeDir)) &&+ !declaredRoots(context).some(root => pathIsInside(root, themeDir))+ ) {+ const found = candidatesUnder(context, themeDir);+ if (found?.length === 1 && found[0] === file) {+ return {what: `${shown(context, themeDir)}/`, folder: true};+ }+ }+ const sources = sourcesBeside(file, 'theme');+ const doc = path.basename(file);+ if (sources.length === 0) return {what: doc, folder: false};+ if (sources.length > 1) {+ return {+ what: `${doc} and its same-stem sources (with any local files they import)`,+ folder: false,+ };+ }+ return {+ what: `${doc} and ${sources[0]} (with any local files it imports)`,+ folder: false,+ };+}++/**+ * @param {FixContext} context+ * @param {string} file+ * @param {ContributionStamp} stamp+ * @param {string} root the themes root the theme moves under+ * @param {string} [slug] the folder it takes there+ */+function moveTheme(+ context,+ file,+ stamp,+ root,+ slug = themeSlug(context, file, stamp),+) {+ const {what, folder} = themeFiles(context, file, path.join(root, slug));+ const target = `${root === context.packageDir ? '' : `${shown(context, root)}/`}${slug}/`;+ return folder ? `move ${what} to ${target}` : `move ${what} into ${target}`;+}++/**+ * Moving metadata under its kind's declared root.+ * @param {FixContext} context+ * @param {string} file+ * @param {ContributionStamp} stamp+ * @param {string} root+ * @param {string} [destination] the theme folder, as the fix names it+ * @returns {{main: string, notes: string}}+ */+function moveUnder(context, file, stamp, root, destination) {+ const key = ROOT_FOR_TYPE[stamp.type];+ const overlap = overlapNote(context, root, key);+ if (key === 'themes') {+ const slugDir = path.join(root, themeSlug(context, file, stamp));+ const taken = hasEntry(root, path.basename(slugDir));+ const imports = themeImportNote(+ context,+ file,+ destination ??+ (taken ? `${place(context, root)}<slug>/` : place(context, slugDir)),+ );+ const notes = sourceNote(file, stamp.type) + imports + overlap;+ if (taken) {+ return {+ main: `${place(context, slugDir)} is taken, so give this theme a new lower-kebab slug: ${moveTheme(context, file, stamp, root, '<slug>')} and set \`name\` in ${path.basename(file)} to <slug>`,+ notes,+ };+ }+ return {main: moveTheme(context, file, stamp, root), notes};+ }+ const [source] = sourcesBeside(file, stamp.type);+ const taken = takenIn(context, file, stamp, root);+ if (taken) {+ const name = key === 'components' ? '<Name>' : '<name>';+ const suffix = path.basename(file).slice(docStem(file).length);+ const renamed = source+ ? `rename it and ${source} to ${name}${suffix} and ${name}.tsx`+ : `rename it to ${name}${suffix}`;+ const missing =+ stamp.type === 'generic' || source+ ? ''+ : ` Also add ${name}.tsx beside it.`;+ return {+ main: `${place(context, root)} already has ${taken}, so give this one a new name: ${renamed}, set its \`name\` to ${name}, and move ${source ? 'them' : 'it'} under ${place(context, root)} (the ${key} root)`,+ notes: missing + overlap,+ };+ }+ return {+ main: `move ${source ? `it and ${source}` : 'it'} under ${place(context, root)} (the ${key} root)`,+ notes: sourceNote(file, stamp.type) + overlap,+ };+}++/**+ * Moving metadata whose kind has no root yet: into the conventional folder,+ * when that folder would read cleanly as the new root.+ * @param {FixContext} context+ * @param {string} file+ * @param {ContributionStamp} stamp+ * @returns {{main: string, notes: string}}+ */+function moveToNewRoot(context, file, stamp) {+ const key = ROOT_FOR_TYPE[stamp.type];+ const target = path.join(context.packageDir, key);+ const declare = `set \`${key}: './${key}'\` in ${context.manifest}`;+ const pointAtIt = `set \`${key}\` to that folder in ${context.manifest}`;+ const notes = sourceNote(file, stamp.type);+ const picked = notes + overlapNote(context, undefined, key);+ if (key === 'themes') {+ const themeDir = path.dirname(file);+ const slug = themeSlug(context, file, stamp);+ const slugDir = path.join(target, slug);+ const clear =+ isFreeFolder(context, target) &&+ readsAsThemesRoot(context, target, {+ except: path.dirname(themeDir) === target ? themeDir : undefined,+ ignore: file,+ fixing: file,+ }) &&+ (slugDir === themeDir || !fs.existsSync(slugDir));+ if (clear && slugDir === themeDir) {+ return {+ main: declare,+ notes: notes + themeImportNote(context, file, place(context, themeDir)),+ };+ }+ if (clear) {+ return {+ main: `${moveTheme(context, file, stamp, target)} and ${declare}`,+ notes: notes + themeImportNote(context, file, place(context, slugDir)),+ };+ }+ const {what, folder} = themeFiles(context, file);+ return {+ main: folder+ ? `move ${what} into a folder that holds only themes, as ${slug}/, and ${pointAtIt}`+ : `move ${what} into a ${slug}/ folder inside a folder that holds only themes, and ${pointAtIt}`,+ notes:+ notes ++ themeImportNote(context, file, 'the theme folder') ++ overlapNote(context, undefined, key),+ };+ }+ const [source] = sourcesBeside(file, stamp.type);+ const what = source ? `it and ${source}` : 'it';+ const clear = fs.existsSync(target)+ ? canBeRoot(context, target, key, file) &&+ takenIn(context, file, stamp, target) == null+ : isFreeFolder(context, target);+ if (clear) return {main: `move ${what} into ${key}/ and ${declare}`, notes};+ return {+ main: `move ${what} into a folder that holds only ${ROOT_HOLDS[key]}, and ${pointAtIt}`,+ notes: picked,+ };+}++/**+ * The fix for contribution metadata that sits outside every declared root.+ * @param {FixContext} context+ * @param {string} file+ * @param {ContributionStamp} stamp+ * @returns {string}+ */+export function unreachableFix(context, file, stamp) {+ const key = ROOT_FOR_TYPE[stamp.type];+ const root = context.roots[key];+ // A theme is a directory under the themes root, so the root is its parent.+ const folder = path.dirname(key === 'themes' ? path.dirname(file) : file);+ const declare = `set \`${key}: './${shown(context, folder)}'\` in ${context.manifest}`;+ const folderCanBeRoot = canBeRoot(context, folder, key, file);+ const stays =+ sourceNote(file, stamp.type) ++ (key === 'themes'+ ? themeImportNote(context, file, place(context, path.dirname(file)))+ : '');+ if (root) {+ // Swapping roots would orphan whatever the declared root already reads.+ const swappable =+ folderCanBeRoot && candidatesUnder(context, root)?.length === 0;+ if (swappable && overlapNote(context, root, key) !== '') {+ return `Fix: ${declare}.${stays}`;+ }+ const {main, notes} = moveUnder(+ context,+ file,+ stamp,+ root,+ swappable ? 'the theme folder' : undefined,+ );+ return `Fix: ${main}${swappable ? `, or ${declare}` : ''}.${notes}`;+ }+ if (folderCanBeRoot) return `Fix: ${declare}.${stays}`;+ const {main, notes} = moveToNewRoot(context, file, stamp);+ return `Fix: ${main}.${notes}`;+}++/**+ * Whether the components can move into `dir` out of a components root at the+ * package root: it is missing, or holds only component docs, a doc for every+ * source, and no other root.+ * @param {FixContext} context+ * @param {string} dir+ */+function holdsOnlyComponents(context, dir) {+ if (!fs.existsSync(dir)) return true;+ const found = candidatesUnder(context, dir);+ return (+ found != null &&+ found.every(file => stampOf(context, file)?.type === 'component') &&+ uncoveredSources(dir, found).length === 0 &&+ !METADATA_ROOTS.some(kind => {+ const root = context.roots[kind];+ return kind !== 'components' && root != null && pathIsInside(root, dir);+ })+ );+}++/**+ * The step a component doc added to the components root also needs when+ * another root reads that folder too, and would read the new doc as its own.+ * @param {FixContext} context+ * @returns {string} a sentence with a leading space, or ''+ */+export function newComponentDocNote(context) {+ const components = context.roots.components;+ return components ? overlapNote(context, components, 'components') : '';+}++/**+ * The theme beside \`file\` whose source imports it, if any: such a file is+ * part of that theme, not a codemod.+ * @param {FixContext} context+ * @param {string} file+ * @returns {{doc: string, stamp: ContributionStamp, source: string} | null}+ */+export function themeImporting(context, file) {+ const dir = path.dirname(file);+ let entries;+ try {+ entries = fs.readdirSync(dir);+ } catch {+ return null;+ }+ for (const name of entries.filter(entry => DOC_CANDIDATE_RE.test(entry))) {+ const doc = path.join(dir, name);+ const stamp = stampOf(context, doc);+ const [source] = stamp?.type === 'theme' ? sourcesBeside(doc, 'theme') : [];+ if (!stamp || !source) continue;+ const edges = localImports(path.join(dir, source));+ if (edges?.some(edge => edge.target === file)) return {doc, stamp, source};+ }+ return null;+}++/**+ * The fix for contribution metadata at the top of the codemods root, which+ * the codemod checks read as a stray codemod. `source` names that doc's theme+ * source when the stray file is the source rather than the doc.+ * @param {FixContext} context+ * @param {string} file the metadata doc+ * @param {ContributionStamp} stamp+ * @param {string} [source]+ * @param {string} [stray] a file that source imports, when the stray file is+ * that one+ * @returns {string}+ */+export function notACodemodFix(context, file, stamp, source, stray) {+ const key = ROOT_FOR_TYPE[stamp.type];+ const root = context.roots[key];+ const codemods = context.roots.codemods;+ let lead = `Fix: ${path.basename(file)} has type: '${stamp.type}', so it is not a codemod`;+ if (source && stray) {+ lead = `Fix: ${stray} is imported by ${source}, the source of ${path.basename(file)}, which has type: '${stamp.type}', so none of them is a codemod`;+ } else if (source) {+ lead = `Fix: ${source} is the source of ${path.basename(file)}, which has type: '${stamp.type}', so neither is a codemod`;+ }+ if (root && codemods && pathIsInside(file, root)) {+ // Its own root reads it already; only the codemods root is in the way.+ const [companion] = sourcesBeside(file, stamp.type);+ return `${lead}; move ${path.basename(file)}${companion ? ` and ${companion}` : ''} out of ${place(context, codemods)} to another folder under ${place(context, root)} (the ${key} root).${sourceNote(file, stamp.type)}${overlapNote(context, root, key)}`;+ }+ const {main, notes} = root+ ? moveUnder(context, file, stamp, root)+ : moveToNewRoot(context, file, stamp);+ return `${lead}; ${main}.${notes}`;+}++/**+ * The fix for a doc that the components root reads although its type says it+ * is another kind of metadata.+ * @param {FixContext} context+ * @param {string} file+ * @param {ContributionStamp} stamp a stamp whose type is not `component`+ * @returns {string}+ */+export function notAComponentFix(context, file, stamp) {+ const components = /** @type {string} */ (context.roots.components);+ const key = ROOT_FOR_TYPE[stamp.type];+ const root = context.roots[key];+ const lead = `Fix: ${path.basename(file)} has type: '${stamp.type}', so it is not a component`;+ if (components === context.packageDir) {+ const why = `${lead}, and the components root is the package root, which reads every doc in the package`;+ const target = path.join(context.packageDir, 'components');+ return holdsOnlyComponents(context, target)+ ? `${why}; create components/, move the components into it, and set \`components: './components'\` in ${context.manifest}.${overlapNote(context, target, 'components')}`+ : `${why}; move the components into a folder that holds only components, and set \`components\` to that folder in ${context.manifest}.${overlapNote(context, undefined, 'components')}`;+ }+ if (root && pathIsInside(root, components)) {+ const {main, notes} = separateRoots(context, file, stamp, root);+ return `${lead}, and ${main}.${sourceNote(file, stamp.type)}${notes}`;+ }+ if (root && pathIsInside(file, root)) {+ return `${lead}; move it out of ${place(context, components)} (the components root) to another folder under ${place(context, root)} (the ${key} root).${sourceNote(file, stamp.type)}${overlapNote(context, root, key)}`;+ }+ const {main, notes} = root+ ? moveUnder(context, file, stamp, root)+ : moveToNewRoot(context, file, stamp);+ return `${lead}; ${main}.${notes}`;+}++/**+ * The fix when a kind's root sits inside the components root, so nothing+ * placed in it escapes the components root.+ * @param {FixContext} context+ * @param {string} file+ * @param {ContributionStamp} stamp+ * @param {string} root the declared root for this kind+ * @returns {{main: string, notes: string}}+ */+function separateRoots(context, file, stamp, root) {+ const components = /** @type {string} */ (context.roots.components);+ const key = ROOT_FOR_TYPE[stamp.type];+ const target = path.join(context.packageDir, key);+ const free = !fs.existsSync(target) && isFreeFolder(context, target);+ const picked = overlapNote(context, undefined, key);+ if (root === components) {+ const both = `the ${key} root and the components root are both ${place(context, root)}`;+ return free+ ? {+ main: `${both}; move the ${ROOT_HOLDS[key]} into ${key}/ and set \`${key}: './${key}'\` in ${context.manifest}`,+ notes: '',+ }+ : {+ main: `${both}; move the ${ROOT_HOLDS[key]} into a folder of their own and set \`${key}\` to that folder in ${context.manifest}`,+ notes: picked,+ };+ }+ const overlap = `the components root ${place(context, components)} also reads the ${key} root ${place(context, root)} inside it`;+ const carried = pathIsInside(file, root);+ // The root's contents move with it, so a name it holds is still taken.+ const slug = themeSlug(context, file, stamp);+ const taken =+ !carried &&+ (key === 'themes'+ ? hasEntry(root, slug)+ : takenIn(context, file, stamp, root) != null);+ const [source] = sourcesBeside(file, stamp.type);+ const name = '<name>';+ const suffix = path.basename(file).slice(docStem(file).length);+ const renamed = `give it a new name: ${source ? `rename it and ${source} to ${name}${suffix} and ${name}.tsx` : `rename it to ${name}${suffix}`}, set its \`name\` to ${name}, and move ${source ? 'them' : 'it'}`;+ const newSlug = taken ? '<slug>' : slug;+ const slugNote = taken+ ? ` and set \`name\` in ${path.basename(file)} to <slug>`+ : '';+ if (free) {+ let then = '';+ if (!carried && key === 'themes') {+ then = `, then ${moveTheme(context, file, stamp, target, newSlug)}${slugNote}`;+ } else if (!carried) {+ then = `, then ${taken ? renamed : 'move it'} into ${key}/`;+ }+ return {+ main: `${overlap}; move ${place(context, root)} to ${key}/ and set \`${key}: './${key}'\` in ${context.manifest}${then}`,+ notes: '',+ };+ }+ let then = '';+ if (!carried && key === 'themes') {+ const {what, folder} = themeFiles(context, file, root);+ then = folder+ ? `, then move ${what} into that root as ${newSlug}/${slugNote}`+ : `, then move ${what} into a ${newSlug}/ folder in that root${slugNote}`;+ } else if (!carried) {+ then = `, then ${taken ? renamed : 'move it'} into that root`;+ }+ return {+ main: `${overlap}; move ${place(context, root)} out of ${place(context, components)} and set \`${key}\` to its new path in ${context.manifest}${then}`,+ notes: picked,+ };+}diff --git a/packages/cli/foundation/integrations/contribution-inventory.mjs b/packages/cli/foundation/integrations/contribution-inventory.mjsindex 917a0d82f2..61dffc7dfe 100644--- a/packages/cli/foundation/integrations/contribution-inventory.mjs+++ b/packages/cli/foundation/integrations/contribution-inventory.mjs@@ -14,8 +14,11 @@import * as fs from 'node:fs';import * as path from 'node:path';import {isDeepStrictEqual} from 'node:util';-import {THEME_MANIFEST_BASENAME} from '../discovery/theme-discovery.mjs';-import {discoverIntegrationThemes} from '../discovery/theme-discovery.mjs';+import {+ discoverIntegrationThemes,+ isThemeFolder,+ listThemeFiles,+} from '../discovery/theme-discovery.mjs';import {discoverIntegrationComponents} from '../discovery/component-discovery.mjs';import {loadComponentDoc} from '../discovery/component-loader.mjs';import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';@@ -65,27 +68,21 @@ function rel(packageDir, file) {/** @param {string} root @param {string} pkgDir */function enumerateThemeFiles(root, pkgDir) {+ if (!root || !fs.existsSync(root) || !fs.statSync(root).isDirectory()) {+ return [];+ }+ // Exactly what `theme add` copies: each theme folder's files, including+ // tests and fixtures, but no dot entry or file npm never publishes. Files+ // beside the theme folders belong to no theme./** @type {string[]} */const files = [];- const catalog = path.join(root, THEME_MANIFEST_BASENAME);- if (!fs.existsSync(catalog)) return files;- files.push(rel(pkgDir, catalog));- try {- const data = JSON.parse(fs.readFileSync(catalog, 'utf-8'));- if (data?.version !== 1 || !Array.isArray(data.themes)) return files;- for (const theme of data.themes) {- if (typeof theme.slug !== 'string' || !Array.isArray(theme.files))- continue;- for (const f of theme.files) {- if (typeof f === 'string') {- files.push(rel(pkgDir, path.join(root, theme.slug, f)));- }- }+ for (const entry of fs.readdirSync(root, {withFileTypes: true})) {+ const full = path.join(root, entry.name);+ if (entry.isDirectory() && isThemeFolder(full)) {+ files.push(...listThemeFiles(full).map(file => path.join(full, file)));}- } catch {- /* Phase 1 catches structural issues */}- return files;+ return files.sort().map(file => rel(pkgDir, file));}/** @param {string} root @param {string} pkgDir */@@ -158,7 +155,7 @@ const ROOT_KINDS = /** @type {const} */ ([/*** Compute the files the tarball must contain for an integration's- * contributions to be visible. Reads catalogs and walks directories;+ * contributions to be visible. Walks descriptor-owned directories;* never imports or executes authored modules.** @param {import('./integrations.mjs').LoadedIntegration} loadeddiff --git a/packages/cli/foundation/integrations/contribution-inventory.test.mjs b/packages/cli/foundation/integrations/contribution-inventory.test.mjsindex 6b967da30e..98bf4b78d6 100644--- a/packages/cli/foundation/integrations/contribution-inventory.test.mjs+++ b/packages/cli/foundation/integrations/contribution-inventory.test.mjs@@ -37,30 +37,37 @@ function loaded(overrides = {}) {function writeTheme(slug, files = [`${slug}Theme.ts`]) {const root = path.join(tmpDir, 'themes');- fs.mkdirSync(path.join(root, slug), {recursive: true});- for (const f of files) {- fs.writeFileSync(path.join(root, slug, f), `// ${f}\n`);+ const themeDir = path.join(root, slug);+ fs.mkdirSync(themeDir, {recursive: true});+ for (const file of files) {+ const target = path.join(themeDir, file);+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.writeFileSync(target, `// ${file}\n`);}- const catalogPath = path.join(root, 'manifest.json');- let catalog = {version: 1, themes: []};- if (fs.existsSync(catalogPath)) {- catalog = JSON.parse(fs.readFileSync(catalogPath, 'utf-8'));- }- catalog.themes.push({- slug,- displayName: slug,- description: `${slug} theme.`,- maintained: true,- entry: files[0],- exportName: `${slug}Theme`,- files,- });- fs.writeFileSync(catalogPath, JSON.stringify(catalog, null, 2) + '\n');+ fs.writeFileSync(+ path.join(themeDir, `${slug}Theme.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: '${slug}', displayName: '${slug}', description: '${slug} theme.', maintained: true};\n`,+ );return root;}+const UNPUBLISHED = [+ '.DS_Store',+ '._oceanTheme.ts',+ '.gitignore',+ '.npmignore',+ '.npmrc',+ 'oceanTheme.ts.orig',+ 'npm-debug.log',+ 'palette/.DS_Store',+ 'palette/npm-debug.log',+ '.git/HEAD',+ 'CVS/Entries',+ 'node_modules/dep/index.js',+];+describe('computeRequiredFiles', () => {- it('enumerates manifest + theme catalog files', () => {+ it('enumerates each complete descriptor-owned theme directory', () => {const root = writeTheme('ocean', ['oceanTheme.ts', 'tokens.ts']);const inv = computeRequiredFiles(loaded({themes: root}));@@ -69,13 +76,46 @@ describe('computeRequiredFiles', () => {expect(inv.roots[0].kind).toBe('themes');expect(inv.roots[0].files).toEqual(expect.arrayContaining([- 'themes/manifest.json',+ 'themes/ocean/oceanTheme.doc.mjs','themes/ocean/oceanTheme.ts','themes/ocean/tokens.ts',]),);expect(inv.allFiles).toContain('astryx.integration.mjs');- expect(inv.allFiles).toContain('themes/manifest.json');+ expect(inv.allFiles).toContain('themes/ocean/oceanTheme.doc.mjs');+ expect(inv.allFiles).not.toContain('themes/manifest.json');+ });++ it('requires no file npm leaves out, at any depth, and none beside the themes', () => {+ const root = writeTheme('ocean', ['oceanTheme.ts', 'palette/tokens.ts']);+ for (const file of [+ ...UNPUBLISHED.map(name => `ocean/${name}`),+ 'README.md',+ 'npm-debug.log',+ ]) {+ fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true});+ fs.writeFileSync(path.join(root, file), 'x\n');+ }+ expect(computeRequiredFiles(loaded({themes: root})).roots[0].files).toEqual(+ [+ 'themes/ocean/oceanTheme.doc.mjs',+ 'themes/ocean/oceanTheme.ts',+ 'themes/ocean/palette/tokens.ts',+ ],+ );+ });++ it('requires only the folders theme discovery reads', () => {+ const root = writeTheme('ocean');+ for (const file of ['shared/palette.ts', '.cache/state.json']) {+ fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true});+ fs.writeFileSync(path.join(root, file), '{}\n');+ }+ const inv = computeRequiredFiles(loaded({themes: root}));+ expect(inv.roots[0].files).toEqual([+ 'themes/ocean/oceanTheme.doc.mjs',+ 'themes/ocean/oceanTheme.ts',+ ]);});it('enumerates paired component metadata and source files', () => {@@ -139,31 +179,31 @@ describe('computeRequiredFiles', () => {const root = path.join(tmpDir, 'templates');fs.mkdirSync(path.join(root, 'dashboard'), {recursive: true});fs.writeFileSync(- path.join(root, 'dashboard', 'dashboard.template.mjs'),+ path.join(root, 'dashboard', 'dashboard.doc.mjs'),'// tmpl\n',);fs.writeFileSync(path.join(root, 'dashboard', 'dashboard.tsx'), '// src\n');const inv = computeRequiredFiles(loaded({templates: root}));expect(inv.roots[0].files).toContain(- 'templates/dashboard/dashboard.template.mjs',+ 'templates/dashboard/dashboard.doc.mjs',);expect(inv.roots[0].files).toContain('templates/dashboard/dashboard.tsx');});- it('enumerates legacy .doc template metadata with paired sources', () => {+ it('enumerates released .template compatibility metadata with paired sources', () => {const root = path.join(tmpDir, 'templates');fs.mkdirSync(path.join(root, 'dashboard'), {recursive: true});fs.writeFileSync(- path.join(root, 'dashboard', 'dashboard.doc.mjs'),- '// legacy template\n',+ path.join(root, 'dashboard', 'dashboard.template.mjs'),+ '// released compatibility template\n',);fs.writeFileSync(path.join(root, 'dashboard', 'dashboard.tsx'), '// src\n');const inv = computeRequiredFiles(loaded({templates: root}));expect(inv.roots[0].files).toEqual([- 'templates/dashboard/dashboard.doc.mjs',+ 'templates/dashboard/dashboard.template.mjs','templates/dashboard/dashboard.tsx',]);});diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex ec47929311..7e9df230e7 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -29,6 +29,7 @@ import {} from '../../authoring/integration/schema.mjs';import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';import {parseGapReportHandler} from '../../authoring/gap-report/parse.mjs';+import {resolveProviders} from './provider-resolution.mjs';/*** A fully-resolved, loaded integration. Identity (`name`, `version`) comes from@@ -116,107 +117,20 @@ function providerIdForPackage(name) {* issues, Doctor, and the per-command warning name the one set aside instead of* dropping it without a word.*+ * The conflict pass of {@link resolveProviders}, for a list that is already+ * assembled.+ ** @param {LoadedIntegration[]} integrations in precedence order* @returns {LoadedIntegration[]}*/export function markProviderConflicts(integrations) {- /** @type {Map<string, LoadedIntegration>} */- const claims = new Map();- for (const integration of integrations) {- if (integration?.__local && claimsProvider(integration)) {- const providerId = /** @type {string} */ (integration.providerId);- if (!claims.has(providerId)) claims.set(providerId, integration);- }- }- /** @type {LoadedIntegration[]} */- const resolved = [];- for (const integration of integrations) {- if (!claimsProvider(integration)) {- resolved.push(integration);- continue;- }- const providerId = /** @type {string} */ (integration.providerId);- const claimant = claims.get(providerId);- if (claimant == null) {- claims.set(providerId, integration);- resolved.push(integration);- } else if (claimant === integration) {- resolved.push(integration);- } else if (- claimant.name !== integration.name ||- claimant.version !== integration.version- ) {- resolved.push(providerConflict(integration, claimant));- }- }- return resolved;-}--/**- * Whether an entry contributes under its provider ID: it has one, its manifest- * loaded, and it has not already been set aside.- * @param {LoadedIntegration | undefined} integration- * @returns {boolean}- */-function claimsProvider(integration) {- return (- integration?.providerId != null &&- integration.__loadError == null &&- integration.__providerConflict == null- );-}--/**- * @param {LoadedIntegration} integration- * @returns {string}- */-function describeIntegration(integration) {- const id = integration.version- ? `${integration.name}@${integration.version}`- : integration.name;- return integration.__spec && integration.__spec !== integration.name- ? `${id} (from "${integration.__spec}")`- : id;-}--/**- * An inert record for a package whose provider ID is already claimed. It keeps- * the package's identity and location for reporting, and drops every- * contribution root and handler.- * @param {LoadedIntegration} integration- * @param {LoadedIntegration} claimant- * @returns {LoadedIntegration}- */-function providerConflict(integration, claimant) {- const providerId =- /** @type {import('../../authoring/identity/type').ProviderId} */ (- integration.providerId- );- const winner = describeIntegration(claimant);- const setAside = describeIntegration(integration);- const reason = claimant.__local- ? 'is the package being authored, so it is used'- : 'loads first and is used';- return {- name: integration.name,- providerId,- version: integration.version,- __spec: integration.__spec,- __packageDir: integration.__packageDir,- __manifestFile: integration.__manifestFile,- ...(integration.__local ? {__local: true} : {}),- ...(integration.__autolinked- ? {__autolinked: true, __dependencyField: integration.__dependencyField}- : {}),- __providerConflict: {- providerId,- claimedBy: claimant.name,- message:- `${setAside} and ${winner} both claim provider ID "${providerId}". ` +- `${winner} ${reason}; ${setAside} contributes nothing ` +- 'until one package changes its providerId.',- },- };+ return resolveProviders(+ integrations.map(integration => ({+ source: /** @type {const} */ ('configured'),+ integration,+ spec: integration?.__spec,+ })),+ ).integrations;}/**diff --git a/packages/cli/foundation/integrations/provider-ledger.test.mjs b/packages/cli/foundation/integrations/provider-ledger.test.mjsnew file mode 100644index 0000000000..ffcc5ce8f9--- /dev/null+++ b/packages/cli/foundation/integrations/provider-ledger.test.mjs@@ -0,0 +1,275 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The provider ledger property: over seeded, generated projects, the+ * real Project.load and the real `upgrade` context account for every candidate+ * exactly once, and agree on the winner of every provider ID except where the+ * codemod policy says otherwise.+ *+ * The expected candidates come from the scenario description, never from the+ * resolver. Fixtures live under a repo-local temp dir, not /tmp, because Vite+ * refuses to dynamically import a module from outside the project root.+ */++import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {Project, providerLedgerOf} from '../config/project.mjs';+import {loadProjectContext} from '../../api/upgrade/_adapter.mjs';+import {+ expectedProjectInputs,+ generateScenario,+ isRunnable,+ writeScenario,+} from '../../test-utils/provider-scenarios.mjs';++// 200 seeds keep this near 4 s; any seed range must hold.+const SEEDS = Array.from({length: 200}, (_, index) => index + 1);+const OUTCOMES = ['contributes', 'set-aside', 'load-failed', 'alias-of'];++/** @type {string} */+let root;+/** @type {string} */+let originalCwd;++beforeAll(() => {+ originalCwd = process.cwd();+ root = fs.mkdtempSync(path.join(process.cwd(), '.astryx-provider-ledger-'));+});++afterAll(() => {+ process.chdir(originalCwd);+ fs.rmSync(root, {recursive: true, force: true});+});++/**+ * The contributing package for each provider ID. Fails when two contribute+ * under one ID.+ * @param {Map<string, any>} ledger+ * @returns {Map<string, any>}+ */+function winners(ledger) {+ /** @type {Map<string, any>} */+ const byProvider = new Map();+ for (const entry of ledger.values()) {+ if (entry.outcome !== 'contributes' || entry.providerId == null) continue;+ expect(byProvider.has(entry.providerId)).toBe(false);+ byProvider.set(entry.providerId, entry);+ }+ return byProvider;+}++/**+ * Assert the ledger records one outcome for exactly the given inputs.+ * @param {Map<string, any>} ledger+ * @param {Array<{source: string, spec: string, key: string}>} inputs+ */+function expectAccounted(ledger, inputs) {+ const refs = [...ledger.values()].flatMap(entry =>+ entry.refs.map(ref => ({entry, ref})),+ );+ for (const input of inputs) {+ const holders = refs.filter(+ ({ref}) => ref.source === input.source && ref.spec === input.spec,+ );+ expect(holders.map(({entry}) => entry.key)).toEqual([input.key]);+ }+ expect(refs).toHaveLength(inputs.length);+ expect(new Set(ledger.keys())).toEqual(+ new Set(inputs.map(input => input.key)),+ );+ for (const [key, entry] of ledger) {+ expect(entry.key).toBe(key);+ expect(OUTCOMES).toContain(entry.outcome);+ if (entry.outcome === 'set-aside') {+ expect(ledger.has(entry.winner)).toBe(true);+ expect(entry.reason).toEqual(expect.any(String));+ }+ if (entry.outcome === 'alias-of') {+ expect(ledger.has(entry.aliasOf)).toBe(true);+ }+ }+}++describe('provider ledger over generated projects', () => {+ it('accounts for every candidate once and agrees across Project and upgrade', async () => {+ const coverage = {+ scenarios: 0,+ setAside: 0,+ aliasOf: 0,+ loadFailed: 0,+ replaced: 0,+ agreed: 0,+ standIn: 0,+ extraReordered: 0,+ };++ for (const seed of SEEDS) {+ const scenario = generateScenario(seed);+ if (!isRunnable(scenario)) continue;+ coverage.scenarios++;+ const dir = path.join(root, `seed-${seed}`);+ fs.mkdirSync(dir);+ writeScenario(dir, scenario);+ const context = `seed ${seed}: ${JSON.stringify(scenario)}`;++ const project = await Project.load(dir, {fresh: true});+ const ledger = providerLedgerOf(project);+ const inputs = expectedProjectInputs(dir, scenario);+ try {+ expectAccounted(ledger, inputs);++ // Nothing leaves the list without a recorded reason.+ const listed = new Set(project.loadedIntegrations);+ for (const integration of project.loadedIntegrations) {+ expect(ledger.has(fs.realpathSync(integration.__packageDir))).toBe(+ true,+ );+ }+ for (const entry of ledger.values()) {+ if (entry.integration != null) {+ expect(listed.has(entry.integration)).toBe(true);+ continue;+ }+ expect(entry.outcome).not.toBe('contributes');+ if (entry.outcome === 'set-aside') {+ expect(entry.reason).toBe('replaced-by-authored');+ }+ if (entry.outcome === 'load-failed') {+ expect(entry.error).toEqual(expect.any(String));+ }+ }+ } catch (error) {+ throw new Error(`${context}\n${error}`, {cause: error});+ }++ for (const entry of ledger.values()) {+ if (entry.outcome === 'set-aside') coverage.setAside++;+ if (entry.outcome === 'alias-of') coverage.aliasOf++;+ if (entry.outcome === 'load-failed') coverage.loadFailed++;+ if (entry.reason === 'replaced-by-authored') coverage.replaced++;+ }++ // `--integration` specs resolve from the process cwd.+ process.chdir(dir);+ const upgrade = await loadProjectContext(dir, scenario.extras);+ process.chdir(originalCwd);++ const modules = path.join(dir, 'node_modules');+ /** @param {string} spec */+ const installedKey = spec =>+ fs.realpathSync(path.join(modules, ...spec.split('/')));+ /** @param {string} spec */+ const installedName = spec =>+ JSON.parse(+ fs.readFileSync(+ path.join(modules, ...spec.split('/'), 'package.json'),+ 'utf8',+ ),+ ).name;+ const configured = new Set(scenario.config ?? []);+ const extras = [...new Set(scenario.extras)].filter(+ spec => !configured.has(spec),+ );+ const {local} = scenario;+ const localKey = fs.realpathSync(dir);+ const selfListed = local != null && configured.has(local.name);+ // The codemod policy: the installed copy stands in for the package being+ // authored when it lists itself or is named with --integration.+ const localStandsIn =+ local != null &&+ (selfListed || extras.some(spec => installedName(spec) === local.name));++ try {+ // Upgrade accounts for everything Project did, plus its own inputs.+ expectAccounted(upgrade.ledger, [+ ...inputs,+ ...(selfListed+ ? [+ {+ source: 'installed',+ spec: local.name,+ key: installedKey(local.name),+ },+ ]+ : []),+ ...extras.map(spec => ({+ source: 'extra',+ spec,+ key: installedKey(spec),+ })),+ ]);+ } catch (error) {+ throw new Error(`${context}\n${error}`, {cause: error});+ }++ const projectWinners = winners(ledger);+ const upgradeWinners = winners(upgrade.ledger);+ for (const providerId of new Set([+ ...projectWinners.keys(),+ ...upgradeWinners.keys(),+ ])) {+ const inProject = projectWinners.get(providerId);+ const inUpgrade = upgradeWinners.get(providerId);+ const same =+ inProject != null &&+ inUpgrade != null &&+ (inProject.key === inUpgrade.key ||+ upgrade.ledger.get(inProject.key)?.aliasOf === inUpgrade.key);+ if (same) {+ coverage.agreed++;+ continue;+ }+ // The one documented exception, asserted explicitly: an installed+ // copy took the authored package's place, so either upgrade's winner+ // is an installed copy of that package, or Project's winner is the+ // authored package it replaced.+ const upgradeName =+ inUpgrade?.integration?.name ??+ inUpgrade?.candidate.integration?.name;+ const standInWins =+ localStandsIn && inUpgrade != null && upgradeName === local?.name;+ const localReplaced =+ localStandsIn && inProject != null && inProject.key === localKey;+ // Project never saw an extra, so an ID only an extra claims has no+ // Project winner to agree with.+ const extraOnly =+ inProject == null && inUpgrade?.candidate.source === 'extra';+ // Known disagreement, pinned by the `it.fails` repros in+ // api/upgrade/provider-agreement.test.mjs: upgrade replaces an+ // autolinked winner with any extra of the same name@version, from+ // any directory, and orders it with the extras. Another extra can+ // then win, or nothing does, in upgrade only.+ const projectWinnerInUpgrade =+ inProject == null ? undefined : upgrade.ledger.get(inProject.key);+ const repeatedByExtra =+ projectWinnerInUpgrade != null &&+ (projectWinnerInUpgrade.refs.some(ref => ref.source === 'extra') ||+ (projectWinnerInUpgrade.outcome === 'alias-of' &&+ upgrade.ledger+ .get(projectWinnerInUpgrade.aliasOf)+ ?.refs.some(ref => ref.source === 'extra')));+ const extraReordered =+ inProject?.candidate.source === 'autolinked' && repeatedByExtra;+ if (extraReordered) {+ coverage.extraReordered++;+ continue;+ }+ expect(+ standInWins || localReplaced || extraOnly,+ `${context}\nprovider ${providerId}: Project ${inProject?.label ?? 'none'} vs upgrade ${inUpgrade?.label ?? 'none'}`,+ ).toBe(true);+ if (standInWins || localReplaced) coverage.standIn++;+ }+ }++ // The generator must keep reaching every shape, or the property is vacuous.+ expect(coverage.scenarios).toBeGreaterThanOrEqual(190);+ expect(coverage.setAside).toBeGreaterThan(0);+ expect(coverage.aliasOf).toBeGreaterThan(0);+ expect(coverage.loadFailed).toBeGreaterThan(0);+ expect(coverage.replaced).toBeGreaterThan(0);+ expect(coverage.agreed).toBeGreaterThan(0);+ expect(coverage.standIn).toBeGreaterThan(0);+ }, 120_000);+});diff --git a/packages/cli/foundation/integrations/provider-resolution.mjs b/packages/cli/foundation/integrations/provider-resolution.mjsnew file mode 100644index 0000000000..18606c9254--- /dev/null+++ b/packages/cli/foundation/integrations/provider-resolution.mjs@@ -0,0 +1,576 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Provider resolution — one resolver and one package identity for every+ * path that decides which integration package contributes under a provider ID.+ *+ * Project resolves configured, then autolinked, then local packages here.+ * `upgrade` resolves the same set plus its own candidates here, under the+ * codemod policy. `markProviderConflicts` is a wrapper over the same conflict+ * pass. Besides the resolved list, every resolution returns a ledger with+ * exactly one outcome for every package directory it was handed, so no+ * candidate can leave the list without a record.+ *+ * Identity is the real package directory. `name@version` labels an entry for+ * display. It also decides whether two DIFFERENT directories hold one published+ * package (an npm alias installed as a copy), because precedence has always+ * treated those as one package, but it never keys the ledger.+ *+ * @input Candidates in precedence order, each a loaded integration record or a+ * load failure, tagged with the source that reached it; a policy.+ * @output The resolved LoadedIntegration list, and the ledger keyed by real+ * package directory.+ * @position foundation/integrations — the only place precedence is decided;+ * callers load packages, this module picks winners.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++/**+ * @typedef {import('./integrations.mjs').LoadedIntegration} LoadedIntegration+ */++/**+ * Where a candidate came from. Precedence follows candidate order; the source+ * selects which rules apply.+ * - `configured`: named by astryx.config; listed even when its manifest fails+ * - `autolinked`: a declared dependency that ships one root manifest+ * - `local`: the package being authored, loaded from its working bytes+ * - `installed`: codemod policy — the installed copy of a package being+ * authored that lists itself+ * - `extra`: codemod policy — a package named with `upgrade --integration`+ * @typedef {'configured' | 'autolinked' | 'local' | 'installed' | 'extra'} CandidateSource+ */++/**+ * One package reached by one input. A candidate without `integration` failed+ * to load (`error`) or reached a directory an earlier candidate already+ * reached (`repeat`).+ * @typedef {object} ProviderCandidate+ * @property {CandidateSource} source+ * @property {LoadedIntegration} [integration]+ * @property {string} [spec] the input that reached the package+ * @property {string} [packageDir] required when `integration` is absent+ * @property {string} [error] why loading threw+ * @property {boolean} [repeat] another input for a directory already reached+ */++/**+ * @typedef {'contributes' | 'set-aside' | 'load-failed' | 'alias-of'} ProviderOutcome+ */++/**+ * Why a package is set aside.+ * - `claimed-earlier`: a package earlier in precedence claims its provider ID+ * - `authored-claims`: the package being authored claims its provider ID+ * - `replaced-by-authored`: it is the installed copy of the package being+ * authored, whose working bytes are used instead+ * - `installed-stands-in`: codemod policy — the package being authored is+ * represented by its installed copy+ * @typedef {'claimed-earlier' | 'authored-claims' | 'replaced-by-authored' | 'installed-stands-in'} SetAsideReason+ */++/**+ * The one outcome for one real package directory.+ * @typedef {object} ProviderLedgerEntry+ * @property {string} key real package directory+ * @property {string} label `name@version`, for display only+ * @property {ProviderOutcome} outcome+ * @property {ProviderCandidate} candidate the candidate this outcome belongs to+ * @property {ProviderCandidate[]} refs every candidate that reached this+ * directory, in order+ * @property {string} [providerId]+ * @property {string} [winner] set-aside: key of the package used instead+ * @property {SetAsideReason} [reason] set-aside: why+ * @property {string} [aliasOf] alias-of: key of the package this one repeats+ * @property {LoadedIntegration} [integration] the record this package left in+ * the resolved list, when it left one+ * @property {string} [error] load-failed: the load error+ */++/** @typedef {Map<string, ProviderLedgerEntry>} ProviderLedger */++/**+ * @typedef {object} ProviderPolicy+ * @property {boolean} [codemods] upgrade's codemod rule. Candidates are an+ * already resolved Project list plus `installed` and `extra` candidates. The+ * installed copy stands in for a package being authored that lists itself or+ * is named as an extra, and an extra stands in for the autolinked package it+ * repeats. Autolinked and local packages still claim provider IDs, but they+ * are not listed: upgrade has never run their codemods.+ * @property {ProviderLedger} [prior] the ledger this resolution builds on. A+ * record it already set aside keeps that winner, and its entries this+ * resolution never reaches are carried over unchanged.+ */++/**+ * @typedef {object} CandidateState+ * @property {ProviderCandidate} candidate+ * @property {LoadedIntegration | undefined} record+ * @property {string} key+ * @property {ProviderOutcome} [outcome]+ * @property {CandidateState} [winner]+ * @property {SetAsideReason} [reason]+ * @property {CandidateState} [aliasOf]+ * @property {LoadedIntegration} [listed]+ */++/**+ * @typedef {object} Slot+ * @property {CandidateState} state+ * @property {LoadedIntegration} record+ */++/** Lower wins when several candidates reach one directory. */+const OUTCOME_RANK = /** @type {const} */ ({+ contributes: 0,+ 'set-aside': 1,+ 'load-failed': 2,+ 'alias-of': 3,+});++/**+ * The identity of a package directory: its real path, so every symlinked+ * spelling of one pnpm store entry is one package.+ * @param {string} packageDir+ * @returns {string}+ */+export function packageKey(packageDir) {+ try {+ return fs.realpathSync(packageDir);+ } catch {+ return path.resolve(packageDir);+ }+}++/**+ * @param {ProviderCandidate} candidate+ * @param {number} index+ * @returns {string}+ */+function candidateKey(candidate, index) {+ const dir = candidate.integration?.__packageDir ?? candidate.packageDir;+ // Only a hand-built record lacks a directory; it is its own package.+ return typeof dir === 'string' && dir.length > 0+ ? packageKey(dir)+ : `#${index}`;+}++/**+ * Whether an entry contributes under its provider ID: it has one, its manifest+ * loaded, and it has not already been set aside.+ * @param {LoadedIntegration | undefined} integration+ * @returns {boolean}+ */+function claimsProvider(integration) {+ return (+ integration?.providerId != null &&+ integration.__loadError == null &&+ integration.__providerConflict == null+ );+}++/**+ * The display label of a package: `name@version`, plus the spec that reached+ * it when that differs from the name.+ * @param {LoadedIntegration} integration+ * @returns {string}+ */+function describeIntegration(integration) {+ const id = integration.version+ ? `${integration.name}@${integration.version}`+ : integration.name;+ return integration.__spec && integration.__spec !== integration.name+ ? `${id} (from "${integration.__spec}")`+ : id;+}++/**+ * An inert record for a package whose provider ID is already claimed. It keeps+ * the package's identity and location for reporting, and drops every+ * contribution root and handler.+ * @param {LoadedIntegration} integration+ * @param {LoadedIntegration} claimant+ * @returns {LoadedIntegration}+ */+function providerConflict(integration, claimant) {+ const providerId =+ /** @type {import('../../authoring/identity/type').ProviderId} */ (+ integration.providerId+ );+ const winner = describeIntegration(claimant);+ const setAside = describeIntegration(integration);+ const reason = claimant.__local+ ? 'is the package being authored, so it is used'+ : 'loads first and is used';+ return {+ name: integration.name,+ providerId,+ version: integration.version,+ __spec: integration.__spec,+ __packageDir: integration.__packageDir,+ __manifestFile: integration.__manifestFile,+ ...(integration.__local ? {__local: true} : {}),+ ...(integration.__autolinked+ ? {__autolinked: true, __dependencyField: integration.__dependencyField}+ : {}),+ __providerConflict: {+ providerId,+ claimedBy: claimant.name,+ message:+ `${setAside} and ${winner} both claim provider ID "${providerId}". ` ++ `${winner} ${reason}; ${setAside} contributes nothing ` ++ 'until one package changes its providerId.',+ },+ };+}++/**+ * `name@version`, the display label of a package.+ * @param {LoadedIntegration} integration+ * @returns {string}+ */+function packageLabel(integration) {+ return integration.version+ ? `${integration.name}@${integration.version}`+ : integration.name;+}++/**+ * One published package at one version. Two directories that share it hold+ * the same package; it never keys the ledger.+ * @param {LoadedIntegration} integration+ * @returns {string}+ */+function publishedIdentity(integration) {+ return `${integration.name}\u0000${integration.version ?? ''}`;+}++/**+ * @param {CandidateState} state+ * @param {ProviderOutcome} outcome+ * @param {Partial<Pick<CandidateState, 'winner' | 'reason' | 'aliasOf' | 'listed'>>} [detail]+ */+function settle(state, outcome, detail = {}) {+ state.outcome = outcome;+ state.winner = detail.winner;+ state.reason = detail.reason;+ state.aliasOf = detail.aliasOf;+ state.listed = detail.listed;+}++/**+ * Project precedence: configured packages in config order, then autolinked+ * packages that do not repeat one already loaded, then the package being+ * authored, which replaces the first entry with its name.+ * @param {CandidateState[]} states+ * @returns {Slot[]}+ */+function assembleProject(states) {+ /** @type {Slot[]} */+ const slots = [];+ // Published identities of configured entries and of kept autolinked ones.+ /** @type {Map<string, CandidateState>} */+ const loaded = new Map();+ for (const state of states) {+ const {candidate, record} = state;+ if (candidate.repeat) {+ settle(state, 'alias-of');+ continue;+ }+ if (candidate.source === 'autolinked') {+ // A dependency the project never named cannot fail its load, so a+ // broken one is recorded here and listed nowhere.+ if (record == null || record.__loadError != null) {+ settle(state, 'load-failed');+ continue;+ }+ const repeated = loaded.get(publishedIdentity(record));+ if (repeated != null) {+ settle(state, 'alias-of', {aliasOf: repeated});+ continue;+ }+ loaded.set(publishedIdentity(record), state);+ slots.push({state, record});+ continue;+ }+ if (candidate.source === 'local' && record != null) {+ const replaced = slots.findIndex(+ slot => slot.record?.name === record.name,+ );+ if (replaced === -1) {+ slots.push({state, record});+ } else {+ settle(slots[replaced].state, 'set-aside', {+ winner: state,+ reason: 'replaced-by-authored',+ });+ slots[replaced] = {state, record};+ }+ continue;+ }+ if (record != null && typeof record === 'object') {+ const identity = publishedIdentity(record);+ if (!loaded.has(identity)) loaded.set(identity, state);+ }+ slots.push({state, record: /** @type {LoadedIntegration} */ (record)});+ }+ return slots;+}++/**+ * Upgrade precedence under the codemod policy, over an already resolved+ * Project list: configured packages (the installed copy in place of a package+ * being authored that lists itself), then claimants, then extras.+ * @param {CandidateState[]} states+ * @returns {{slots: Slot[], claimants: CandidateState[]}}+ */+function assembleCodemods(states) {+ const configured = states.filter(+ state => state.candidate.source === 'configured' && !state.candidate.repeat,+ );+ const installed = states.filter(+ state => state.candidate.source === 'installed',+ );+ const extras = states.filter(state => state.candidate.source === 'extra');+ const local = states.find(+ state => state.record?.__local && !state.candidate.repeat,+ );+ const selfListed = local != null && configured.includes(local);++ /** @type {CandidateState[]} */+ const participants = [...configured];+ if (local != null && selfListed && installed.length > 0) {+ participants.splice(participants.indexOf(local), 1, ...installed);+ settle(local, 'set-aside', {+ winner: installed[0],+ reason: 'installed-stands-in',+ });+ }+ const namedLocal =+ local == null+ ? undefined+ : extras.find(extra => extra.record?.name === local.record?.name);+ const localStandsIn = local != null && (selfListed || namedLocal != null);+ if (local != null && !selfListed && namedLocal != null) {+ settle(local, 'set-aside', {+ winner: namedLocal,+ reason: 'installed-stands-in',+ });+ }++ /** @type {Map<string, CandidateState>} */+ const extraIdentities = new Map();+ for (const extra of extras) {+ if (extra.record == null) continue;+ const identity = publishedIdentity(extra.record);+ if (!extraIdentities.has(identity)) extraIdentities.set(identity, extra);+ }+ /** @type {CandidateState[]} */+ const claimants = [];+ for (const state of states) {+ const {candidate, record} = state;+ if (candidate.repeat || record == null) continue;+ const claimant =+ candidate.source === 'autolinked' ||+ (candidate.source === 'local' && !localStandsIn);+ if (!claimant) continue;+ const named = extraIdentities.get(publishedIdentity(record));+ if (named != null) {+ settle(state, 'alias-of', {aliasOf: named});+ continue;+ }+ claimants.push(state);+ }++ for (const state of states) {+ if (state.candidate.repeat) settle(state, 'alias-of');+ }++ const slots = [...participants, ...claimants, ...extras].map(state => ({+ state,+ record: /** @type {LoadedIntegration} */ (state.record),+ }));+ return {slots, claimants};+}++/**+ * The provider-ID pass over assembled entries. The package being authored+ * claims first; everything else claims in order. A later claimant that is the+ * same published package as the winner is the same package reached twice and+ * loads once; any other later claimant becomes an inert conflict record.+ * @param {Slot[]} slots+ * @returns {LoadedIntegration[]}+ */+function markConflicts(slots) {+ /** @type {Map<string, Slot>} */+ const claims = new Map();+ for (const slot of slots) {+ if (slot.record?.__local && claimsProvider(slot.record)) {+ const providerId = /** @type {string} */ (slot.record.providerId);+ if (!claims.has(providerId)) claims.set(providerId, slot);+ }+ }+ /** @type {LoadedIntegration[]} */+ const resolved = [];+ for (const slot of slots) {+ const {state, record} = slot;+ if (!claimsProvider(record)) {+ resolved.push(record);+ if (record?.__providerConflict != null) {+ settle(state, 'set-aside', {listed: record});+ } else if (record == null || record.__loadError != null) {+ settle(state, 'load-failed', {listed: record});+ } else {+ settle(state, 'contributes', {listed: record});+ }+ continue;+ }+ const providerId = /** @type {string} */ (record.providerId);+ const claimant = claims.get(providerId);+ if (claimant == null) {+ claims.set(providerId, slot);+ resolved.push(record);+ settle(state, 'contributes', {listed: record});+ } else if (claimant.record === record) {+ resolved.push(record);+ settle(state, 'contributes', {listed: record});+ } else if (+ claimant.record.name !== record.name ||+ claimant.record.version !== record.version+ ) {+ const conflict = providerConflict(record, claimant.record);+ resolved.push(conflict);+ settle(state, 'set-aside', {+ winner: claimant.state,+ reason: claimant.record.__local ? 'authored-claims' : 'claimed-earlier',+ listed: conflict,+ });+ } else {+ settle(state, 'alias-of', {aliasOf: claimant.state});+ }+ }+ return resolved;+}++/**+ * Fold candidate outcomes into one entry per real package directory. A+ * directory reached by several candidates keeps the strongest outcome among+ * them; every candidate stays listed in `refs`.+ * @param {CandidateState[]} states+ * @param {ProviderLedger | undefined} prior+ * @param {Set<LoadedIntegration>} listed records in the final list+ * @returns {ProviderLedger}+ */+function buildLedger(states, prior, listed) {+ /** @type {Map<string, CandidateState>} */+ const chosen = new Map();+ /** @type {Map<string, ProviderCandidate[]>} */+ const refs = new Map();+ for (const state of states) {+ const current = chosen.get(state.key);+ const outcome = state.outcome ?? 'load-failed';+ if (+ current == null ||+ OUTCOME_RANK[outcome] < OUTCOME_RANK[current.outcome ?? 'load-failed']+ ) {+ chosen.set(state.key, state);+ }+ const list = refs.get(state.key) ?? [];+ list.push(state.candidate);+ refs.set(state.key, list);+ }++ /** @type {ProviderLedger} */+ const ledger = new Map();+ for (const [key, state] of chosen) {+ const {candidate, record} = state;+ const outcome = state.outcome ?? 'load-failed';+ const previous = prior?.get(key);+ /** @type {ProviderLedgerEntry} */+ const entry = {+ key,+ label:+ record != null && typeof record === 'object' && record.name+ ? packageLabel(record)+ : (candidate.spec ?? key),+ outcome,+ candidate,+ // A resolution on top of a prior ledger re-reads that ledger's records;+ // only its own new inputs join the inputs already recorded there.+ refs:+ previous == null+ ? (refs.get(key) ?? [candidate])+ : [+ ...previous.refs,+ ...(refs.get(key) ?? []).filter(+ ref => ref.source === 'installed' || ref.source === 'extra',+ ),+ ],+ };+ if (record?.providerId != null) entry.providerId = record.providerId;+ if (outcome === 'set-aside') {+ const winner = state.winner?.key ?? previous?.winner;+ if (winner != null) entry.winner = winner;+ const reason = state.reason ?? previous?.reason;+ if (reason != null) entry.reason = reason;+ }+ if (outcome === 'alias-of') entry.aliasOf = state.aliasOf?.key ?? key;+ if (state.listed != null && listed.has(state.listed)) {+ entry.integration = state.listed;+ }+ const error = record?.__loadError ?? candidate.error;+ if (outcome === 'load-failed' && error != null) entry.error = error;+ ledger.set(key, entry);+ }+ for (const [key, entry] of prior ?? []) {+ if (!ledger.has(key)) ledger.set(key, entry);+ }+ return ledger;+}++/**+ * Resolve provider identity over candidates in precedence order.+ *+ * Returns the resolved integration list every command reads, and a ledger+ * with one outcome for every real package directory among the candidates:+ * `contributes`, `set-aside` (with the winner and a reason), `load-failed`, or+ * `alias-of` (the same published package already loaded from another+ * directory, or another input for a directory already reached).+ *+ * @param {ProviderCandidate[]} candidates in precedence order+ * @param {ProviderPolicy} [policy]+ * @returns {{integrations: LoadedIntegration[], ledger: ProviderLedger}}+ */+export function resolveProviders(candidates, policy = {}) {+ /** @type {CandidateState[]} */+ const states = candidates.map((candidate, index) => ({+ candidate,+ record: candidate.integration,+ key: candidateKey(candidate, index),+ }));++ /** @type {LoadedIntegration[]} */+ let integrations;+ if (policy.codemods) {+ const {slots, claimants} = assembleCodemods(states);+ const resolved = markConflicts(slots);+ // Claimants leave by package directory: the pass can hand one back as a+ // new conflict record, and upgrade must not report a package every other+ // command uses as set aside.+ const claimantDirs = new Set(+ claimants.map(state => state.record?.__packageDir),+ );+ integrations = resolved.filter(+ integration =>+ integration.__packageDir == null ||+ !claimantDirs.has(integration.__packageDir),+ );+ } else {+ integrations = markConflicts(assembleProject(states));+ }++ const ledger = buildLedger(states, policy.prior, new Set(integrations));+ return {integrations, ledger};+}diff --git a/packages/cli/foundation/integrations/provider-resolution.test.mjs b/packages/cli/foundation/integrations/provider-resolution.test.mjsnew file mode 100644index 0000000000..29749c1b43--- /dev/null+++ b/packages/cli/foundation/integrations/provider-resolution.test.mjs@@ -0,0 +1,369 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated tests for the provider resolver: one outcome per real package+ * directory, precedence, and the wrappers that keep their old results.+ *+ * Fixtures live under a repo-local temp dir, not /tmp, because Vite refuses to+ * dynamically import a module from outside the project root.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {packageKey, resolveProviders} from './provider-resolution.mjs';+import {markProviderConflicts} from './integrations.mjs';+import {autolinkIntegrations} from './autolink.mjs';+import {Project, providerLedgerOf} from '../config/project.mjs';++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-provider-resolution-'),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/**+ * A loaded-integration record in a real directory.+ * @param {string} dir directory under the temp root+ * @param {Record<string, unknown>} fields+ * @returns {any}+ */+function record(dir, fields) {+ const packageDir = path.join(tmpDir, dir);+ fs.mkdirSync(packageDir, {recursive: true});+ return {+ providerId: fields.name,+ __spec: fields.name,+ __packageDir: packageDir,+ __manifestFile: path.join(packageDir, 'astryx.integration.mjs'),+ ...fields,+ };+}++/**+ * @param {string} source+ * @param {any} integration+ */+const candidate = (source, integration) => ({+ source,+ integration,+ spec: integration.__spec,+});++/** @param {Map<string, any>} ledger */+function outcomes(ledger) {+ return [...ledger.values()].map(entry => [entry.label, entry.outcome]);+}++describe('resolveProviders ledger', () => {+ it('records one outcome for every candidate, keyed by real directory', () => {+ const widgets = record('widgets', {+ name: '@acme/widgets',+ version: '1.0.0',+ });+ const renamed = record('renamed', {+ name: '@acme/renamed',+ version: '2.0.0',+ providerId: '@acme/widgets',+ });+ const broken = record('broken', {+ name: '@acme/broken',+ version: '1.0.0',+ __loadError: 'boom',+ });+ const {integrations, ledger} = resolveProviders([+ candidate('configured', widgets),+ candidate('configured', renamed),+ candidate('configured', broken),+ ]);++ expect([...ledger.keys()]).toEqual(+ [widgets, renamed, broken].map(entry => packageKey(entry.__packageDir)),+ );+ expect(outcomes(ledger)).toEqual([+ ['@acme/[email protected]', 'contributes'],+ ['@acme/[email protected]', 'set-aside'],+ ['@acme/[email protected]', 'load-failed'],+ ]);+ const setAside = ledger.get(packageKey(renamed.__packageDir));+ expect(setAside).toMatchObject({+ winner: packageKey(widgets.__packageDir),+ reason: 'claimed-earlier',+ integration: integrations[1],+ });+ expect(integrations[1].__providerConflict.claimedBy).toBe('@acme/widgets');+ });++ it('keeps two packages that share a name apart', () => {+ const old = record('widgets-old', {+ name: '@acme/widgets',+ version: '1.0.0',+ __spec: 'widgets-old',+ });+ const next = record('widgets-next', {+ name: '@acme/widgets',+ version: '2.0.0',+ __spec: 'widgets-next',+ });+ const {ledger} = resolveProviders([+ candidate('configured', old),+ candidate('configured', next),+ ]);++ expect(outcomes(ledger)).toEqual([+ ['@acme/[email protected]', 'contributes'],+ ['@acme/[email protected]', 'set-aside'],+ ]);+ });++ it('folds every spelling of one real directory into one entry', () => {+ const ui = record('ui', {name: '@acme/ui', version: '0.1.22'});+ const link = path.join(tmpDir, 'legacy-ui');+ fs.symlinkSync(ui.__packageDir, link, 'dir');+ const legacy = {...ui, __spec: '@acme/legacy-ui', __packageDir: link};+ const {integrations, ledger} = resolveProviders([+ candidate('configured', ui),+ candidate('configured', legacy),+ ]);++ expect(integrations).toEqual([ui]);+ expect([...ledger.keys()]).toEqual([packageKey(ui.__packageDir)]);+ const [entry] = ledger.values();+ expect(entry.outcome).toBe('contributes');+ expect(entry.refs.map(ref => ref.spec)).toEqual([+ '@acme/ui',+ '@acme/legacy-ui',+ ]);+ });++ it('records an autolinked copy of a loaded package as alias-of it', () => {+ const ui = record('ui', {name: '@acme/ui', version: '0.1.22'});+ const copy = record('legacy-ui', {+ name: '@acme/ui',+ version: '0.1.22',+ __spec: '@acme/legacy-ui',+ __autolinked: true,+ });+ const {integrations, ledger} = resolveProviders([+ candidate('configured', ui),+ candidate('autolinked', copy),+ ]);++ expect(integrations).toEqual([ui]);+ expect(ledger.get(packageKey(copy.__packageDir))).toMatchObject({+ outcome: 'alias-of',+ aliasOf: packageKey(ui.__packageDir),+ });+ });++ it('records an autolinked package that failed to load, and lists it nowhere', () => {+ const packageDir = path.join(tmpDir, 'unreadable');+ const {integrations, ledger} = resolveProviders([+ {+ source: 'autolinked',+ spec: '@acme/unreadable',+ packageDir,+ error: 'bad json',+ },+ ]);++ expect(integrations).toEqual([]);+ expect(ledger.get(packageKey(packageDir))).toMatchObject({+ outcome: 'load-failed',+ error: 'bad json',+ });+ });++ it('lets the package being authored replace its installed copy and claim first', () => {+ const installed = record('installed', {+ name: '@acme/widgets',+ version: '1.0.0',+ });+ const rival = record('rival', {+ name: '@acme/rival',+ version: '1.0.0',+ providerId: '@acme/widgets',+ });+ const local = record('local', {+ name: '@acme/widgets',+ version: '2.0.0-dev',+ __local: true,+ });+ const {integrations, ledger} = resolveProviders([+ candidate('configured', rival),+ candidate('configured', installed),+ candidate('local', local),+ ]);++ expect(integrations.map(entry => entry.name)).toEqual([+ '@acme/rival',+ '@acme/widgets',+ ]);+ expect(integrations[1]).toBe(local);+ expect(ledger.get(packageKey(installed.__packageDir))).toMatchObject({+ outcome: 'set-aside',+ reason: 'replaced-by-authored',+ winner: packageKey(local.__packageDir),+ });+ expect(ledger.get(packageKey(rival.__packageDir))).toMatchObject({+ outcome: 'set-aside',+ reason: 'authored-claims',+ winner: packageKey(local.__packageDir),+ });+ });++ it('keeps configured precedence ahead of autolinked', () => {+ const configured = record('configured', {+ name: '@acme/one',+ version: '1.0.0',+ });+ const autolinked = record('autolinked', {+ name: '@acme/two',+ version: '1.0.0',+ providerId: '@acme/one',+ __autolinked: true,+ });+ const {ledger} = resolveProviders([+ candidate('configured', configured),+ candidate('autolinked', autolinked),+ ]);++ expect(outcomes(ledger)).toEqual([+ ['@acme/[email protected]', 'contributes'],+ ['@acme/[email protected]', 'set-aside'],+ ]);+ });++ it('under the codemod policy, records the installed copy standing in', () => {+ const local = record('local', {+ name: '@acme/widgets',+ version: '2.0.0-dev',+ __local: true,+ });+ const installed = record('installed', {+ name: '@acme/widgets',+ version: '1.0.0',+ });+ const {integrations, ledger} = resolveProviders(+ [candidate('configured', local), candidate('installed', installed)],+ {codemods: true},+ );++ expect(integrations).toEqual([installed]);+ expect(ledger.get(packageKey(local.__packageDir))).toMatchObject({+ outcome: 'set-aside',+ reason: 'installed-stands-in',+ winner: packageKey(installed.__packageDir),+ });+ });+});++describe('markProviderConflicts', () => {+ const a = {name: 'a', version: '1', providerId: 'x', __spec: 'a'};+ const b = {name: 'b', version: '1', providerId: 'x', __spec: 'b'};+ const alias = {name: 'a', version: '1', providerId: 'x', __spec: 'a-alias'};+ const local = {+ name: 'l',+ version: '1',+ providerId: 'x',+ __spec: 'l',+ __local: true,+ };+ /** @param {any[]} list */+ const claimsOf = list =>+ markProviderConflicts(list).map(entry => [+ entry?.name ?? null,+ entry?.__providerConflict?.claimedBy ?? null,+ ]);++ it('drops an alias of the winner and keeps a record listed twice', () => {+ expect(claimsOf([a, b, alias, a, undefined])).toEqual([+ ['a', null],+ ['b', 'a'],+ ['a', null],+ [null, null],+ ]);+ });++ it('lets the package being authored claim first', () => {+ expect(claimsOf([a, undefined, b, alias, a, local])).toEqual([+ ['a', 'l'],+ [null, null],+ ['b', 'l'],+ ['a', 'l'],+ ['a', 'l'],+ ['l', null],+ ]);+ });+});++describe('Project.load keeps a ledger', () => {+ /**+ * @param {string} dir node_modules key+ * @param {{name: string, version: string}} pkg+ */+ function install(dir, pkg) {+ const pkgDir = path.join(tmpDir, 'node_modules', ...dir.split('/'));+ fs.mkdirSync(pkgDir, {recursive: true});+ fs.writeFileSync(path.join(pkgDir, 'package.json'), JSON.stringify(pkg));+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ 'export default {};\n',+ );+ return pkgDir;+ }++ it('records the autolink alias it drops as alias-of the loaded copy', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ dependencies: {+ '@acme/legacy-ui': 'npm:@acme/[email protected]',+ '@acme/ui': '0.1.22',+ },+ }),+ );+ const legacy = install('@acme/legacy-ui', {+ name: '@acme/ui',+ version: '0.1.22',+ });+ const ui = install('@acme/ui', {name: '@acme/ui', version: '0.1.22'});++ const project = await Project.load(tmpDir, {fresh: true});+ expect(project.loadedIntegrations.map(entry => entry.__spec)).toEqual([+ '@acme/legacy-ui',+ ]);+ const ledger = providerLedgerOf(project);+ expect(ledger.get(packageKey(ui))).toMatchObject({+ outcome: 'alias-of',+ aliasOf: packageKey(legacy),+ });+ expect(await autolinkIntegrations({projectDir: tmpDir})).toHaveLength(1);+ });++ it('records a dependency key that repeats a configured package', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer', dependencies: {'@acme/ui': '0.1.22'}}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.config.mjs'),+ "export default {integrations: ['@acme/ui']};\n",+ );+ const ui = install('@acme/ui', {name: '@acme/ui', version: '0.1.22'});++ const ledger = providerLedgerOf(await Project.load(tmpDir, {fresh: true}));+ expect([...ledger.keys()]).toEqual([packageKey(ui)]);+ expect(ledger.get(packageKey(ui))?.refs.map(ref => ref.source)).toEqual([+ 'configured',+ 'autolinked',+ ]);+ });+});diff --git a/packages/cli/foundation/integrations/theme-descriptor.mjs b/packages/cli/foundation/integrations/theme-descriptor.mjsnew file mode 100644index 0000000000..e695b80c6a--- /dev/null+++ b/packages/cli/foundation/integrations/theme-descriptor.mjs@@ -0,0 +1,44 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The source text of a typed integration theme descriptor.+ *+ * @input A theme's descriptor fields.+ * @output The `.doc.mjs` source that declares them under their ThemeDoc type.+ * @position Shared by `integration add theme`, which scaffolds a descriptor,+ * and the codemod that turns a 0.6 theme catalog into descriptors, so both+ * write the same bytes.+ */++/**+ * A single-quoted JavaScript string literal for any text.+ * @param {string} value+ */+function quote(value) {+ const escaped = value+ .replace(/\\/gu, '\\\\')+ .replace(/'/gu, "\\'")+ .replace(/\n/gu, '\\n')+ .replace(/\r/gu, '\\r')+ .replace(/\u2028/gu, '\\u2028')+ .replace(/\u2029/gu, '\\u2029');+ return `'${escaped}'`;+}++/**+ * @param {import('../../authoring/doctypes/theme/type.js').ThemeDoc} doc+ * @returns {string}+ */+export function themeDescriptorSource(doc) {+ return [+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */",+ 'export default {',+ " type: 'theme',",+ ` name: ${quote(doc.name)},`,+ ` displayName: ${quote(doc.displayName)},`,+ ` description: ${quote(doc.description)},`,+ ` maintained: ${doc.maintained},`,+ '};',+ '',+ ].join('\n');+}diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjsindex d48435bc43..ed7f8f7696 100644--- a/packages/cli/foundation/integrations/validate-contributions.mjs+++ b/packages/cli/foundation/integrations/validate-contributions.mjs@@ -25,6 +25,23 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {isValidSemver} from '../env/semver.mjs';import {findSourceOnlyCandidates} from './contribution-inventory.mjs';+import {+ CODEMOD_FILE_RE,+ CODEMOD_SKIP_DIRS,+ CODEMOD_TEST_RE,+ createFixContext,+ DOC_CANDIDATE_RE,+ heldRootFix,+ newComponentDocNote,+ notACodemodFix,+ notAComponentFix,+ readContributionStamp,+ sharedCodemodsRootFix,+ stampOf,+ themeImporting,+ TEMPLATE_CANDIDATE_RE,+} from './contribution-fixes.mjs';+import {MANIFEST_BASENAMES} from './integrations.mjs';import {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';import * as componentDiscovery from '../discovery/component-discovery.mjs';@@ -119,32 +136,82 @@ function checkRoots(resolved, issues) {*/async function checkCodemods(integration, issues) {if (!integration.codemods || !fs.existsSync(integration.codemods)) return;+ const context = integration.__packageDir+ ? createFixContext(integration.__packageDir, integration)+ : null;+ const shared = context && sharedCodemodsRootFix(context);for (const entry of fs.readdirSync(integration.codemods, {withFileTypes: true,})) {if (entry.isFile() &&- /\.(?:ts|mjs|js)$/u.test(entry.name) &&- !/\.(?:test|spec|fixture)\.(?:ts|mjs|js)$/u.test(entry.name)+ CODEMOD_FILE_RE.test(entry.name) &&+ !CODEMOD_TEST_RE.test(entry.name) &&+ // The manifest sits beside package.json and is never a codemod.+ !(+ integration.codemods === integration.__packageDir &&+ MANIFEST_BASENAMES.includes(entry.name)+ )) {+ const shown = path+ .relative(+ integration.__packageDir ?? path.dirname(integration.codemods),+ path.join(integration.codemods, entry.name),+ )+ .split(path.sep)+ .join('/');+ const root = path.dirname(shown);+ const full = path.join(integration.codemods, entry.name);+ const stamp =+ context &&+ (DOC_CANDIDATE_RE.test(entry.name) ||+ TEMPLATE_CANDIDATE_RE.test(entry.name))+ ? stampOf(context, full)+ : null;+ // A theme's entry module may sit beside its descriptor.+ const themeDoc = ['.doc.mjs', '.doc.ts', '.doc.js']+ .map(suffix => full.replace(/\.(?:ts|mjs|js)$/u, suffix))+ .find(candidate => candidate !== full && fs.existsSync(candidate));+ const themeStamp =+ context && !stamp && themeDoc ? stampOf(context, themeDoc) : null;+ let fix = `Fix: move it into the folder named for the version it migrates to, for example ${root}/1.2.0/${entry.name}.`;+ if (shared) fix = sharedCodemodsRootFix(context, entry.name) ?? fix;+ else if (context && stamp) fix = notACodemodFix(context, full, stamp);+ else if (context && themeDoc && themeStamp?.type === 'theme') {+ fix = notACodemodFix(context, themeDoc, themeStamp, entry.name);+ } else if (context) {+ const owner = themeImporting(context, full);+ if (owner) {+ fix = notACodemodFix(+ context,+ owner.doc,+ owner.stamp,+ owner.source,+ entry.name,+ );+ }+ }issues.push(issueWarning('codemod_outside_version',- `Codemod file "${path.join(integration.codemods, entry.name)}" is outside a version folder, so upgrade will never load it.`,+ `Codemod file "${shown}" is outside a version folder, so upgrade will never load it. ${fix}`,),);}if (entry.isDirectory() &&- !['node_modules', '.git', '__tests__', '__fixtures__'].includes(- entry.name,- ) &&+ !CODEMOD_SKIP_DIRS.has(entry.name) &&!isValidSemver(entry.name)) {+ const fix =+ shared ??+ (context &&+ heldRootFix(context, path.join(integration.codemods, entry.name))) ??+ 'Fix: rename it to the exact version its codemods migrate to.';issues.push(issueError('invalid_codemod_version',- `Codemod folder "${entry.name}" is not an exact semver version such as 1.2.0.`,+ `Codemod folder "${entry.name}" is not an exact semver version such as 1.2.0. ${fix}`,),);}@@ -196,24 +263,51 @@ async function checkComponents(integration, issues) {if (typeof discover !== 'function') return; // feature not present yettry {const records = (await discover(integration)) ?? [];+ /** @type {import('./contribution-fixes.mjs').FixContext | undefined} */+ let context;for (const record of records) {if (record?.sourcePath == null) {+ const docPath = record?.docPath;+ let fix = `Fix: add ${record?.name}.tsx beside ${docPath ? path.basename(docPath) : `${record?.name}.doc.mjs`}.`;+ const stamp = docPath ? readContributionStamp(docPath, false) : null;+ if (stamp && stamp.type !== 'component' && integration.__packageDir) {+ context ??= createFixContext(integration.__packageDir, integration);+ fix = notAComponentFix(context, docPath, stamp);+ }issues.push(issueError('invalid_component',- `Component "${record?.name}" is missing its same-stem source file ${record?.name}.tsx.`,+ `Component "${record?.name}" is missing its same-stem source file ${record?.name}.tsx. ${fix}`,),);}}+ const overlap = integration.__packageDir+ ? newComponentDocNote(+ (context ??= createFixContext(integration.__packageDir, integration)),+ )+ : '';for (const name of findSourceOnlyCandidates(integration.components,records.map(record => record.name),)) {+ // A hidden doc still pairs with its source; discovery just skips it.+ if (+ ['.doc.ts', '.doc.mjs', '.doc.js'].some(suffix =>+ fs.existsSync(+ path.join(+ /** @type {string} */ (integration.components),+ `${name}${suffix}`,+ ),+ ),+ )+ ) {+ continue;+ }issues.push(issueWarning('source_without_component_doc',- `Component source "${name}.tsx" has no same-stem metadata file ${name}.doc.mjs, so Astryx ignores it.`,+ `Component source "${name}.tsx" has no same-stem metadata file ${name}.doc.mjs, so Astryx ignores it. Fix: add ${name}.doc.mjs beside it with type: 'component'; \`astryx docs authoring component-doc\` lists its fields.${overlap}`,),);}@@ -250,7 +344,7 @@ async function checkDocs(integration, issues) {}/**- * Validate the integration's source-theme catalog. The same discovery function+ * Validate the integration's source-theme descriptors. The same discovery function* powers Project and theme list/add, so validation cannot accept a shape that* consumers later fail to use.* @param {LoadedIntegration} integrationdiff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjsindex b47c9933a2..3d0570c130 100644--- a/packages/cli/foundation/response/error-codes.doc.mjs+++ b/packages/cli/foundation/response/error-codes.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'enum',name: 'error-codes',displayName: 'Error Codes',- namespace: 'cli',+ namespace: 'cli/api',description:'Stable, append-only machine-readable error codes on the --json error envelope (envelope.code). Codes never change or get removed; branch on these, not on prose.',members: [@@ -203,7 +203,7 @@ export const doc = {{value: 'ERR_THEME_INVALID',description:- 'A theme definition or contributed theme catalog is invalid.',+ 'A theme definition or contributed theme descriptor is invalid.',},{value: 'ERR_THEME_LOAD',diff --git a/packages/cli/foundation/response/error-codes.mjs b/packages/cli/foundation/response/error-codes.mjsindex 54fd85ffd8..bc6eb49670 100644--- a/packages/cli/foundation/response/error-codes.mjs+++ b/packages/cli/foundation/response/error-codes.mjs@@ -185,7 +185,7 @@ export const ERROR_CODES = Object.freeze({ERR_WRITE_FAILED: 'ERR_WRITE_FAILED',// ── Theme build ──────────────────────────────────────────────────- /** A theme definition or contributed theme catalog is invalid. */+ /** A theme definition or contributed theme descriptor is invalid. */ERR_THEME_INVALID: 'ERR_THEME_INVALID',/** A theme file could not be loaded / parsed into a defineTheme result. */ERR_THEME_LOAD: 'ERR_THEME_LOAD',diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex cb6d55a8b5..8b738b9d68 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -13,7 +13,7 @@ export const doc = {type: 'enum',name: 'response-types',displayName: 'Response Types',- namespace: 'cli',+ namespace: 'cli/api',description:'The `type` discriminant present on every --json success envelope. Consumers switch on it to narrow `data`.',members: [diff --git a/packages/cli/foundation/response/response.doc.mjs b/packages/cli/foundation/response/response.doc.mjsindex 13c2abf493..51e7c19626 100644--- a/packages/cli/foundation/response/response.doc.mjs+++ b/packages/cli/foundation/response/response.doc.mjs@@ -12,7 +12,7 @@ export const doc = {type: 'schema',name: 'output',displayName: 'Output Envelope',- namespace: 'cli',+ namespace: 'cli/api',description:'The single JSON envelope every command emits under --json. Success is ' +'{ apiVersion, type, data, meta? }; failure is { apiVersion, error, code, ' +diff --git a/packages/cli/foundation/text/string-utils.mjs b/packages/cli/foundation/text/string-utils.mjsindex 3f2603b9b5..f5289da0ef 100644--- a/packages/cli/foundation/text/string-utils.mjs+++ b/packages/cli/foundation/text/string-utils.mjs@@ -56,7 +56,7 @@ export function findClosestComponents(name, components, maxDistance = 3) {* @returns {Promise<{name: string, score: number, reason: string}[]>}*/export async function searchComponents(needle, coreDir, components) {- const {pathToFileURL} = await import('node:url');+ const {readDocView} = await import('../doc-compiler/read.mjs');const fs = await import('node:fs');const path = await import('node:path');@@ -100,8 +100,10 @@ export async function searchComponents(needle, coreDir, components) {// Levenshtein on nameconst dist = levenshteinDistance(term, compLower);if (dist === 1) addMatch(comp, 80, 'similar name (distance ' + dist + ')');- else if (dist === 2) addMatch(comp, 40, 'similar name (distance ' + dist + ')');- else if (dist === 3) addMatch(comp, 20, 'similar name (distance ' + dist + ')');+ else if (dist === 2)+ addMatch(comp, 40, 'similar name (distance ' + dist + ')');+ else if (dist === 3)+ addMatch(comp, 20, 'similar name (distance ' + dist + ')');}// --- Pass 2: Keyword + description matching (async, reads doc files) ---@@ -124,15 +126,22 @@ export async function searchComponents(needle, coreDir, components) {for (const entry of entries) {if (!entry.isDirectory()) continue;const nested = path.join(srcDir, entry.name, comp, comp + '.doc.mjs');- if (fs.existsSync(nested)) { docPath = nested; break; }+ if (fs.existsSync(nested)) {+ docPath = nested;+ break;+ }}}if (!docPath) continue;try {- const mod = await import(pathToFileURL(docPath).href);- const docs = mod.docs;+ // Only the legacy `docs` export has ever been indexed here.+ const docs = await readDocView(docPath, {+ root: 'components',+ loader: 'native',+ exports: ['docs'],+ });if (!docs) continue;// Keyword matching@@ -157,8 +166,10 @@ export async function searchComponents(needle, coreDir, components) {}const dist = levenshteinDistance(term, kwLower);- if (dist === 1) addMatch(comp, 70, 'keyword "' + kw + '" (distance ' + dist + ')');- else if (dist === 2) addMatch(comp, 30, 'keyword "' + kw + '" (distance ' + dist + ')');+ if (dist === 1)+ addMatch(comp, 70, 'keyword "' + kw + '" (distance ' + dist + ')');+ else if (dist === 2)+ addMatch(comp, 30, 'keyword "' + kw + '" (distance ' + dist + ')');}}@@ -191,8 +202,9 @@ export async function searchComponents(needle, coreDir, components) {}}- const results = Array.from(scored.values())- .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));+ const results = Array.from(scored.values()).sort(+ (a, b) => b.score - a.score || a.name.localeCompare(b.name),+ );return results;}diff --git a/packages/cli/test-utils/provider-scenarios.mjs b/packages/cli/test-utils/provider-scenarios.mjsnew file mode 100644index 0000000000..8657b3e9fc--- /dev/null+++ b/packages/cli/test-utils/provider-scenarios.mjs@@ -0,0 +1,323 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Seeded provider-resolution scenarios for property tests.+ *+ * @input A seed.+ * @output A scenario description (installed packages, config, declared+ * dependencies, the package being authored, `--integration` extras), a+ * writer that lays it out on disk, and the candidate inputs a correct ledger+ * must account for — derived from the description, never from the resolver.+ * @position test-utils — shared by the provider ledger property tests.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++/** Package names in the pool. Small on purpose, so claims collide often. */+const POOL = ['@acme/a', '@acme/b', '@acme/c'];+/** Install directories that hold a package under another key. */+const ALIASES = ['@acme/alias-1', '@acme/alias-2'];+const VERSIONS = ['1.0.0', '2.0.0'];+const FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies'];++/**+ * @typedef {'ok' | 'throws' | 'none' | 'two'} ManifestShape+ * `throws`: fails on import; `none`: no root manifest; `two`: two root+ * manifests+ */++/**+ * @typedef {object} ScenarioPackage+ * @property {string} dir the node_modules key it is installed under+ * @property {string} name its package.json name+ * @property {string} [version]+ * @property {string} [providerId] its manifest providerId+ * @property {ManifestShape} manifest+ * @property {string} [linkTo] installed as a symlink to this other key's+ * directory, the way pnpm links one store entry under two keys+ */++/**+ * @typedef {object} Scenario+ * @property {number} seed+ * @property {ScenarioPackage[]} packages+ * @property {string[] | null} config integrations; null means no config file+ * @property {Array<{name: string, field: string}>} dependencies+ * @property {{name: string, version: string, providerId?: string, manifest: 'ok' | 'throws'} | null} local+ * the package being authored; null means the project has no manifest+ * @property {string[]} extras `upgrade --integration` specs+ */++/**+ * A small deterministic PRNG (mulberry32).+ * @param {number} seed+ * @returns {() => number} uniform in [0, 1)+ */+export function prng(seed) {+ let state = seed >>> 0;+ return () => {+ state = (state + 0x6d2b79f5) >>> 0;+ let t = state;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/**+ * @template T+ * @param {() => number} random+ * @param {readonly T[]} items+ * @returns {T}+ */+function pick(random, items) {+ return items[Math.floor(random() * items.length)];+}++/**+ * A random subset in random order.+ * @template T+ * @param {() => number} random+ * @param {readonly T[]} items+ * @param {number} chance+ * @returns {T[]}+ */+function subset(random, items, chance) {+ const chosen = items.filter(() => random() < chance);+ for (let i = chosen.length - 1; i > 0; i--) {+ const j = Math.floor(random() * (i + 1));+ [chosen[i], chosen[j]] = [chosen[j], chosen[i]];+ }+ return chosen;+}++/**+ * Generate one scenario. Every scenario loads without a hard error: configured+ * specs and extras are installed with one root manifest, and a package that+ * lists itself has an installed copy.+ * @param {number} seed+ * @returns {Scenario}+ */+export function generateScenario(seed) {+ const random = prng(seed);+ /** @type {ScenarioPackage[]} */+ const packages = [];++ for (const name of POOL) {+ if (random() < 0.2) continue;+ const roll = random();+ packages.push({+ dir: name,+ name,+ version: random() < 0.1 ? undefined : pick(random, VERSIONS),+ providerId: random() < 0.35 ? pick(random, POOL) : undefined,+ manifest:+ roll < 0.08+ ? 'throws'+ : roll < 0.13+ ? 'none'+ : roll < 0.17+ ? 'two'+ : 'ok',+ });+ }+ for (const dir of ALIASES) {+ const roll = random();+ if (roll < 0.35) continue;+ const linkable = packages.filter(pkg => !pkg.linkTo);+ if (roll < 0.6 && linkable.length > 0) {+ const target = pick(random, linkable);+ packages.push({...target, dir, linkTo: target.dir});+ continue;+ }+ // An npm alias installed as a copy: often the same name and version as a+ // pool package, sometimes another version of it.+ const twin =+ packages.length > 0 && random() < 0.6 ? pick(random, packages) : null;+ packages.push({+ dir,+ name: twin?.name ?? pick(random, POOL),+ version:+ twin != null && random() < 0.7 ? twin.version : pick(random, VERSIONS),+ providerId: twin != null && random() < 0.7 ? twin.providerId : undefined,+ manifest: random() < 0.08 ? 'throws' : 'ok',+ });+ }++ const loadable = packages.filter(+ pkg => pkg.manifest === 'ok' || pkg.manifest === 'throws',+ );+ const local =+ random() < 0.55+ ? {+ name: random() < 0.7 ? pick(random, POOL) : '@acme/self',+ version: '3.0.0-dev',+ ...(random() < 0.45+ ? {providerId: pick(random, [...POOL, '@acme/next'])}+ : {}),+ manifest: /** @type {'ok' | 'throws'} */ (+ random() < 0.1 ? 'throws' : 'ok'+ ),+ }+ : null;++ const config =+ random() < 0.2+ ? null+ : subset(+ random,+ loadable.map(pkg => pkg.dir),+ 0.45,+ );+ const dependencies = subset(+ random,+ packages.map(pkg => pkg.dir),+ 0.5,+ ).map(name => ({name, field: pick(random, FIELDS)}));+ const extras = subset(+ random,+ loadable.map(pkg => pkg.dir),+ 0.25,+ );++ return {seed, packages, config, dependencies, local, extras};+}++/**+ * @param {ScenarioPackage | {providerId?: string, manifest: ManifestShape}} pkg+ * @returns {string}+ */+function manifestSource(pkg) {+ if (pkg.manifest === 'throws') return "throw new Error('broken manifest');\n";+ return `export default ${JSON.stringify(+ pkg.providerId == null ? {} : {providerId: pkg.providerId},+ )};\n`;+}++/**+ * Lay a scenario out under `projectDir`.+ * @param {string} projectDir+ * @param {Scenario} scenario+ */+export function writeScenario(projectDir, scenario) {+ const modules = path.join(projectDir, 'node_modules');+ for (const pkg of scenario.packages.filter(entry => !entry.linkTo)) {+ const dir = path.join(modules, ...pkg.dir.split('/'));+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: pkg.name, version: pkg.version}),+ );+ if (pkg.manifest === 'none') continue;+ fs.writeFileSync(+ path.join(dir, 'astryx.integration.mjs'),+ manifestSource(pkg),+ );+ if (pkg.manifest === 'two') {+ fs.writeFileSync(+ path.join(dir, 'astryx.integration.js'),+ manifestSource(pkg),+ );+ }+ }+ for (const pkg of scenario.packages.filter(entry => entry.linkTo)) {+ const link = path.join(modules, ...pkg.dir.split('/'));+ fs.mkdirSync(path.dirname(link), {recursive: true});+ fs.symlinkSync(+ path.join(modules, .../** @type {string} */ (pkg.linkTo).split('/')),+ link,+ 'dir',+ );+ }++ /** @type {Record<string, Record<string, string>>} */+ const declared = {};+ for (const {name, field} of scenario.dependencies) {+ declared[field] = {...declared[field], [name]: '*'};+ }+ const {local} = scenario;+ fs.writeFileSync(+ path.join(projectDir, 'package.json'),+ JSON.stringify({+ name: local?.name ?? 'consumer',+ ...(local ? {version: local.version} : {}),+ ...declared,+ }),+ );+ if (local) {+ fs.writeFileSync(+ path.join(projectDir, 'astryx.integration.mjs'),+ manifestSource(local),+ );+ }+ if (scenario.config) {+ fs.writeFileSync(+ path.join(projectDir, 'astryx.config.mjs'),+ `export default ${JSON.stringify({integrations: scenario.config})};\n`,+ );+ }+}++/**+ * A scenario is runnable when nothing in it is a hard load error: the package+ * being authored, when it lists itself, has an installed copy with one root+ * manifest.+ * @param {Scenario} scenario+ * @returns {boolean}+ */+export function isRunnable(scenario) {+ const {local, config} = scenario;+ if (local == null || config == null || !config.includes(local.name)) {+ return true;+ }+ const installed = scenario.packages.find(pkg => pkg.dir === local.name);+ return (+ installed != null &&+ (installed.manifest === 'ok' || installed.manifest === 'throws')+ );+}++/**+ * The inputs a Project ledger must account for, from the scenario alone: each+ * configured spec, each declared dependency installed with exactly one root+ * manifest, and the package being authored.+ * @param {string} projectDir+ * @param {Scenario} scenario+ * @returns {Array<{source: string, spec: string, key: string}>}+ */+export function expectedProjectInputs(projectDir, scenario) {+ const modules = path.join(projectDir, 'node_modules');+ /** @param {string} dir */+ const keyOf = dir => fs.realpathSync(path.join(modules, ...dir.split('/')));+ /** @param {string} dir */+ const packageOf = dir => {+ const pkg = scenario.packages.find(entry => entry.dir === dir);+ const target = pkg?.linkTo+ ? scenario.packages.find(entry => entry.dir === pkg.linkTo)+ : pkg;+ return target;+ };+ /** @type {Array<{source: string, spec: string, key: string}>} */+ const inputs = [];+ for (const spec of new Set(scenario.config ?? [])) {+ inputs.push({source: 'configured', spec, key: keyOf(spec)});+ }+ const seen = new Set();+ for (const {name} of scenario.dependencies) {+ if (seen.has(name)) continue;+ seen.add(name);+ const pkg = packageOf(name);+ if (pkg == null || pkg.manifest === 'none' || pkg.manifest === 'two')+ continue;+ inputs.push({source: 'autolinked', spec: name, key: keyOf(name)});+ }+ if (scenario.local) {+ inputs.push({+ source: 'local',+ spec: scenario.local.name,+ key: fs.realpathSync(projectDir),+ });+ }+ return inputs;+}diff --git a/packages/cli/test/__golden__/component-props.json b/packages/cli/test/__golden__/component-props.jsonnew file mode 100644index 0000000000..7fa9b2bd8f--- /dev/null+++ b/packages/cli/test/__golden__/component-props.json@@ -0,0 +1,18 @@+{+ "apiVersion": 1,+ "type": "component.detail.props",+ "data": [+ {+ "name": "title",+ "type": "string",+ "required": true,+ "description": "Heading text."+ },+ {+ "name": "tone",+ "type": "'calm' | 'loud'",+ "default": "'calm'",+ "description": "Visual weight."+ }+ ]+}diff --git a/packages/cli/test/__golden__/component-text.txt b/packages/cli/test/__golden__/component-text.txtnew file mode 100644index 0000000000..159e7d4456--- /dev/null+++ b/packages/cli/test/__golden__/component-text.txt@@ -0,0 +1,18 @@+# AcmeCard++A zorblax card that groups one topic.++**Import:** `import {AcmeCard} from '@acme/kit';`++## Best Practices++- **Do:** Keep one idea per card.+- **Don't:** Do not nest cards.++## Props++| Prop | Type | Default | Description |+|------|------|---------|-------------|+| `title` | `string` | - | Heading text. **(required)** |+| `tone` | `'calm' \| 'loud'` | `'calm'` | Visual weight. |+diff --git a/packages/cli/test/__golden__/component-zh.json b/packages/cli/test/__golden__/component-zh.jsonnew file mode 100644index 0000000000..94109b7f43--- /dev/null+++ b/packages/cli/test/__golden__/component-zh.json@@ -0,0 +1,49 @@+{+ "apiVersion": 1,+ "type": "component.detail",+ "data": {+ "type": "component",+ "name": "AcmeCard",+ "displayName": "Acme Card",+ "category": "Layout",+ "keywords": [+ "zorblax",+ "card"+ ],+ "usage": {+ "description": "一张 zorblax 卡片。",+ "bestPractices": [+ {+ "guidance": true,+ "description": "Keep one idea per card."+ },+ {+ "guidance": false,+ "description": "Do not nest cards."+ }+ ]+ },+ "props": [+ {+ "name": "title",+ "type": "string",+ "required": true,+ "description": "标题文字。"+ },+ {+ "name": "tone",+ "type": "'calm' | 'loud'",+ "default": "'calm'",+ "description": "Visual weight."+ }+ ],+ "playground": {+ "defaults": {+ "tone": "calm"+ }+ },+ "package": "@acme/kit",+ "import": "@acme/kit",+ "sourceAvailable": true+ }+}diff --git a/packages/cli/test/__golden__/component.json b/packages/cli/test/__golden__/component.jsonnew file mode 100644index 0000000000..f67cf3981b--- /dev/null+++ b/packages/cli/test/__golden__/component.json@@ -0,0 +1,49 @@+{+ "apiVersion": 1,+ "type": "component.detail",+ "data": {+ "type": "component",+ "name": "AcmeCard",+ "displayName": "Acme Card",+ "category": "Layout",+ "keywords": [+ "zorblax",+ "card"+ ],+ "usage": {+ "description": "A zorblax card that groups one topic.",+ "bestPractices": [+ {+ "guidance": true,+ "description": "Keep one idea per card."+ },+ {+ "guidance": false,+ "description": "Do not nest cards."+ }+ ]+ },+ "props": [+ {+ "name": "title",+ "type": "string",+ "required": true,+ "description": "Heading text."+ },+ {+ "name": "tone",+ "type": "'calm' | 'loud'",+ "default": "'calm'",+ "description": "Visual weight."+ }+ ],+ "playground": {+ "defaults": {+ "tone": "calm"+ }+ },+ "package": "@acme/kit",+ "import": "@acme/kit",+ "sourceAvailable": true+ }+}diff --git a/packages/cli/test/__golden__/docs-index.txt b/packages/cli/test/__golden__/docs-index.txtnew file mode 100644index 0000000000..c125981495--- /dev/null+++ b/packages/cli/test/__golden__/docs-index.txt@@ -0,0 +1,8 @@+Acme guide+How zorblax cards fit together.++start Start - Install the kit.+colors Colors - Cards use the core tokens.++Read one section: pnpm exec astryx docs acme-guide <section>+Read everything: pnpm exec astryx docs acme-guidediff --git a/packages/cli/test/__golden__/docs-list.json b/packages/cli/test/__golden__/docs-list.jsonnew file mode 100644index 0000000000..6bfa10e584--- /dev/null+++ b/packages/cli/test/__golden__/docs-list.json@@ -0,0 +1,11 @@+{+ "apiVersion": 1,+ "type": "docs.list",+ "data": [+ {+ "topic": "acme-guide",+ "description": "How zorblax cards fit together.",+ "package": "@acme/kit"+ }+ ]+}diff --git a/packages/cli/test/__golden__/docs-section.json b/packages/cli/test/__golden__/docs-section.jsonnew file mode 100644index 0000000000..c57e99ab03--- /dev/null+++ b/packages/cli/test/__golden__/docs-section.json@@ -0,0 +1,18 @@+{+ "apiVersion": 1,+ "type": "docs.detail.section",+ "data": {+ "title": "Colors",+ "content": [+ {+ "type": "prose",+ "text": "Cards use the core tokens."+ },+ {+ "type": "prose",+ "text": "[token-ref: unknown topic \"no-such-topic\"]"+ }+ ],+ "id": "colors"+ }+}diff --git a/packages/cli/test/__golden__/docs-topic-text.txt b/packages/cli/test/__golden__/docs-topic-text.txtnew file mode 100644index 0000000000..7ace5a8627--- /dev/null+++ b/packages/cli/test/__golden__/docs-topic-text.txt@@ -0,0 +1,13 @@+# Acme guide++How zorblax cards fit together.++## Start++Install the kit.++## Colors++Cards use the core tokens.++[token-ref: unknown topic "no-such-topic"]diff --git a/packages/cli/test/__golden__/docs-topic.json b/packages/cli/test/__golden__/docs-topic.jsonnew file mode 100644index 0000000000..7cfb5cadf6--- /dev/null+++ b/packages/cli/test/__golden__/docs-topic.json@@ -0,0 +1,36 @@+{+ "apiVersion": 1,+ "type": "docs.detail",+ "data": {+ "name": "acme-guide",+ "description": "How zorblax cards fit together.",+ "type": "generic",+ "title": "Acme guide",+ "sections": [+ {+ "title": "Start",+ "content": [+ {+ "type": "prose",+ "text": "Install the kit."+ }+ ],+ "id": "start"+ },+ {+ "title": "Colors",+ "content": [+ {+ "type": "prose",+ "text": "Cards use the core tokens."+ },+ {+ "type": "prose",+ "text": "[token-ref: unknown topic \"no-such-topic\"]"+ }+ ],+ "id": "colors"+ }+ ]+ }+}diff --git a/packages/cli/test/__golden__/search.json b/packages/cli/test/__golden__/search.jsonnew file mode 100644index 0000000000..a06163ed8f--- /dev/null+++ b/packages/cli/test/__golden__/search.json@@ -0,0 +1,38 @@+{+ "apiVersion": 1,+ "type": "search",+ "data": {+ "query": "zorblax",+ "matchCount": 3,+ "results": [+ {+ "domain": "component",+ "name": "AcmeCard",+ "score": 90,+ "reason": "keyword \"zorblax\"",+ "description": "A zorblax card that groups one topic.",+ "import": "@acme/kit",+ "command": "astryx component AcmeCard"+ },+ {+ "domain": "doc",+ "name": "acme-guide",+ "score": 50,+ "reason": "description mentions \"zorblax\"",+ "description": "How zorblax cards fit together.",+ "title": "Acme guide",+ "command": "astryx docs acme-guide"+ },+ {+ "domain": "template",+ "name": "hero",+ "score": 50,+ "reason": "description mentions \"zorblax\"",+ "description": "A zorblax hero block.",+ "displayName": "Zorblax hero",+ "kind": "block",+ "command": "astryx template hero"+ }+ ]+ }+}diff --git a/packages/cli/test/__golden__/template.json b/packages/cli/test/__golden__/template.jsonnew file mode 100644index 0000000000..65f44af83f--- /dev/null+++ b/packages/cli/test/__golden__/template.json@@ -0,0 +1,11 @@+{+ "apiVersion": 1,+ "type": "template.show",+ "data": {+ "template": "hero",+ "description": "A zorblax hero block.",+ "type": "block",+ "components": [],+ "source": "export default function Hero() { return <section>zorblax</section>; }\n"+ }+}diff --git a/packages/cli/test/__golden__/theme-list.json b/packages/cli/test/__golden__/theme-list.jsonnew file mode 100644index 0000000000..3f151e11a5--- /dev/null+++ b/packages/cli/test/__golden__/theme-list.json@@ -0,0 +1,13 @@+{+ "apiVersion": 1,+ "type": "theme.list",+ "data": [+ {+ "slug": "ocean",+ "displayName": "Ocean",+ "description": "A zorblax blue.",+ "maintained": true,+ "package": "@acme/kit"+ }+ ]+}diff --git a/packages/cli/test/authoring-self-docs-match-types.test.mjs b/packages/cli/test/authoring-self-docs-match-types.test.mjsindex f801d1c22e..5d2811e110 100644--- a/packages/cli/test/authoring-self-docs-match-types.test.mjs+++ b/packages/cli/test/authoring-self-docs-match-types.test.mjs@@ -37,7 +37,10 @@ const SELF_DOCS = {'doctypes/command/command.doc.mjs': 'CommandDoc','doctypes/enum/enum.doc.mjs': 'EnumDoc','doctypes/namespace/namespace.doc.mjs': 'NamespaceDoc',+ 'doctypes/theme/theme.doc.mjs': 'ThemeDoc','config/config.doc.mjs': 'AstryxConfig',+ 'debug/debug.doc.mjs': 'DebugEvent',+ 'gap-report/gap-report.doc.mjs': 'GapReportHandler','integration/integration.doc.mjs': 'AstryxIntegration',// The codemod types describe a loaded codemod, whose `isOptional` has its// default; the self-doc describes what an author writes.diff --git a/packages/cli/test/authoring-types/all-kinds.doc.ts b/packages/cli/test/authoring-types/all-kinds.doc.tsindex 3c0405d7aa..326b06d0b4 100644--- a/packages/cli/test/authoring-types/all-kinds.doc.ts+++ b/packages/cli/test/authoring-types/all-kinds.doc.ts@@ -15,6 +15,7 @@ import type {ReferenceDoc,SchemaDoc,TemplateDoc,+ ThemeDoc,} from '@astryxdesign/cli/authoring';import type {BlockTemplateDoc, PageTemplateDoc} from '@astryxdesign/cli/doc';@@ -98,6 +99,14 @@ export const enumDoc = {members: [{value: 'ready', description: 'Loaded and usable.'}],} satisfies EnumDoc;+export const theme = {+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: 'Blue and calm.',+ maintained: true,+} satisfies ThemeDoc;+// A required field left out is a type error, not a runtime surprise.export const missingUsage = {type: 'component',diff --git a/packages/cli/test/authoring-types/theme.doc.mjs b/packages/cli/test/authoring-types/theme.doc.mjsnew file mode 100644index 0000000000..c7edd3575b--- /dev/null+++ b/packages/cli/test/authoring-types/theme.doc.mjs@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export const docs = {+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: 'Blue and calm.',+ maintained: true,+};diff --git a/packages/cli/test/cli-integrations-doc-drift.test.mjs b/packages/cli/test/cli-integrations-doc-drift.test.mjsindex 243152cbe4..1218c32aaa 100644--- a/packages/cli/test/cli-integrations-doc-drift.test.mjs+++ b/packages/cli/test/cli-integrations-doc-drift.test.mjs@@ -17,7 +17,7 @@ import {doc as integrationAddDoc} from '../clients/cli/commands/integration-add.import {parseDoc} from '../authoring/doctypes/parse.mjs';import {parseCodemod} from '../authoring/codemod/parse.mjs';import {resolvePackageDir} from '../foundation/integrations/integrations.mjs';-import {discoverThemeCatalog} from '../foundation/discovery/theme-discovery.mjs';+import {discoverThemeDirectory} from '../foundation/discovery/theme-discovery.mjs';import {integrationAddTheme} from '../api/integration/add-theme.mjs';import {themePaletteGenerate} from '../api/theme/palette/generate/generate.mjs';import * as fs from 'node:fs';@@ -111,27 +111,17 @@ describe('resolvePackageDir keeps integration specs beneath node_modules', () =>});});-describe('discoverThemeCatalog validates all documented required fields', () => {+describe('a theme descriptor carries every documented field', () => {let tmpDir;- function writeCatalog(themes) {- const root = path.join(tmpDir, 'themes');- fs.mkdirSync(root, {recursive: true});- fs.writeFileSync(- path.join(root, 'manifest.json'),- JSON.stringify({version: 1, themes}),- );- return root;- }-- function writeThemeFiles(slug, entry, exportName) {- const dir = path.join(tmpDir, 'themes', slug);- fs.mkdirSync(dir, {recursive: true});- fs.writeFileSync(- path.join(dir, entry),- `export const ${exportName} = {};\n`,- );- }+ const descriptor = (/** @type {object} */ fields = {}) => ({+ type: 'theme',+ name: 'ocean',+ displayName: 'Ocean',+ description: 'Ocean theme.',+ maintained: true,+ ...fields,+ });beforeEach(() => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'doc-drift-'));@@ -140,101 +130,34 @@ describe('discoverThemeCatalog validates all documented required fields', () =>fs.rmSync(tmpDir, {recursive: true, force: true});});- it('accepts a valid entry with all required fields', () => {- const root = writeCatalog([- {- slug: 'ocean',- displayName: 'Ocean',- description: 'Ocean theme.',- maintained: true,- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts'],- },- ]);- writeThemeFiles('ocean', 'oceanTheme.ts', 'oceanTheme');- expect(() => discoverThemeCatalog(root, '@test/pkg')).not.toThrow();- });-- it('rejects missing slug', () => {- const root = writeCatalog([- {- displayName: 'Ocean',- description: 'x',- maintained: true,- entry: 'a.ts',- exportName: 'a',- files: ['a.ts'],- },- ]);- expect(() => discoverThemeCatalog(root, '@test/pkg')).toThrow();- });-- it('rejects missing displayName', () => {- const root = writeCatalog([- {- slug: 'ocean',- description: 'x',- maintained: true,- entry: 'a.ts',- exportName: 'a',- files: ['a.ts'],- },- ]);- expect(() => discoverThemeCatalog(root, '@test/pkg')).toThrow();- });-- it('rejects missing exportName', () => {- const root = writeCatalog([- {- slug: 'ocean',- displayName: 'Ocean',- description: 'x',- maintained: true,- entry: 'a.ts',- files: ['a.ts'],- },- ]);- expect(() => discoverThemeCatalog(root, '@test/pkg')).toThrow();- });-- it('rejects empty files array', () => {- const root = writeCatalog([- {- slug: 'ocean',- displayName: 'Ocean',- description: 'x',- maintained: true,- entry: 'a.ts',- exportName: 'a',- files: [],- },- ]);- expect(() => discoverThemeCatalog(root, '@test/pkg')).toThrow();- });-- it('rejects missing maintained boolean', () => {- const root = writeCatalog([- {- slug: 'ocean',- displayName: 'Ocean',- description: 'x',- entry: 'a.ts',- exportName: 'a',- files: ['a.ts'],- },- ]);- expect(() => discoverThemeCatalog(root, '@test/pkg')).toThrow();- });-- it('requires version: 1 in the catalog root', () => {- const root = path.join(tmpDir, 'themes');- fs.mkdirSync(root, {recursive: true});+ it('accepts a descriptor with every documented field', () => {+ expect(parseDoc(descriptor(), 'oceanTheme.doc.mjs').type).toBe('theme');+ });++ it.each(['name', 'displayName', 'description', 'maintained'])(+ 'rejects a descriptor without %s',+ field => {+ const {[field]: _, ...rest} = descriptor();+ expect(() => parseDoc(rest, 'oceanTheme.doc.mjs')).toThrow(field);+ },+ );++ it('rejects a slug that is not lowercase kebab-case', () => {+ expect(() =>+ parseDoc(descriptor({name: 'Ocean'}), 'oceanTheme.doc.mjs'),+ ).toThrow(/kebab-case/);+ });++ it('rejects a theme directory without its same-stem descriptor', () => {+ const dir = path.join(tmpDir, 'themes', 'ocean');+ fs.mkdirSync(dir, {recursive: true});fs.writeFileSync(- path.join(root, 'manifest.json'),- JSON.stringify({version: 2, themes: []}),+ path.join(dir, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',);- expect(() => discoverThemeCatalog(root, '@test/pkg')).toThrow(/version 1/);+ expect(() =>+ discoverThemeDirectory(path.join(tmpDir, 'themes'), '@test/pkg'),+ ).toThrow();});});@@ -253,7 +176,7 @@ describe('documented theme palette workflow', () => {fs.rmSync(tmpDir, {recursive: true, force: true});});- it('generates and discovers the exact slug-relative catalog inventory', async () => {+ it('generates and discovers the exact documented theme directory', async () => {await integrationAddTheme('ocean', {cwd: tmpDir});const themeDir = path.join(tmpDir, 'themes', 'ocean');fs.mkdirSync(path.join(themeDir, 'tokens'), {recursive: true});@@ -281,26 +204,25 @@ describe('documented theme palette workflow', () => {path.join(themeDir, 'oceanTheme.ts'),"import {palette} from './tokens/ocean.palette';\nexport const oceanTheme = {palette};\n",);- const catalogPath = path.join(tmpDir, 'themes', 'manifest.json');- const catalog = JSON.parse(fs.readFileSync(catalogPath, 'utf-8'));- catalog.themes[0].files = [+ const [theme] = discoverThemeDirectory(+ path.join(tmpDir, 'themes'),+ '@acme/brand-integration',+ );+ expect(theme).toMatchObject({slug: 'ocean', entry: 'oceanTheme.ts'});+ const documented = ['oceanTheme.ts',+ 'oceanTheme.doc.mjs','palette.config.json',- 'tokens/ocean.palette.ts','tokens/ocean.palette.receipt.json',+ 'tokens/ocean.palette.ts',];- fs.writeFileSync(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`);-- expect(- discoverThemeCatalog(- path.join(tmpDir, 'themes'),- '@acme/brand-integration',- ),- ).toEqual([expect.objectContaining({slug: 'ocean'})]);+ // The documented layout is exactly what the theme directory ships, entry+ // first.+ expect(theme.files).toEqual(documented);const text = guideText(integrationGuide);- for (const documentedPath of catalog.themes[0].files) {- expect(text).toContain(documentedPath);+ for (const documentedPath of documented) {+ expect(text).toContain(documentedPath.split('/').pop());}expect(paletteGenerateDoc.examples.some(@@ -332,9 +254,24 @@ describe('cli-integrations guide required content', () => {}});- it('contrasts component, doc, and template metadata suffixes', () => {- expect(text).toContain('.doc.{ts,mjs,js}');- expect(text).toContain('.template.{ts,mjs,js}');+ it('names .doc.mjs as the authoring suffix and the released ones it still reads', () => {+ expect(text).toContain('strongly typed `.doc.mjs`');+ expect(text).toContain(+ 'Released `.doc.js` docs remain readable for compatibility. A `.doc.ts` component doc reads only when the package is linked from outside node_modules, not once it is installed.',+ );+ expect(text).toContain('Released `.template.*` files remain readable');+ });++ it('says which released suffixes still load for each kind', () => {+ expect(text).toContain(+ 'Released .doc.js files, template .doc.ts files, and .template.{ts,mjs,js}\ntemplates still load.',+ );+ expect(text).toContain(+ 'A component or topic .doc.ts loads only from a package\nlinked from outside node_modules; installed, it is listed but cannot be read.',+ );+ expect(text).not.toContain(+ 'Released `.doc.ts` and `.doc.js` inputs remain readable',+ );});it('documents the codemod version-directory layout', () => {@@ -349,19 +286,18 @@ describe('cli-integrations guide required content', () => {expect(text).toMatch(/no `--dry-run` flag/i);});- it('documents all required theme catalog manifest.json fields', () => {+ it('documents every ThemeDoc field and the same-stem source rule', () => {for (const field of [- '`slug`',+ '`ThemeDoc`',+ '`name`','`displayName`','`description`','`maintained`',- '`entry`',- '`exportName`',- '`files`',]) {expect(text).toContain(field);}- expect(text).toContain('"version": 1');+ expect(text).toMatch(/stem supplies the source entry/);+ expect(text).not.toContain('manifest.json entry');});it('documents the generated palette inventory exactly', () => {@@ -430,10 +366,10 @@ describe('upgrade FunctionDoc --integration param', () => {});});-describe('palette generate doc mentions catalog connection', () => {- it('description references theme catalog files array', () => {- expect(paletteGenerateDoc.description).toMatch(/catalog/i);- expect(paletteGenerateDoc.description).toMatch(/files.*array/i);+describe('palette generate doc says where its outputs ship', () => {+ it('keeps the outputs in the theme directory that theme add copies', () => {+ expect(paletteGenerateDoc.description).toMatch(/theme directory/i);+ expect(paletteGenerateDoc.description).not.toMatch(/catalog/i);});});diff --git a/packages/cli/test/doc-routes.ids.json b/packages/cli/test/doc-routes.ids.jsonnew file mode 100644index 0000000000..fde577ab42--- /dev/null+++ b/packages/cli/test/doc-routes.ids.json@@ -0,0 +1,1066 @@+{+ "@astryxdesign/core/component": [+ "AlertDialog",+ "AppShell",+ "AspectRatio",+ "Avatar",+ "AvatarGroup",+ "AvatarGroupOverflow",+ "AvatarStatusDot",+ "Badge",+ "Banner",+ "BaseTypeahead",+ "Blockquote",+ "BottomSheet",+ "BottomSheetSwitcher",+ "BreadcrumbItem",+ "Breadcrumbs",+ "Button",+ "ButtonGroup",+ "Calendar",+ "Card",+ "Carousel",+ "Center",+ "Chat",+ "ChatComposer",+ "ChatComposerDrawer",+ "ChatComposerInput",+ "ChatComposerTokenElement",+ "ChatDictationButton",+ "ChatLayout",+ "ChatLayoutScrollButton",+ "ChatMessage",+ "ChatMessageBubble",+ "ChatMessageList",+ "ChatMessageMetadata",+ "ChatSendButton",+ "ChatSystemMessage",+ "ChatTokenizedText",+ "ChatToolCalls",+ "CheckboxInput",+ "CheckboxList",+ "CheckboxListItem",+ "Citation",+ "ClickableCard",+ "Code",+ "CodeBlock",+ "Collapsible",+ "CollapsibleGroup",+ "CommandPalette",+ "CommandPaletteEmpty",+ "CommandPaletteFooter",+ "CommandPaletteGroup",+ "CommandPaletteInput",+ "CommandPaletteItem",+ "CommandPaletteList",+ "ComplexSelector",+ "ContextMenu",+ "ContextMenuItem",+ "DateInput",+ "DateRangeInput",+ "DateTimeInput",+ "Dialog",+ "DialogHeader",+ "Divider",+ "DropdownMenu",+ "DropdownMenuCheckboxItem",+ "DropdownMenuDivider",+ "DropdownMenuItem",+ "DropdownMenuRadioGroup",+ "DropdownMenuRadioItem",+ "DropdownMenuSubMenu",+ "EmptyState",+ "Field",+ "FieldLabel",+ "FieldStatus",+ "FileInput",+ "FormLayout",+ "Grid",+ "GridSpan",+ "Heading",+ "HoverCard",+ "Icon",+ "IconButton",+ "Indicator",+ "InputGroup",+ "InputGroupText",+ "InternationalizationProvider",+ "Item",+ "Kbd",+ "Layer",+ "Layout",+ "LayoutContent",+ "LayoutFooter",+ "LayoutHeader",+ "LayoutPanel",+ "Lightbox",+ "Link",+ "LinkProvider",+ "List",+ "ListItem",+ "Markdown",+ "MediaTheme",+ "MetadataList",+ "MetadataListItem",+ "MobileNav",+ "MoreMenu",+ "MultiSelector",+ "NavIcon",+ "NavMenu",+ "NumberInput",+ "Outline",+ "OverflowList",+ "Overlay",+ "Pagination",+ "Popover",+ "PowerSearch",+ "ProgressBar",+ "RadioList",+ "RadioListItem",+ "Resizable",+ "ScrollableArea",+ "Section",+ "SegmentedControl",+ "SegmentedControlItem",+ "SelectableCard",+ "Selector",+ "SelectorOption",+ "SideNav",+ "SideNavCollapseButton",+ "SideNavHeading",+ "SideNavItem",+ "SideNavSection",+ "Skeleton",+ "Slider",+ "Spinner",+ "Stack",+ "StatusDot",+ "Step",+ "Stepper",+ "Switch",+ "SyntaxTheme",+ "Tab",+ "Table",+ "TableBody",+ "TableCell",+ "TableFooter",+ "TableHeader",+ "TableHeaderCell",+ "TableRow",+ "TabList",+ "TabMenu",+ "Text",+ "TextArea",+ "TextInput",+ "Theme",+ "Thumbnail",+ "TimeInput",+ "Timer",+ "Timestamp",+ "Toast",+ "ToggleButton",+ "ToggleButtonGroup",+ "Token",+ "Tokenizer",+ "Toolbar",+ "Tooltip",+ "TopNav",+ "TopNavHeading",+ "TopNavItem",+ "TopNavMegaMenu",+ "TopNavMegaMenuFeaturedCard",+ "TopNavMegaMenuItem",+ "TopNavMenu",+ "TreeList",+ "Typeahead",+ "TypeaheadItem",+ "VisuallyHidden"+ ],+ "@astryxdesign/core/component-member": [+ "CheckboxIndicator",+ "CheckIndicator",+ "HStack",+ "LayerProvider",+ "MobileNavToggle",+ "NavHeadingMenu",+ "RadioIndicator",+ "ResizeHandle",+ "StackItem",+ "VStack"+ ],+ "@astryxdesign/core/hook": [+ "useAnnounce",+ "useAppShellMobile",+ "useClickableContainer",+ "useClipboard",+ "useCollapsible",+ "useCollator",+ "useContainerReveal",+ "useDevWarning",+ "useEntryAnimation",+ "useFocusTrap",+ "useGridFocus",+ "useHotkeys",+ "useHoverCard",+ "useImageMode",+ "useImperativeAlertDialog",+ "useImperativeDialog",+ "useIndicatorFocusRing",+ "useInputContainer",+ "useInputStatusIcon",+ "useInteractiveRole",+ "useKeyboardHint",+ "useLayer",+ "useListFocus",+ "useLocale",+ "useLongPress",+ "useMediaQuery",+ "useMergedRefs",+ "useOverflow",+ "usePopover",+ "useResizable",+ "useScrollableArea",+ "useScrollLock",+ "useScrollOverflow",+ "useStreamingText",+ "useTableColumnResize",+ "useTableColumnSettings",+ "useTableFiltering",+ "useTableFilterState",+ "useTableGroupedRows",+ "useTablePagination",+ "useTableRowExpansion",+ "useTableRowIndex",+ "useTableRowStatus",+ "useTableSelection",+ "useTableSelectionState",+ "useTableSortable",+ "useTableStickyColumns",+ "useTableTreeData",+ "useTableTreeState",+ "useTheme",+ "useToast",+ "useTooltip",+ "useTranslator",+ "useTreeFocus",+ "useTypeahead"+ ],+ "@astryxdesign/core/page": [+ "ai-chat",+ "ai-chat-landing",+ "blank",+ "canvas-editor",+ "centered-hero",+ "checkout-wizard",+ "classic-gallery",+ "contact-form",+ "dashboard",+ "dashboard-alert-rail",+ "dashboard-cohort-funnel",+ "dashboard-comparison",+ "dashboard-composition",+ "dashboard-progress",+ "dashboard-scorecard",+ "detail-page",+ "documentation",+ "documentation-design",+ "documentation-technical",+ "editor",+ "file-explorer",+ "form-two-column",+ "form-wizard",+ "form-wizard-dialog",+ "form-wizard-inline",+ "form-wizard-vertical",+ "gallery-hero",+ "ide",+ "incident-console",+ "kanban-board",+ "library",+ "login",+ "login-card",+ "login-split",+ "login-sso",+ "messaging-shell",+ "mixed-gallery",+ "payment-form",+ "product-detail",+ "product-gallery",+ "settings",+ "settings-dialog",+ "settings-sidebar",+ "shell-nav",+ "shell-side-nav",+ "shell-top-nav",+ "side-gallery",+ "table",+ "table-filter",+ "table-grouped",+ "table-inbox",+ "table-page",+ "table-tree",+ "theme-showcase",+ "work-item-detail"+ ],+ "@astryxdesign/core/block": [+ "AlertDialogAsyncAction",+ "AlertDialogDeleteConfirmation",+ "AppShellContentOnly",+ "AppShellMobileHookUsage",+ "AppShellShowcase",+ "AppShellSideNavOnly",+ "AppShellTopNavOnly",+ "AppShellTopNavWithSideNav",+ "AppShellWithBanner",+ "AspectRatioCircleImage",+ "AspectRatioImageGallery",+ "AspectRatioShowcase",+ "AspectRatioSquareImage",+ "AspectRatioWidescreen",+ "AspectRatioWithSkeleton",+ "AvatarFallbackChain",+ "AvatarGroup",+ "AvatarGroupInteractive",+ "AvatarGroupOverflowCustomText",+ "AvatarGroupOverflowDefault",+ "AvatarGroupOverflowShowcase",+ "AvatarGroupShowcase",+ "AvatarInitialsFallback",+ "AvatarInteractive",+ "AvatarShowcase",+ "AvatarStatusDotShowcase",+ "AvatarStatusDotVariants",+ "AvatarTooltip",+ "AvatarUserCard",+ "AvatarWithImage",+ "AvatarWithStatus",+ "BadgeCategoryTags",+ "BadgeCountBadges",+ "BadgeShowcase",+ "BadgeStatusLabels",+ "BannerCollapsibleContent",+ "BannerDismissable",+ "BannerFloating",+ "BannerSectionVariant",+ "BannerShowcase",+ "BannerStatuses",+ "BannerWithActionButton",+ "BaseTypeaheadCustomSearch",+ "BaseTypeaheadShowcase",+ "BlockquoteShowcase",+ "BlockquoteTestimonials",+ "BlockquoteWithCite",+ "BottomSheetHeights",+ "BottomSheetMobileKeyboard",+ "BottomSheetNoScrim",+ "BottomSheetShowcase",+ "BottomSheetSnapPoints",+ "BottomSheetSwitcherReviewFlow",+ "BottomSheetSwitcherShowcase",+ "BreadcrumbItemBasic",+ "BreadcrumbItemShowcase",+ "BreadcrumbsCustomSeparator",+ "BreadcrumbsDeepHierarchy",+ "BreadcrumbsMenuItem",+ "BreadcrumbsShowcase",+ "BreadcrumbsSupportingVariant",+ "BreadcrumbsWithIcons",+ "ButtonFloating",+ "ButtonGroupBasic",+ "ButtonGroupFloating",+ "ButtonGroupShowcase",+ "ButtonShowcase",+ "ButtonSizeVariants",+ "ButtonVariants",+ "ButtonWithEndSlot",+ "ButtonWithIcon",+ "CalendarConstraints",+ "CalendarRangeWithValue",+ "CalendarShowcase",+ "CalendarSingle",+ "CalendarTwoMonths",+ "CardCallout",+ "CardElevations",+ "CardShowcase",+ "CardVariants",+ "CardWithInnerLayout",+ "CardWithSimpleContent",+ "CarouselCards",+ "CarouselShowcase",+ "CarouselSnap",+ "CenterHorizontal",+ "CenterInsideACard",+ "CenterShowcase",+ "ChatComposerAttachments",+ "ChatComposerDrawerAttachments",+ "ChatComposerDrawerCollapsible",+ "ChatComposerDrawerFeedback",+ "ChatComposerDrawerShowcase",+ "ChatComposerDrawerWithProgress",+ "ChatComposerFlat",+ "ChatComposerFooterActions",+ "ChatComposerFullFeatured",+ "ChatComposerInputControlledInput",+ "ChatComposerInputDisabled",+ "ChatComposerInputMentionTrigger",+ "ChatComposerInputMultipleTriggers",+ "ChatComposerInputShowcase",+ "ChatComposerInputSlashCommands",+ "ChatComposerShowcase",+ "ChatComposerSimple",+ "ChatComposerStreaming",+ "ChatComposerValidation",+ "ChatDictationButtonBasic",+ "ChatDictationButtonShowcase",+ "ChatDictationDictationInComposer",+ "ChatDictationDictationStates",+ "ChatDictationSizes",+ "ChatLayoutPanelChat",+ "ChatLayoutScrollButtonLabels",+ "ChatLayoutScrollButtonStates",+ "ChatLayoutShowcase",+ "ChatMessageAvatarName",+ "ChatMessageBubbleCustomContent",+ "ChatMessageBubbleDensity",+ "ChatMessageBubbleGrouping",+ "ChatMessageBubbleMetadata",+ "ChatMessageBubbleShowcase",+ "ChatMessageBubbleVariants",+ "ChatMessageGhost",+ "ChatMessageListDensity",+ "ChatMessageListFullFeatured",+ "ChatMessageListShowcase",+ "ChatMessageMetadataFooter",+ "ChatMessageMetadataShowcase",+ "ChatMessageMetadataStatus",+ "ChatMessageMetadataTimestamp",+ "ChatMessageMultiBubble",+ "ChatMessageShowcase",+ "ChatSendButtonCustomIcon",+ "ChatSendButtonInComposer",+ "ChatSendButtonShowcase",+ "ChatSendButtonStates",+ "ChatSystemMessageShowcase",+ "ChatSystemMessageStatusUpdates",+ "ChatSystemMessageVariants",+ "ChatSystemMessageWithIcon",+ "ChatTokenizedTextBasic",+ "ChatTokenizedTextColors",+ "ChatTokenizedTextShowcase",+ "ChatToolCallsInteractiveToolCalls",+ "ChatToolCallsShowcase",+ "ChatToolCallsStatuses",+ "ChatToolCallsToolCallsWithNodes",+ "CheckboxInputBasic",+ "CheckboxInputIndeterminateState",+ "CheckboxInputShowcase",+ "CheckboxInputStatusVariations",+ "CheckboxListItemBasic",+ "CheckboxListItemShowcase",+ "CheckboxListSelectAllPattern",+ "CheckboxListShowcase",+ "CheckboxListWithEndContent",+ "CitationInlineText",+ "CitationShowcase",+ "CitationSourceList",+ "ClickableCardElevated",+ "ClickableCardShowcase",+ "ClickableCardWithNestedButton",+ "CodeAcrossTextSizes",+ "CodeBlockBashCommand",+ "CodeBlockHighlightedLines",+ "CodeBlockJSONConfig",+ "CodeBlockScrollableBlock",+ "CodeBlockShowcase",+ "CodeBlockTerminal",+ "CodeInlineInParagraph",+ "CodeShowcase",+ "CodeVariousContent",+ "CollapsibleControlledAccordion",+ "CollapsibleDividedAccordion",+ "CollapsibleGroupAccordion",+ "CollapsibleGroupShowcase",+ "CollapsibleHookUsage",+ "CollapsibleMultipleAccordion",+ "CollapsibleShowcase",+ "CollapsibleSingleAccordion",+ "CollapsibleWithoutCard",+ "ColumnResizeHookUsage",+ "CommandPaletteAsyncSearch",+ "CommandPaletteAutoGrouped",+ "CommandPaletteCustomFooter",+ "CommandPaletteEmptyBasic",+ "CommandPaletteEmptyShowcase",+ "CommandPaletteFooterBasic",+ "CommandPaletteFooterShowcase",+ "CommandPaletteGroupBasic",+ "CommandPaletteGroupShowcase",+ "CommandPaletteInputBasic",+ "CommandPaletteInputShowcase",+ "CommandPaletteItemBasic",+ "CommandPaletteItemShowcase",+ "CommandPaletteListBasic",+ "CommandPaletteListShowcase",+ "CommandPalettePickerMode",+ "CommandPaletteRichItems",+ "CommandPaletteShowcase",+ "ComplexSelectorDeadlinePicker",+ "ComplexSelectorShowcase",+ "ComplexSelectorTreeSearch",+ "ContextMenuBasic",+ "ContextMenuBottomSheet",+ "ContextMenuItemBasic",+ "ContextMenuItemShowcase",+ "ContextMenuShowcase",+ "DateInputClearable",+ "DateInputDateRange",+ "DateInputFormats",+ "DateInputShowcase",+ "DateInputWithDescription",+ "DateInputWithValidation",+ "DateRangeInputShowcase",+ "DateRangeInputWithPresets",+ "DateRangeInputWithValidation",+ "DateTimeInputShowcase",+ "DateTimeInputWithValidation",+ "DialogAdaptivePresentation",+ "DialogConfirmationDialog",+ "DialogFormDialog",+ "DialogFullscreenDialog",+ "DialogHeaderBasic",+ "DialogHeaderShowcase",+ "DialogScrollingContent",+ "DialogShowcase",+ "DialogWithSubtitle",+ "DividerFullBleed",+ "DividerShowcase",+ "DividerVariants",+ "DividerVertical",+ "DropdownMenuActions",+ "DropdownMenuBottomSheet",+ "DropdownMenuItemBasic",+ "DropdownMenuItemShowcase",+ "DropdownMenuNoChevron",+ "DropdownMenuShowcase",+ "DropdownMenuWithDisabledItems",+ "DropdownMenuWithSections",+ "DropdownMenuWithSubmenu",+ "EmptyStateActions",+ "EmptyStateCompact",+ "EmptyStateContainer",+ "EmptyStateShowcase",+ "FieldLabelBasic",+ "FieldLabelShowcase",+ "FieldRequired",+ "FieldShowcase",+ "FieldStatusBasic",+ "FieldStatusShowcase",+ "FieldStatusVariants",+ "FieldWithDescription",+ "FileInputBasic",+ "FileInputShowcase",+ "FormLayoutHorizontal",+ "FormLayoutHorizontalLabels",+ "FormLayoutMixedControls",+ "FormLayoutNested",+ "FormLayoutShowcase",+ "GridDashboardLayout",+ "GridGalleryExample",+ "GridResponsiveAutoFit",+ "GridShowcase",+ "GridSpanColumns",+ "GridSpanShowcase",+ "GridWithGridSpan",+ "HeadingCardGrid",+ "HeadingPageLayout",+ "HeadingShowcase",+ "HeadingTruncation",+ "HoverCardHookUsage",+ "HoverCardInlineTextHoverCard",+ "HoverCardInteractiveContent",+ "HoverCardProfileHoverCard",+ "HoverCardShowcase",+ "HStackBasic",+ "HStackShowcase",+ "IconButtonActionBar",+ "IconButtonFloating",+ "IconButtonLoadingToggle",+ "IconButtonShowcase",+ "IconButtonTooltipIconButton",+ "IconNonSemanticColors",+ "IconSemanticColors",+ "IconShowcase",+ "IconSizes",+ "IconStatusIcons",+ "InputGroupBasic",+ "InputGroupShowcase",+ "InternationalizationProvider01ShippedLocale",+ "InternationalizationProvider02Overrides",+ "InternationalizationProvider03RtlDirection",+ "ItemBasicItem",+ "ItemShowcase",+ "ItemWithMedia",+ "ItemWithMetadata",+ "KbdInlineInstructions",+ "KbdMenuShortcuts",+ "KbdModifierCombos",+ "KbdShowcase",+ "LayerHookUsage",+ "LayoutBasicCardLayout",+ "LayoutContentBasic",+ "LayoutContentOnlyLayout",+ "LayoutContentShowcase",+ "LayoutContentWidth",+ "LayoutDualPanelLayout",+ "LayoutFooterActions",+ "LayoutFooterShowcase",+ "LayoutFullBleedContent",+ "LayoutHeaderShowcase",+ "LayoutHeaderWithActions",+ "LayoutPanelNavigation",+ "LayoutPanelShowcase",+ "LayoutShowcase",+ "LayoutSidebarLayout",+ "LightboxGallery",+ "LightboxShowcase",+ "LightboxVideo",+ "LightboxZoom",+ "LinkExternalLinks",+ "LinkInlineLink",+ "LinkProviderCustomLink",+ "LinkShowcase",+ "LinksWithTooltips",+ "ListBasicList",+ "ListBulletedFeatures",+ "ListItemBasicItem",+ "ListItemShowcase",+ "ListItemWithMedia",+ "ListItemWithMetadata",+ "ListMessageList",+ "ListOrderedSteps",+ "ListShowcase",+ "MarkdownCitedContent",+ "MarkdownCompactAIResponse",+ "MarkdownDataTable",+ "MarkdownRichContent",+ "MarkdownShowcase",+ "MediaThemeImageOverlay",+ "MediaThemeLightScrim",+ "MediaThemeShowcase",+ "MetadataListBasicMetadata",+ "MetadataListCollapsibleMetadata",+ "MetadataListHorizontalMetadata",+ "MetadataListItemBasic",+ "MetadataListItemShowcase",+ "MetadataListMultiColumnMetadata",+ "MetadataListShowcase",+ "MobileNavBasicMobileNav",+ "MobileNavEndSideMobileNav",+ "MobileNavShowcase",+ "MobileNavToggleBasic",+ "MobileNavToggleShowcase",+ "MobileNavWithoutTitleMobileNav",+ "MoreMenuBottomSheet",+ "MoreMenuDefaultMoreMenu",+ "MoreMenuShowcase",+ "MoreMenuWithDividers",+ "MoreMenuWithSections",+ "MultiSelectorBottomSheet",+ "MultiSelectorColumnVisibilitySelector",+ "MultiSelectorForm",+ "MultiSelectorGhostToolbar",+ "MultiSelectorSearchableMultiSelector",+ "MultiSelectorSectionedMultiSelector",+ "MultiSelectorShowcase",+ "NavHeadingMenuShowcase",+ "NavIconBasic",+ "NavIconShowcase",+ "NumberInputClearableNumberInput",+ "NumberInputRangeNumberInput",+ "NumberInputShowcase",+ "NumberInputStatuses",+ "NumberInputWithUnits",+ "OutlineControlled",+ "OutlineDeepNesting",+ "OutlineDensity",+ "OutlineShowcase",+ "OverflowListCappedToolbar",+ "OverflowListCollapseFromStartList",+ "OverflowListMultiRowTags",+ "OverflowListOverflowBadges",+ "OverflowListOverflowDropdownActions",+ "OverflowListShowcase",+ "OverlayBottomStrip",+ "OverlayHoverReveal",+ "OverlayShowcase",+ "PaginationDotsCarousel",+ "PaginationPageSize",+ "PaginationVariants",+ "PaginationWithTable",+ "PopoverBottomSheetAlternative",+ "PopoverConfirmAction",+ "PopoverFilterPanel",+ "PopoverHookUsage",+ "PopoverKeyboardShortcuts",+ "PopoverSettingsPanel",+ "PopoverShowcase",+ "PowerSearchContentSearch",+ "PowerSearchFullFeatured",+ "PowerSearchPresetFilters",+ "PowerSearchSearchWithTable",+ "PowerSearchShowcase",+ "ProgressBarCustomFormat",+ "ProgressBarIndeterminate",+ "ProgressBarSemanticVariants",+ "ProgressBarShowcase",+ "ProgressBarWithValueLabel",+ "RadioListHorizontalLayout",+ "RadioListItemBasic",+ "RadioListItemShowcase",+ "RadioListPricingTier",+ "RadioListShowcase",+ "RadioListWithDescriptions",+ "RadioListWithValidation",+ "ResizableShowcase",+ "ResizableSidebar",+ "SectionVariants",+ "SectionWashHighlight",+ "SectionWithDividers",+ "SegmentedControlDisabledItem",+ "SegmentedControlFillLayout",+ "SegmentedControlIconOnly",+ "SegmentedControlItemBasic",+ "SegmentedControlItemShowcase",+ "SegmentedControlShowcase",+ "SegmentedControlWithIcons",+ "SelectableCardElevated",+ "SelectableCardMulti",+ "SelectableCardShowcase",+ "SelectorBottomSheet",+ "SelectorClearable",+ "SelectorGhostToolbar",+ "SelectorOptionBasic",+ "SelectorOptionDescriptions",+ "SelectorOptionShowcase",+ "SelectorShowcase",+ "SelectorWithSections",+ "SelectorWithStatus",+ "SideNavCollapseButtonBasic",+ "SideNavCollapseButtonShowcase",+ "SideNavEndContent",+ "SideNavHeadingBasic",+ "SideNavHeadingShowcase",+ "SideNavItemBasic",+ "SideNavItemShowcase",+ "SideNavNestedItems",+ "SideNavSectionBasic",+ "SideNavSectionShowcase",+ "SideNavShowcase",+ "SideNavWithHeaderMenu",+ "SkeletonCardSkeleton",+ "SkeletonShowcase",+ "SkeletonStaggeredList",+ "SkeletonTableRowSkeleton",+ "SliderFormattedValue",+ "SliderRangeSlider",+ "SliderShowcase",+ "SliderWithMarks",+ "SliderWithStatus",+ "SpinnerOnMedia",+ "SpinnerShowcase",+ "SpinnerSizes",+ "SpinnerWithLabel",+ "StackAlignment",+ "StackDirections",+ "StackFillItem",+ "StackItemFill",+ "StackItemShowcase",+ "StatusDotPulsing",+ "StatusDotShowcase",+ "StatusDotStatusIndicators",+ "StatusDotVariants",+ "StepContent",+ "StepIndicator",+ "StepperCustomContent",+ "StepperIndicatorModes",+ "StepperOnTrackHorizontal",+ "StepperOnTrackVertical",+ "StepperShowcase",+ "StepperStatus",+ "StepperWidthResponsiveCollapse",+ "StepShowcase",+ "StepStates",+ "StickyColumnsHookUsage",+ "SwitchDisabled",+ "SwitchSettingsPanel",+ "SwitchShowcase",+ "SwitchWithDescription",+ "SwitchWithStatus",+ "SyntaxThemeDarkPreset",+ "SyntaxThemeLightPreset",+ "SyntaxThemeShowcase",+ "TableColumnSettingsTable",+ "TableFilterableTable",+ "TableGridDividersTable",+ "TableGroupedRowsTable",+ "TableInCard",+ "TableInlineFilterTable",+ "TablePaginatedTable",+ "TableResizableTable",+ "TableRichCellTable",+ "TableRowExpansionTable",+ "TableRowIndexTable",+ "TableRowStatusTable",+ "TableSelectableTable",+ "TableShowcase",+ "TableSortableTable",+ "TableStripedTable",+ "TableTreeTable",+ "TabListShowcase",+ "TabListTabsFillLayout",+ "TabListTabsWithActions",+ "TabListTabsWithBadge",+ "TabListTabsWithIcons",+ "TabListTabsWithMenu",+ "TabListTabsWithStatusDot",+ "TabMenuBasic",+ "TabMenuShowcase",+ "TabShowcase",+ "TabWithSelectedIcon",+ "TextAreaCharacterCount",+ "TextAreaShowcase",+ "TextAreaStates",+ "TextAreaValidation",+ "TextAreaWithIcon",+ "TextColors",+ "TextHeadingLevels",+ "TextInline",+ "TextInputIcon",+ "TextInputSearch",+ "TextInputShowcase",+ "TextInputSizes",+ "TextInputStates",+ "TextInputStatusVariant",+ "TextInputTypes",+ "TextShowcase",+ "TextTruncation",+ "TextTypes",+ "TextWeight",+ "TextWordBreak",+ "TextWrap",+ "ThemeApply",+ "ThemeNested",+ "ThemeShowcase",+ "ThemeSwitcher",+ "ThumbnailDisabled",+ "ThumbnailGallery",+ "ThumbnailRemovable",+ "ThumbnailShowcase",+ "ThumbnailStates",+ "TimeInputConstrained",+ "TimeInputFormats",+ "TimeInputIncrement",+ "TimeInputShowcase",+ "TimeInputStates",+ "TimerFormats",+ "TimerInline",+ "TimerShowcase",+ "TimerTypography",+ "TimestampAutoFormat",+ "TimestampColors",+ "TimestampFormats",+ "TimestampRelativeFormat",+ "TimestampShowcase",+ "TimestampTimezone",+ "TimestampTooltipTimezones",+ "ToastAction",+ "ToastDeduplication",+ "ToastDismiss",+ "ToastShowcase",+ "ToastStacking",+ "ToastTypes",+ "ToggleButtonColor",+ "ToggleButtonGroup",+ "ToggleButtonGroupShowcase",+ "ToggleButtonGroupVertical",+ "ToggleButtonIconSwap",+ "ToggleButtonLabel",+ "ToggleButtonShowcase",+ "ToggleButtonStates",+ "TokenClickable",+ "TokenColors",+ "TokenEndContent",+ "TokenIcon",+ "TokenizerClear",+ "TokenizerCreatable",+ "TokenizerEndContent",+ "TokenizerIcon",+ "TokenizerMaxEntries",+ "TokenizerOverflow",+ "TokenizerShowcase",+ "TokenizerStates",+ "TokenRemovable",+ "TokenShowcase",+ "ToolbarBulkActions",+ "ToolbarCardHeader",+ "ToolbarSizes",+ "ToolbarTableFilter",+ "ToolbarThreeSlot",+ "ToolbarWithTabs",+ "TooltipActionBarTooltips",+ "TooltipHookUsage",+ "TooltipInlineTextTooltips",+ "TooltipShowcase",+ "TopNavCenteredNavigation",+ "TopNavEnterpriseDashboard",+ "TopNavHeadingBasic",+ "TopNavHeadingShowcase",+ "TopNavHoverMenu",+ "TopNavItemBasic",+ "TopNavItemShowcase",+ "TopNavMegaMenu",+ "TopNavMegaMenuBasic",+ "TopNavMegaMenuFeaturedCardBasic",+ "TopNavMegaMenuFeaturedCardShowcase",+ "TopNavMegaMenuItemBasic",+ "TopNavMegaMenuItemShowcase",+ "TopNavMegaMenuShowcase",+ "TopNavMenuBasic",+ "TopNavMenuShowcase",+ "TopNavMultipleDropdowns",+ "TopNavShowcase",+ "TopNavWithLogo",+ "TreeListFileTreeWithIcons",+ "TreeListInteractiveSettings",+ "TreeListMailboxTree",+ "TreeListNavigationTree",+ "TreeListShowcase",+ "TreeListVariants",+ "TypeaheadItemBasic",+ "TypeaheadItemShowcase",+ "TypeaheadLimitedResults",+ "TypeaheadSearchField",+ "TypeaheadShowcase",+ "TypeaheadWithHelperText",+ "TypeaheadWithValidation",+ "useContainerRevealHookUsage",+ "useKeyboardHintHookUsage",+ "useStreamingTextHookUsage",+ "useThemeHookUsage",+ "VisuallyHiddenLiveRegion",+ "VisuallyHiddenShowcase",+ "VisuallyHiddenStructuralHeading",+ "VisuallyHiddenSupplementaryContext",+ "VStackBasic",+ "VStackShowcase"+ ],+ "@astryxdesign/cli/theme": [+ "butter",+ "chocolate",+ "gothic",+ "matcha",+ "neutral",+ "stone",+ "y2k"+ ],+ "@astryxdesign/cli/command": [+ "blog",+ "build",+ "component",+ "discover",+ "docs",+ "doctor",+ "doctor integration",+ "doctor integration components",+ "doctor integration docs",+ "doctor integration templates",+ "doctor integration validate",+ "gap-report",+ "hook",+ "init",+ "integration",+ "integration add",+ "integration pack",+ "layout",+ "layout check",+ "layout expand",+ "layout grammar",+ "manifest",+ "search",+ "swizzle",+ "template",+ "theme",+ "theme add",+ "theme build",+ "theme list",+ "theme palette",+ "theme palette generate",+ "theme targets",+ "theme template",+ "upgrade"+ ],+ "@astryxdesign/cli/function": [+ "assertResponse",+ "blog",+ "build",+ "component",+ "discover",+ "docs",+ "doctor",+ "gapReport",+ "generateTonalPalette",+ "hook",+ "init",+ "integrationAdd",+ "integrationAddAgentDoc",+ "integrationAddCodemod",+ "integrationAddComponent",+ "integrationAddDoc",+ "integrationAddTemplate",+ "integrationAddTheme",+ "integrationComponentConflicts",+ "integrationDocConflicts",+ "integrationPackCheck",+ "integrationTemplateConflicts",+ "isError",+ "layoutCheck",+ "layoutExpand",+ "layoutGrammar",+ "listThemes",+ "parseResponse",+ "search",+ "summarizeIssues",+ "swizzle",+ "template",+ "themeAdd",+ "themeBuild",+ "themeList",+ "themeListAvailable",+ "themePaletteGenerate",+ "themeTargets",+ "themeTemplate",+ "upgrade",+ "validateIntegration"+ ],+ "@astryxdesign/cli/schema": [+ "authored-doc-graph-fields",+ "codemod",+ "command-doc",+ "component-doc",+ "config",+ "debug-event",+ "enum-doc",+ "function-doc",+ "gap-report-handler",+ "hook-doc",+ "integration",+ "namespace-doc",+ "output",+ "provider-identity",+ "reference-doc",+ "schema-doc",+ "template-doc",+ "theme-doc"+ ],+ "@astryxdesign/cli/enum": ["error-codes", "response-types"]+}diff --git a/packages/cli/test/doc-routes.json b/packages/cli/test/doc-routes.jsonnew file mode 100644index 0000000000..216a2b8e96--- /dev/null+++ b/packages/cli/test/doc-routes.json@@ -0,0 +1,3107 @@+{+ "about": [+ "Every current doc route with a PROPOSED docs-graph placement. The docs graph spec is not decided; nothing here moves anything, and doc-routes.test.mjs fails when a current route has no row, a row names a route that no longer exists, or a row breaks the placement rules below.",+ "Rows: one per built-in topic (`astryx docs <topic>`) and per section key (`astryx docs <topic> <key>`); typed descriptors take one row per provider and kind, with `count` and the ids in doc-routes.ids.json under the row id. Placeholders <id> expand per id. Per-item rows would repeat one decision per group hundreds of times (704 templates alone).",+ "placement: keep-flat (the route stays where it is), namespace:<path> (the doc becomes <path> in the graph), or generated:<provider>/<kind> (the unorganized bucket for typed descriptors that author no placement). Anything but keep-flat carries a one-line evidence note, and a namespace must be decided `create` under namespaces.",+ "aliasNeeded: true when the proposal leaves the old CLI route or docsite URL without its content unless an alias keeps it resolving. Sections move with their topic.",+ "oldDocsiteUrl: the public docsite URL (paths on astryx.atmeta.com). Topic and section URLs are checked; section anchors are the docsite outline ids (slugged titles). docsiteExceptions on descriptor rows were measured on 2026-09-24 from a canary data build of apps/docsite and are not rechecked by the test; production documents the latest published core, so a newer component has no page until release."+ ],+ "idsFile": "doc-routes.ids.json",+ "namespaces": [+ {+ "name": "cli",+ "decision": "create",+ "evidence": "cli-integrations documents the CLI's integration surface (see its row), and the NamespaceDoc contract's own example is a 'cli' namespace for commands, APIs and integration authoring.",+ "note": "`astryx docs cli` is the namespace's first reader: every doc whose namespace is cli/commands or cli/api, one section each. /docs/cli is still the @astryxdesign/cli package page on the docsite; the namespace page must take that URL before the docsite publishes it. Considered and left out: authoring, whose section docs declare namespace 'authoring', a sibling of 'cli' in the SchemaDoc contract."+ },+ {+ "name": "foundations",+ "decision": "reject",+ "evidence": "Only the docsite's 'foundations' category label groups color, elevation, icons, illustrations, motion, shape, spacing, tokens and typography. The docsite serves each flat at /docs/<topic>, and icons and illustrations are not token pages."+ },+ {+ "name": "styling",+ "decision": "reject",+ "evidence": "styling-libraries is linked from styling and from theme; only the hyphen suggests styling/libraries."+ },+ {+ "name": "theme",+ "decision": "reject",+ "evidence": "No topic is a child of theme: theme descriptors and theme command docs are typed descriptors (generated bucket), and theme's 17 sections stay with it."+ },+ {+ "name": "migration",+ "decision": "reject",+ "evidence": "migration is one guide with no child topics; the draft shadcn-compatibility doc is not a route, and version upgrades are the upgrade command doc."+ },+ {+ "name": "tokens",+ "decision": "reject",+ "evidence": "The six token-category pages pull their tables from tokens by token reference; the only other tie is the tokenCategory label. Nothing authored nests them."+ }+ ],+ "rows": [+ {+ "kind": "topic",+ "id": "authoring",+ "oldCliRoute": "astryx docs authoring",+ "oldDocsiteUrl": "/docs/authoring",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Integration-author reference, built from the CLI's authoring self-docs (one section each). Stays top-level: the SchemaDoc contract names 'cli' and 'authoring' as sibling namespace paths, and 12 of its 15 section docs declare namespace 'authoring'. On the docsite, 14 of its 15 anchors come from section titles and differ from the section keys.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#integration",+ "oldCliRoute": "astryx docs authoring integration",+ "oldDocsiteUrl": "/docs/authoring#astryx-integration",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `integration` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#config",+ "oldCliRoute": "astryx docs authoring config",+ "oldDocsiteUrl": "/docs/authoring#astryx-config",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `config` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#debug-event",+ "oldCliRoute": "astryx docs authoring debug-event",+ "oldDocsiteUrl": "/docs/authoring#debugevent",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `debug-event` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#gap-report-handler",+ "oldCliRoute": "astryx docs authoring gap-report-handler",+ "oldDocsiteUrl": "/docs/authoring#gapreporthandler",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `gap-report-handler` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#codemod",+ "oldCliRoute": "astryx docs authoring codemod",+ "oldDocsiteUrl": "/docs/authoring#astryx-codemod",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `codemod` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#provider-identity",+ "oldCliRoute": "astryx docs authoring provider-identity",+ "oldDocsiteUrl": "/docs/authoring#provider-and-artifact-identity",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `provider-identity` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#authored-doc-graph-fields",+ "oldCliRoute": "astryx docs authoring authored-doc-graph-fields",+ "oldDocsiteUrl": "/docs/authoring#authored-doc-graph-fields",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `authored-doc-graph-fields` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#component-doc",+ "oldCliRoute": "astryx docs authoring component-doc",+ "oldDocsiteUrl": "/docs/authoring#componentdoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `component-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#hook-doc",+ "oldCliRoute": "astryx docs authoring hook-doc",+ "oldDocsiteUrl": "/docs/authoring#hookdoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `hook-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#function-doc",+ "oldCliRoute": "astryx docs authoring function-doc",+ "oldDocsiteUrl": "/docs/authoring#functiondoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `function-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#command-doc",+ "oldCliRoute": "astryx docs authoring command-doc",+ "oldDocsiteUrl": "/docs/authoring#commanddoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `command-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#enum-doc",+ "oldCliRoute": "astryx docs authoring enum-doc",+ "oldDocsiteUrl": "/docs/authoring#enumdoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `enum-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#namespace-doc",+ "oldCliRoute": "astryx docs authoring namespace-doc",+ "oldDocsiteUrl": "/docs/authoring#namespacedoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `namespace-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#reference-doc",+ "oldCliRoute": "astryx docs authoring reference-doc",+ "oldDocsiteUrl": "/docs/authoring#referencedoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `reference-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#schema-doc",+ "oldCliRoute": "astryx docs authoring schema-doc",+ "oldDocsiteUrl": "/docs/authoring#schemadoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `schema-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#template-doc",+ "oldCliRoute": "astryx docs authoring template-doc",+ "oldDocsiteUrl": "/docs/authoring#templatedoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `template-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "authoring#theme-doc",+ "oldCliRoute": "astryx docs authoring theme-doc",+ "oldDocsiteUrl": "/docs/authoring#themedoc",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `theme-doc` (schema row), which the topic renders as one section.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "cli",+ "oldCliRoute": "astryx docs cli",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Built from every doc whose namespace is cli/commands or cli/api; astryx doctor fails on a CLI doc with no namespace or one no topic reads.",+ "rationale": "The cli namespace page: one section per command, API function, output schema, and enum doc the CLI ships, keyed commands-<name> and api-<name>. The docsite does not publish it yet, because /docs/cli is the @astryxdesign/cli package page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-blog",+ "oldCliRoute": "astryx docs cli commands-blog",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `blog` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-build",+ "oldCliRoute": "astryx docs cli commands-build",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `build` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-component",+ "oldCliRoute": "astryx docs cli commands-component",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `component` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-discover",+ "oldCliRoute": "astryx docs cli commands-discover",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `discover` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-docs",+ "oldCliRoute": "astryx docs cli commands-docs",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `docs` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-doctor",+ "oldCliRoute": "astryx docs cli commands-doctor",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `doctor` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-doctor-integration",+ "oldCliRoute": "astryx docs cli commands-doctor-integration",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `doctor integration` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-doctor-integration-components",+ "oldCliRoute": "astryx docs cli commands-doctor-integration-components",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `doctor integration components` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-doctor-integration-docs",+ "oldCliRoute": "astryx docs cli commands-doctor-integration-docs",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `doctor integration docs` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-doctor-integration-templates",+ "oldCliRoute": "astryx docs cli commands-doctor-integration-templates",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `doctor integration templates` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-doctor-integration-validate",+ "oldCliRoute": "astryx docs cli commands-doctor-integration-validate",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `doctor integration validate` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-gap-report",+ "oldCliRoute": "astryx docs cli commands-gap-report",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `gap-report` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-hook",+ "oldCliRoute": "astryx docs cli commands-hook",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `hook` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-init",+ "oldCliRoute": "astryx docs cli commands-init",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `init` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-integration",+ "oldCliRoute": "astryx docs cli commands-integration",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `integration` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-integration-add",+ "oldCliRoute": "astryx docs cli commands-integration-add",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `integration add` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-integration-pack",+ "oldCliRoute": "astryx docs cli commands-integration-pack",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `integration pack` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-layout",+ "oldCliRoute": "astryx docs cli commands-layout",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `layout` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-layout-check",+ "oldCliRoute": "astryx docs cli commands-layout-check",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `layout check` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-layout-expand",+ "oldCliRoute": "astryx docs cli commands-layout-expand",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `layout expand` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-layout-grammar",+ "oldCliRoute": "astryx docs cli commands-layout-grammar",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `layout grammar` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-manifest",+ "oldCliRoute": "astryx docs cli commands-manifest",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `manifest` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-search",+ "oldCliRoute": "astryx docs cli commands-search",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `search` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-swizzle",+ "oldCliRoute": "astryx docs cli commands-swizzle",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `swizzle` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-template",+ "oldCliRoute": "astryx docs cli commands-template",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `template` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-theme",+ "oldCliRoute": "astryx docs cli commands-theme",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `theme` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-theme-add",+ "oldCliRoute": "astryx docs cli commands-theme-add",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `theme add` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-theme-build",+ "oldCliRoute": "astryx docs cli commands-theme-build",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `theme build` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-theme-list",+ "oldCliRoute": "astryx docs cli commands-theme-list",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `theme list` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-theme-palette",+ "oldCliRoute": "astryx docs cli commands-theme-palette",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `theme palette` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-theme-palette-generate",+ "oldCliRoute": "astryx docs cli commands-theme-palette-generate",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `theme palette generate` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-theme-targets",+ "oldCliRoute": "astryx docs cli commands-theme-targets",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `theme targets` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-theme-template",+ "oldCliRoute": "astryx docs cli commands-theme-template",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `theme template` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#commands-upgrade",+ "oldCliRoute": "astryx docs cli commands-upgrade",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/commands.",+ "rationale": "The command doc `upgrade` (command row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-assert-response",+ "oldCliRoute": "astryx docs cli api-assert-response",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `assertResponse` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-blog",+ "oldCliRoute": "astryx docs cli api-blog",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `blog` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-build",+ "oldCliRoute": "astryx docs cli api-build",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `build` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-component",+ "oldCliRoute": "astryx docs cli api-component",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `component` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-discover",+ "oldCliRoute": "astryx docs cli api-discover",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `discover` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-docs",+ "oldCliRoute": "astryx docs cli api-docs",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `docs` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-doctor",+ "oldCliRoute": "astryx docs cli api-doctor",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `doctor` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-gap-report",+ "oldCliRoute": "astryx docs cli api-gap-report",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `gapReport` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-generate-tonal-palette",+ "oldCliRoute": "astryx docs cli api-generate-tonal-palette",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `generateTonalPalette` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-hook",+ "oldCliRoute": "astryx docs cli api-hook",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `hook` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-init",+ "oldCliRoute": "astryx docs cli api-init",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `init` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-add",+ "oldCliRoute": "astryx docs cli api-integration-add",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationAdd` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-add-agent-doc",+ "oldCliRoute": "astryx docs cli api-integration-add-agent-doc",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationAddAgentDoc` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-add-codemod",+ "oldCliRoute": "astryx docs cli api-integration-add-codemod",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationAddCodemod` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-add-component",+ "oldCliRoute": "astryx docs cli api-integration-add-component",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationAddComponent` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-add-doc",+ "oldCliRoute": "astryx docs cli api-integration-add-doc",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationAddDoc` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-add-template",+ "oldCliRoute": "astryx docs cli api-integration-add-template",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationAddTemplate` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-add-theme",+ "oldCliRoute": "astryx docs cli api-integration-add-theme",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationAddTheme` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-component-conflicts",+ "oldCliRoute": "astryx docs cli api-integration-component-conflicts",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationComponentConflicts` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-doc-conflicts",+ "oldCliRoute": "astryx docs cli api-integration-doc-conflicts",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationDocConflicts` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-pack-check",+ "oldCliRoute": "astryx docs cli api-integration-pack-check",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationPackCheck` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-integration-template-conflicts",+ "oldCliRoute": "astryx docs cli api-integration-template-conflicts",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `integrationTemplateConflicts` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-is-error",+ "oldCliRoute": "astryx docs cli api-is-error",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `isError` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-layout-check",+ "oldCliRoute": "astryx docs cli api-layout-check",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `layoutCheck` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-layout-expand",+ "oldCliRoute": "astryx docs cli api-layout-expand",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `layoutExpand` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-layout-grammar",+ "oldCliRoute": "astryx docs cli api-layout-grammar",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `layoutGrammar` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-list-themes",+ "oldCliRoute": "astryx docs cli api-list-themes",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `listThemes` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-parse-response",+ "oldCliRoute": "astryx docs cli api-parse-response",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `parseResponse` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-search",+ "oldCliRoute": "astryx docs cli api-search",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `search` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-summarize-issues",+ "oldCliRoute": "astryx docs cli api-summarize-issues",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `summarizeIssues` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-swizzle",+ "oldCliRoute": "astryx docs cli api-swizzle",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `swizzle` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-template",+ "oldCliRoute": "astryx docs cli api-template",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `template` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-theme-add",+ "oldCliRoute": "astryx docs cli api-theme-add",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `themeAdd` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-theme-build",+ "oldCliRoute": "astryx docs cli api-theme-build",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `themeBuild` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-theme-list",+ "oldCliRoute": "astryx docs cli api-theme-list",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `themeList` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-theme-list-available",+ "oldCliRoute": "astryx docs cli api-theme-list-available",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `themeListAvailable` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-theme-palette-generate",+ "oldCliRoute": "astryx docs cli api-theme-palette-generate",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `themePaletteGenerate` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-theme-targets",+ "oldCliRoute": "astryx docs cli api-theme-targets",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `themeTargets` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-theme-template",+ "oldCliRoute": "astryx docs cli api-theme-template",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `themeTemplate` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-upgrade",+ "oldCliRoute": "astryx docs cli api-upgrade",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `upgrade` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-validate-integration",+ "oldCliRoute": "astryx docs cli api-validate-integration",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The API function doc `validateIntegration` (function row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-output",+ "oldCliRoute": "astryx docs cli api-output",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The schema doc `output` (schema row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-error-codes",+ "oldCliRoute": "astryx docs cli api-error-codes",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The enum doc `error-codes` (enum row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli#api-response-types",+ "oldCliRoute": "astryx docs cli api-response-types",+ "oldDocsiteUrl": null,+ "placement": "namespace:cli",+ "aliasNeeded": false,+ "evidence": "Its doc declares namespace cli/api.",+ "rationale": "The enum doc `response-types` (enum row), read as one section of the cli namespace page.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "browser-support",+ "oldCliRoute": "astryx docs browser-support",+ "oldDocsiteUrl": "/docs/browser-support",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Standalone guide: no topic links to it, and nothing authored places it under another topic.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "browser-support#overview",+ "oldCliRoute": "astryx docs browser-support overview",+ "oldDocsiteUrl": "/docs/browser-support#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of browser-support under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "browser-support#support-tiers",+ "oldCliRoute": "astryx docs browser-support support-tiers",+ "oldDocsiteUrl": "/docs/browser-support#support-tiers",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of browser-support under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "browser-support#which-features-set-the-floor",+ "oldCliRoute": "astryx docs browser-support which-features-set-the-floor",+ "oldDocsiteUrl": "/docs/browser-support#which-features-set-the-floor",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of browser-support under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "browser-support#which-components-are-affected",+ "oldCliRoute": "astryx docs browser-support which-components-are-affected",+ "oldDocsiteUrl": "/docs/browser-support#which-components-are-affected",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of browser-support under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "browser-support#what-astryx-guarantees",+ "oldCliRoute": "astryx docs browser-support what-astryx-guarantees",+ "oldDocsiteUrl": "/docs/browser-support#what-astryx-guarantees",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of browser-support under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "browser-support#supporting-older-browsers",+ "oldCliRoute": "astryx docs browser-support supporting-older-browsers",+ "oldDocsiteUrl": "/docs/browser-support#supporting-older-browsers",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of browser-support under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "browser-support#how-these-tiers-move-over-time",+ "oldCliRoute": "astryx docs browser-support how-these-tiers-move-over-time",+ "oldDocsiteUrl": "/docs/browser-support#how-these-tiers-move-over-time",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of browser-support under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "cli-integrations",+ "oldCliRoute": "astryx docs cli-integrations",+ "oldDocsiteUrl": "/docs/cli-integrations",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Its subject is the CLI's integration surface: 10 of its 14 sections drive `astryx integration add|pack`, `astryx doctor integration ...`, `astryx init` or `astryx upgrade`.",+ "rationale": "Guide for integration authors. `astryx docs cli-integrations` and /docs/cli-integrations must keep resolving. The docsite already serves /docs/cli as the @astryxdesign/cli package page, so the cli namespace page has to take over that URL.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#overview",+ "oldCliRoute": "astryx docs cli-integrations overview",+ "oldDocsiteUrl": "/docs/cli-integrations#overview",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#authoring-with-the-cli",+ "oldCliRoute": "astryx docs cli-integrations authoring-with-the-cli",+ "oldDocsiteUrl": "/docs/cli-integrations#authoring-with-the-cli",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#theme-package-walkthrough",+ "oldCliRoute": "astryx docs cli-integrations theme-package-walkthrough",+ "oldDocsiteUrl": "/docs/cli-integrations#theme-package-walkthrough",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#contribution-kinds-at-a-glance",+ "oldCliRoute": "astryx docs cli-integrations contribution-kinds-at-a-glance",+ "oldDocsiteUrl": "/docs/cli-integrations#contribution-kinds-at-a-glance",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#the-integration-file",+ "oldCliRoute": "astryx docs cli-integrations the-integration-file",+ "oldDocsiteUrl": "/docs/cli-integrations#the-integration-file",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#components",+ "oldCliRoute": "astryx docs cli-integrations components",+ "oldDocsiteUrl": "/docs/cli-integrations#components",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#templates",+ "oldCliRoute": "astryx docs cli-integrations templates",+ "oldDocsiteUrl": "/docs/cli-integrations#templates",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#docs",+ "oldCliRoute": "astryx docs cli-integrations docs",+ "oldDocsiteUrl": "/docs/cli-integrations#docs",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#themes",+ "oldCliRoute": "astryx docs cli-integrations themes",+ "oldDocsiteUrl": "/docs/cli-integrations#themes",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#agent-docs",+ "oldCliRoute": "astryx docs cli-integrations agent-docs",+ "oldDocsiteUrl": "/docs/cli-integrations#agent-docs",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#codemods",+ "oldCliRoute": "astryx docs cli-integrations codemods",+ "oldDocsiteUrl": "/docs/cli-integrations#codemods",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#recording-runs",+ "oldCliRoute": "astryx docs cli-integrations recording-runs",+ "oldDocsiteUrl": "/docs/cli-integrations#recording-runs",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#gap-report-handler",+ "oldCliRoute": "astryx docs cli-integrations gap-report-handler",+ "oldDocsiteUrl": "/docs/cli-integrations#gap-report-handler",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "cli-integrations#how-it-works",+ "oldCliRoute": "astryx docs cli-integrations how-it-works",+ "oldDocsiteUrl": "/docs/cli-integrations#how-it-works",+ "placement": "namespace:cli/integrations",+ "aliasNeeded": true,+ "evidence": "Moves with cli-integrations.",+ "rationale": "Stays a section of cli-integrations under the same key, so its old route needs an alias along with the topic's.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "color",+ "oldCliRoute": "astryx docs color",+ "oldDocsiteUrl": "/docs/color",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Token-category page (tokenCategory 'color') whose tables come from `tokens` through token references. Only the docsite's 'foundations' category label groups it with the other token pages, and a label alone is not evidence for a route segment.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "color#overview",+ "oldCliRoute": "astryx docs color overview",+ "oldDocsiteUrl": "/docs/color#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of color under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "color#surface-colors",+ "oldCliRoute": "astryx docs color surface-colors",+ "oldDocsiteUrl": "/docs/color#surface-colors",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of color under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "color#usage",+ "oldCliRoute": "astryx docs color usage",+ "oldDocsiteUrl": "/docs/color#usage",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of color under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "color#best-practices",+ "oldCliRoute": "astryx docs color best-practices",+ "oldDocsiteUrl": "/docs/color#best-practices",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of color under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "elevation",+ "oldCliRoute": "astryx docs elevation",+ "oldDocsiteUrl": "/docs/elevation",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Token-category page (tokenCategory 'shadow') whose tables come from `tokens` through token references. Only the docsite's 'foundations' category label groups it with the other token pages, and a label alone is not evidence for a route segment.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "elevation#overview",+ "oldCliRoute": "astryx docs elevation overview",+ "oldDocsiteUrl": "/docs/elevation#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of elevation under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "elevation#elevation-scale",+ "oldCliRoute": "astryx docs elevation elevation-scale",+ "oldDocsiteUrl": "/docs/elevation#elevation-scale",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of elevation under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "elevation#choosing-a-level",+ "oldCliRoute": "astryx docs elevation choosing-a-level",+ "oldDocsiteUrl": "/docs/elevation#choosing-a-level",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of elevation under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "elevation#the-elevation-prop",+ "oldCliRoute": "astryx docs elevation the-elevation-prop",+ "oldDocsiteUrl": "/docs/elevation#the-elevation-prop",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of elevation under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "elevation#usage",+ "oldCliRoute": "astryx docs elevation usage",+ "oldDocsiteUrl": "/docs/elevation#usage",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of elevation under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "elevation#best-practices",+ "oldCliRoute": "astryx docs elevation best-practices",+ "oldDocsiteUrl": "/docs/elevation#best-practices",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of elevation under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "getting-started",+ "oldCliRoute": "astryx docs getting-started",+ "oldDocsiteUrl": "/docs/getting-started",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Entry guide: the docsite redirects /docs here, and it links out to migration, styling, theme and tokens. Nothing places it under another topic.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "getting-started#quick-start-with-ai",+ "oldCliRoute": "astryx docs getting-started quick-start-with-ai",+ "oldDocsiteUrl": "/docs/getting-started#quick-start-with-ai",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of getting-started under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "getting-started#install",+ "oldCliRoute": "astryx docs getting-started install",+ "oldDocsiteUrl": "/docs/getting-started#install",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of getting-started under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "getting-started#add-the-theme-css",+ "oldCliRoute": "astryx docs getting-started add-the-theme-css",+ "oldDocsiteUrl": "/docs/getting-started#add-the-theme-css",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of getting-started under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "getting-started#add-your-first-component",+ "oldCliRoute": "astryx docs getting-started add-your-first-component",+ "oldDocsiteUrl": "/docs/getting-started#add-your-first-component",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of getting-started under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "getting-started#customize-with-stylex",+ "oldCliRoute": "astryx docs getting-started customize-with-stylex",+ "oldDocsiteUrl": "/docs/getting-started#customize-with-stylex",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of getting-started under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "getting-started#example-apps",+ "oldCliRoute": "astryx docs getting-started example-apps",+ "oldDocsiteUrl": "/docs/getting-started#example-apps",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of getting-started under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "getting-started#explore-the-cli",+ "oldCliRoute": "astryx docs getting-started explore-the-cli",+ "oldDocsiteUrl": "/docs/getting-started#explore-the-cli",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of getting-started under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "icons",+ "oldCliRoute": "astryx docs icons",+ "oldDocsiteUrl": "/docs/icons",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Shares only the 'foundations' category label with the token pages; it has no tokenCategory and no topic links to it.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "icons#available-names",+ "oldCliRoute": "astryx docs icons available-names",+ "oldDocsiteUrl": "/docs/icons#available-names",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of icons under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "icons#custom-icons",+ "oldCliRoute": "astryx docs icons custom-icons",+ "oldDocsiteUrl": "/docs/icons#custom-icons",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of icons under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "icons#theme-overrides",+ "oldCliRoute": "astryx docs icons theme-overrides",+ "oldDocsiteUrl": "/docs/icons#theme-overrides",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of icons under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "icons#component-and-library-icons",+ "oldCliRoute": "astryx docs icons component-and-library-icons",+ "oldDocsiteUrl": "/docs/icons#component-and-library-icons",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of icons under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "icons#adding-new-icons",+ "oldCliRoute": "astryx docs icons adding-new-icons",+ "oldDocsiteUrl": "/docs/icons#adding-new-icons",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of icons under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "illustrations",+ "oldCliRoute": "astryx docs illustrations",+ "oldDocsiteUrl": "/docs/illustrations",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Shares only the 'foundations' category label with the token pages; it has no tokenCategory and no topic links to it.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "illustrations#when-to-use",+ "oldCliRoute": "astryx docs illustrations when-to-use",+ "oldDocsiteUrl": "/docs/illustrations#when-to-use",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of illustrations under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "illustrations#guidelines",+ "oldCliRoute": "astryx docs illustrations guidelines",+ "oldDocsiteUrl": "/docs/illustrations#guidelines",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of illustrations under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "illustrations#placement",+ "oldCliRoute": "astryx docs illustrations placement",+ "oldDocsiteUrl": "/docs/illustrations#placement",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of illustrations under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "internationalization",+ "oldCliRoute": "astryx docs internationalization",+ "oldDocsiteUrl": "/docs/internationalization",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Standalone guide: no topic links to it, and nothing authored places it under another topic.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "internationalization#quick-start",+ "oldCliRoute": "astryx docs internationalization quick-start",+ "oldDocsiteUrl": "/docs/internationalization#quick-start",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of internationalization under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "internationalization#runtime-language-swap",+ "oldCliRoute": "astryx docs internationalization runtime-language-swap",+ "oldDocsiteUrl": "/docs/internationalization#runtime-language-swap",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of internationalization under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "internationalization#text-direction-rtl",+ "oldCliRoute": "astryx docs internationalization text-direction-rtl",+ "oldDocsiteUrl": "/docs/internationalization#text-direction-rtl",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of internationalization under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "internationalization#overriding-astryx-s-default-text",+ "oldCliRoute": "astryx docs internationalization overriding-astryx-s-default-text",+ "oldDocsiteUrl": "/docs/internationalization#overriding-astryx-s-default-text",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of internationalization under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "internationalization#using-astryx-with-your-own-i18n-library",+ "oldCliRoute": "astryx docs internationalization using-astryx-with-your-own-i18n-library",+ "oldDocsiteUrl": "/docs/internationalization#using-astryx-with-your-own-i18n-library",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of internationalization under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "internationalization#using-astryx-as-your-i18n-library",+ "oldCliRoute": "astryx docs internationalization using-astryx-as-your-i18n-library",+ "oldDocsiteUrl": "/docs/internationalization#using-astryx-as-your-i18n-library",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of internationalization under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "internationalization#testing-your-translations",+ "oldCliRoute": "astryx docs internationalization testing-your-translations",+ "oldDocsiteUrl": "/docs/internationalization#testing-your-translations",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of internationalization under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "internationalization#for-contributors",+ "oldCliRoute": "astryx docs internationalization for-contributors",+ "oldDocsiteUrl": "/docs/internationalization#for-contributors",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of internationalization under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "layout",+ "oldCliRoute": "astryx docs layout",+ "oldDocsiteUrl": "/docs/layout",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Standalone guide, linked from principles. The `layout` command group has its own command docs (generated bucket), so they are not children of this topic.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "layout#overview",+ "oldCliRoute": "astryx docs layout overview",+ "oldDocsiteUrl": "/docs/layout#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of layout under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "layout#scaffold",+ "oldCliRoute": "astryx docs layout scaffold",+ "oldDocsiteUrl": "/docs/layout#scaffold",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of layout under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "layout#structure",+ "oldCliRoute": "astryx docs layout structure",+ "oldDocsiteUrl": "/docs/layout#structure",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of layout under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "layout#spacing",+ "oldCliRoute": "astryx docs layout spacing",+ "oldDocsiteUrl": "/docs/layout#spacing",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of layout under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "layout#breakpoints",+ "oldCliRoute": "astryx docs layout breakpoints",+ "oldDocsiteUrl": "/docs/layout#breakpoints",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of layout under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "migration",+ "oldCliRoute": "astryx docs migration",+ "oldDocsiteUrl": "/docs/migration",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "One incremental guide (Tailwind, shadcn, Radix): its sections are the steps of that guide, and it only links out (styling, theme). Version upgrades are the `upgrade` command doc, and the draft shadcn-compatibility file is not a route, so no topic would sit under a migration namespace.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#overview",+ "oldCliRoute": "astryx docs migration overview",+ "oldDocsiteUrl": "/docs/migration#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#recommended-order",+ "oldCliRoute": "astryx docs migration recommended-order",+ "oldDocsiteUrl": "/docs/migration#recommended-order",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#cli-workflow",+ "oldCliRoute": "astryx docs migration cli-workflow",+ "oldDocsiteUrl": "/docs/migration#cli-workflow",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#theme-and-css-setup",+ "oldCliRoute": "astryx docs migration theme-and-css-setup",+ "oldDocsiteUrl": "/docs/migration#theme-and-css-setup",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#cascade-layer-safety",+ "oldCliRoute": "astryx docs migration cascade-layer-safety",+ "oldDocsiteUrl": "/docs/migration#cascade-layer-safety",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#foundation-smoke-test",+ "oldCliRoute": "astryx docs migration foundation-smoke-test",+ "oldDocsiteUrl": "/docs/migration#foundation-smoke-test",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#move-the-app-frame-first",+ "oldCliRoute": "astryx docs migration move-the-app-frame-first",+ "oldDocsiteUrl": "/docs/migration#move-the-app-frame-first",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#map-shadcn-and-radix-primitives",+ "oldCliRoute": "astryx docs migration map-shadcn-and-radix-primitives",+ "oldDocsiteUrl": "/docs/migration#map-shadcn-and-radix-primitives",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#command-palette-settings-and-theme",+ "oldCliRoute": "astryx docs migration command-palette-settings-and-theme",+ "oldDocsiteUrl": "/docs/migration#command-palette-settings-and-theme",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#verification-checklist",+ "oldCliRoute": "astryx docs migration verification-checklist",+ "oldDocsiteUrl": "/docs/migration#verification-checklist",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "migration#ai-migration-prompt",+ "oldCliRoute": "astryx docs migration ai-migration-prompt",+ "oldDocsiteUrl": "/docs/migration#ai-migration-prompt",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of migration under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "motion",+ "oldCliRoute": "astryx docs motion",+ "oldDocsiteUrl": "/docs/motion",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Token-category page (tokenCategory 'duration') whose tables come from `tokens` through token references. Only the docsite's 'foundations' category label groups it with the other token pages, and a label alone is not evidence for a route segment.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#overview",+ "oldCliRoute": "astryx docs motion overview",+ "oldDocsiteUrl": "/docs/motion#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#duration",+ "oldCliRoute": "astryx docs motion duration",+ "oldDocsiteUrl": "/docs/motion#duration",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#easing",+ "oldCliRoute": "astryx docs motion easing",+ "oldDocsiteUrl": "/docs/motion#easing",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#where-motion-helps",+ "oldCliRoute": "astryx docs motion where-motion-helps",+ "oldDocsiteUrl": "/docs/motion#where-motion-helps",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#where-motion-hurts",+ "oldCliRoute": "astryx docs motion where-motion-hurts",+ "oldDocsiteUrl": "/docs/motion#where-motion-hurts",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#movement-principles",+ "oldCliRoute": "astryx docs motion movement-principles",+ "oldDocsiteUrl": "/docs/motion#movement-principles",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#respecting-user-preferences",+ "oldCliRoute": "astryx docs motion respecting-user-preferences",+ "oldDocsiteUrl": "/docs/motion#respecting-user-preferences",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#usage",+ "oldCliRoute": "astryx docs motion usage",+ "oldDocsiteUrl": "/docs/motion#usage",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "motion#best-practices",+ "oldCliRoute": "astryx docs motion best-practices",+ "oldDocsiteUrl": "/docs/motion#best-practices",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of motion under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "principles",+ "oldCliRoute": "astryx docs principles",+ "oldDocsiteUrl": "/docs/principles",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Cross-cutting rules that link out to layout, styling and tokens. No topic links to it, and nothing places it under another topic.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "principles#design-philosophy",+ "oldCliRoute": "astryx docs principles design-philosophy",+ "oldDocsiteUrl": "/docs/principles#design-philosophy",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of principles under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "principles#rules",+ "oldCliRoute": "astryx docs principles rules",+ "oldDocsiteUrl": "/docs/principles#rules",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of principles under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "principles#styling-approach",+ "oldCliRoute": "astryx docs principles styling-approach",+ "oldDocsiteUrl": "/docs/principles#styling-approach",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of principles under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "principles#anti-patterns",+ "oldCliRoute": "astryx docs principles anti-patterns",+ "oldDocsiteUrl": "/docs/principles#anti-patterns",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of principles under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "principles#design-tokens",+ "oldCliRoute": "astryx docs principles design-tokens",+ "oldDocsiteUrl": "/docs/principles#design-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of principles under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "shape",+ "oldCliRoute": "astryx docs shape",+ "oldDocsiteUrl": "/docs/shape",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Token-category page (tokenCategory 'radius') whose tables come from `tokens` through token references. Only the docsite's 'foundations' category label groups it with the other token pages, and a label alone is not evidence for a route segment.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "shape#overview",+ "oldCliRoute": "astryx docs shape overview",+ "oldDocsiteUrl": "/docs/shape#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of shape under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "shape#radius-scale",+ "oldCliRoute": "astryx docs shape radius-scale",+ "oldDocsiteUrl": "/docs/shape#radius-scale",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of shape under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "shape#concentric-radius",+ "oldCliRoute": "astryx docs shape concentric-radius",+ "oldDocsiteUrl": "/docs/shape#concentric-radius",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of shape under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "shape#best-practices",+ "oldCliRoute": "astryx docs shape best-practices",+ "oldDocsiteUrl": "/docs/shape#best-practices",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of shape under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "spacing",+ "oldCliRoute": "astryx docs spacing",+ "oldDocsiteUrl": "/docs/spacing",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Token-category page (tokenCategory 'spacing') whose tables come from `tokens` through token references. Only the docsite's 'foundations' category label groups it with the other token pages, and a label alone is not evidence for a route segment.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "spacing#overview",+ "oldCliRoute": "astryx docs spacing overview",+ "oldDocsiteUrl": "/docs/spacing#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of spacing under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "spacing#scale",+ "oldCliRoute": "astryx docs spacing scale",+ "oldDocsiteUrl": "/docs/spacing#scale",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of spacing under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "spacing#usage",+ "oldCliRoute": "astryx docs spacing usage",+ "oldDocsiteUrl": "/docs/spacing#usage",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of spacing under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "spacing#best-practices",+ "oldCliRoute": "astryx docs spacing best-practices",+ "oldDocsiteUrl": "/docs/spacing#best-practices",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of spacing under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "styling-libraries",+ "oldCliRoute": "astryx docs styling-libraries",+ "oldDocsiteUrl": "/docs/styling-libraries",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Two topics send readers here: styling (Overview, Tailwind Integration) and theme (useTheme Hook). With no single parent, only the hyphen would put it under styling, and a hyphen alone is not evidence.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#core-principle",+ "oldCliRoute": "astryx docs styling-libraries core-principle",+ "oldDocsiteUrl": "/docs/styling-libraries#core-principle",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#choose-an-integration-path",+ "oldCliRoute": "astryx docs styling-libraries choose-an-integration-path",+ "oldDocsiteUrl": "/docs/styling-libraries#choose-an-integration-path",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#best-practices",+ "oldCliRoute": "astryx docs styling-libraries best-practices",+ "oldDocsiteUrl": "/docs/styling-libraries#best-practices",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#plain-css-and-css-modules",+ "oldCliRoute": "astryx docs styling-libraries plain-css-and-css-modules",+ "oldDocsiteUrl": "/docs/styling-libraries#plain-css-and-css-modules",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#stylex",+ "oldCliRoute": "astryx docs styling-libraries stylex",+ "oldDocsiteUrl": "/docs/styling-libraries#stylex",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#tailwind",+ "oldCliRoute": "astryx docs styling-libraries tailwind",+ "oldDocsiteUrl": "/docs/styling-libraries#tailwind",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#panda-chakra-and-other-semantic-token-systems",+ "oldCliRoute": "astryx docs styling-libraries panda-chakra-and-other-semantic-token-systems",+ "oldDocsiteUrl": "/docs/styling-libraries#panda-chakra-and-other-semantic-token-systems",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#mui-and-palette-based-themes",+ "oldCliRoute": "astryx docs styling-libraries mui-and-palette-based-themes",+ "oldDocsiteUrl": "/docs/styling-libraries#mui-and-palette-based-themes",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#emotion-styled-components-theme-ui-and-styled-system",+ "oldCliRoute": "astryx docs styling-libraries emotion-styled-components-theme-ui-and-styled-system",+ "oldDocsiteUrl": "/docs/styling-libraries#emotion-styled-components-theme-ui-and-styled-system",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#unocss-and-custom-utility-systems",+ "oldCliRoute": "astryx docs styling-libraries unocss-and-custom-utility-systems",+ "oldDocsiteUrl": "/docs/styling-libraries#unocss-and-custom-utility-systems",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#non-css-processing",+ "oldCliRoute": "astryx docs styling-libraries non-css-processing",+ "oldDocsiteUrl": "/docs/styling-libraries#non-css-processing",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#non-css-processing-best-practices",+ "oldCliRoute": "astryx docs styling-libraries non-css-processing-best-practices",+ "oldDocsiteUrl": "/docs/styling-libraries#non-css-processing-best-practices",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling-libraries#interop-checklist",+ "oldCliRoute": "astryx docs styling-libraries interop-checklist",+ "oldDocsiteUrl": "/docs/styling-libraries#interop-checklist",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling-libraries under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "styling",+ "oldCliRoute": "astryx docs styling",+ "oldDocsiteUrl": "/docs/styling",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Linked from six topics (getting-started, migration, principles, theme, tokens, working-with-ai). No topic or authored field places it under another topic.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#overview",+ "oldCliRoute": "astryx docs styling overview",+ "oldDocsiteUrl": "/docs/styling#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#xstyle-prop",+ "oldCliRoute": "astryx docs styling xstyle-prop",+ "oldDocsiteUrl": "/docs/styling#xstyle-prop",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#tailwind-integration",+ "oldCliRoute": "astryx docs styling tailwind-integration",+ "oldDocsiteUrl": "/docs/styling#tailwind-integration",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#classname-and-style-props",+ "oldCliRoute": "astryx docs styling classname-and-style-props",+ "oldDocsiteUrl": "/docs/styling#classname-and-style-props",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#rest-props-prop-drilling",+ "oldCliRoute": "astryx docs styling rest-props-prop-drilling",+ "oldDocsiteUrl": "/docs/styling#rest-props-prop-drilling",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#compound-components",+ "oldCliRoute": "astryx docs styling compound-components",+ "oldDocsiteUrl": "/docs/styling#compound-components",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#preferred-selector-surface-data-attributes",+ "oldCliRoute": "astryx docs styling preferred-selector-surface-data-attributes",+ "oldDocsiteUrl": "/docs/styling#preferred-selector-surface-data-attributes",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#deprecated-bare-prop-and-state-classes",+ "oldCliRoute": "astryx docs styling deprecated-bare-prop-and-state-classes",+ "oldDocsiteUrl": "/docs/styling#deprecated-bare-prop-and-state-classes",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#design-tokens",+ "oldCliRoute": "astryx docs styling design-tokens",+ "oldDocsiteUrl": "/docs/styling#design-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#stylex-build-setup-required-for-swizzled-components",+ "oldCliRoute": "astryx docs styling stylex-build-setup-required-for-swizzled-components",+ "oldDocsiteUrl": "/docs/styling#stylex-build-setup-required-for-swizzled-components",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "styling#what-not-to-do",+ "oldCliRoute": "astryx docs styling what-not-to-do",+ "oldDocsiteUrl": "/docs/styling#what-not-to-do",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of styling under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "theme",+ "oldCliRoute": "astryx docs theme",+ "oldDocsiteUrl": "/docs/theme",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Linked from getting-started, migration, styling and tokens, and its --dense and --zh overlays resolve by this route. The theme descriptors and the `theme` command docs are typed descriptors (generated bucket), so nothing authored would sit under a theme namespace.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#quick-start",+ "oldCliRoute": "astryx docs theme quick-start",+ "oldDocsiteUrl": "/docs/theme#quick-start",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#available-themes",+ "oldCliRoute": "astryx docs theme available-themes",+ "oldDocsiteUrl": "/docs/theme#available-themes",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#theme-props",+ "oldCliRoute": "astryx docs theme theme-props",+ "oldDocsiteUrl": "/docs/theme#theme-props",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#using-a-theme-from-an-integration",+ "oldCliRoute": "astryx docs theme using-a-theme-from-an-integration",+ "oldDocsiteUrl": "/docs/theme#using-a-theme-from-an-integration",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#creating-a-custom-theme",+ "oldCliRoute": "astryx docs theme creating-a-custom-theme",+ "oldDocsiteUrl": "/docs/theme#creating-a-custom-theme",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#definetheme",+ "oldCliRoute": "astryx docs theme definetheme",+ "oldDocsiteUrl": "/docs/theme#definetheme",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#extending-a-theme",+ "oldCliRoute": "astryx docs theme extending-a-theme",+ "oldDocsiteUrl": "/docs/theme#extending-a-theme",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#theme-adaptations",+ "oldCliRoute": "astryx docs theme theme-adaptations",+ "oldDocsiteUrl": "/docs/theme#theme-adaptations",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#component-style-overrides",+ "oldCliRoute": "astryx docs theme component-style-overrides",+ "oldDocsiteUrl": "/docs/theme#component-style-overrides",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#custom-variants",+ "oldCliRoute": "astryx docs theme custom-variants",+ "oldDocsiteUrl": "/docs/theme#custom-variants",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#building-themes-for-production",+ "oldCliRoute": "astryx docs theme building-themes-for-production",+ "oldDocsiteUrl": "/docs/theme#building-themes-for-production",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#building-a-theme-family",+ "oldCliRoute": "astryx docs theme building-a-theme-family",+ "oldDocsiteUrl": "/docs/theme#building-a-theme-family",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#runtime-vs-built-themes",+ "oldCliRoute": "astryx docs theme runtime-vs-built-themes",+ "oldDocsiteUrl": "/docs/theme#runtime-vs-built-themes",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#light-dark-mode",+ "oldCliRoute": "astryx docs theme light-dark-mode",+ "oldDocsiteUrl": "/docs/theme#light-dark-mode",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#nesting-themes",+ "oldCliRoute": "astryx docs theme nesting-themes",+ "oldDocsiteUrl": "/docs/theme#nesting-themes",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#token-utilities",+ "oldCliRoute": "astryx docs theme token-utilities",+ "oldDocsiteUrl": "/docs/theme#token-utilities",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "theme#usetheme-hook",+ "oldCliRoute": "astryx docs theme usetheme-hook",+ "oldDocsiteUrl": "/docs/theme#usetheme-hook",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "tokens",+ "oldCliRoute": "astryx docs tokens",+ "oldDocsiteUrl": "/docs/tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Complete token reference. The six token-category pages pull their tables from it by token reference, which is a reference, not containment: each keeps its own route.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#color-tokens",+ "oldCliRoute": "astryx docs tokens color-tokens",+ "oldDocsiteUrl": "/docs/tokens#color-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#spacing-tokens",+ "oldCliRoute": "astryx docs tokens spacing-tokens",+ "oldDocsiteUrl": "/docs/tokens#spacing-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#size-tokens",+ "oldCliRoute": "astryx docs tokens size-tokens",+ "oldDocsiteUrl": "/docs/tokens#size-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#border-tokens",+ "oldCliRoute": "astryx docs tokens border-tokens",+ "oldDocsiteUrl": "/docs/tokens#border-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#focus-tokens",+ "oldCliRoute": "astryx docs tokens focus-tokens",+ "oldDocsiteUrl": "/docs/tokens#focus-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#radius-tokens",+ "oldCliRoute": "astryx docs tokens radius-tokens",+ "oldDocsiteUrl": "/docs/tokens#radius-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#shadow-tokens",+ "oldCliRoute": "astryx docs tokens shadow-tokens",+ "oldDocsiteUrl": "/docs/tokens#shadow-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#duration-tokens",+ "oldCliRoute": "astryx docs tokens duration-tokens",+ "oldDocsiteUrl": "/docs/tokens#duration-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#easing-tokens",+ "oldCliRoute": "astryx docs tokens easing-tokens",+ "oldDocsiteUrl": "/docs/tokens#easing-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#font-family-tokens",+ "oldCliRoute": "astryx docs tokens font-family-tokens",+ "oldDocsiteUrl": "/docs/tokens#font-family-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#font-size-tokens",+ "oldCliRoute": "astryx docs tokens font-size-tokens",+ "oldDocsiteUrl": "/docs/tokens#font-size-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#font-weight-tokens",+ "oldCliRoute": "astryx docs tokens font-weight-tokens",+ "oldDocsiteUrl": "/docs/tokens#font-weight-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#type-scale-tokens",+ "oldCliRoute": "astryx docs tokens type-scale-tokens",+ "oldDocsiteUrl": "/docs/tokens#type-scale-tokens",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "tokens#usage-in-stylex",+ "oldCliRoute": "astryx docs tokens usage-in-stylex",+ "oldDocsiteUrl": "/docs/tokens#usage-in-stylex",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of tokens under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "typography",+ "oldCliRoute": "astryx docs typography",+ "oldDocsiteUrl": "/docs/typography",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Token-category page (tokenCategory 'typography') whose tables come from `tokens` through token references. Only the docsite's 'foundations' category label groups it with the other token pages, and a label alone is not evidence for a route segment.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#overview",+ "oldCliRoute": "astryx docs typography overview",+ "oldDocsiteUrl": "/docs/typography#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#font-families",+ "oldCliRoute": "astryx docs typography font-families",+ "oldDocsiteUrl": "/docs/typography#font-families",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#loading-custom-fonts",+ "oldCliRoute": "astryx docs typography loading-custom-fonts",+ "oldDocsiteUrl": "/docs/typography#loading-custom-fonts",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#font-sizes",+ "oldCliRoute": "astryx docs typography font-sizes",+ "oldDocsiteUrl": "/docs/typography#font-sizes",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#font-weights",+ "oldCliRoute": "astryx docs typography font-weights",+ "oldDocsiteUrl": "/docs/typography#font-weights",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#line-height",+ "oldCliRoute": "astryx docs typography line-height",+ "oldDocsiteUrl": "/docs/typography#line-height",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#type-scale",+ "oldCliRoute": "astryx docs typography type-scale",+ "oldDocsiteUrl": "/docs/typography#type-scale",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#display-text",+ "oldCliRoute": "astryx docs typography display-text",+ "oldDocsiteUrl": "/docs/typography#display-text",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#usage",+ "oldCliRoute": "astryx docs typography usage",+ "oldDocsiteUrl": "/docs/typography#usage",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "typography#best-practices",+ "oldCliRoute": "astryx docs typography best-practices",+ "oldDocsiteUrl": "/docs/typography#best-practices",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of typography under the same key.",+ "status": "proposed"+ },+ {+ "kind": "topic",+ "id": "working-with-ai",+ "oldCliRoute": "astryx docs working-with-ai",+ "oldDocsiteUrl": "/docs/working-with-ai",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Setup guide for AI coding tools (agent files, the hosted MCP server). It covers the reader's tooling, none of its sections is a CLI command's doc, and nothing places it under cli.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "working-with-ai#overview",+ "oldCliRoute": "astryx docs working-with-ai overview",+ "oldDocsiteUrl": "/docs/working-with-ai#overview",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of working-with-ai under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "working-with-ai#quick-start",+ "oldCliRoute": "astryx docs working-with-ai quick-start",+ "oldDocsiteUrl": "/docs/working-with-ai#quick-start",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of working-with-ai under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "working-with-ai#what-gets-generated",+ "oldCliRoute": "astryx docs working-with-ai what-gets-generated",+ "oldDocsiteUrl": "/docs/working-with-ai#what-gets-generated",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of working-with-ai under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "working-with-ai#cursor-setup",+ "oldCliRoute": "astryx docs working-with-ai cursor-setup",+ "oldDocsiteUrl": "/docs/working-with-ai#cursor-setup",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of working-with-ai under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "working-with-ai#checking-your-setup",+ "oldCliRoute": "astryx docs working-with-ai checking-your-setup",+ "oldDocsiteUrl": "/docs/working-with-ai#checking-your-setup",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of working-with-ai under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "working-with-ai#the-astryx-pattern",+ "oldCliRoute": "astryx docs working-with-ai the-astryx-pattern",+ "oldDocsiteUrl": "/docs/working-with-ai#the-astryx-pattern",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of working-with-ai under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "working-with-ai#the-dense-flag",+ "oldCliRoute": "astryx docs working-with-ai the-dense-flag",+ "oldDocsiteUrl": "/docs/working-with-ai#the-dense-flag",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of working-with-ai under the same key.",+ "status": "proposed"+ },+ {+ "kind": "section",+ "id": "working-with-ai#mcp-server",+ "oldCliRoute": "astryx docs working-with-ai mcp-server",+ "oldDocsiteUrl": "/docs/working-with-ai#mcp-server",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of working-with-ai under the same key.",+ "status": "proposed"+ },+ {+ "kind": "component",+ "id": "@astryxdesign/core/component",+ "provider": "@astryxdesign/core",+ "count": 175,+ "oldCliRoute": "astryx component <id>",+ "oldDocsiteUrl": "/components/<id>",+ "docsiteExceptions": {+ "Chat": "No page: a family doc with no props of its own; its members have pages.",+ "Indicator": "No page: a family doc with no props of its own; its members have pages.",+ "Layer": "No page: a family doc with no props of its own; its members have pages.",+ "NavMenu": "No page under this id: the doc declares the name NavHeadingMenu, and the page is /components/NavHeadingMenu.",+ "Resizable": "No page: a family doc with no props of its own; its members have pages."+ },+ "placement": "generated:@astryxdesign/core/component",+ "aliasNeeded": false,+ "evidence": "No component doc authors a docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket, not a guessed hierarchy; group and category fields are labels. The ids include the 10 core docs that `component <Name>` reads but `component --list` omits. No alias: `astryx component <id>` and /components/<id> are not docs-graph routes, and nothing here moves them.",+ "status": "proposed"+ },+ {+ "kind": "component-member",+ "id": "@astryxdesign/core/component-member",+ "provider": "@astryxdesign/core",+ "count": 10,+ "oldCliRoute": "astryx component <id>",+ "oldDocsiteUrl": "/components/<id>",+ "placement": "generated:@astryxdesign/core/component",+ "aliasNeeded": true,+ "evidence": "No doc of its own: `component <id>` resolves into another component doc, as a member of its components list or as the name the doc declares (NavMenu declares NavHeadingMenu).",+ "rationale": "Neither `component --list` nor the compiler inputs list these names, yet each reads by name and has its own docsite page. The docs graph keeps one identity per doc file, so each name needs an alias to its parent doc.",+ "status": "proposed"+ },+ {+ "kind": "hook",+ "id": "@astryxdesign/core/hook",+ "provider": "@astryxdesign/core",+ "count": 55,+ "oldCliRoute": "astryx hook <id>",+ "oldDocsiteUrl": "/components/<id>",+ "placement": "generated:@astryxdesign/core/hook",+ "aliasNeeded": false,+ "evidence": "No hook doc authors a docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. The docsite serves hooks under /components/, next to components. No alias: neither route is a docs-graph route.",+ "status": "proposed"+ },+ {+ "kind": "page",+ "id": "@astryxdesign/core/page",+ "provider": "@astryxdesign/core",+ "count": 55,+ "oldCliRoute": "astryx template <id> --type page",+ "oldDocsiteUrl": "/templates?preview=<id>",+ "docsiteExceptions": {+ "blank": "No docsite route: the docsite skips scaffold templates.",+ "incident-console": "Not ready: /templates/<id> redirects to the gallery, which drops the preview without a message.",+ "login": "Hidden from the overview: /templates/<id> redirects to the gallery, which drops the preview without a message.",+ "messaging-shell": "Not ready: /templates/<id> redirects to the gallery, which drops the preview without a message.",+ "table": "Hidden and not ready: /templates/<id> redirects to the gallery, which drops the preview without a message.",+ "theme-showcase": "Hidden from the overview: /templates/<id> redirects to the gallery, which drops the preview without a message."+ },+ "placement": "generated:@astryxdesign/core/page",+ "aliasNeeded": false,+ "evidence": "No template doc authors a docs-graph placement; its category (for example 'Dashboard - Analytics') is a label.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. Discovery reports built-in templates as @astryxdesign/core (the `template --list` package field) although the files ship in @astryxdesign/cli, and the provider follows discovery. /templates/<id> redirects to this canonical preview URL.",+ "status": "proposed"+ },+ {+ "kind": "block",+ "id": "@astryxdesign/core/block",+ "provider": "@astryxdesign/core",+ "count": 650,+ "oldCliRoute": "astryx template <id> --type block",+ "oldDocsiteUrl": null,+ "placement": "generated:@astryxdesign/core/block",+ "aliasNeeded": false,+ "evidence": "No block doc authors a docs-graph placement; its directory and category are not placements.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. The docsite renders blocks inside component pages as showcases and examples; no block has a URL of its own. Provider follows discovery, as for pages.",+ "status": "proposed"+ },+ {+ "kind": "theme",+ "id": "@astryxdesign/cli/theme",+ "provider": "@astryxdesign/cli",+ "count": 7,+ "oldCliRoute": "astryx theme add <id>",+ "oldDocsiteUrl": "/themes?theme=<id>",+ "docsiteExceptions": {+ "chocolate": "Not a docsite dependency: /themes?theme=chocolate shows Neutral without a message."+ },+ "placement": "generated:@astryxdesign/cli/theme",+ "aliasNeeded": false,+ "evidence": "No theme descriptor authors a docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. No read-only single-theme route exists: `astryx theme list` prints every descriptor, and `theme add <id>`, which writes files, is the only command that takes the slug.",+ "status": "proposed"+ },+ {+ "kind": "command",+ "id": "@astryxdesign/cli/command",+ "provider": "@astryxdesign/cli",+ "count": 34,+ "oldCliRoute": "astryx <id> --help",+ "oldDocsiteUrl": null,+ "placement": "generated:@astryxdesign/cli/command",+ "aliasNeeded": false,+ "evidence": "No command doc authors a docs-graph placement.",+ "rationale": "Each CommandDoc builds its command's --help, and is also read as the section commands-<name> of `astryx docs cli` (see those rows): every command doc declares namespace cli/commands.",+ "status": "proposed"+ },+ {+ "kind": "function",+ "id": "@astryxdesign/cli/function",+ "provider": "@astryxdesign/cli",+ "count": 41,+ "oldCliRoute": null,+ "oldDocsiteUrl": null,+ "placement": "generated:@astryxdesign/cli/function",+ "aliasNeeded": false,+ "evidence": "No function doc authors a docs-graph placement.",+ "rationale": "API reference for @astryxdesign/cli/api, read as the section api-<name> of `astryx docs cli` (see those rows): every function doc declares namespace cli/api. A wrapping command's --help also reuses its parameter descriptions.",+ "status": "proposed"+ },+ {+ "kind": "schema",+ "id": "@astryxdesign/cli/schema",+ "provider": "@astryxdesign/cli",+ "count": 18,+ "oldCliRoute": null,+ "oldDocsiteUrl": null,+ "placement": "generated:@astryxdesign/cli/schema",+ "aliasNeeded": false,+ "evidence": "No schema doc authors a docs-graph placement.",+ "rationale": "17 declare namespace 'authoring' and are read as sections of `astryx docs authoring`; `output` declares cli/api and is read as the section api-output of `astryx docs cli` (see those rows).",+ "status": "proposed"+ },+ {+ "kind": "enum",+ "id": "@astryxdesign/cli/enum",+ "provider": "@astryxdesign/cli",+ "count": 2,+ "oldCliRoute": null,+ "oldDocsiteUrl": null,+ "placement": "generated:@astryxdesign/cli/enum",+ "aliasNeeded": false,+ "evidence": "No enum doc authors a docs-graph placement.",+ "rationale": "Error codes and response types declare namespace cli/api and are read as the sections api-error-codes and api-response-types of `astryx docs cli`; the CLI README's generated tables also read them.",+ "status": "proposed"+ }+ ]+}diff --git a/packages/cli/test/doc-routes.test.mjs b/packages/cli/test/doc-routes.test.mjsnew file mode 100644index 0000000000..af252e972a--- /dev/null+++ b/packages/cli/test/doc-routes.test.mjs@@ -0,0 +1,579 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every current doc route has one reviewed row in doc-routes.json.+ *+ * @input doc-routes.json and doc-routes.ids.json beside this file, and the+ * routes the CLI answers today: its built-in doc topics and their section+ * keys, the docsite pages built from those topic files, and every typed+ * descriptor the doc compiler reads, with the read that reaches each one.+ * @output Failures naming each route the table misses, each row naming a+ * route that no longer exists, and each row without a rationale or with a+ * placement the proposal does not define.+ * @position Guard for the docs-graph migration. The table is a proposal a+ * person reviews; this test keeps it complete and well formed, so a new+ * route cannot land unmapped. It reads the CLI and changes nothing.+ */++import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {pathToFileURL} from 'node:url';+import {component} from '../api/component/component.mjs';+import {docs} from '../api/docs/docs.mjs';+import {hook} from '../api/hook/hook.mjs';+import {template} from '../api/template/template.mjs';+import {themeListAvailable} from '../api/theme/list/list.mjs';+import {program} from '../clients/cli/index.mjs';+import {Project} from '../foundation/config/project.mjs';+import {loadDocs} from '../foundation/discovery/component-loader.mjs';+import {collectDocInputs} from '../foundation/doc-compiler/inputs.mjs';+import {CLI_ROOT} from '../foundation/fs/paths.mjs';++const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');+const TABLE_FILE = path.join(CLI_ROOT, 'test', 'doc-routes.json');+const SLOW = 120_000;++/**+ * How the CLI reaches one typed descriptor today, by kind. A kind missing+ * here is new: decide its route before mapping it.+ * @type {Record<string, string | null>}+ */+const DESCRIPTOR_ROUTES = {+ component: 'astryx component <id>',+ 'component-member': 'astryx component <id>',+ hook: 'astryx hook <id>',+ page: 'astryx template <id> --type page',+ block: 'astryx template <id> --type block',+ theme: 'astryx theme add <id>',+ command: 'astryx <id> --help',+ function: null,+ schema: null,+ enum: null,+};++const SEGMENT = '[a-z0-9]+(?:-[a-z0-9]+)*';+const PACKAGE = '(?:@[a-z0-9][a-z0-9._-]*/)?[a-z0-9][a-z0-9._-]*';+const PLACEMENT = new RegExp(+ `^(?:keep-flat|namespace:(${SEGMENT})(?:/${SEGMENT})*|generated:(${PACKAGE})/(${SEGMENT}))$`,+);++/**+ * @typedef {object} RouteRow+ * @property {string} kind+ * @property {string} id+ * @property {string} [provider]+ * @property {number} [count]+ * @property {string | null} oldCliRoute+ * @property {string | null} oldDocsiteUrl+ * @property {Record<string, string>} [docsiteExceptions]+ * @property {string} placement+ * @property {unknown} aliasNeeded+ * @property {string} [evidence]+ * @property {string} rationale+ * @property {string} status+ */++/**+ * A topic or section route as the CLI and the docsite answer it today.+ * @typedef {object} Route+ * @property {'topic' | 'section'} kind+ * @property {string} id `topic` or `topic#key`+ * @property {string} oldCliRoute+ * @property {string | null} oldDocsiteUrl+ */++/**+ * Typed descriptors of one provider and kind.+ * @typedef {object} Group+ * @property {string} id `<provider>/<kind>`+ * @property {string} provider+ * @property {string} kind+ * @property {Set<string>} ids+ * @property {Set<string>} unreachable ids the kind's route does not reach+ * @property {Set<string>} placed ids whose descriptor authors a placement+ */++/** @type {string} */+let tmpDir;+/** @type {Map<string, Route>} */+let routes;+/** @type {Map<string, Group>} */+let groups;+/** @type {{idsFile: string, namespaces: any[], rows: RouteRow[]}} */+let table;+/** @type {Record<string, string[]>} */+let idsFile;++beforeAll(async () => {+ // Inside the repo, so the project finds this checkout's Core, and bare, so+ // no integration adds a route.+ tmpDir = fs.mkdtempSync(path.join(REPO_ROOT, '.astryx-doc-routes-'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer', version: '1.0.0'}),+ );+ table = JSON.parse(fs.readFileSync(TABLE_FILE, 'utf-8'));+ idsFile = JSON.parse(+ fs.readFileSync(+ path.join(path.dirname(TABLE_FILE), table.idsFile),+ 'utf-8',+ ),+ );+ routes = await currentTopicRoutes(tmpDir);+ groups = await currentDescriptorGroups(tmpDir);+}, SLOW);++afterAll(() => {+ if (tmpDir) fs.rmSync(tmpDir, {recursive: true, force: true});+});++/**+ * Topics the docsite does not publish: /docs/cli is the @astryxdesign/cli+ * package page, so apps/docsite/scripts/generate-data.mjs skips the cli topic+ * until the namespace page takes that URL.+ */+const DOCSITE_SKIPPED_TOPICS = new Set(['cli']);++/**+ * Every built-in topic and section key, with the docsite URL for each.+ * @param {string} cwd+ * @returns {Promise<Map<string, Route>>}+ */+async function currentTopicRoutes(cwd) {+ /** @type {Map<string, Route>} */+ const found = new Map();+ const list = /** @type {any} */ (await docs(undefined, undefined, {cwd}));+ for (const {topic} of list.data) {+ // The docsite builds one page per topic file the CLI ships, except the+ // topics apps/docsite/scripts/generate-data.mjs skips.+ const file = path.join(CLI_ROOT, 'assets', 'docs', `${topic}.doc.mjs`);+ const page =+ fs.existsSync(file) && !DOCSITE_SKIPPED_TOPICS.has(topic)+ ? `/docs/${topic}`+ : null;+ found.set(topic, {+ kind: 'topic',+ id: topic,+ oldCliRoute: `astryx docs ${topic}`,+ oldDocsiteUrl: page,+ });+ const index = /** @type {any} */ (+ await docs(topic, undefined, {index: true, cwd})+ );+ const authored = page ? (await authoredDoc(file)).sections : [];+ const anchors = docsiteAnchors(authored);+ index.data.sections.forEach(+ (+ /** @type {{id: string, title: string}} */ section,+ /** @type {number} */ i,+ ) => {+ const anchored = page != null && authored[i]?.title === section.title;+ found.set(`${topic}#${section.id}`, {+ kind: 'section',+ id: `${topic}#${section.id}`,+ oldCliRoute: `astryx docs ${topic} ${section.id}`,+ oldDocsiteUrl: anchored ? `${page}#${anchors[i]}` : null,+ });+ },+ );+ }+ return found;+}++/**+ * The docsite's outline ids for a topic's sections, in order. Mirrors+ * apps/docsite ReferenceDocView: slugged titles, deduped across sections and+ * their heading blocks in reading order.+ * @param {Array<{title: string, content?: Array<{type: string, text?: string}>}>} sections+ * @returns {string[]}+ */+function docsiteAnchors(sections) {+ /** @type {Map<string, number>} */+ const seen = new Map();+ /** @param {string} value @param {string} fallback */+ const unique = (value, fallback) => {+ const slug =+ value+ .toLowerCase()+ .trim()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '') || fallback;+ const count = seen.get(slug) ?? 0;+ seen.set(slug, count + 1);+ return count === 0 ? slug : `${slug}-${count + 1}`;+ };+ return sections.map(section => {+ const id = unique(section.title, 'section');+ for (const block of section.content ?? []) {+ if (block.type === 'heading' && block.text) {+ unique(`${section.title} ${block.text}`, `${id}-heading`);+ }+ }+ return id;+ });+}++/**+ * The authored object a descriptor file exports. Fails closed: a file with+ * none would otherwise pass every check on the fields it lacks.+ * @param {string} file+ * @returns {Promise<Record<string, any>>}+ */+async function authoredDoc(file) {+ const mod = await import(pathToFileURL(file).href);+ const doc = mod.docs ?? mod.doc ?? mod.default;+ if (doc == null || typeof doc !== 'object') {+ throw new Error(`${path.relative(REPO_ROOT, file)} exports no doc object`);+ }+ return doc;+}++/**+ * @param {Map<string, Group>} found+ * @param {string} provider+ * @param {string} kind+ * @returns {Group}+ */+function groupOf(found, provider, kind) {+ const id = `${provider}/${kind}`;+ let group = found.get(id);+ if (!group) {+ group = {+ id,+ provider,+ kind,+ ids: new Set(),+ unreachable: new Set(),+ placed: new Set(),+ };+ found.set(id, group);+ }+ return group;+}++/**+ * Every typed descriptor the compiler reads, grouped by provider and kind,+ * plus the component names that read into another component's doc.+ * @param {string} cwd+ * @returns {Promise<Map<string, Group>>}+ */+async function currentDescriptorGroups(cwd) {+ const {inputs, problems} = await collectDocInputs(await Project.load(cwd));+ if (problems.length > 0) throw new Error(JSON.stringify(problems));++ /** @type {Map<string, Group>} */+ const found = new Map();+ for (const input of inputs) {+ // A topic's own file is a topic route; everything else is a descriptor.+ if (input.root === 'docs' && input.role === 'base') continue;+ const doc = await authoredDoc(input.file);+ let kind = input.root.replace(/s$/u, '');+ let id = input.name;+ if (input.root === 'templates') [kind, id] = input.name.split('/');+ if (input.root === 'self-docs') [kind, id] = [doc.type, doc.name];+ const group = groupOf(found, input.owner, kind);+ if (group.ids.has(id)) throw new Error(`${group.id} reads "${id}" twice`);+ group.ids.add(id);+ if ('placement' in doc) group.placed.add(id);+ }++ await addComponentMembers(found, inputs, cwd);+ await markUnreachable(found, cwd);+ return found;+}++/**+ * Names `component <Name>` resolves into another component's doc: a member+ * of its `components` list, or the name the doc declares for itself. Only a+ * name the read answers under that name is a route.+ * @param {Map<string, Group>} found+ * @param {import('../foundation/doc-compiler/inputs.mjs').DocInput[]} inputs+ * @param {string} cwd+ */+async function addComponentMembers(found, inputs, cwd) {+ const own = new Set(+ inputs+ .filter(input => input.root === 'components' || input.root === 'hooks')+ .map(input => input.name),+ );+ for (const input of inputs) {+ if (input.root !== 'components') continue;+ const doc = /** @type {any} */ (await loadDocs(input.file));+ const names = (doc.components ?? [])+ .filter((/** @type {object} */ entry) => Object.keys(entry).length > 1)+ .map((/** @type {{name?: string}} */ entry) => String(entry.name ?? ''));+ if (typeof doc.name === 'string') names.push(doc.name);+ for (const raw of names) {+ const name = raw.replace(/^XDS/u, '');+ if (!name || name === input.name || own.has(name)) continue;+ const read = await component(name, {cwd}).catch(() => null);+ if (read?.type === 'component.detail' && read.data?.name === name) {+ groupOf(found, input.owner, 'component-member').ids.add(name);+ }+ }+ }+}++/**+ * Record every id its kind's route does not reach.+ * @param {Map<string, Group>} found+ * @param {string} cwd+ */+async function markUnreachable(found, cwd) {+ const list = /** @type {any} */ (+ await template(undefined, {list: true, cwd})+ );+ const templates = new Set(+ list.data.map(+ (/** @type {{type: string, id: string}} */ t) => `${t.type}/${t.id}`,+ ),+ );+ const themes = new Set(+ (await themeListAvailable({cwd})).data.map(theme => theme.slug),+ );+ const commands = commandPaths();+ for (const group of found.values()) {+ for (const id of group.ids) {+ let reached = true;+ if (group.kind === 'component') {+ const read = await component(id, {cwd}).catch(() => null);+ reached = read?.type === 'component.detail';+ } else if (group.kind === 'hook') {+ const read = await hook(id, {cwd}).catch(() => null);+ reached = read?.type === 'hook.detail';+ } else if (group.kind === 'page' || group.kind === 'block') {+ // `template <id> --type <kind>` resolves against this same list.+ reached = templates.has(`${group.kind}/${id}`);+ } else if (group.kind === 'theme') {+ reached = themes.has(id);+ } else if (group.kind === 'command') {+ reached = commands.has(id);+ }+ if (!reached) group.unreachable.add(id);+ }+ }+}++/** Every command path the CLI registers, as typed after `astryx`. */+function commandPaths() {+ /** @type {Set<string>} */+ const paths = new Set();+ /** @param {import('commander').Command} parent @param {string} prefix */+ const walk = (parent, prefix) => {+ for (const cmd of parent.commands) {+ const name = prefix ? `${prefix} ${cmd.name()}` : cmd.name();+ paths.add(name);+ walk(cmd, name);+ }+ };+ walk(program, '');+ return paths;+}++/** @param {RouteRow} row @returns {boolean} */+const isDescriptorRow = row => row.kind !== 'topic' && row.kind !== 'section';++/**+ * A row to paste and complete: the rationale and placement stay empty, so+ * the table fails until a person decides them.+ * @param {Route | Group} route+ */+function skeleton(route) {+ const fields =+ 'provider' in route+ ? {provider: route.provider, count: route.ids.size}+ : {oldCliRoute: route.oldCliRoute, oldDocsiteUrl: route.oldDocsiteUrl};+ return JSON.stringify({+ kind: route.kind,+ id: route.id,+ ...fields,+ placement: '',+ aliasNeeded: false,+ rationale: '',+ status: 'proposed',+ });+}++describe('doc route inventory', () => {+ it('(a) maps every current route', () => {+ const rows = new Map(table.rows.map(row => [row.id, row]));+ /** @type {string[]} */+ const missing = [];+ for (const route of routes.values()) {+ if (rows.get(route.id)?.kind !== route.kind) {+ missing.push(`no row for ${route.oldCliRoute}: ${skeleton(route)}`);+ }+ }+ for (const group of groups.values()) {+ if (rows.get(group.id)?.kind !== group.kind) {+ missing.push(`no row for ${group.id}: ${skeleton(group)}`);+ continue;+ }+ const listed = new Set(idsFile[group.id] ?? []);+ for (const id of group.ids) {+ if (!listed.has(id)) {+ missing.push(`${group.id} "${id}" is missing from ${table.idsFile}`);+ }+ }+ }+ expect(missing).toEqual([]);+ });++ it('(b) names only routes that exist', () => {+ /** @type {string[]} */+ const stale = [];+ for (const row of table.rows) {+ if (!isDescriptorRow(row)) {+ const route = routes.get(row.id);+ if (route?.kind !== row.kind) {+ stale.push(`${row.id}: no such ${row.kind}`);+ continue;+ }+ if (row.oldCliRoute !== route.oldCliRoute) {+ stale.push(`${row.id}: the CLI route is ${route.oldCliRoute}`);+ }+ if (row.oldDocsiteUrl !== route.oldDocsiteUrl) {+ stale.push(`${row.id}: the docsite URL is ${route.oldDocsiteUrl}`);+ }+ continue;+ }+ const group = groups.get(row.id);+ if (group?.kind !== row.kind) {+ stale.push(`${row.id}: no ${row.kind} descriptors under this id`);+ continue;+ }+ if (!(row.kind in DESCRIPTOR_ROUTES)) {+ stale.push(`${row.id}: no known route for kind ${row.kind}`);+ } else if (row.oldCliRoute !== DESCRIPTOR_ROUTES[row.kind]) {+ stale.push(+ `${row.id}: the CLI route is ${DESCRIPTOR_ROUTES[row.kind]}`,+ );+ }+ if (row.provider !== group.provider) {+ stale.push(`${row.id}: the provider is ${group.provider}`);+ }+ const listed = idsFile[row.id] ?? [];+ if (row.count !== listed.length) {+ stale.push(+ `${row.id}: count ${row.count}, ${table.idsFile} lists ${listed.length}`,+ );+ }+ const seen = new Set();+ for (const id of listed) {+ if (seen.has(id)) stale.push(`${row.id} "${id}" is listed twice`);+ seen.add(id);+ if (!group.ids.has(id)) {+ stale.push(`${row.id} "${id}" no longer exists`);+ } else if (group.unreachable.has(id)) {+ stale.push(`${row.id} "${id}": ${row.oldCliRoute} does not reach it`);+ }+ }+ for (const id of Object.keys(row.docsiteExceptions ?? {})) {+ if (!group.ids.has(id)) {+ stale.push(+ `${row.id}: docsite exception for "${id}", which no longer exists`,+ );+ }+ }+ }+ const rowIds = new Set(table.rows.map(row => row.id));+ for (const key of Object.keys(idsFile)) {+ if (!rowIds.has(key)) stale.push(`${table.idsFile}: "${key}" has no row`);+ }+ expect(stale).toEqual([]);+ });++ it('(c) gives every row a rationale and a known placement', () => {+ const created = new Set(+ table.namespaces+ .filter(ns => ns.decision === 'create')+ .map(ns => ns.name),+ );+ const topics = new Map(+ table.rows.filter(row => row.kind === 'topic').map(row => [row.id, row]),+ );+ /** @type {string[]} */+ const bad = [];+ const seen = new Set();+ for (const row of table.rows) {+ const at = row.id;+ if (seen.has(at)) bad.push(`${at}: two rows`);+ seen.add(at);+ if (typeof row.rationale !== 'string' || row.rationale.trim() === '') {+ bad.push(`${at}: no rationale`);+ }+ if (row.status !== 'proposed') {+ bad.push(`${at}: status is not "proposed"`);+ }+ if (typeof row.aliasNeeded !== 'boolean') {+ bad.push(`${at}: aliasNeeded is not a boolean`);+ }+ const form = PLACEMENT.exec(row.placement ?? '');+ if (!form) {+ bad.push(`${at}: unknown placement "${row.placement}"`);+ continue;+ }+ const [, namespace, provider, kind] = form;+ if (row.placement === 'keep-flat') {+ if (row.aliasNeeded === true) {+ bad.push(`${at}: keep-flat needs no alias`);+ }+ } else if (+ typeof row.evidence !== 'string' ||+ row.evidence.trim() === ''+ ) {+ bad.push(`${at}: ${row.placement} needs an evidence note`);+ }+ if (namespace != null && !created.has(namespace)) {+ bad.push(`${at}: namespace "${namespace}" is not decided "create"`);+ }+ if (provider != null) {+ // A member has no doc of its own; it goes where its parent doc goes.+ const placedAs =+ row.kind === 'component-member' ? 'component' : row.kind;+ const placed = [...(groups.get(at)?.placed ?? [])];+ if (!isDescriptorRow(row)) {+ bad.push(`${at}: generated placement is for typed descriptors`);+ } else if (provider !== row.provider || kind !== placedAs) {+ bad.push(+ `${at}: generated placement must be ${row.provider}/${placedAs}`,+ );+ } else if (placed.length > 0) {+ bad.push(`${at}: ${placed.join(', ')} author a placement`);+ }+ }+ if (row.kind === 'section') {+ const hash = at.indexOf('#');+ const topic = hash > 0 ? topics.get(at.slice(0, hash)) : undefined;+ if (topic && row.placement !== topic.placement && !row.evidence) {+ bad.push(`${at}: leaves its topic without an evidence note`);+ }+ if (topic?.aliasNeeded === true && row.aliasNeeded !== true) {+ bad.push(`${at}: its topic moves, so its old route needs an alias`);+ }+ }+ }+ for (const ns of table.namespaces) {+ const at = `namespace "${ns.name}"`;+ if (!new RegExp(`^${SEGMENT}$`).test(ns.name)) {+ bad.push(`${at}: not a path segment`);+ }+ if (ns.decision !== 'create' && ns.decision !== 'reject') {+ bad.push(`${at}: decision must be create or reject`);+ }+ if (typeof ns.evidence !== 'string' || ns.evidence.trim() === '') {+ bad.push(`${at}: no evidence`);+ }+ const used = table.rows.some(+ row =>+ row.placement === `namespace:${ns.name}` ||+ row.placement?.startsWith(`namespace:${ns.name}/`),+ );+ if (ns.decision === 'create' && !used) {+ bad.push(`${at}: created, but no row is placed in it`);+ }+ }+ expect(bad).toEqual([]);+ });+});diff --git a/packages/cli/test/golden-reads.test.mjs b/packages/cli/test/golden-reads.test.mjsnew file mode 100644index 0000000000..5f273a648a--- /dev/null+++ b/packages/cli/test/golden-reads.test.mjs@@ -0,0 +1,189 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Golden reads: what `astryx` prints, as text and as JSON, for docs an+ * integration contributes. Every doc kind reaches these readers through the+ * doc compiler; these snapshots pin what a reader sees, so a change to the+ * compiler that moves a byte of output fails here.+ *+ * Update after an intended output change: `vitest run -u` on this file, then+ * review the diff of `__golden__/`.+ */++import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {CLI_ROOT} from '../foundation/fs/paths.mjs';++const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');+const CLI_BIN = path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs');+const GOLDEN = path.join(CLI_ROOT, 'test', '__golden__');++let project;++/**+ * @param {string} rel+ * @param {string} text+ */+function write(rel, text) {+ const file = path.join(project, 'node_modules', '@acme', 'kit', rel);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, text);+}++/**+ * Run the CLI in the fixture project; machine paths become placeholders.+ * @param {string[]} args+ * @returns {string}+ */+function astryx(args) {+ const result = spawnSync(process.execPath, [CLI_BIN, ...args], {+ cwd: project,+ encoding: 'utf8',+ env: {...process.env, NO_COLOR: '1', FORCE_COLOR: '0', COLUMNS: '100'},+ });+ expect(result.status).toBe(0);+ return result.stdout+ .split(project)+ .join('<project>')+ .split(REPO_ROOT)+ .join('<repo>');+}++/**+ * The entries of a `--json` list that the fixture contributed.+ * @param {string} out+ * @param {(entry: any) => boolean} mine+ */+function fixtureEntries(out, mine) {+ const parsed = JSON.parse(out);+ return `${JSON.stringify({...parsed, data: parsed.data.filter(mine)}, null, 2)}\n`;+}++beforeAll(() => {+ // Inside the repo, so the project finds this checkout's Core.+ project = fs.mkdtempSync(path.join(REPO_ROOT, '.astryx-golden-'));+ fs.writeFileSync(+ path.join(project, 'package.json'),+ JSON.stringify({+ name: 'golden-consumer',+ version: '1.0.0',+ dependencies: {'@acme/kit': '^1.0.0'},+ }),+ );+ write('package.json', JSON.stringify({name: '@acme/kit', version: '1.2.3'}));+ write(+ 'astryx.integration.mjs',+ "export default {components: './components', templates: './templates', docs: './docs', themes: './themes'};\n",+ );+ write(+ 'components/AcmeCard.tsx',+ 'export function AcmeCard() { return null; }\n',+ );+ write(+ 'components/AcmeCard.doc.mjs',+ `/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */+export default {+ type: 'component',+ name: 'AcmeCard',+ displayName: 'Acme Card',+ category: 'Layout',+ keywords: ['zorblax', 'card'],+ usage: {+ description: 'A zorblax card that groups one topic.',+ bestPractices: [+ {guidance: true, description: 'Keep one idea per card.'},+ {guidance: false, description: 'Do not nest cards.'},+ ],+ },+ props: [+ {name: 'title', type: 'string', required: true, description: 'Heading text.'},+ {name: 'tone', type: "'calm' | 'loud'", default: "'calm'", description: 'Visual weight.'},+ ],+ playground: {defaults: {onPress: undefined, tone: 'calm'}},+};+export const docsZh = {+ usage: {description: '一张 zorblax 卡片。'},+ propDescriptions: {title: '标题文字。'},+};+`,+ );+ write(+ 'templates/hero.tsx',+ 'export default function Hero() { return <section>zorblax</section>; }\n',+ );+ write(+ 'templates/hero.doc.mjs',+ "export default {type: 'block', name: 'Zorblax hero', description: 'A zorblax hero block.', aspectRatio: 2, componentsUsed: ['AcmeCard']};\n",+ );+ const topic = (/** @type {object} */ fields) =>+ `export default ${JSON.stringify(+ {+ type: 'generic',+ title: 'Acme guide',+ description: 'How zorblax cards fit together.',+ sections: [+ {+ title: 'Start',+ content: [{type: 'prose', text: 'Install the kit.'}],+ },+ {+ title: 'Colors',+ content: [+ {type: 'prose', text: 'Cards use the core tokens.'},+ {type: 'token-ref', topic: 'no-such-topic', section: 'x'},+ ],+ },+ ],+ ...fields,+ },+ null,+ 2,+ )};\n`;+ write('docs/acme-guide.doc.mjs', topic({name: 'acme-guide'}));+ write('themes/ocean/oceanTheme.ts', 'export const oceanTheme = {};\n');+ write(+ 'themes/ocean/oceanTheme.doc.mjs',+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'A zorblax blue.', maintained: true};\n",+ );+});++afterAll(() => {+ fs.rmSync(project, {recursive: true, force: true});+});++describe('golden reads of integration docs', () => {+ it.each([+ ['component-text.txt', ['component', 'AcmeCard']],+ ['component.json', ['component', 'AcmeCard', '--json']],+ ['component-zh.json', ['component', 'AcmeCard', '--zh', '--json']],+ ['component-props.json', ['component', 'AcmeCard', '--props', '--json']],+ ['template.json', ['template', 'hero', '--type', 'block', '--json']],+ ['docs-topic.json', ['docs', 'acme-guide', '--json']],+ ['docs-topic-text.txt', ['docs', 'acme-guide']],+ ['docs-index.txt', ['docs', 'acme-guide', '--index']],+ ['docs-section.json', ['docs', 'acme-guide', 'colors', '--json']],+ ['search.json', ['search', 'zorblax', '--json']],+ ])('%s', async (name, args) => {+ await expect(astryx(args)).toMatchFileSnapshot(path.join(GOLDEN, name));+ });++ it('theme-list.json', async () => {+ await expect(+ fixtureEntries(+ astryx(['theme', 'list', '--json']),+ entry => entry.package === '@acme/kit',+ ),+ ).toMatchFileSnapshot(path.join(GOLDEN, 'theme-list.json'));+ });++ it('docs-list.json', async () => {+ await expect(+ fixtureEntries(+ astryx(['docs', '--json']),+ entry => entry.package === '@acme/kit',+ ),+ ).toMatchFileSnapshot(path.join(GOLDEN, 'docs-list.json'));+ });+});diff --git a/packages/themes/butter/src/butterTheme.doc.mjs b/packages/themes/butter/src/butterTheme.doc.mjsnew file mode 100644index 0000000000..2c667adbd1--- /dev/null+++ b/packages/themes/butter/src/butterTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'butter',+ displayName: 'Butter',+ description:+ 'Warm, creamy yellows with a friendly blue accent. Playful enough for consumer surfaces, soft enough to stay readable.',+ maintained: false,+};diff --git a/packages/themes/chocolate/src/chocolateTheme.doc.mjs b/packages/themes/chocolate/src/chocolateTheme.doc.mjsnew file mode 100644index 0000000000..ca24f2aa7d--- /dev/null+++ b/packages/themes/chocolate/src/chocolateTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'chocolate',+ displayName: 'Chocolate',+ description:+ 'Warm chocolate theme for Astryx — rich brown palette with Fraunces headings, Albert Sans body, and Lucide icons',+ maintained: false,+};diff --git a/packages/themes/gothic/src/gothicTheme.doc.mjs b/packages/themes/gothic/src/gothicTheme.doc.mjsnew file mode 100644index 0000000000..ce4e9161e0--- /dev/null+++ b/packages/themes/gothic/src/gothicTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'gothic',+ displayName: 'Gothic',+ description:+ 'Deep blue-grays and a signature display serif. Dramatic and editorial, for surfaces that want to be remembered.',+ maintained: false,+};diff --git a/packages/themes/matcha/src/matchaTheme.doc.mjs b/packages/themes/matcha/src/matchaTheme.doc.mjsnew file mode 100644index 0000000000..0944d4161a--- /dev/null+++ b/packages/themes/matcha/src/matchaTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'matcha',+ displayName: 'Matcha',+ description:+ 'Earthy greens with a calm, organic feel. Naturalistic and grounded, great for wellness or content-first apps.',+ maintained: false,+};diff --git a/packages/themes/neutral/src/neutralTheme.doc.mjs b/packages/themes/neutral/src/neutralTheme.doc.mjsnew file mode 100644index 0000000000..0d0a291685--- /dev/null+++ b/packages/themes/neutral/src/neutralTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'neutral',+ displayName: 'Neutral',+ description:+ 'Restrained warm grays. Minimal and quiet, so the content stays the focus.',+ maintained: true,+};diff --git a/packages/themes/stone/src/stoneTheme.doc.mjs b/packages/themes/stone/src/stoneTheme.doc.mjsnew file mode 100644index 0000000000..1969201e57--- /dev/null+++ b/packages/themes/stone/src/stoneTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'stone',+ displayName: 'Stone',+ description:+ 'Warm stone and slate, earthy and understated, with just enough character to feel handcrafted.',+ maintained: false,+};diff --git a/packages/themes/y2k/src/y2kTheme.doc.mjs b/packages/themes/y2k/src/y2kTheme.doc.mjsnew file mode 100644index 0000000000..f4cecf6a99--- /dev/null+++ b/packages/themes/y2k/src/y2kTheme.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: 'y2k',+ displayName: 'Y2K',+ description:+ 'Hot pinks, lime greens, and Poppins. Bubbly, playful, and unmistakably retro.',+ maintained: false,+};diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjsindex 4e98633129..3a3e12f37e 100644--- a/scripts/check-cli-structure.mjs+++ b/scripts/check-cli-structure.mjs@@ -9,8 +9,8 @@* precisely what typechecking and unit tests cannot see — every individual file* is valid, the set is incomplete.*- * 1. Every doc-type ships a complete trio, and re-exports its parser from the- * authoring barrel:+ * 1. Every doc-type ships a complete trio, re-exports its public type from the+ * doc vocabulary, and re-exports its parser from the authoring barrel:* type.ts the authored shape* parse.mjs the sealed parser (the CLI's load boundary)* <kind>.doc.mjs the doc-type documenting itself@@ -39,7 +39,10 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {fileURLToPath} from 'node:url';-const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const REPO_ROOT = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '..',+);const CLI = path.join(REPO_ROOT, 'packages/cli');const DOCTYPES = path.join(CLI, 'authoring/doctypes');const API = path.join(CLI, 'api');@@ -51,7 +54,9 @@ const DOCTYPE_EXEMPT = new Set(['base']);/** @param {string} dir @returns {string[]} */const dirsIn = dir =>fs.existsSync(dir)- ? fs.readdirSync(dir).filter(f => fs.statSync(path.join(dir, f)).isDirectory())+ ? fs+ .readdirSync(dir)+ .filter(f => fs.statSync(path.join(dir, f)).isDirectory()): [];/** Recursively collect file names under a directory. @param {string} dir @returns {string[]} */@@ -71,8 +76,15 @@ let doctypeCount = 0;let apiCount = 0;// ── 1. doc-type quartets ────────────────────────────────────────────────-const authoringIndexTypes = fs.readFileSync(path.join(CLI, 'authoring/index.d.ts'), 'utf8');-const authoringIndexImpl = fs.readFileSync(path.join(CLI, 'authoring/index.mjs'), 'utf8');+const authoringIndexTypes = fs.readFileSync(+ path.join(CLI, 'authoring/index.d.ts'),+ 'utf8',+);+const docTypeExports = fs.readFileSync(path.join(DOCTYPES, 'types.ts'), 'utf8');+const authoringIndexImpl = fs.readFileSync(+ path.join(CLI, 'authoring/index.mjs'),+ 'utf8',+);/*** parseDoc's own `@returns {...}` union — the source the emitted declaration* derives from. Scoped to the JSDoc block immediately above `export function@@ -80,11 +92,16 @@ const authoringIndexImpl = fs.readFileSync(path.join(CLI, 'authoring/index.mjs')* whole file would find every kind name and never fail.*/const parseSrc = fs.readFileSync(path.join(DOCTYPES, 'parse.mjs'), 'utf8');-const parseDocJsdoc = parseSrc.slice(0, parseSrc.indexOf('export function parseDoc'));+const parseDocJsdoc = parseSrc.slice(+ 0,+ parseSrc.indexOf('export function parseDoc'),+);const returnsMatches = parseDocJsdoc.match(/@returns\s*\{[^}]*\}/g) ?? [];const aggregateParserReturns = returnsMatches[returnsMatches.length - 1] ?? '';if (!aggregateParserReturns) {- errors.push('could not find a @returns union on parseDoc in authoring/doctypes/parse.mjs');+ errors.push(+ 'could not find a @returns union on parseDoc in authoring/doctypes/parse.mjs',+ );}for (const kind of dirsIn(DOCTYPES)) {@@ -100,13 +117,24 @@ for (const kind of dirsIn(DOCTYPES)) {}}+ const typeSpec = `./${kind}/type`;+ if (!docTypeExports.includes(typeSpec)) {+ errors.push(+ `doc-type "${kind}" type is not re-exported from authoring/doctypes/types.ts`,+ );+ }+// A parser nobody re-exports is unreachable from @astryxdesign/cli/authoring.const spec = `./doctypes/${kind}/parse.mjs`;if (!authoringIndexTypes.includes(spec)) {- errors.push(`doc-type "${kind}" parser is not re-exported from authoring/index.d.ts`);+ errors.push(+ `doc-type "${kind}" parser is not re-exported from authoring/index.d.ts`,+ );}if (!authoringIndexImpl.includes(spec)) {- errors.push(`doc-type "${kind}" parser is not re-exported from authoring/index.mjs`);+ errors.push(+ `doc-type "${kind}" parser is not re-exported from authoring/index.mjs`,+ );}// parseDoc's own `@returns` is what the generated declaration derives its@@ -134,7 +162,10 @@ for (const name of dirsIn(API)) {// Types ship as colocated JSDoc typedefs, or — for a barrel that only// re-exports other leaves' types (api/json) — as the published index.ts that// package.json's "exports" points at.- if (!files.some(f => f.endsWith('.type.mjs')) && !topLevel.includes('index.ts')) {+ if (+ !files.some(f => f.endsWith('.type.mjs')) &&+ !topLevel.includes('index.ts')+ ) {errors.push(`api/${name}/ is missing response typedefs (*.type.mjs, or a published index.ts)`,);diff --git a/scripts/check-cli-theme-bundle.test.mjs b/scripts/check-cli-theme-bundle.test.mjsindex 5a7bd31e5c..91f32353c1 100644--- a/scripts/check-cli-theme-bundle.test.mjs+++ b/scripts/check-cli-theme-bundle.test.mjs@@ -3,20 +3,21 @@/*** @file Drift guard for the bundled CLI themes.*- * `scripts/generate-cli-themes.mjs` copies each theme's source verbatim into- * `packages/cli/assets/templates/themes/` so `astryx theme add` can scaffold a- * theme without the package installed. Nothing verified the bundle stayed in- * sync with source, so the neutral theme's WCAG text-secondary fix (and a- * StatusDot override block) shipped to source but never reached the bundle —- * `astryx theme add neutral` scaffolded a theme below AA contrast. This test- * pins the copies to their source byte-for-byte; when a theme changes, run- * `pnpm bundle:cli-themes` and commit the regenerated bundle.+ * `scripts/generate-cli-themes.mjs` copies each public theme's source,+ * strongly typed same-stem descriptor, and supported authoring artifacts into+ * the CLI bundle. This test pins every copied byte and rejects the obsolete+ * central catalog. When a theme changes, run `pnpm bundle:cli-themes` and commit+ * the regenerated bundle.*/+import {spawnSync} from 'node:child_process';import fs from 'node:fs';+import os from 'node:os';import path from 'node:path';import {fileURLToPath} from 'node:url';import {describe, it, expect} from 'vitest';+import {discoverBundledThemes} from '../packages/cli/foundation/discovery/theme-discovery.mjs';+import {listThemeSlugs} from './generate-cli-themes.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const REPO_ROOT = path.resolve(__dirname, '..');@@ -30,43 +31,84 @@ const CLI_THEMES_OUT = path.join('themes',);-const toIdentifier = (slug) =>- slug.replace(/-([a-z])/g, (_, c) => c.toUpperCase());+const toIdentifier = slug =>+ slug.replace(/-([a-z])/g, (_, character) => character.toUpperCase());-const readJSON = (file) => JSON.parse(fs.readFileSync(file, 'utf-8'));+const readJSON = file => JSON.parse(fs.readFileSync(file, 'utf-8'));-/** Theme slugs discovered the same way the generator discovers them. */+/** @param {string} directory @param {string} [prefix] */+function filesUnder(directory, prefix = '') {+ if (!fs.existsSync(directory)) return [];+ const files = [];+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {+ const relative = prefix ? path.join(prefix, entry.name) : entry.name;+ const full = path.join(directory, entry.name);+ if (entry.isDirectory()) files.push(...filesUnder(full, relative));+ else if (entry.isFile()) files.push(relative.split(path.sep).join('/'));+ }+ return files.sort();+}++/** Public theme packages: a source theme in a package that is not private. */function themeSlugs() {if (!fs.existsSync(THEMES_SRC_ROOT)) return [];return fs.readdirSync(THEMES_SRC_ROOT, {withFileTypes: true})- .filter((e) => e.isDirectory())- .map((e) => e.name)- .filter((slug) => {- const themeFile = path.join(- THEMES_SRC_ROOT,- slug,- 'src',- `${toIdentifier(slug)}Theme.ts`,- );- if (!fs.existsSync(themeFile)) return false;- // Private packages are not themes a user can pick — packages/themes/probe- // is a generated visual-gate fixture. The generator skips them, so this- // discovery must too, or it would demand the fixture be bundled.+ .filter(entry => entry.isDirectory())+ .map(entry => entry.name)+ .filter(slug => {+ const stem = `${toIdentifier(slug)}Theme`;+ const source = path.join(THEMES_SRC_ROOT, slug, 'src', `${stem}.ts`);+ if (!fs.existsSync(source)) return false;const pkg = path.join(THEMES_SRC_ROOT, slug, 'package.json');return !fs.existsSync(pkg) || readJSON(pkg).private !== true;}).sort();}+/** @param {string} slug */+function expectedFiles(slug) {+ const id = toIdentifier(slug);+ const sourceDir = path.join(THEMES_SRC_ROOT, slug, 'src');+ const candidates = [+ {source: path.join(sourceDir, `${id}Theme.ts`), output: `${id}Theme.ts`},+ {+ source: path.join(sourceDir, `${id}Theme.doc.mjs`),+ output: `${id}Theme.doc.mjs`,+ },+ {source: path.join(sourceDir, 'icons.tsx'), output: 'icons.tsx'},+ {+ source: path.join(sourceDir, `${id}Palettes.ts`),+ output: `${id}Palettes.ts`,+ },+ {+ source: path.join(sourceDir, `${id}Palettes.generated.ts`),+ output: `${id}Palettes.generated.ts`,+ },+ {+ source: path.join(sourceDir, `${id}PaletteRefs.generated.ts`),+ output: `${id}PaletteRefs.generated.ts`,+ },+ {+ source: path.join(sourceDir, `${id}Palettes.generated.receipt.json`),+ output: `${id}Palettes.generated.receipt.json`,+ },+ {+ source: path.join(THEMES_SRC_ROOT, slug, 'palette.config.json'),+ output: 'palette.config.json',+ },+ ];+ return candidates.filter(file => fs.existsSync(file.source));+}+/** Theme dirs that exist but must never reach the CLI tarball. */function privateThemeSlugs() {if (!fs.existsSync(THEMES_SRC_ROOT)) return [];return fs.readdirSync(THEMES_SRC_ROOT, {withFileTypes: true})- .filter((e) => e.isDirectory())- .map((e) => e.name)- .filter((slug) => {+ .filter(entry => entry.isDirectory())+ .map(entry => entry.name)+ .filter(slug => {const pkg = path.join(THEMES_SRC_ROOT, slug, 'package.json');return fs.existsSync(pkg) && readJSON(pkg).private === true;})@@ -80,40 +122,122 @@ describe('CLI theme bundle is in sync with source', () => {expect(slugs.length).toBeGreaterThan(0);});- for (const slug of slugs) {- const id = toIdentifier(slug);- const themeFileName = `${id}Theme.ts`;- const src = path.join(THEMES_SRC_ROOT, slug, 'src', themeFileName);- const bundled = path.join(CLI_THEMES_OUT, slug, themeFileName);+ it('every public theme package descriptor reads back through the CLI', () => {+ expect(() => listThemeSlugs()).not.toThrow();+ });- it(`${slug}: bundled ${themeFileName} matches source (run \`pnpm bundle:cli-themes\`)`, () => {+ it('the generator runs when its path goes through a symlinked directory', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-gen-'));+ try {+ const repo = path.join(root, 'repo');+ const cli = path.join(repo, 'packages', 'cli');+ fs.mkdirSync(path.join(repo, 'scripts'), {recursive: true});+ fs.mkdirSync(cli, {recursive: true});+ fs.copyFileSync(+ path.join(__dirname, 'generate-cli-themes.mjs'),+ path.join(repo, 'scripts', 'generate-cli-themes.mjs'),+ );+ for (const dir of ['authoring', 'foundation']) {+ fs.symlinkSync(+ path.join(REPO_ROOT, 'packages', 'cli', dir),+ path.join(cli, dir),+ );+ }+ const src = path.join(repo, 'packages', 'themes', 'ocean', 'src');+ fs.mkdirSync(src, {recursive: true});+ fs.writeFileSync(+ path.join(src, '..', 'package.json'),+ JSON.stringify({name: '@acme/theme-ocean'}),+ );+ fs.writeFileSync(+ path.join(src, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',+ );+ fs.writeFileSync(+ path.join(src, 'oceanTheme.doc.mjs'),+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Blue.', maintained: true};\n",+ );+ fs.symlinkSync(repo, path.join(root, 'link'));+ const run = spawnSync(+ process.execPath,+ [path.join(root, 'link', 'scripts', 'generate-cli-themes.mjs')],+ {cwd: path.parse(root).root, encoding: 'utf-8'},+ );+ expect(run.status, run.stderr).toBe(0);expect(- fs.existsSync(bundled),- `missing bundled theme: ${path.relative(REPO_ROOT, bundled)}`,- ).toBe(true);- expect(fs.readFileSync(bundled, 'utf8')).toBe(- fs.readFileSync(src, 'utf8'),+ fs.readdirSync(+ path.join(cli, 'assets', 'templates', 'themes', 'ocean'),+ ),+ ).toEqual(['oceanTheme.doc.mjs', 'oceanTheme.ts']);+ } finally {+ fs.rmSync(root, {recursive: true, force: true});+ }+ });++ it('every public theme package ships its same-stem descriptor', () => {+ const missing = slugs.filter(slug => {+ const stem = `${toIdentifier(slug)}Theme`;+ return !fs.existsSync(+ path.join(THEMES_SRC_ROOT, slug, 'src', `${stem}.doc.mjs`),);});+ expect(missing, 'packages/themes/<slug> without a descriptor').toEqual([]);+ });- const srcIcons = path.join(THEMES_SRC_ROOT, slug, 'src', 'icons.tsx');- if (fs.existsSync(srcIcons)) {- it(`${slug}: bundled icons.tsx matches source`, () => {- const bundledIcons = path.join(CLI_THEMES_OUT, slug, 'icons.tsx');- expect(- fs.existsSync(bundledIcons),- `missing bundled icons: ${path.relative(REPO_ROOT, bundledIcons)}`,- ).toBe(true);- expect(fs.readFileSync(bundledIcons, 'utf8')).toBe(- fs.readFileSync(srcIcons, 'utf8'),+ it('the generator refuses a public theme package with no descriptor', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-src-'));+ try {+ for (const [slug, pkg] of [+ ['ocean', {name: '@acme/theme-ocean'}],+ ['probe', {name: '@acme/theme-probe', private: true}],+ ]) {+ fs.mkdirSync(path.join(root, slug, 'src'), {recursive: true});+ fs.writeFileSync(+ path.join(root, slug, 'package.json'),+ JSON.stringify(pkg),);- });+ fs.writeFileSync(+ path.join(root, slug, 'src', `${slug}Theme.ts`),+ `export const ${slug}Theme = {};\n`,+ );+ }+ expect(() => listThemeSlugs(root)).toThrow(+ `Theme package @acme/theme-ocean (${path.basename(root)}/ocean) has src/oceanTheme.ts but no src/oceanTheme.doc.mjs descriptor, so it cannot be bundled.`,+ );+ const descriptor = path.join(root, 'ocean', 'src', 'oceanTheme.doc.mjs');+ const named = `Theme package @acme/theme-ocean (${path.basename(root)}/ocean) descriptor src/oceanTheme.doc.mjs`;+ fs.writeFileSync(descriptor, 'export default {};\n');+ expect(() => listThemeSlugs(root)).toThrow(+ `${named} must declare its public ThemeDoc type from @astryxdesign/cli/authoring.`,+ );+ const typed = (/** @type {string} */ name) =>+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: '${name}', displayName: 'Ocean', description: 'Blue.', maintained: true};\n`;+ fs.writeFileSync(descriptor, typed('sea'));+ expect(() => listThemeSlugs(root)).toThrow(+ `${named} names "sea", but the package folder is "ocean".`,+ );+ fs.writeFileSync(descriptor, typed('ocean'));+ expect(listThemeSlugs(root)).toEqual(['ocean']);+ } finally {+ fs.rmSync(root, {recursive: true, force: true});}+ });++ for (const slug of slugs) {+ it(`${slug}: bundled directory matches source (run \`pnpm bundle:cli-themes\`)`, () => {+ const bundledDir = path.join(CLI_THEMES_OUT, slug);+ const expected = expectedFiles(slug);+ expect(filesUnder(bundledDir)).toEqual(+ expected.map(file => file.output).sort(),+ );+ for (const file of expected) {+ expect(fs.readFileSync(path.join(bundledDir, file.output))).toEqual(+ fs.readFileSync(file.source),+ );+ }+ });}- // These assets ship inside the CLI tarball, so a private package that- // happens to live in packages/themes becomes an installable theme unless- // the generator excludes it. The probe fixture did exactly that once.for (const slug of privateThemeSlugs()) {it(`${slug}: private theme package is not shipped to CLI users`, () => {expect(@@ -124,12 +248,28 @@ describe('CLI theme bundle is in sync with source', () => {});}- it('bundles exactly the discovered themes, and nothing else', () => {+ it('theme add copies each bundled theme in bundle order, without its descriptor', () => {+ const discovered = new Map(+ discoverBundledThemes().map(theme => [theme.slug, theme.files]),+ );+ for (const slug of slugs) {+ expect(discovered.get(slug), slug).toEqual(+ expectedFiles(slug)+ .map(file => file.output)+ .filter(file => !file.endsWith('.doc.mjs')),+ );+ }+ });++ it('bundles exactly the discovered themes and no central catalog', () => {const bundled = fs.readdirSync(CLI_THEMES_OUT, {withFileTypes: true})- .filter((e) => e.isDirectory())- .map((e) => e.name)+ .filter(entry => entry.isDirectory())+ .map(entry => entry.name).sort();expect(bundled).toEqual(slugs);+ expect(fs.existsSync(path.join(CLI_THEMES_OUT, 'manifest.json'))).toBe(+ false,+ );});});diff --git a/scripts/generate-cli-themes.mjs b/scripts/generate-cli-themes.mjsindex 9960a22399..dbd40d257d 100644--- a/scripts/generate-cli-themes.mjs+++ b/scripts/generate-cli-themes.mjs@@ -1,16 +1,19 @@+#!/usr/bin/env node// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Bundles each theme's source, optional icons and palette-authoring- * artifacts, and a `manifest.json` into+ * @file Bundles each public theme's source, strongly typed same-stem descriptor,+ * optional icons, and palette-authoring artifacts into* `packages/cli/assets/templates/themes/` so `astryx theme add` can scaffold a- * complete, reproducible theme without the package installed. Run from the repo- * root; commit the output so the published CLI carries it.+ * complete theme without the package installed. There is no central catalog.+ * Run from the repo root and commit the generated bundle.*/import * as fs from 'node:fs';import * as path from 'node:path';import {fileURLToPath} from 'node:url';+import {parseTheme} from '../packages/cli/authoring/doctypes/theme/parse.mjs';+import {readThemeDescriptorValue} from '../packages/cli/foundation/discovery/theme-discovery.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const REPO_ROOT = path.resolve(__dirname, '..');@@ -24,92 +27,114 @@ const CLI_THEMES_OUT = path.join('themes',);-// Flagged in the manifest so `theme list` can mark it "(maintained)".-const MAINTAINED_SLUG = 'neutral';-function toIdentifier(slug) {- return slug.replace(/-([a-z])/g, (_, c) => c.toUpperCase());-}--/** Title-case a slug for display ("y2k" → "Y2K" is special-cased). */-function toDisplayName(slug) {- if (slug === 'y2k') return 'Y2K';- return slug.charAt(0).toUpperCase() + slug.slice(1);+ return slug.replace(/-([a-z])/g, (_, character) => character.toUpperCase());}function readJSON(file) {return JSON.parse(fs.readFileSync(file, 'utf-8'));}-function listThemeSlugs() {- if (!fs.existsSync(THEMES_SRC_ROOT)) return [];+/**+ * The public theme packages to bundle: each directory with a package.json and+ * a `src/<name>Theme.ts`, unless the package is private. A public one whose+ * same-stem descriptor is missing, or is not a ThemeDoc the CLI reads for that+ * slug, throws rather than dropping out of the bundle or breaking it.+ * @param {string} [themesRoot]+ * @returns {string[]}+ */+export function listThemeSlugs(themesRoot = THEMES_SRC_ROOT) {+ if (!fs.existsSync(themesRoot)) return [];return fs- .readdirSync(THEMES_SRC_ROOT, {withFileTypes: true})- .filter(e => e.isDirectory())- .map(e => e.name)+ .readdirSync(themesRoot, {withFileTypes: true})+ .filter(entry => entry.isDirectory())+ .map(entry => entry.name).filter(slug => {- // A theme dir must have a package.json + a src/<slug>Theme.ts to qualify.- const pkg = path.join(THEMES_SRC_ROOT, slug, 'package.json');- const themeFile = path.join(- THEMES_SRC_ROOT,- slug,- 'src',- `${toIdentifier(slug)}Theme.ts`,+ const sourceDir = path.join(themesRoot, slug, 'src');+ const stem = `${toIdentifier(slug)}Theme`;+ const pkg = path.join(themesRoot, slug, 'package.json');+ const source = path.join(sourceDir, `${stem}.ts`);+ if (!fs.existsSync(pkg) || !fs.existsSync(source)) return false;+ const manifest = readJSON(pkg);+ // A private theme package is a test fixture, not a selectable theme.+ if (manifest.private === true) return false;+ const where = `${path.basename(themesRoot)}/${slug}`;+ const name =+ typeof manifest.name === 'string'+ ? `${manifest.name} (${where})`+ : where;+ const descriptor = path.join(sourceDir, `${stem}.doc.mjs`);+ if (!fs.existsSync(descriptor)) {+ throw new Error(+ `Theme package ${name} has src/${stem}.ts but no src/${stem}.doc.mjs descriptor, so it cannot be bundled.`,+ );+ }+ // The CLI's own reader and parser, so a bundled theme always reads back.+ const label = `Theme package ${name} descriptor src/${stem}.doc.mjs`;+ const doc = parseTheme(+ readThemeDescriptorValue(descriptor, label),+ label,);- if (!fs.existsSync(pkg) || !fs.existsSync(themeFile)) return false;- // A PRIVATE theme package is not a theme a user can pick — it is a test- // fixture that happens to live here (packages/themes/probe). These- // assets ship inside the CLI tarball, so without this the fixture- // becomes a selectable theme in `astryx theme add`.- return readJSON(pkg).private !== true;+ if (doc.name !== slug) {+ throw new Error(+ `${label} names "${doc.name}", but the package folder is "${slug}".`,+ );+ }+ return true;}).sort();}function main() {- const slugs = listThemeSlugs();+ let slugs;+ try {+ slugs = listThemeSlugs();+ } catch (error) {+ console.error(+ `generate-cli-themes: ${error instanceof Error ? error.message : error}`,+ );+ process.exitCode = 1;+ return;+ }if (slugs.length === 0) {console.warn('generate-cli-themes: no theme packages found — skipping.');return;}- // Reset the output dir so removed themes don't linger.+ // Reset the output dir so removed themes and obsolete catalog files do not linger.fs.rmSync(CLI_THEMES_OUT, {recursive: true, force: true});fs.mkdirSync(CLI_THEMES_OUT, {recursive: true});- const entries = [];-for (const slug of slugs) {const id = toIdentifier(slug);- const srcDir = path.join(THEMES_SRC_ROOT, slug, 'src');- const themeFileName = `${id}Theme.ts`;- const themeFile = path.join(srcDir, themeFileName);-+ const sourceDir = path.join(THEMES_SRC_ROOT, slug, 'src');const outDir = path.join(CLI_THEMES_OUT, slug);+ const stem = `${id}Theme`;fs.mkdirSync(outDir, {recursive: true});- const files = [themeFileName];- fs.copyFileSync(themeFile, path.join(outDir, themeFileName));+ const files = [`${stem}.ts`, `${stem}.doc.mjs`];+ for (const file of files) {+ fs.copyFileSync(path.join(sourceDir, file), path.join(outDir, file));+ }// Keep optional theme-owned authoring artifacts with the template. A- // palette-backed theme must remain reproducible after `theme add`, not- // merely compile because a generated palette file happened to be copied.+ // palette-backed theme must remain reproducible after `theme add`.const optionalFiles = [- {source: path.join(srcDir, 'icons.tsx'), output: 'icons.tsx'},+ {source: path.join(sourceDir, 'icons.tsx'), output: 'icons.tsx'},{- source: path.join(srcDir, `${id}Palettes.ts`),+ source: path.join(sourceDir, `${id}Palettes.ts`),output: `${id}Palettes.ts`,},{- source: path.join(srcDir, `${id}Palettes.generated.ts`),+ source: path.join(sourceDir, `${id}Palettes.generated.ts`),output: `${id}Palettes.generated.ts`,},{- source: path.join(srcDir, `${id}PaletteRefs.generated.ts`),+ source: path.join(sourceDir, `${id}PaletteRefs.generated.ts`),output: `${id}PaletteRefs.generated.ts`,},{- source: path.join(srcDir, `${id}Palettes.generated.receipt.json`),+ source: path.join(sourceDir, `${id}Palettes.generated.receipt.json`),output: `${id}Palettes.generated.receipt.json`,},{@@ -123,41 +148,24 @@ function main() {fs.copyFileSync(file.source, path.join(outDir, file.output));}- // Pull the human description from the package.json (falls back to empty).- let description = '';- try {- const pkg = readJSON(path.join(THEMES_SRC_ROOT, slug, 'package.json'));- description = pkg.description || '';- } catch {- /* best-effort */- }-- entries.push({- slug,- displayName: toDisplayName(slug),- description,- maintained: slug === MAINTAINED_SLUG,- entry: themeFileName,- exportName: `${id}Theme`,- files,- });-console.log(` bundled theme "${slug}" (${files.length} files)`);}- const manifest = {- version: 1,- generatedBy: 'scripts/generate-cli-themes.mjs',- themes: entries,- };- fs.writeFileSync(- path.join(CLI_THEMES_OUT, 'manifest.json'),- JSON.stringify(manifest, null, 2) + '\n',- );-console.log(- `generate-cli-themes: wrote ${entries.length} themes + manifest to ${path.relative(REPO_ROOT, CLI_THEMES_OUT)}`,+ `generate-cli-themes: wrote ${slugs.length} typed theme directories to ${path.relative(REPO_ROOT, CLI_THEMES_OUT)}`,);}-main();+/** Whether this module is the entry point, however the path to it was spelled. */+function isEntryPoint() {+ try {+ return (+ fs.realpathSync(process.argv[1] ?? '') ===+ fs.realpathSync(fileURLToPath(import.meta.url))+ );+ } catch {+ return false;+ }+}++if (isEntryPoint()) main();