An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): add complete integration authoring and verification (#6245)
Joeyf574abdf7424
diff --git a/.changeset/integration-add-and-check.md b/.changeset/integration-add-and-check.mdnew file mode 100644index 0000000000..a983084169--- /dev/null+++ b/.changeset/integration-add-and-check.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[feature] Add integration authoring and packed-package verification. `astryx integration add <kind> <name>` and the per-kind `integrationAddComponent`, `integrationAddDoc`, `integrationAddTemplate`, `integrationAddCodemod`, `integrationAddAgentDoc`, and `integrationAddTheme` APIs write complete contributions. Existing component, docs, template, and theme commands see the package being authored without publishing it first. `astryx integration pack --check` proves the same contributions survive the npm tarball and that packed components remain available through their public imports. Doctor now names source-only components, unreachable metadata, codemods outside a version folder, and invalid version folders.+@josephfarinadiff --git a/.changeset/themes-as-integration-kind.md b/.changeset/themes-as-integration-kind.mdnew file mode 100644index 0000000000..ffc764a7d1--- /dev/null+++ b/.changeset/themes-as-integration-kind.md@@ -0,0 +1,9 @@+---+'@astryxdesign/cli': patch+---++[feat] Let integration packages contribute source themes++An integration can declare a themes root using the same bundle shape as Astryx's built-in themes. Installed themes now appear in `theme list`, and `theme add` can copy one by owner.++@josephfarinadiff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjsindex df83dd2230..9e1aa2d1ee 100644--- a/.github/scripts/api-cli-parity-test.mjs+++ b/.github/scripts/api-cli-parity-test.mjs@@ -200,14 +200,33 @@ if (firstTemplate) {add('template nonexistent', ['template', 'nonexistent99'],() => apiCall(api.template, 'nonexistent99'));+// Integration authoring — each per-kind API must match the generic CLI route.+add('integration add component (dry run)',+ ['integration', 'add', 'component', 'ParityProbe', '--dry-run'],+ () => apiCall(api.integrationAddComponent, 'ParityProbe', {cwd: ROOT, dryRun: true}));+add('integration add doc (dry run)',+ ['integration', 'add', 'doc', 'parity-probe', '--dry-run'],+ () => apiCall(api.integrationAddDoc, 'parity-probe', {cwd: ROOT, dryRun: true}));+add('integration add template (dry run)',+ ['integration', 'add', 'template', 'parity-probe', '--type', 'block', '--dry-run'],+ () => apiCall(api.integrationAddTemplate, 'parity-probe', {cwd: ROOT, type: 'block', dryRun: true}));+add('integration add codemod (dry run)',+ ['integration', 'add', 'codemod', 'parity-probe', '--to', '9.9.9', '--dry-run'],+ () => apiCall(api.integrationAddCodemod, 'parity-probe', {cwd: ROOT, to: '9.9.9', dryRun: true}));+add('integration add agent-doc (dry run)',+ ['integration', 'add', 'agent-doc', 'Use ParityProbe.', '--dry-run'],+ () => apiCall(api.integrationAddAgentDoc, 'Use ParityProbe.', {cwd: ROOT, dryRun: true}));+add('integration add theme (dry run)',+ ['integration', 'add', 'theme', 'parity-probe', '--dry-run'],+ () => apiCall(api.integrationAddTheme, 'parity-probe', {cwd: ROOT, dryRun: true}));+// Theme list + add error path (read-only; never scaffolds files here).-// `theme list` / `theme add --list` are served by the dedicated themeList()-// leaf (the CLI routes the --list affordance there); themeAdd() now only-// scaffolds a named slug and throws on a missing/unknown one.+// The CLI routes its project-aware list surfaces to themeListAvailable(); the+// synchronous themeList() export stays bundled-only for API compatibility.add('theme list', ['theme', 'list'],- () => apiCall(api.themeList));+ () => apiCall(api.themeListAvailable, {cwd: ROOT}));add('theme add --list', ['theme', 'add', '--list'],- () => apiCall(api.themeList));+ () => apiCall(api.themeListAvailable, {cwd: ROOT}));add('theme add nonexistent', ['theme', 'add', 'nonexistent99'],() => apiCall(api.themeAdd, 'nonexistent99', {cwd: ROOT}));diff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjsindex d581e15696..2f95741c69 100644--- a/.github/scripts/cli-api-types-verify.mjs+++ b/.github/scripts/cli-api-types-verify.mjs@@ -99,11 +99,19 @@ import {component, docs, blog, discover, template, hook, search, build, swizzle,upgrade, init, doctor, layoutExpand, layoutCheck, layoutGrammar,themeBuild, themeAdd, themeList, listThemes,+ integrationAdd, integrationAddComponent, integrationAddDoc,+ integrationAddTemplate, integrationAddCodemod, integrationAddAgentDoc,+ integrationAddTheme, integrationPackCheck,validateIntegration, summarizeIssues, logger, AstryxError,} from '@astryxdesign/cli/api';import type {ComponentOptions, SearchOptions, UpgradeOptions,ComponentDetailResponse, SearchResponse, UpgradeRunResponse, Logger,+ IntegrationAddComponentOptions, IntegrationAddDocOptions,+ IntegrationAddTemplateOptions, IntegrationAddCodemodOptions,+ IntegrationAddAgentDocOptions, IntegrationAddThemeOptions,+ IntegrationAddResponse, IntegrationPackCheckOptions,+ IntegrationPackCheckResponse,} from '@astryxdesign/cli/api';async function main() {@@ -119,6 +127,28 @@ async function main() {}void main;+async function integrationSurface() {+ const componentOptions: IntegrationAddComponentOptions = {dryRun: true};+ const docOptions: IntegrationAddDocOptions = {dryRun: true, replaces: 'old'};+ const templateOptions: IntegrationAddTemplateOptions = {dryRun: true, type: 'block'};+ const codemodOptions: IntegrationAddCodemodOptions = {dryRun: true, to: '1.2.0'};+ const agentDocOptions: IntegrationAddAgentDocOptions = {dryRun: true};+ const themeOptions: IntegrationAddThemeOptions = {dryRun: true};+ const packOptions: IntegrationPackCheckOptions = {cwd: '.'};+ const responses: IntegrationAddResponse[] = [+ await integrationAddComponent('Card', componentOptions),+ await integrationAddDoc('guide', docOptions),+ await integrationAddTemplate('account-page', templateOptions),+ await integrationAddCodemod('rename-card', codemodOptions),+ await integrationAddAgentDoc('Use Card.', agentDocOptions),+ await integrationAddTheme('ocean', themeOptions),+ await integrationAdd('component', 'Card', {dryRun: true}),+ ];+ const packed: IntegrationPackCheckResponse = await integrationPackCheck(packOptions);+ void [responses, packed];+}+void integrationSurface;+// ── ./authoring ─────────────────────────────────────────────────────────// These declarations are generated from JSDoc too. The narrowing below is the// regression test for a stale parseDoc return union: when three doc kinds werediff --git a/.gitignore b/.gitignoreindex e207baf26d..a5e606d507 100644--- a/.gitignore+++ b/.gitignore@@ -49,8 +49,8 @@ e2e/playwright/.cache/internal/vibe-tests/results/internal/vibe-tests/.fixture-runs/-# Astryx agent docs (generated)-.astryx-docs/+# Astryx agent docs and test scratch directories (generated)+.astryx-*/apps/sandbox/.next/apps/sandbox/out/apps/sandbox/next-env.d.tsdiff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.mdindex 62d4a95a02..475d9817cb 100644--- a/docs/architecture/cli-surface.md+++ b/docs/architecture/cli-surface.md@@ -20,6 +20,14 @@ verified_by:foundation/response/error-codes.test.mjs,foundation/agent-docs/agent-docs.test.mjs,foundation/integrations/autolink.test.mjs,+ foundation/integrations/manifest-writer.test.mjs,+ foundation/integrations/contribution-inventory.test.mjs,+ clients/cli/commands/integration-authoring.test.mjs,+ clients/cli/commands/integration-real-world.test.mjs,+ api/integration/add-contribution.test.mjs,+ api/integration/pack-check.test.mjs,+ api/integration/validate-integration.test.mjs,+ api/theme/integration-themes.test.mjs,clients/cli/commands/upgrade.integration-policy.test.mjs,clients/cli/formatters/index.test.mjs,]@@ -63,7 +71,7 @@ rather than left to the command author.single envelope. Otherwise the formatters render the same values as text.Nothing else may write to stdout.-Discovery of components, templates, codemods and docs is not per-command. It+Discovery of components, templates, themes, codemods and docs is not per-command. Itgoes through the `Project` seam in `foundation/config`, which resolves theintegrations named in `astryx.config` and then autolinks any DECLARED dependencythat ships a root `astryx.integration.*` manifest — a config entry is how a@@ -127,6 +135,36 @@ test, applicable text, and consumer-documentation projections.alias or a non-semver protocol resolves like any other. A config entry keepsprecedence over the same package autolinked, and a dependency whose manifestfails to load is dropped rather than raised as the consuming project's issue.+- **INV15 — Integration authoring writes one complete, discoverable contribution.**+ `integration add <kind> <name>` and its typed per-kind APIs share one receipt+ contract. A dry run reports the same planned paths without writing. A real run+ refuses to clobber authored files, stages related writes atomically, declares+ a contribution root only with valid bytes behind it, and verifies visibility+ through the same discovery seam consumers use.+- **INV16 — Authoring preserves package policy and local source wins while it is+ being edited.** Writers never create `files` or `exports`; when either field+ already exists, they add only the required manifest, root, or public subpath+ and preserve every author-owned entry. The integration beside the current+ package.json replaces the same installed package in place, preserving its+ configured order while making working bytes authoritative.+- **INV17 — Pack verification examines the artifact consumers receive.**+ `integration pack --check` runs the package lifecycle through `npm pack`,+ compares the required file inventory with the actual tarball, extracts that+ tarball into a scratch consumer, reruns contribution discovery, and verifies+ advertised component and template imports through Node's package resolver.+- **INV18 — Integration diagnostics are read-only and package-specific.** Doctor+ validation reports malformed or unreachable roots and contribution conflicts+ without rewriting the package. Everyday discovery skips a broken integration+ and records its issue; a package-scoped theme lookup surfaces that package's+ blocking 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.## Change coupling@@ -139,7 +177,12 @@ updated in the same pull request when it moves an invariant:follows `spec:AST-017/DEC-4`;- adding a formatter, or writing to stdout from anywhere other than `emit` and`jsonOut`;-- changing the file layout under `clients/cli/commands`.+- changing the file layout under `clients/cli/commands`;+- changing an integration writer's receipt, no-clobber/rollback behavior, or+ package.json mutation policy;+- changing what `integration pack --check` executes or proves about the tarball;+- changing local, configured, or autolinked integration precedence;+- changing the integration theme catalog or 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@@ -158,8 +201,15 @@ non-interactive guarantee.- `foundation/response/json.mjs` — `API_VERSION`, `jsonOut`, `jsonError`,`toErrorEnvelope`, `humanLog`, `humanWarn`, the JSON-mode flag.- `foundation/response/error-codes.mjs` — the frozen, append-only code set.-- `foundation/config` — the `Project` discovery seam and the integration- manifest loader.+- `foundation/config` — the `Project` discovery seam and integration precedence.+- `foundation/integrations/manifest-writer.mjs` — safe manifest-root patching,+ verification, and rollback.+- `foundation/integrations/contribution-inventory.mjs` — the shared local and+ packed contribution identity/file contract.+- `api/integration` — contribution writers, diagnostics, and packed-artifact+ verification.+- `foundation/discovery/theme-discovery.mjs` and `api/theme` — integration theme+ catalog 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/<subject>/…` — the scriptable functions the commands wrap; each owns the@@ -172,14 +222,20 @@ non-interactive guarantee.## Verification-| Invariant | Evidence | Failure signal |-| --------- | --------------------------------------------------- | ---------------------------------------------------------------------- |-| INV1 | `clients/cli/commands/interactive-guard.test.mjs` | The subprocess hangs: `signal === 'SIGTERM'` and `status === null`. |-| INV2 | `clients/cli/commands/json-contract.test.mjs` | `--json` stdout does not parse, or parses to a shape outside the two. |-| INV3 | `foundation/response/error-codes.test.mjs` | A shipped code disappears, or an envelope carries an unregistered one. |-| INV4 | `clients/cli/formatters/index.test.mjs`, type tests | `emit` accepts a bare string, or output varies between pipe and TTY. |-| INV6 | `pnpm check:cli-structure` | A command's file or its doc is missing, or sits at the wrong path. |-| INV8 | `clients/cli/cli-exit-codes.test.mjs` | The same condition exits differently with and without `--json`. |+| Invariant | Evidence | Failure signal |+| --------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |+| INV1 | `clients/cli/commands/interactive-guard.test.mjs` | The subprocess hangs: `signal === 'SIGTERM'` and `status === null`. |+| INV2 | `clients/cli/commands/json-contract.test.mjs` | `--json` stdout does not parse, or parses to a shape outside the two. |+| INV3 | `foundation/response/error-codes.test.mjs` | A shipped code disappears, or an envelope carries an unregistered one. |+| INV4 | `clients/cli/formatters/index.test.mjs`, type tests | `emit` accepts a bare string, or output varies between pipe and TTY. |+| INV6 | `pnpm check:cli-structure` | A command's file or its doc is missing, or sits at the wrong path. |+| INV8 | `clients/cli/cli-exit-codes.test.mjs` | The same condition exits differently with and without `--json`. |+| INV14 | `foundation/integrations/autolink.test.mjs`, `foundation/config/project.test.mjs` | An undeclared package contributes, or configured/local precedence changes. |+| INV15 | `api/integration/add-contribution.test.mjs`, `clients/cli/commands/integration-authoring.test.mjs` | Dry-run/write paths differ, a writer clobbers bytes, or the new contribution is not discoverable. |+| INV16 | `foundation/integrations/manifest-writer.test.mjs`, `api/integration/add-contribution.test.mjs` | A writer invents package policy, replaces an author entry, or local bytes lose precedence. |+| INV17 | `api/integration/pack-check.test.mjs` | Lifecycle output, packed files, identities, or public imports diverge without failing the gate. |+| INV18 | `api/integration/validate-integration.test.mjs`, `api/theme/integration-themes.test.mjs` | Diagnostics mutate files, or a selected broken theme package is reported as merely unknown. |+| INV19 | `clients/cli/commands/integration-real-world.test.mjs` | A CLI-authored theme, nested palette, or guides fail across pack, install, list, add, and build. |## Open questionsdiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 203b010ac1..149c633bc3 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -58,22 +58,23 @@ Options:<!-- BEGIN GENERATED: commands -->-| Command | Description |-| ----------- | ----------------------------------------------------------------------------- |-| `blog` | Read the Astryx blog from the published feed |-| `build` | Build a page: composition kit for an idea, or the workflow playbook (no args) |-| `component` | List components or print component docs |-| `discover` | Discover external packages and components |-| `docs` | Print reference docs |-| `doctor` | Diagnose Astryx projects and integration packages |-| `hook` | List hooks or print hook docs |-| `init` | Initialize the design system in your project |-| `layout` | Generate XDS layouts from compressed expressions (XLE/XLO) |-| `search` | Search components, hooks, docs, and templates in one ranked list |-| `swizzle` | Copy component source for customization |-| `template` | Inject a page or block template |-| `theme` | Theme tools: build, export, and manage themes |-| `upgrade` | Migrate versions and update ShadCN-copied compositions |+| Command | Description |+| ------------- | ----------------------------------------------------------------------------- |+| `blog` | Read the Astryx blog from the published feed |+| `build` | Build a page: composition kit for an idea, or the workflow playbook (no args) |+| `component` | List components or print component docs |+| `discover` | Discover external packages and components |+| `docs` | Print reference docs |+| `doctor` | Diagnose Astryx projects and integration packages |+| `hook` | List hooks or print hook docs |+| `init` | Initialize the design system in your project |+| `integration` | Author and verify an Astryx integration package |+| `layout` | Generate XDS layouts from compressed expressions (XLE/XLO) |+| `search` | Search components, hooks, docs, and templates in one ranked list |+| `swizzle` | Copy component source for customization |+| `template` | Inject a page or block template |+| `theme` | Theme tools: build, export, and manage themes |+| `upgrade` | Migrate versions and update ShadCN-copied compositions |<!-- END GENERATED: commands --><!-- Generated by scripts/generate-cli-readme.mjs from `astryx manifest`. Run `pnpm -F @astryxdesign/cli readme`. -->@@ -137,55 +138,58 @@ if (isError(result)) {<!-- BEGIN GENERATED: error-codes -->-| Code | Meaning |-| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `ERR_UNKNOWN` | Fallback for any error without a more specific code. |-| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |-| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a command group was not recognized (e.g. `astryx theme bogus`). |-| `ERR_INVALID_OPTION` | An unknown flag/option was passed (Commander `unknownOption`). |-| `ERR_INVALID_ARGUMENT` | An option/argument had a value Commander's parser rejected. |-| `ERR_MISSING_ARGUMENT` | A required positional argument was omitted (Commander `missingArgument`). |-| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (en, zh, dense). |-| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (full, compact, brief). |-| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |-| `ERR_CORE_NOT_FOUND` | `@astryxdesign/core` could not be located (not installed / not in a monorepo). |-| `ERR_CORE_INCOMPATIBLE` | The installed `@astryxdesign/core` loaded but is too old for this input — it lacks a capability the CLI must call to emit correct output (upgrade core). |-| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |-| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |-| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |-| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |-| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |-| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |-| `ERR_AMBIGUOUS_TEMPLATE` | A template id matched more than one template (narrow with --type/--package). |-| `ERR_AMBIGUOUS_COMPONENT` | A component name is owned by more than one package (narrow with --package). |-| `ERR_UNKNOWN_THEME` | No theme matched the requested slug (theme add). |-| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name (discover). |-| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to agent-docs/init. |-| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |-| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |-| `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |-| `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |-| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |-| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |-| `ERR_NO_SOURCE` | No source file could be located for the requested component/template. |-| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |-| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |-| `ERR_FILE_EXISTS` | Refused to overwrite an existing file in non-interactive mode. |-| `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 was missing a required property (e.g. `name`). |-| `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. |-| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |-| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |-| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |-| `ERR_UNKNOWN_POST` | No blog post matched the requested slug in the feed. |-| `ERR_FETCH_FAILED` | A network fetch (RSS feed or post text) failed. |-| `ERR_LAYOUT_PARSE` | A layout expression failed to parse (syntax error, with line/col). |-| `ERR_LAYOUT_INVALID` | A layout expression parsed but failed validation (unknown component/prop/enum/block). |-| `ERR_UNCLASSIFIED_EXIT` | Recorded in the debug log, never printed: a command exited non-zero without going through cliError/jsonError, so no stable code was available. |-| `ERR_SIGNAL_TERMINATED` | Recorded in the debug log, never printed: the process was ended by a signal (Ctrl-C, SIGTERM) before the command reached a terminal path. |+| Code | Meaning |+| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `ERR_UNKNOWN` | Fallback for any error without a more specific code. |+| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |+| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a command group was not recognized (e.g. `astryx theme bogus`). |+| `ERR_INVALID_OPTION` | An unknown flag/option was passed (Commander `unknownOption`). |+| `ERR_INVALID_ARGUMENT` | An option/argument had a value Commander's parser rejected. |+| `ERR_MISSING_ARGUMENT` | A required positional argument was omitted (Commander `missingArgument`). |+| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (en, zh, dense). |+| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (full, compact, brief). |+| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |+| `ERR_CORE_NOT_FOUND` | `@astryxdesign/core` could not be located (not installed / not in a monorepo). |+| `ERR_CORE_INCOMPATIBLE` | The installed `@astryxdesign/core` loaded but is too old for this input — it lacks a capability the CLI must call to emit correct output (upgrade core). |+| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |+| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |+| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |+| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |+| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |+| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |+| `ERR_AMBIGUOUS_TEMPLATE` | A template id matched more than one template (narrow with --type/--package). |+| `ERR_AMBIGUOUS_COMPONENT` | A component name is owned by more than one package (narrow with --package). |+| `ERR_AMBIGUOUS_THEME` | A theme slug is owned by more than one package (narrow with --package). |+| `ERR_UNKNOWN_THEME` | No theme matched the requested slug (theme add). |+| `ERR_INTEGRATION_ROOT_CONFLICT` | An integration manifest already declares a different path for the requested contribution root. |+| `ERR_INTEGRATION_EXPORT_CONFLICT` | A package export already maps a generated contribution subpath to a different target. |+| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name (discover). |+| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to agent-docs/init. |+| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |+| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |+| `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |+| `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |+| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |+| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |+| `ERR_NO_SOURCE` | No source file could be located for the requested component/template. |+| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |+| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |+| `ERR_FILE_EXISTS` | Refused to overwrite an existing file in non-interactive mode. |+| `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_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. |+| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |+| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |+| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |+| `ERR_UNKNOWN_POST` | No blog post matched the requested slug in the feed. |+| `ERR_FETCH_FAILED` | A network fetch (RSS feed or post text) failed. |+| `ERR_LAYOUT_PARSE` | A layout expression failed to parse (syntax error, with line/col). |+| `ERR_LAYOUT_INVALID` | A layout expression parsed but failed validation (unknown component/prop/enum/block). |+| `ERR_UNCLASSIFIED_EXIT` | Recorded in the debug log, never printed: a command exited non-zero without going through cliError/jsonError, so no stable code was available. |+| `ERR_SIGNAL_TERMINATED` | Recorded in the debug log, never printed: the process was ended by a signal (Ctrl-C, SIGTERM) before the command reached a terminal path. |<!-- END GENERATED: error-codes --><!-- Generated by scripts/generate-cli-readme.mjs from the error-codes EnumDoc (== ERROR_CODES). Run `pnpm -F @astryxdesign/cli readme`. -->@@ -421,8 +425,8 @@ Every response has a `type` discriminant. The full set is below (generated from| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. || `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. || `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |-| `theme.list` | Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag. |-| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |+| `theme.list` | Every bundled or installed integration theme as a ThemeListEntry[]: each with slug, displayName, description, maintained flag, and owner package. |+| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, owner package, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. || `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. || `theme.targets` | The whole themeable surface: the echoed filter, the component count, and one entry per theming target — {key, className, component, props, states}, where props and states are its legal override keys. || `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |@@ -431,6 +435,8 @@ Every response has a `type` discriminant. The full set is below (generated from| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. || `manifest` | The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index. || `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |+| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |+| `integration.pack-check` | The packed-package check: package identity, tarball facts, local and packed contribution inventories, and issues. || `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. || `integration.template-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration template id is also owned by Core; each conflict includes the exact package-qualified command. || `integration.component-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex 31ab67eeb6..4dfd691b1a 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -361,7 +361,7 @@ export async function checkConfig(ctx) {** The CLI autolinks an installed dependency that ships an* `astryx.integration.*` manifest, so a project can be getting components,- * templates, docs and codemods from a package nothing in the project mentions.+ * templates, themes, docs and codemods from a package nothing in the project mentions.* Two questions follow, and this line is the answer to both:** - "Why can the CLI see this?" — asked by an author who greps the project@@ -417,7 +417,7 @@ export function checkImplicitIntegrations(ctx) {integration.__spec && integration.__spec !== integration.name? ` (declared as "${integration.__spec}")`: '';- const roots = ['components', 'templates', 'docs', 'codemods'].filter(+ const roots = ['components', 'templates', 'themes', 'docs', 'codemods'].filter(root => integration[/** @type {'components'} */ (root)],);const contributes = roots.length > 0 ? roots.join(', ') : 'nothing';diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjsindex f132cc494d..6b39e21d42 100644--- a/packages/cli/api/doctor/doctor.test.mjs+++ b/packages/cli/api/doctor/doctor.test.mjs@@ -249,11 +249,15 @@ describe('checkImplicitIntegrations', () => {it('names the package, the field, and what it contributes', () => {const c = checkImplicitIntegrations({- integrations: [autolinked({templates: '/abs/templates'})],+ integrations: [+ autolinked({templates: '/abs/templates', themes: '/abs/themes'}),+ ],});expect(c.message).toContain('@acme/[email protected]');expect(c.message).toContain('from dependencies');- expect(c.message).toContain('contributing components, templates');+ expect(c.message).toContain(+ 'contributing components, templates, themes',+ );});it('names the declared key too when an npm alias makes them differ', () => {diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjsindex 8f2cdb56cc..89f9cd17a9 100644--- a/packages/cli/api/index.mjs+++ b/packages/cli/api/index.mjs@@ -25,7 +25,16 @@ export {docs} from './docs/docs.mjs';export {blog} from './blog/blog.mjs';export {discover} from './discover/discover.mjs';export {template} from './template/template.mjs';-export {themeBuild, themeAdd, themeList, themeTargets, themePaletteGenerate, generateTonalPalette, listThemes} from './theme/theme.mjs';+export {+ themeBuild,+ themeAdd,+ themeList,+ themeListAvailable,+ themeTargets,+ themePaletteGenerate,+ generateTonalPalette,+ listThemes,+} from './theme/theme.mjs';export {hook} from './hook/hook.mjs';export {search} from './search/search.mjs';export {build} from './build/build.mjs';@@ -34,6 +43,16 @@ export {upgrade} from './upgrade/upgrade.mjs';export {init} from './init/init.mjs';export {doctor} from './doctor/doctor.mjs';export {layoutExpand, layoutCheck, layoutGrammar} from './layout/layout.mjs';+export {+ integrationAdd,+ integrationAddAgentDoc,+ integrationAddCodemod,+ integrationAddComponent,+ integrationAddDoc,+ integrationAddTemplate,+} from './integration/add-contribution.mjs';+export {integrationAddTheme} from './integration/add-theme.mjs';+export {integrationPackCheck} from './integration/pack-check.mjs';export {validateIntegration,summarizeIssues,@@ -70,5 +89,7 @@ export * from './upgrade/upgrade.type.mjs';export * from './init/init.type.mjs';export * from './doctor/doctor.type.mjs';export * from './layout/layout.type.mjs';+export * from './integration/integration-authoring.type.mjs';+export * from './integration/pack-check.type.mjs';export * from './integration/validate-integration.type.mjs';export * from './integration/authoring-checks.type.mjs';diff --git a/packages/cli/api/integration/add-contribution.mjs b/packages/cli/api/integration/add-contribution.mjsnew file mode 100644index 0000000000..14cccdddee--- /dev/null+++ b/packages/cli/api/integration/add-contribution.mjs@@ -0,0 +1,1160 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `integrationAdd(kind, name, options)` — generate one valid+ * 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+ * 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.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import jscodeshift from 'jscodeshift';+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {+ assertWithin,+ PathSafetyError,+ sanitizeName,+} from '../../foundation/fs/path-safety.mjs';+import {+ findManifestObject,+ unwrapManifestExpression,+ patchIntegrationRoot,+ findLocalIntegrationManifestOrNull,+ IntegrationRootConflictError,+} from '../../foundation/integrations/manifest-writer.mjs';+import {+ loadManifestObject,+ loadManifest,+} from '../../foundation/integrations/integrations.mjs';+import {isValidSemver} from '../../foundation/env/semver.mjs';+import {assertContributionVisible} from '../../foundation/integrations/contribution-inventory.mjs';+import {parseAgentDocsField} from '../../authoring/integration/schema.mjs';+import {integrationAddTheme} from './add-theme.mjs';+import {+ findPackageDir,+ projectPath,+ packageJsonUpdate,+ packageJsonFilesUpdate,+ applyWrites,+} from './add-helpers.mjs';++// ── Name grammars ───────────────────────────────────────────────────++const COMPONENT_NAME_RE = /^[A-Z][A-Za-z0-9]*$/;+const KEBAB_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;+const TOPIC_NAME_RE = /^[\w-]+$/;++// ── Default roots (used when the manifest declares nothing) ─────────++const DEFAULT_ROOTS = {+ components: './components',+ templates: './templates',+ docs: './docs',+ codemods: './codemods',+};++// ── Shared manifest / package plumbing ──────────────────────────────++/**+ * Read package identity + resolve the manifest path.+ * @param {string} cwd+ */+function resolvePackage(cwd) {+ const packageDir = findPackageDir(cwd);+ const packageFile = path.join(packageDir, 'package.json');+ /** @type {any} */+ let pkg;+ try {+ pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(+ `Cannot read package.json: ${message}`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const owner = typeof pkg.name === 'string' ? pkg.name : '(local integration)';+ const existingManifest = findLocalIntegrationManifestOrNull(packageDir);+ const manifestFile =+ existingManifest ?? path.join(packageDir, 'astryx.integration.mjs');+ return {+ packageDir,+ packageFile,+ pkg,+ owner,+ manifestFile,+ manifestExists: existingManifest != null,+ };+}++/**+ * Load the current manifest's parsed object (or an empty object when no+ * manifest exists yet).+ * @param {string} manifestFile+ * @param {boolean} manifestExists+ * @returns {Promise<import('../../authoring/integration/type').AstryxIntegration>}+ */+async function loadCurrentManifest(manifestFile, manifestExists) {+ if (!manifestExists) return {};+ return loadManifestObject(+ manifestFile,+ `Integration manifest ${path.basename(manifestFile)}`,+ {fresh: true},+ );+}++/**+ * Build and return the common receipt shape.+ * @param {import('./integration-authoring.type.mjs').IntegrationAddResponse['data']['kind']} kind+ * @param {string} name+ * @param {{path: string, created: boolean}|null} root+ * @param {string} manifestPath+ * @param {string[]} files+ * @param {boolean} dryRun+ * @returns {import('./integration-authoring.type.mjs').IntegrationAddResponse}+ */+function receipt(kind, name, root, manifestPath, files, dryRun) {+ return {+ type: 'integration.add',+ data: {+ kind,+ name,+ root,+ manifest: manifestPath,+ files,+ written: !dryRun,+ dryRun,+ },+ };+}++// ── Helpers ─────────────────────────────────────────────────────────++/** @param {string} slug */+function kebabToPascal(slug) {+ return slug.replace(/(^|-)([a-z0-9])/gu, (_, _sep, ch) => ch.toUpperCase());+}++/** @param {string} slug */+function kebabToTitle(slug) {+ const words = slug.split(/[-_]+/u).filter(Boolean);+ if (words.length === 0) return slug;+ return words.map(word => word[0].toUpperCase() + word.slice(1)).join(' ');+}++// ── AST helper (for agent-doc manifest patching) ────────────────────++/** @param {any} prop @param {string} name */+function propNamed(prop, name) {+ const key = prop?.key;+ if (!key) return false;+ return (+ (key.type === 'Identifier' && key.name === name) ||+ (key.type === 'StringLiteral' && key.value === name)+ );+}++// ── Contribution: COMPONENT ─────────────────────────────────────────++/**+ * @param {string} name PascalCase component name+ * @param {{cwd?: string, dryRun?: boolean}} options+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}+ */+async function addComponent(name, options) {+ const {cwd = process.cwd(), dryRun = false} = options;+ if (!COMPONENT_NAME_RE.test(name)) {+ throw new AstryxError(+ `Invalid component name "${name}": use PascalCase starting with an uppercase letter (e.g. MyWidget).`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ try {+ sanitizeName(name, {label: 'component name'});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ throw error;+ }++ const {packageDir, packageFile, owner, manifestFile, manifestExists} =+ resolvePackage(cwd);+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);+ const rootPath = manifest.components ?? DEFAULT_ROOTS.components;+ /** @type {string} */+ let root;+ try {+ root = assertWithin(rootPath, packageDir, {label: 'components root'});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }++ // Pre-flight root patch+ try {+ await patchIntegrationRoot(packageDir, 'components', rootPath, {+ dryRun: true,+ createIfMissing: true,+ });+ } catch (error) {+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ throw error;+ }++ // Target files+ const docFile = assertWithin(`${name}.doc.mjs`, root, {+ label: 'component doc',+ });+ const sourceFile = assertWithin(`${name}.tsx`, root, {+ label: 'component source',+ });+ if (fs.existsSync(docFile)) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, docFile))}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }+ if (fs.existsSync(sourceFile)) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, sourceFile))}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }++ const sourcePath = projectPath(path.relative(packageDir, sourceFile));+ const importSpecifier = `${owner}/${sourcePath}`;+ const docContents = `export default {\n type: 'component',\n name: '${name}',\n import: ${JSON.stringify(importSpecifier)},\n 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[]} */+ const plans = [+ {path: docFile, contents: docContents, createOnly: true},+ {path: sourceFile, contents: sourceContents, createOnly: true},+ ];+ const pkgUpdate = packageJsonUpdate(+ packageFile,+ rootPath,+ path.basename(manifestFile),+ [{subpath: sourcePath, target: sourcePath}],+ );+ if (pkgUpdate != null) {+ plans.push({+ path: packageFile,+ contents: pkgUpdate.contents,+ createOnly: false,+ expectedOriginal: pkgUpdate.expectedOriginal,+ });+ }++ const writtenFiles = plans.map(p =>+ projectPath(path.relative(packageDir, p.path)),+ );+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));++ /** @type {{path: string, created: boolean}} */+ let rootReceipt = {path: rootPath, created: !manifest.components};+ if (!dryRun) {+ let rollback = () => {};+ try {+ rollback = applyWrites(plans);+ rootReceipt = await patchIntegrationRoot(+ packageDir,+ 'components',+ rootPath,+ {+ createIfMissing: true,+ verify: async () => {+ const m = await loadManifestObject(manifestFile, 'verify', {+ fresh: true,+ });+ if (!m.components)+ throw new Error('components root not visible after writing.');+ const compsRoot = assertWithin(m.components, packageDir, {+ label: 'components root',+ });+ await assertContributionVisible(+ {name: owner, components: compsRoot},+ 'component',+ name,+ );+ },+ },+ );+ } catch (error) {+ rollback();+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ if (error instanceof AstryxError) throw error;+ throw new AstryxError(+ `Failed to write component contribution: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ }+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {+ writtenFiles.push(manifestPath);+ }+ return receipt(+ 'component',+ name,+ rootReceipt,+ manifestPath,+ writtenFiles,+ dryRun,+ );+}++// ── Contribution: DOC TOPIC ─────────────────────────────────────────++/**+ * @param {string} name topic name (must match [\w-]+)+ * @param {{cwd?: string, dryRun?: boolean, replaces?: string, extends?: string}} options+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}+ */+async function addDoc(name, options) {+ const {cwd = process.cwd(), dryRun = false} = options;+ if (!TOPIC_NAME_RE.test(name)) {+ throw new AstryxError(+ `Invalid topic name "${name}": use letters, digits, _ and - only.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ if (options.replaces != null && options.extends != null) {+ throw new AstryxError(+ 'A topic either replaces another or extends it, not both.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ for (const [option, value] of [+ ['--replaces', options.replaces],+ ['--extends', options.extends],+ ]) {+ if (value != null && !TOPIC_NAME_RE.test(value)) {+ throw new AstryxError(+ `${option} must name a topic using letters, digits, _ and - only.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ }++ const {packageDir, packageFile, owner, manifestFile, manifestExists} =+ resolvePackage(cwd);+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);+ const rootPath = manifest.docs ?? DEFAULT_ROOTS.docs;+ /** @type {string} */+ let root;+ try {+ root = assertWithin(rootPath, packageDir, {label: 'docs root'});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }++ try {+ await patchIntegrationRoot(packageDir, 'docs', rootPath, {+ dryRun: true,+ createIfMissing: true,+ });+ } catch (error) {+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ throw error;+ }++ const docFile = assertWithin(`${name}.doc.mjs`, root, {+ label: 'doc topic file',+ });+ if (fs.existsSync(docFile)) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, docFile))}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }++ const title = kebabToTitle(name);+ const relationship = options.replaces+ ? `\n replaces: '${options.replaces}',`+ : 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`;++ /** @type {import('./add-helpers.mjs').WritePlan[]} */+ const plans = [{path: docFile, contents: docContents, createOnly: true}];+ const pkgUpdate = packageJsonUpdate(+ packageFile,+ rootPath,+ path.basename(manifestFile),+ );+ if (pkgUpdate != null) {+ plans.push({+ path: packageFile,+ contents: pkgUpdate.contents,+ createOnly: false,+ expectedOriginal: pkgUpdate.expectedOriginal,+ });+ }++ const writtenFiles = plans.map(p =>+ projectPath(path.relative(packageDir, p.path)),+ );+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));++ let rootReceipt = {path: rootPath, created: !manifest.docs};+ if (!dryRun) {+ let rollback = () => {};+ try {+ rollback = applyWrites(plans);+ rootReceipt = await patchIntegrationRoot(packageDir, 'docs', rootPath, {+ createIfMissing: true,+ verify: async () => {+ const m = await loadManifestObject(manifestFile, 'verify', {+ fresh: true,+ });+ if (!m.docs) throw new Error('docs root not visible after writing.');+ const docsRoot = assertWithin(m.docs, packageDir, {+ label: 'docs root',+ });+ await assertContributionVisible(+ {name: owner, docs: docsRoot},+ 'doc',+ name,+ );+ },+ });+ } catch (error) {+ rollback();+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ if (error instanceof AstryxError) throw error;+ throw new AstryxError(+ `Failed to write doc contribution: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ }+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {+ writtenFiles.push(manifestPath);+ }+ return receipt('doc', name, rootReceipt, manifestPath, writtenFiles, dryRun);+}++// ── Contribution: TEMPLATE ──────────────────────────────────────────++/**+ * @param {string} name template id (kebab-case)+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block'}} options+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}+ */+async function addTemplate(name, options) {+ const {cwd = process.cwd(), dryRun = false, templateType = 'page'} = options;+ if (!KEBAB_NAME_RE.test(name)) {+ throw new AstryxError(+ `Invalid template name "${name}": use lowercase kebab-case starting with a letter.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ if (templateType !== 'page' && templateType !== 'block') {+ throw new AstryxError(+ `Invalid template type "${templateType}": must be "page" or "block".`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }++ const {packageDir, packageFile, owner, manifestFile, manifestExists} =+ resolvePackage(cwd);+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);+ const rootPath = manifest.templates ?? DEFAULT_ROOTS.templates;+ /** @type {string} */+ let root;+ try {+ root = assertWithin(rootPath, packageDir, {label: 'templates root'});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }++ try {+ await patchIntegrationRoot(packageDir, 'templates', rootPath, {+ dryRun: true,+ createIfMissing: true,+ });+ } catch (error) {+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ throw error;+ }++ const specFile = assertWithin(`${name}.template.mjs`, root, {+ label: 'template spec',+ });+ const sourceFile = assertWithin(`${name}.tsx`, root, {+ label: 'template source',+ });+ if (fs.existsSync(specFile)) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, specFile))}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }+ if (fs.existsSync(sourceFile)) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, sourceFile))}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }++ const pascalName = kebabToPascal(name);+ const sourcePath = projectPath(path.relative(packageDir, sourceFile));+ const specContents = `export default {\n type: '${templateType}',\n name: '${name}',\n description: '${kebabToTitle(name)} template.',\n};\n`;+ const sourceContents = `export default function ${pascalName}() {\n return <div>${kebabToTitle(name)}</div>;\n}\n`;++ /** @type {import('./add-helpers.mjs').WritePlan[]} */+ const plans = [+ {path: specFile, contents: specContents, createOnly: true},+ {path: sourceFile, contents: sourceContents, createOnly: true},+ ];+ const pkgUpdate = packageJsonUpdate(+ packageFile,+ rootPath,+ path.basename(manifestFile),+ [{subpath: sourcePath, target: sourcePath}],+ );+ if (pkgUpdate != null) {+ plans.push({+ path: packageFile,+ contents: pkgUpdate.contents,+ createOnly: false,+ expectedOriginal: pkgUpdate.expectedOriginal,+ });+ }++ const writtenFiles = plans.map(p =>+ projectPath(path.relative(packageDir, p.path)),+ );+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));++ let rootReceipt = {path: rootPath, created: !manifest.templates};+ if (!dryRun) {+ let rollback = () => {};+ try {+ rollback = applyWrites(plans);+ rootReceipt = await patchIntegrationRoot(+ packageDir,+ 'templates',+ rootPath,+ {+ createIfMissing: true,+ verify: async () => {+ const m = await loadManifestObject(manifestFile, 'verify', {+ fresh: true,+ });+ if (!m.templates)+ throw new Error('templates root not visible after writing.');+ const tplRoot = assertWithin(m.templates, packageDir, {+ label: 'templates root',+ });+ await assertContributionVisible(+ {name: owner, templates: tplRoot},+ 'template',+ name,+ );+ },+ },+ );+ } catch (error) {+ rollback();+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ if (error instanceof AstryxError) throw error;+ throw new AstryxError(+ `Failed to write template contribution: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ }+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {+ writtenFiles.push(manifestPath);+ }+ return receipt(+ 'template',+ name,+ rootReceipt,+ manifestPath,+ writtenFiles,+ dryRun,+ );+}++// ── Contribution: CODEMOD ───────────────────────────────────────────++/**+ * @param {string} name codemod id (kebab-case)+ * @param {{cwd?: string, dryRun?: boolean, to?: string}} options+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}+ */+async function addCodemod(name, options) {+ const {cwd = process.cwd(), dryRun = false, to} = options;+ if (!to || !isValidSemver(to)) {+ throw new AstryxError(+ `--to is required and must be an exact semver version (e.g. 1.0.0). Received: "${to ?? ''}"`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ if (!KEBAB_NAME_RE.test(name)) {+ throw new AstryxError(+ `Invalid codemod id "${name}": use lowercase kebab-case starting with a letter.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }++ const {packageDir, packageFile, owner, manifestFile, manifestExists} =+ resolvePackage(cwd);+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);+ const rootPath = manifest.codemods ?? DEFAULT_ROOTS.codemods;+ /** @type {string} */+ let root;+ try {+ root = assertWithin(rootPath, packageDir, {label: 'codemods root'});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }++ try {+ await patchIntegrationRoot(packageDir, 'codemods', rootPath, {+ dryRun: true,+ createIfMissing: true,+ });+ } catch (error) {+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ throw error;+ }++ const versionDir = assertWithin(to, root, {label: 'codemod version dir'});+ const codemodFile = assertWithin(`${name}.mjs`, versionDir, {+ label: 'codemod file',+ });+ if (fs.existsSync(codemodFile)) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, codemodFile))}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }++ const title = kebabToTitle(name);+ const codemodContents = `export default {\n type: 'code',\n title: '${title}',\n transform(file, api) {\n // Replace this with your transform logic.\n return file.source;\n },\n};\n`;++ /** @type {import('./add-helpers.mjs').WritePlan[]} */+ const plans = [+ {path: codemodFile, contents: codemodContents, createOnly: true},+ ];+ const pkgUpdate = packageJsonUpdate(+ packageFile,+ rootPath,+ path.basename(manifestFile),+ );+ if (pkgUpdate != null) {+ plans.push({+ path: packageFile,+ contents: pkgUpdate.contents,+ createOnly: false,+ expectedOriginal: pkgUpdate.expectedOriginal,+ });+ }++ const writtenFiles = plans.map(p =>+ projectPath(path.relative(packageDir, p.path)),+ );+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));++ let rootReceipt = {path: rootPath, created: !manifest.codemods};+ if (!dryRun) {+ let rollback = () => {};+ try {+ rollback = applyWrites(plans);+ rootReceipt = await patchIntegrationRoot(+ packageDir,+ 'codemods',+ rootPath,+ {+ createIfMissing: true,+ verify: async () => {+ const m = await loadManifestObject(manifestFile, 'verify', {+ fresh: true,+ });+ if (!m.codemods)+ throw new Error('codemods root not visible after writing.');+ const codemodsRoot = assertWithin(m.codemods, packageDir, {+ label: 'codemods root',+ });+ await assertContributionVisible(+ {name: owner, codemods: codemodsRoot},+ 'codemod',+ name,+ {version: to},+ );+ },+ },+ );+ } catch (error) {+ rollback();+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ if (error instanceof AstryxError) throw error;+ throw new AstryxError(+ `Failed to write codemod contribution: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ }+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {+ writtenFiles.push(manifestPath);+ }+ return receipt(+ 'codemod',+ name,+ rootReceipt,+ manifestPath,+ writtenFiles,+ dryRun,+ );+}++// ── Contribution: AGENT-DOC ─────────────────────────────────────────++/**+ * @param {string} line the literal agent-doc line+ * @param {{cwd?: string, dryRun?: boolean}} options+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}+ */+async function addAgentDoc(line, options) {+ const {cwd = process.cwd(), dryRun = false} = options;++ // Validate against the real schema+ try {+ parseAgentDocsField({append: [line]}, 'agentDocs');+ } catch (error) {+ throw new AstryxError(+ error instanceof Error ? error.message : String(error),+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }++ const {packageDir, packageFile, manifestFile, manifestExists, owner} =+ resolvePackage(cwd);+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));++ // Load current agentDocs.append. A bad existing value is author-owned data;+ // refuse it rather than "repairing" it by silently replacing the lines.+ /** @type {string[]} */+ let currentAppend = [];+ if (manifestExists) {+ try {+ const loaded = await loadManifest(+ manifestFile,+ `Integration manifest ${path.basename(manifestFile)}`,+ {fresh: true},+ );+ if (loaded.agentDocsError) throw new Error(loaded.agentDocsError);+ if (loaded.manifest.agentDocs?.append) {+ currentAppend = [...loaded.manifest.agentDocs.append];+ }+ } catch (error) {+ throw new AstryxError(+ `Cannot update agentDocs: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ }++ // Converge: if line is already present, return idempotent receipt+ if (currentAppend.includes(line)) {+ return {+ type: 'integration.add',+ data: {+ kind: 'agent-doc',+ name: line,+ root: null,+ manifest: manifestPath,+ files: [],+ written: false,+ dryRun,+ },+ };+ }++ // Compute and validate the new array+ const newAppend = [...currentAppend, line];+ try {+ parseAgentDocsField({append: newAppend}, 'agentDocs');+ } catch (error) {+ throw new AstryxError(+ `Cannot add agent-doc line: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }++ // AST-patch the manifest+ const source = manifestExists+ ? fs.readFileSync(manifestFile, 'utf-8')+ : 'export default {};\n';+ const j = jscodeshift.withParser('tsx');+ /** @type {ReturnType<ReturnType<typeof jscodeshift.withParser>>} */+ let ast;+ try {+ ast = j(source);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(+ `Could not parse ${path.basename(manifestFile)}: ${message}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ const object = findManifestObject(j, ast);+ if (!object) {+ throw new AstryxError(+ `Could not update ${path.basename(manifestFile)} safely: its default export is not a static object literal.`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }++ const agentDocsProperties = object.properties.filter(+ (/** @type {any} */ property) => propNamed(property, 'agentDocs'),+ );+ if (agentDocsProperties.length > 1) {+ throw new AstryxError(+ 'Cannot update agentDocs safely: the manifest declares it more than once.',+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }++ if (agentDocsProperties.length === 1) {+ const agentDocsProperty = /** @type {any} */ (agentDocsProperties[0]);+ const agentDocsObject = unwrapManifestExpression(agentDocsProperty.value);+ if (!j.ObjectExpression.check(agentDocsObject)) {+ throw new AstryxError(+ 'Cannot update agentDocs safely: it is not a static object literal.',+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ const appendProperties = agentDocsObject.properties.filter(+ (/** @type {any} */ property) => propNamed(property, 'append'),+ );+ if (appendProperties.length > 1) {+ throw new AstryxError(+ 'Cannot update agentDocs safely: append is declared more than once.',+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ if (appendProperties.length === 1) {+ const appendProperty = /** @type {any} */ (appendProperties[0]);+ const appendArray = unwrapManifestExpression(appendProperty.value);+ if (!j.ArrayExpression.check(appendArray)) {+ throw new AstryxError(+ 'Cannot update agentDocs safely: append is not a static array literal.',+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ appendArray.elements.push(j.stringLiteral(line));+ } else {+ agentDocsObject.properties.push(+ j.objectProperty(+ j.identifier('append'),+ j.arrayExpression([j.stringLiteral(line)]),+ ),+ );+ }+ } else {+ if (currentAppend.length > 0) {+ throw new AstryxError(+ 'Cannot update agentDocs safely: it comes from a spread or computed property.',+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ object.properties.push(+ j.objectProperty(+ j.identifier('agentDocs'),+ j.objectExpression([+ j.objectProperty(+ j.identifier('append'),+ j.arrayExpression([j.stringLiteral(line)]),+ ),+ ]),+ ),+ );+ }++ let next = ast.toSource({quote: 'single', reuseWhitespace: true});+ if (source.endsWith('\n') && !next.endsWith('\n')) next += '\n';++ /** @type {import('./add-helpers.mjs').WritePlan[]} */+ const plans = [+ {+ path: manifestFile,+ contents: next,+ createOnly: !manifestExists,+ expectedOriginal: manifestExists ? Buffer.from(source) : undefined,+ },+ ];+ const packageUpdate = packageJsonFilesUpdate(packageFile, [manifestPath]);+ if (packageUpdate != null) {+ plans.push({+ path: packageFile,+ contents: packageUpdate.contents,+ createOnly: false,+ expectedOriginal: packageUpdate.expectedOriginal,+ });+ }+ const writtenFiles = plans.map(plan =>+ projectPath(path.relative(packageDir, plan.path)),+ );+ if (dryRun) {+ return receipt('agent-doc', line, null, manifestPath, writtenFiles, true);+ }++ const rollback = applyWrites(plans);++ // Verify through the real parser+ try {+ const verified = await loadManifest(manifestFile, 'verify', {fresh: true});+ await assertContributionVisible(+ {name: owner, agentDocs: verified.manifest.agentDocs},+ 'agent-doc',+ line,+ );+ if (verified.agentDocsError) {+ throw new Error(verified.agentDocsError);+ }+ } catch (error) {+ rollback();+ throw new AstryxError(+ `Post-write verification failed: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }++ return receipt('agent-doc', line, null, manifestPath, writtenFiles, false);+}++// ── Public per-kind APIs ────────────────────────────────────────────++/**+ * @param {string} name+ * @param {import('./integration-authoring.type.mjs').IntegrationAddComponentOptions} [options]+ */+export function integrationAddComponent(name, options = {}) {+ return addComponent(name, options);+}++/**+ * @param {string} name+ * @param {import('./integration-authoring.type.mjs').IntegrationAddDocOptions} [options]+ */+export function integrationAddDoc(name, options = {}) {+ return addDoc(name, options);+}++/**+ * @param {string} name+ * @param {import('./integration-authoring.type.mjs').IntegrationAddTemplateOptions} [options]+ */+export function integrationAddTemplate(name, options = {}) {+ const {type, ...shared} = options;+ return addTemplate(name, {...shared, templateType: type});+}++/**+ * @param {string} name+ * @param {import('./integration-authoring.type.mjs').IntegrationAddCodemodOptions} options+ */+export function integrationAddCodemod(name, options) {+ return addCodemod(name, options);+}++/**+ * @param {string} line+ * @param {import('./integration-authoring.type.mjs').IntegrationAddAgentDocOptions} [options]+ */+export function integrationAddAgentDoc(line, options = {}) {+ return addAgentDoc(line, options);+}++// ── Public dispatcher ───────────────────────────────────────────────++const KIND_OPTIONS = {+ component: new Set(['cwd', 'dryRun']),+ doc: new Set(['cwd', 'dryRun', 'replaces', 'extends']),+ template: new Set(['cwd', 'dryRun', 'templateType']),+ codemod: new Set(['cwd', 'dryRun', 'to']),+ 'agent-doc': new Set(['cwd', 'dryRun']),+ theme: new Set(['cwd', 'dryRun']),+};++/**+ * Refuse options that belong to another contribution kind. Ignoring one is a+ * silent success: the command exits zero while not doing what the caller asked.+ * @param {keyof typeof KIND_OPTIONS} kind+ * @param {Record<string, unknown>} options+ */+function validateKindOptions(kind, options) {+ const allowed = KIND_OPTIONS[kind];+ for (const [key, value] of Object.entries(options)) {+ if (value !== undefined && !allowed.has(key)) {+ throw new AstryxError(+ `Option "${key}" does not apply to integration kind "${kind}".`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ }+}++/**+ * Add one contribution to the local integration package.+ *+ * @param {'component'|'doc'|'template'|'codemod'|'agent-doc'|'theme'} kind+ * @param {string} name+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string}} [options]+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}+ */+export async function integrationAdd(kind, name, options = {}) {+ if (!Object.prototype.hasOwnProperty.call(KIND_OPTIONS, kind)) {+ throw new AstryxError(+ `Unknown contribution kind "${kind}". Choose component, doc, template, codemod, agent-doc, or theme.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ validateKindOptions(kind, options);+ switch (kind) {+ case 'component':+ return integrationAddComponent(name, options);+ case 'doc':+ return integrationAddDoc(name, options);+ case 'template':+ return integrationAddTemplate(name, {+ cwd: options.cwd,+ dryRun: options.dryRun,+ type: options.templateType,+ });+ case 'codemod':+ return integrationAddCodemod(name, {+ cwd: options.cwd,+ dryRun: options.dryRun,+ to: /** @type {string} */ (options.to),+ });+ case 'agent-doc':+ return integrationAddAgentDoc(name, options);+ case 'theme':+ return integrationAddTheme(name, options);+ }+}diff --git a/packages/cli/api/integration/add-contribution.test.mjs b/packages/cli/api/integration/add-contribution.test.mjsnew file mode 100644index 0000000000..40d1d0b698--- /dev/null+++ b/packages/cli/api/integration/add-contribution.test.mjs@@ -0,0 +1,733 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ integrationAdd,+ integrationAddAgentDoc,+ integrationAddCodemod,+ integrationAddComponent,+ integrationAddDoc,+ integrationAddTemplate,+} from './add-contribution.mjs';+import {validateLocalIntegration} from './validate-integration.mjs';++let tmpDir;++/**+ * @param {{manifest?: string, files?: string[], includeFiles?: boolean, name?: string, exports?: unknown}} [opts]+ */+function setup({+ manifest = 'export default {};\n',+ files = ['dist'],+ includeFiles = true,+ name = '@acme/integration',+ exports,+} = {}) {+ /** @type {{name: string, version: string, files?: string[], exports?: unknown}} */+ const pkg = {name, version: '1.0.0'};+ if (includeFiles) pkg.files = files;+ if (exports !== undefined) pkg.exports = exports;+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify(pkg, null, 2)}\n`,+ );+ fs.writeFileSync(path.join(tmpDir, 'astryx.integration.mjs'), manifest);+}++/** Create a bare package dir with no manifest (first-add scenario). */+function setupBare({files, includeFiles = true} = {}) {+ /** @type {{name: string, version: string, files?: string[]}} */+ const pkg = {name: '@acme/integration', version: '1.0.0'};+ if (includeFiles) pkg.files = files ?? ['dist'];+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify(pkg, null, 2)}\n`,+ );+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-add-contrib-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++// ── COMPONENT ───────────────────────────────────────────────────────++describe('integrationAdd component', () => {+ it('writes doc + source, patches root, and appends to files array', async () => {+ setup();+ const result = await integrationAdd('component', 'MyWidget', {cwd: tmpDir});++ expect(result.type).toBe('integration.add');+ expect(result.data.kind).toBe('component');+ expect(result.data.name).toBe('MyWidget');+ expect(result.data.root).toEqual({path: './components', created: true});+ expect(result.data.written).toBe(true);+ expect(result.data.dryRun).toBe(false);+ expect(result.data.files).toContain('components/MyWidget.doc.mjs');+ expect(result.data.files).toContain('components/MyWidget.tsx');+ expect(result.data.files).toContain('astryx.integration.mjs');++ // Doc file is valid+ const doc = fs.readFileSync(+ path.join(tmpDir, 'components/MyWidget.doc.mjs'),+ 'utf-8',+ );+ expect(doc).toContain("type: 'component'");+ expect(doc).toContain("name: 'MyWidget'");+ expect(doc).toContain('props: []');++ // Source file exists+ expect(fs.existsSync(path.join(tmpDir, 'components/MyWidget.tsx'))).toBe(+ true,+ );++ // Manifest updated+ const manifestContent = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ expect(manifestContent).toContain("components: './components'");++ // package.json files updated+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.files).toContain('components');+ expect(pkg.files).toContain('astryx.integration.mjs');++ // Doctor validates cleanly+ const validation = await validateLocalIntegration(tmpDir);+ const componentErrors = validation.issues.filter(+ i => i.code === 'invalid_component',+ );+ expect(componentErrors).toEqual([]);+ });++ it('publishes and documents the generated component in an existing exports map', async () => {+ setup({exports: {'.': './index.mjs'}});++ await integrationAddComponent('MyWidget', {cwd: tmpDir});++ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.exports).toEqual({+ '.': './index.mjs',+ './components/MyWidget.tsx': './components/MyWidget.tsx',+ });+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'components/MyWidget.doc.mjs'),+ 'utf-8',+ ),+ ).toContain('import: "@acme/integration/components/MyWidget.tsx"');+ });++ it('does not create exports when the package has no exports map', async () => {+ setup();++ await integrationAddComponent('MyWidget', {cwd: tmpDir});++ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.exports).toBeUndefined();+ });++ it('refuses an existing conflicting component export before writing files', async () => {+ setup({+ exports: {+ '.': './index.mjs',+ './components/MyWidget.tsx': './different.tsx',+ },+ });++ await expect(+ integrationAddComponent('MyWidget', {cwd: tmpDir}),+ ).rejects.toMatchObject({code: 'ERR_INTEGRATION_EXPORT_CONFLICT'});+ expect(fs.existsSync(path.join(tmpDir, 'components'))).toBe(false);+ });++ it('dry-runs without writing', async () => {+ setup();+ const result = await integrationAdd('component', 'MyWidget', {+ cwd: tmpDir,+ dryRun: true,+ });+ expect(result.data.written).toBe(false);+ expect(result.data.dryRun).toBe(true);+ expect(result.data.root).toEqual({path: './components', created: true});+ expect(fs.existsSync(path.join(tmpDir, 'components'))).toBe(false);+ });++ it('creates the manifest on first add', async () => {+ setupBare();+ const result = await integrationAdd('component', 'MyWidget', {cwd: tmpDir});+ expect(result.data.root.created).toBe(true);+ expect(fs.existsSync(path.join(tmpDir, 'astryx.integration.mjs'))).toBe(+ true,+ );+ });++ it('refuses to overwrite an existing doc file', async () => {+ setup();+ fs.mkdirSync(path.join(tmpDir, 'components'), {recursive: true});+ fs.writeFileSync(+ path.join(tmpDir, 'components/MyWidget.doc.mjs'),+ 'existing',+ );+ await expect(+ integrationAdd('component', 'MyWidget', {cwd: tmpDir}),+ ).rejects.toThrow(/Refusing to overwrite/);+ });++ it('refuses to overwrite an existing source file', async () => {+ setup();+ fs.mkdirSync(path.join(tmpDir, 'components'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, 'components/MyWidget.tsx'), 'existing');+ await expect(+ integrationAdd('component', 'MyWidget', {cwd: tmpDir}),+ ).rejects.toThrow(/Refusing to overwrite/);+ });++ it('rejects a lowercase name', async () => {+ setup();+ await expect(+ integrationAdd('component', 'myWidget', {cwd: tmpDir}),+ ).rejects.toThrow(/PascalCase/);+ });++ // ── MUTATION TESTS: same-stem pair ──────────────────────────────++ it('mutation: doc alone (no .tsx) causes a validate-contributions error', async () => {+ setup();+ await integrationAdd('component', 'MyWidget', {cwd: tmpDir});+ // Remove the .tsx — keep the doc+ fs.rmSync(path.join(tmpDir, 'components/MyWidget.tsx'));+ const validation = await validateLocalIntegration(tmpDir);+ const componentErrors = validation.issues.filter(+ i => i.code === 'invalid_component',+ );+ expect(componentErrors.length).toBeGreaterThan(0);+ });++ it('mutation: source alone (no .doc) is invisible to discovery', async () => {+ setup();+ await integrationAdd('component', 'MyWidget', {cwd: tmpDir});+ // Remove the doc — keep the tsx+ fs.rmSync(path.join(tmpDir, 'components/MyWidget.doc.mjs'));+ const validation = await validateLocalIntegration(tmpDir);+ // No error because the component is simply invisible — it was never discovered+ const componentErrors = validation.issues.filter(+ i => i.code === 'invalid_component',+ );+ expect(componentErrors).toEqual([]);+ expect(+ validation.issues.some(+ issue => issue.code === 'source_without_component_doc',+ ),+ ).toBe(true);+ // The component is not discoverable without metadata.+ const {discoverIntegrationComponents} =+ await import('../../foundation/discovery/component-discovery.mjs');+ const {loadManifestObject} =+ await import('../../foundation/integrations/integrations.mjs');+ const {assertWithin} = await import('../../foundation/fs/path-safety.mjs');+ const manifest = await loadManifestObject(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'test',+ {fresh: true},+ );+ const compsRoot = assertWithin(manifest.components, tmpDir, {+ label: 'test',+ });+ const records = discoverIntegrationComponents({+ name: '@acme/integration',+ components: compsRoot,+ __spec: '@acme/integration',+ __packageDir: tmpDir,+ __manifestFile: path.join(tmpDir, 'astryx.integration.mjs'),+ });+ expect(records.some(r => r.name === 'MyWidget')).toBe(false);+ });+});++// ── FILES ALLOWLIST MUTATION ────────────────────────────────────────++describe('package.json files allowlist', () => {+ it('never creates a files field when absent', async () => {+ setup({includeFiles: false});+ await integrationAdd('component', 'MyWidget', {cwd: tmpDir});+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.files).toBeUndefined();+ });++ it('appends root and manifest to existing files array', async () => {+ setup({files: ['dist']});+ await integrationAdd('component', 'MyWidget', {cwd: tmpDir});+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.files).toEqual(['dist', 'components', 'astryx.integration.mjs']);+ });++ it('does not duplicate entries already in files', async () => {+ setup({files: ['dist', 'components', 'astryx.integration.mjs']});+ await integrationAdd('component', 'MyWidget', {cwd: tmpDir});+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.files).toEqual(['dist', 'components', 'astryx.integration.mjs']);+ });+});++// ── DOC TOPIC ───────────────────────────────────────────────────────++describe('integrationAdd doc', () => {+ it('writes a valid generic topic with receipt', async () => {+ setup();+ const result = await integrationAdd('doc', 'my-guide', {cwd: tmpDir});++ expect(result.data.kind).toBe('doc');+ expect(result.data.name).toBe('my-guide');+ expect(result.data.root).toEqual({path: './docs', created: true});+ expect(result.data.files).toContain('docs/my-guide.doc.mjs');++ const doc = fs.readFileSync(+ path.join(tmpDir, 'docs/my-guide.doc.mjs'),+ 'utf-8',+ );+ expect(doc).toContain("type: 'generic'");+ expect(doc).toContain("name: 'my-guide'");++ const validation = await validateLocalIntegration(tmpDir);+ const docErrors = validation.issues.filter(i => i.code === 'invalid_doc');+ expect(docErrors).toEqual([]);+ });++ it('includes replaces in the generated doc', async () => {+ setup();+ const result = await integrationAdd('doc', 'my-tokens', {+ cwd: tmpDir,+ replaces: 'tokens',+ });+ const doc = fs.readFileSync(+ path.join(tmpDir, 'docs/my-tokens.doc.mjs'),+ 'utf-8',+ );+ expect(doc).toContain("replaces: 'tokens'");+ expect(doc).not.toContain('extends:');+ });++ it('includes extends in the generated doc', async () => {+ setup();+ const result = await integrationAdd('doc', 'extra-tokens', {+ cwd: tmpDir,+ extends: 'tokens',+ });+ const doc = fs.readFileSync(+ path.join(tmpDir, 'docs/extra-tokens.doc.mjs'),+ 'utf-8',+ );+ expect(doc).toContain("extends: 'tokens'");+ expect(doc).not.toContain('replaces:');+ });++ it('rejects replaces + extends together', async () => {+ setup();+ await expect(+ integrationAdd('doc', 'my-tokens', {+ cwd: tmpDir,+ replaces: 'tokens',+ extends: 'tokens',+ }),+ ).rejects.toThrow(/not both/);+ });++ it.each([+ ['my--guide', 'My Guide'],+ ['a-_-b', 'A B'],+ ['___', '___'],+ ])(+ 'accepts topic name %s without crashing title generation',+ async (name, title) => {+ setup();+ await integrationAdd('doc', name, {cwd: tmpDir});+ expect(+ fs.readFileSync(path.join(tmpDir, 'docs', `${name}.doc.mjs`), 'utf-8'),+ ).toContain(`title: '${title}'`);+ },+ );++ it('rejects an unsafe replacement topic before writing source', async () => {+ setup();+ await expect(+ integrationAdd('doc', 'my-guide', {+ cwd: tmpDir,+ replaces: "topic'; process.exit(1); //",+ }),+ ).rejects.toThrow(/--replaces/);+ expect(fs.existsSync(path.join(tmpDir, 'docs'))).toBe(false);+ });+});++// ── TEMPLATE ────────────────────────────────────────────────────────++describe('integrationAdd template', () => {+ it('writes a valid page template with receipt', async () => {+ setup();+ const result = await integrationAdd('template', 'my-widget', {+ cwd: tmpDir,+ });++ 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.tsx');++ const spec = fs.readFileSync(+ path.join(tmpDir, 'templates/my-widget.template.mjs'),+ 'utf-8',+ );+ expect(spec).toContain("type: 'page'");+ expect(spec).toContain("name: 'my-widget'");++ expect(fs.existsSync(path.join(tmpDir, 'templates/my-widget.tsx'))).toBe(+ true,+ );++ const manifest = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ expect(manifest).toContain("templates: './templates'");+ });++ it('publishes generated template source in an existing exports map', async () => {+ setup({exports: './index.mjs'});++ await integrationAddTemplate('my-widget', {cwd: tmpDir, type: 'page'});++ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.exports).toEqual({+ '.': './index.mjs',+ './templates/my-widget.tsx': './templates/my-widget.tsx',+ });+ });++ it('supports block type', async () => {+ setup();+ const result = await integrationAdd('template', 'my-card', {+ cwd: tmpDir,+ templateType: 'block',+ });+ const spec = fs.readFileSync(+ path.join(tmpDir, 'templates/my-card.template.mjs'),+ 'utf-8',+ );+ expect(spec).toContain("type: 'block'");+ });++ it('rejects an invalid template type', async () => {+ setup();+ await expect(+ integrationAdd('template', 'my-widget', {+ cwd: tmpDir,+ templateType: /** @type {any} */ ('invalid'),+ }),+ ).rejects.toThrow(/must be "page" or "block"/);+ });+});++// ── CODEMOD ─────────────────────────────────────────────────────────++describe('integrationAdd codemod', () => {+ it('writes a valid identity codemod under the version folder', async () => {+ setup();+ const result = await integrationAdd('codemod', 'rename-widget', {+ cwd: tmpDir,+ to: '1.0.0',+ });++ expect(result.data.kind).toBe('codemod');+ expect(result.data.name).toBe('rename-widget');+ expect(result.data.root).toEqual({path: './codemods', created: true});+ expect(result.data.files).toContain('codemods/1.0.0/rename-widget.mjs');++ const codemod = fs.readFileSync(+ path.join(tmpDir, 'codemods/1.0.0/rename-widget.mjs'),+ 'utf-8',+ );+ expect(codemod).toContain("type: 'code'");+ expect(codemod).toContain('transform(file, api)');+ expect(codemod).toContain('return file.source');++ const manifest = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ expect(manifest).toContain("codemods: './codemods'");+ });++ it('requires --to as valid semver', async () => {+ setup();+ await expect(+ integrationAdd('codemod', 'rename-widget', {cwd: tmpDir}),+ ).rejects.toThrow(/--to is required/);+ await expect(+ integrationAdd('codemod', 'rename-widget', {+ cwd: tmpDir,+ to: 'v1',+ }),+ ).rejects.toThrow(/exact semver/);+ });++ it('accepts an exact semver prerelease target', async () => {+ setup();+ const result = await integrationAdd('codemod', 'rename-widget', {+ cwd: tmpDir,+ to: '1.0.0-beta.1',+ });+ expect(result.data.files).toContain(+ 'codemods/1.0.0-beta.1/rename-widget.mjs',+ );+ });+});++// ── AGENT-DOC ───────────────────────────────────────────────────────++describe('integrationAdd agent-doc', () => {+ it('adds a line to agentDocs.append and verifies', async () => {+ setup();+ const result = await integrationAdd(+ 'agent-doc',+ 'This integration provides MyWidget.',+ {cwd: tmpDir},+ );++ expect(result.data.kind).toBe('agent-doc');+ expect(result.data.name).toBe('This integration provides MyWidget.');+ expect(result.data.root).toBeNull();+ expect(result.data.files).toContain('astryx.integration.mjs');++ const manifest = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ expect(manifest).toContain('This integration provides MyWidget.');+ expect(manifest).toContain('agentDocs');+ expect(manifest).toContain('append');+ });++ it('converges: adding the same line twice is idempotent', async () => {+ setup();+ await integrationAdd('agent-doc', 'A line.', {cwd: tmpDir});+ const result = await integrationAdd('agent-doc', 'A line.', {+ cwd: tmpDir,+ });+ expect(result.data.written).toBe(false);+ expect(result.data.files).toEqual([]);+ });++ it('appends to existing lines', async () => {+ setup({+ manifest:+ "export default {\n agentDocs: {\n append: ['Line one.'],\n },\n};\n",+ });+ await integrationAdd('agent-doc', 'Line two.', {cwd: tmpDir});+ const manifest = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ expect(manifest).toContain('Line one.');+ expect(manifest).toContain('Line two.');+ });++ it('creates the manifest when none exists', async () => {+ setupBare();+ await integrationAdd('agent-doc', 'A line.', {cwd: tmpDir});+ expect(fs.existsSync(path.join(tmpDir, 'astryx.integration.mjs'))).toBe(+ true,+ );+ const manifest = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ expect(manifest).toContain('A line.');+ });++ it('rejects a blank line', async () => {+ setup();+ await expect(+ integrationAdd('agent-doc', ' ', {cwd: tmpDir}),+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});+ });++ it('adds the manifest to an existing package files allowlist', async () => {+ setup({files: ['dist']});+ await integrationAdd('agent-doc', 'A line.', {cwd: tmpDir});+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.files).toEqual(['dist', 'astryx.integration.mjs']);+ });++ it('refuses invalid existing agent-doc state instead of deleting it', async () => {+ const manifest =+ "export default {agentDocs: {append: [' line with spaces ']}};\n";+ setup({manifest});+ await expect(+ integrationAdd('agent-doc', 'A new line.', {cwd: tmpDir}),+ ).rejects.toThrow(/Cannot update agentDocs/);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toBe(manifest);+ });++ it('preserves comments attached to existing agent-doc state', async () => {+ setup({+ manifest:+ "export default {\n // Keep this owner note.\n agentDocs: {append: ['Line one.']},\n};\n",+ });+ await integrationAdd('agent-doc', 'Line two.', {cwd: tmpDir});+ const manifest = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ expect(manifest).toContain('// Keep this owner note.');+ expect(manifest).toContain('Line one.');+ expect(manifest).toContain('Line two.');+ });++ it('refuses non-static agent-doc state without changing it', async () => {+ const manifest =+ "const docs = {append: ['Line one.']};\nexport default {agentDocs: docs};\n";+ setup({manifest});+ await expect(+ integrationAdd('agent-doc', 'Line two.', {cwd: tmpDir}),+ ).rejects.toThrow(/not a static object literal/);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toBe(manifest);+ });++ it('refuses a runtime-computed manifest without changing it', async () => {+ const manifest =+ "function makeManifest() { return {agentDocs: {append: ['Line one.']}}; }\nexport default makeManifest();\n";+ setup({manifest});+ await expect(+ integrationAdd('agent-doc', 'Line two.', {cwd: tmpDir}),+ ).rejects.toThrow(/default export is not a static object literal/);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toBe(manifest);+ });++ it('dry-run predicts the same files as the real write', async () => {+ setup({files: ['dist']});+ const plan = await integrationAdd('agent-doc', 'A line.', {+ cwd: tmpDir,+ dryRun: true,+ });+ const written = await integrationAdd('agent-doc', 'A line.', {cwd: tmpDir});+ expect(written.data.files).toEqual(plan.data.files);+ });++ it('dry-run predicts without writing', async () => {+ setup();+ const before = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ const result = await integrationAdd('agent-doc', 'A line.', {+ cwd: tmpDir,+ dryRun: true,+ });+ expect(result.data.written).toBe(false);+ expect(result.data.dryRun).toBe(true);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toBe(before);+ });+});++// ── CROSS-KIND: custom root preservation ────────────────────────────++describe('custom root preservation', () => {+ it('uses an existing custom root from the manifest', async () => {+ setup({manifest: "export default {\n components: './src/ui',\n};\n"});+ const result = await integrationAdd('component', 'MyWidget', {+ cwd: tmpDir,+ });+ expect(result.data.root.path).toBe('./src/ui');+ expect(fs.existsSync(path.join(tmpDir, 'src/ui/MyWidget.doc.mjs'))).toBe(+ true,+ );+ });+});++describe('public per-kind APIs', () => {+ it('exposes narrow functions for every non-theme contribution kind', async () => {+ setup();+ const results = await Promise.all([+ integrationAddComponent('MyWidget', {cwd: tmpDir, dryRun: true}),+ integrationAddDoc('my-guide', {cwd: tmpDir, dryRun: true}),+ integrationAddTemplate('my-page', {+ cwd: tmpDir,+ dryRun: true,+ type: 'page',+ }),+ integrationAddCodemod('rename-widget', {+ cwd: tmpDir,+ dryRun: true,+ to: '1.0.0',+ }),+ integrationAddAgentDoc('Use MyWidget.', {cwd: tmpDir, dryRun: true}),+ ]);++ expect(results.map(result => result.data.kind)).toEqual([+ 'component',+ 'doc',+ 'template',+ 'codemod',+ 'agent-doc',+ ]);+ });+});++describe('public dispatcher', () => {+ it('delegates theme authoring to the theme-specific implementation', async () => {+ setup();+ 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');+ });++ it('refuses a kind-specific option on the wrong kind', async () => {+ setup();+ await expect(+ integrationAdd('component', 'MyWidget', {+ cwd: tmpDir,+ to: '1.0.0',+ }),+ ).rejects.toThrow(/does not apply/);+ expect(fs.existsSync(path.join(tmpDir, 'components'))).toBe(false);+ });++ it('names every supported kind when the kind is unknown', async () => {+ setup();+ await expect(+ integrationAdd(/** @type {any} */ ('plugin'), 'thing', {cwd: tmpDir}),+ ).rejects.toThrow(/component, doc, template, codemod, agent-doc, or theme/);+ });+});diff --git a/packages/cli/api/integration/add-helpers.mjs b/packages/cli/api/integration/add-helpers.mjsnew file mode 100644index 0000000000..0cd1838986--- /dev/null+++ b/packages/cli/api/integration/add-helpers.mjs@@ -0,0 +1,333 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Shared helpers for integration contribution writers.+ *+ * Hosts the atomic staged-write transaction, package.json files-array+ * maintenance, package-dir resolution, and project-path normalization that+ * every `integration add <kind>` command needs. Stateless and side-effect-free+ * outside of {@link applyWrites}.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {randomUUID} from 'node:crypto';+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';++/** @param {string} value */+export function projectPath(value) {+ return value.split(path.sep).join('/');+}++/** @param {string} startDir */+export function findPackageDir(startDir) {+ let dir = path.resolve(startDir);+ for (let depth = 0; depth < 50; depth++) {+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ throw new AstryxError(+ 'No package.json found. Run this command inside an integration package.',+ undefined,+ ERROR_CODES.ERR_FILE_NOT_FOUND,+ );+}++/**+ * @typedef {object} WritePlan+ * @property {string} path+ * @property {string} contents+ * @property {boolean} createOnly+ * @property {Buffer} [expectedOriginal] bytes captured before validation;+ * a different current file is a concurrent edit and must never be overwritten+ */++/**+ * @typedef {object} PackageJsonUpdate+ * @property {string} contents+ * @property {Buffer} expectedOriginal+ */++/**+ * @typedef {object} PackageExportEntry+ * @property {string} subpath package export key, e.g. `./components/Card.tsx`+ * @property {string} target package-relative target, e.g. `./components/Card.tsx`+ */++/**+ * Compute one package.json update for an existing `files` allowlist and existing+ * `exports` map. Neither field is created: adding an exports map to a package+ * that has none would make every previously-open deep import private.+ *+ * @param {string} packageFile+ * @param {string[]} entries project-relative files or directories+ * @param {PackageExportEntry[]} [publicExports]+ * @returns {PackageJsonUpdate|null}+ */+export function packageJsonFilesUpdate(+ packageFile,+ entries,+ publicExports = [],+) {+ const expectedOriginal = fs.readFileSync(packageFile);+ const original = expectedOriginal.toString('utf-8');+ /** @type {any} */+ let pkg;+ try {+ pkg = JSON.parse(original);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(+ `Cannot update package.json: ${message}`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }++ const normalize = (/** @type {string} */ value) =>+ projectPath(value).replace(/^\.\//u, '').replace(/\/$/u, '');+ let changed = false;++ if (pkg.files !== undefined) {+ if (+ !Array.isArray(pkg.files) ||+ pkg.files.some((/** @type {unknown} */ item) => typeof item !== 'string')+ ) {+ throw new AstryxError(+ 'package.json files must be an array of strings before Astryx can add the contribution root.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ for (const item of entries.map(normalize)) {+ if (+ pkg.files.some(+ (/** @type {string} */ value) => normalize(value) === item,+ )+ ) {+ continue;+ }+ pkg.files.push(item);+ changed = true;+ }+ }++ if (pkg.exports !== undefined && publicExports.length > 0) {+ const authored = pkg.exports;+ /** @type {Record<string, unknown>} */+ let exportsMap;+ if (+ authored == null ||+ typeof authored !== 'object' ||+ Array.isArray(authored)+ ) {+ exportsMap = {'.': authored};+ } else {+ const keys = Object.keys(authored);+ const hasSubpaths = keys.some(key => key.startsWith('.'));+ const hasConditions = keys.some(key => !key.startsWith('.'));+ if (hasSubpaths && hasConditions) {+ throw new AstryxError(+ 'package.json exports mixes subpaths and conditions, so Astryx cannot add a contribution export safely.',+ undefined,+ ERROR_CODES.ERR_INTEGRATION_EXPORT_CONFLICT,+ );+ }+ exportsMap = hasConditions ? {'.': authored} : {...authored};+ }++ for (const {subpath, target} of publicExports) {+ const key = `./${normalize(subpath)}`;+ const value = `./${normalize(target)}`;+ if (Object.prototype.hasOwnProperty.call(exportsMap, key)) {+ if (exportsMap[key] !== value) {+ throw new AstryxError(+ `package.json exports already maps "${key}" to a different target; refusing to replace it with "${value}".`,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_EXPORT_CONFLICT,+ );+ }+ continue;+ }+ exportsMap[key] = value;+ changed = true;+ }+ if (changed || exportsMap !== authored) pkg.exports = exportsMap;+ }++ if (!changed) return null;+ const indent = original.match(/\n([ \t]+)"/u)?.[1] ?? ' ';+ return {+ contents:+ JSON.stringify(pkg, null, indent) + (original.endsWith('\n') ? '\n' : ''),+ expectedOriginal,+ };+}++/**+ * Include one contribution root, the manifest, and any public source entries in+ * existing package allowlists.+ * @param {string} packageFile+ * @param {string} rootPath+ * @param {string} manifestName+ * @param {PackageExportEntry[]} [publicExports]+ * @returns {PackageJsonUpdate|null}+ */+export function packageJsonUpdate(+ packageFile,+ rootPath,+ manifestName,+ publicExports = [],+) {+ return packageJsonFilesUpdate(+ packageFile,+ [rootPath, manifestName],+ publicExports,+ );+}++// ── Atomic staged-write transaction ─────────────────────────────────++/** @param {string} file */+function removeTemporary(file) {+ try {+ fs.rmSync(file, {force: true});+ } catch {+ // Best effort. The transaction error remains the actionable failure.+ }+}++/**+ * Restore writes that already published. Best-effort so callers preserve+ * the original actionable error.+ * @param {Array<WritePlan & {temporary: string, original: Buffer|null, mode: number}>} published+ */+function rollbackWrites(published) {+ for (const plan of [...published].reverse()) {+ let restore = null;+ try {+ const stat = fs.lstatSync(plan.path);+ if (stat.isSymbolicLink()) continue;+ const current = fs.readFileSync(plan.path);+ if (!current.equals(Buffer.from(plan.contents))) continue;+ if (plan.original == null) {+ fs.rmSync(plan.path, {force: true});+ } else {+ restore = path.join(+ path.dirname(plan.path),+ `.${path.basename(plan.path)}.restore-${randomUUID()}`,+ );+ fs.writeFileSync(restore, plan.original, {mode: plan.mode});+ fs.renameSync(restore, plan.path);+ restore = null;+ }+ } catch {+ // Best effort. A concurrent edit belongs to its writer, not this rollback.+ } finally {+ if (restore != null) removeTemporary(restore);+ }+ }+}++/** @param {string} file */+function assertNotSymlink(file) {+ let stat;+ try {+ stat = fs.lstatSync(file);+ } catch (error) {+ if (+ error instanceof Error &&+ /** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT'+ ) {+ return;+ }+ throw error;+ }+ if (stat.isSymbolicLink()) {+ throw new AstryxError(+ `Refusing to replace symlinked file ${file}.`,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+}++/**+ * Apply several writes as one operation. New files publish with an atomic+ * hard link so a racing creator is never overwritten; replacements are+ * rejected if their bytes changed after preflight or if the path is a symlink.+ * Returns a rollback function for a later step in the same transaction.+ *+ * @param {WritePlan[]} plans+ * @returns {() => void}+ */+export function applyWrites(plans) {+ /** @type {Array<WritePlan & {temporary: string, original: Buffer|null, mode: number}>} */+ const staged = [];+ /** @type {typeof staged} */+ const published = [];+ try {+ for (const plan of plans) {+ fs.mkdirSync(path.dirname(plan.path), {recursive: true});+ assertNotSymlink(plan.path);+ const exists = fs.existsSync(plan.path);+ if (plan.createOnly && exists) {+ throw new AstryxError(+ `Refusing to overwrite existing file ${plan.path}.`,+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }+ const original = exists ? fs.readFileSync(plan.path) : null;+ if (+ plan.expectedOriginal != null &&+ (original == null || !original.equals(plan.expectedOriginal))+ ) {+ throw new Error(`File changed while preparing: ${plan.path}`);+ }+ const mode = exists ? fs.statSync(plan.path).mode : 0o666;+ const temporary = path.join(+ path.dirname(plan.path),+ `.${path.basename(plan.path)}.tmp-${randomUUID()}`,+ );+ let descriptor;+ try {+ descriptor = fs.openSync(temporary, 'wx', mode);+ try {+ fs.writeFileSync(descriptor, plan.contents, 'utf-8');+ } finally {+ fs.closeSync(descriptor);+ }+ } catch (error) {+ removeTemporary(temporary);+ throw error;+ }+ staged.push({...plan, temporary, original, mode});+ }++ for (const plan of staged) {+ if (plan.original == null) {+ fs.linkSync(plan.temporary, plan.path);+ published.push(plan);+ removeTemporary(plan.temporary);+ continue;+ } else {+ assertNotSymlink(plan.path);+ const current = fs.readFileSync(plan.path);+ if (!current.equals(plan.original)) {+ throw new Error(`File changed while writing: ${plan.path}`);+ }+ fs.renameSync(plan.temporary, plan.path);+ }+ published.push(plan);+ }+ return () => rollbackWrites(published);+ } catch (error) {+ for (const plan of staged) removeTemporary(plan.temporary);+ rollbackWrites(published);+ throw error;+ }+}diff --git a/packages/cli/api/integration/add-helpers.test.mjs b/packages/cli/api/integration/add-helpers.test.mjsnew file mode 100644index 0000000000..ad02bbac80--- /dev/null+++ b/packages/cli/api/integration/add-helpers.test.mjs@@ -0,0 +1,161 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {applyWrites, packageJsonFilesUpdate} from './add-helpers.mjs';++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-add-helpers-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('applyWrites', () => {+ it('refuses to replace a symlink and preserves its target', () => {+ const target = path.join(tmpDir, 'target.json');+ const link = path.join(tmpDir, 'manifest.json');+ fs.writeFileSync(target, '{"owner":"author"}\n');+ fs.symlinkSync(target, link);++ expect(() =>+ applyWrites([+ {+ path: link,+ contents: '{"owner":"agent"}\n',+ createOnly: false,+ },+ ]),+ ).toThrow(/Refusing to replace symlinked file/);+ expect(fs.lstatSync(link).isSymbolicLink()).toBe(true);+ expect(fs.readFileSync(target, 'utf-8')).toBe('{"owner":"author"}\n');+ });++ it('rolls back only bytes still owned by the transaction', () => {+ const created = path.join(tmpDir, 'created.txt');+ const replaced = path.join(tmpDir, 'replaced.txt');+ fs.writeFileSync(replaced, 'before\n');++ const rollback = applyWrites([+ {path: created, contents: 'created-by-call\n', createOnly: true},+ {path: replaced, contents: 'replaced-by-call\n', createOnly: false},+ ]);+ fs.writeFileSync(created, 'concurrent-created\n');+ fs.writeFileSync(replaced, 'concurrent-replaced\n');++ rollback();++ expect(fs.readFileSync(created, 'utf-8')).toBe('concurrent-created\n');+ expect(fs.readFileSync(replaced, 'utf-8')).toBe('concurrent-replaced\n');+ });++ it('removes created files and restores replacements when bytes are unchanged', () => {+ const created = path.join(tmpDir, 'created.txt');+ const replaced = path.join(tmpDir, 'replaced.txt');+ fs.writeFileSync(replaced, 'before\n');++ const rollback = applyWrites([+ {path: created, contents: 'created-by-call\n', createOnly: true},+ {path: replaced, contents: 'replaced-by-call\n', createOnly: false},+ ]);+ rollback();++ expect(fs.existsSync(created)).toBe(false);+ expect(fs.readFileSync(replaced, 'utf-8')).toBe('before\n');+ });++ it('refuses a file changed after validation and preserves the new bytes', () => {+ const file = path.join(tmpDir, 'manifest.json');+ const validated = Buffer.from('{"themes":[]}\n');+ fs.writeFileSync(file, validated);+ fs.writeFileSync(file, '{"themes":[{"slug":"concurrent"}]}\n');++ expect(() =>+ applyWrites([+ {+ path: file,+ contents: '{"themes":[{"slug":"mine"}]}\n',+ createOnly: false,+ expectedOriginal: validated,+ },+ ]),+ ).toThrow(/changed while preparing/);+ expect(fs.readFileSync(file, 'utf-8')).toContain('concurrent');+ });+});++describe('packageJsonFilesUpdate', () => {+ it('never creates files when the package has no allowlist', () => {+ const file = path.join(tmpDir, 'package.json');+ fs.writeFileSync(file, '{"name":"fixture"}\n');+ expect(packageJsonFilesUpdate(file, ['astryx.integration.mjs'])).toBeNull();+ });++ it('never creates exports when the package has no exports field', () => {+ const file = path.join(tmpDir, 'package.json');+ fs.writeFileSync(file, '{"name":"fixture"}\n');+ expect(+ packageJsonFilesUpdate(+ file,+ [],+ [{subpath: 'components/Card.tsx', target: 'components/Card.tsx'}],+ ),+ ).toBeNull();+ });++ it('expands exports sugar and appends an exact source subpath', () => {+ const file = path.join(tmpDir, 'package.json');+ fs.writeFileSync(+ file,+ `${JSON.stringify({name: 'fixture', exports: './index.mjs'}, null, 2)}\n`,+ );+ const next = packageJsonFilesUpdate(+ file,+ [],+ [{subpath: 'components/Card.tsx', target: 'components/Card.tsx'}],+ );+ expect(JSON.parse(next?.contents ?? '').exports).toEqual({+ '.': './index.mjs',+ './components/Card.tsx': './components/Card.tsx',+ });+ });++ it('refuses to replace an authored export target', () => {+ const file = path.join(tmpDir, 'package.json');+ fs.writeFileSync(+ file,+ `${JSON.stringify({+ name: 'fixture',+ exports: {'./components/Card.tsx': './different.tsx'},+ })}\n`,+ );+ expect(() =>+ packageJsonFilesUpdate(+ file,+ [],+ [{subpath: 'components/Card.tsx', target: 'components/Card.tsx'}],+ ),+ ).toThrow(/refusing to replace/);+ });++ it('adds only missing normalized paths to an existing allowlist', () => {+ const file = path.join(tmpDir, 'package.json');+ fs.writeFileSync(+ file,+ `${JSON.stringify({name: 'fixture', files: ['./docs/']}, null, 2)}\n`,+ );+ const next = packageJsonFilesUpdate(file, [+ './docs',+ 'astryx.integration.mjs',+ ]);+ expect(JSON.parse(next?.contents ?? '').files).toEqual([+ './docs/',+ 'astryx.integration.mjs',+ ]);+ expect(next?.expectedOriginal.toString('utf-8')).toContain('"./docs/"');+ });+});diff --git a/packages/cli/api/integration/add-theme.mjs b/packages/cli/api/integration/add-theme.mjsnew file mode 100644index 0000000000..d82a0057d9--- /dev/null+++ b/packages/cli/api/integration/add-theme.mjs@@ -0,0 +1,332 @@+// 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.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {+ assertWithin,+ PathSafetyError,+ sanitizeName,+} from '../../foundation/fs/path-safety.mjs';+import {+ discoverThemeCatalog,+ THEME_MANIFEST_BASENAME,+} from '../../foundation/discovery/theme-discovery.mjs';+import {+ findLocalIntegrationManifestOrNull,+ IntegrationRootConflictError,+ patchIntegrationRoot,+} from '../../foundation/integrations/manifest-writer.mjs';+import {loadManifestObject} from '../../foundation/integrations/integrations.mjs';+import {assertContributionVisible} from '../../foundation/integrations/contribution-inventory.mjs';+import {+ applyWrites,+ findPackageDir,+ packageJsonUpdate,+ projectPath,+} from './add-helpers.mjs';++const DEFAULT_THEMES_ROOT = './themes';++/** @param {string} slug */+function themeIdentity(slug) {+ try {+ sanitizeName(slug, {label: 'theme name'});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ throw error;+ }+ if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(slug)) {+ throw new AstryxError(+ `Invalid theme name "${slug}": use lowercase kebab-case starting with a letter.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const identifier = slug.replace(/-([a-z0-9])/gu, (_, character) =>+ character.toUpperCase(),+ );+ const displayName = slug+ .split('-')+ .map(part =>+ part === 'y2k' ? 'Y2K' : part[0].toUpperCase() + part.slice(1),+ )+ .join(' ');+ return {+ slug,+ displayName,+ exportName: `${identifier}Theme`,+ entry: `${identifier}Theme.ts`,+ };+}++/** @param {{slug: string, exportName: string}} identity */+function themeSource(identity) {+ return `import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const ${identity.exportName} = defineTheme({\n name: '${identity.slug}',\n});\n`;+}++/**+ * Read the bytes back through the same integration-theme discovery seam Project+ * uses. A write is not successful until the requested slug resolves.+ * @param {string} packageDir+ * @param {string} manifestFile+ * @param {string} owner+ * @param {string} slug+ */+async function verifyThemeContribution(packageDir, manifestFile, owner, slug) {+ const manifest = await loadManifestObject(+ manifestFile,+ `Integration manifest ${path.basename(manifestFile)}`,+ {fresh: true},+ );+ if (!manifest.themes) {+ throw new Error('The themes root was not visible after writing.');+ }+ const themesRoot = assertWithin(manifest.themes, packageDir, {+ label: 'themes root',+ });+ await assertContributionVisible(+ {+ name: owner,+ themes: themesRoot,+ },+ 'theme',+ slug,+ );+}++/**+ * Add one source theme to the local integration package.+ * @param {string} name lowercase kebab-case theme slug+ * @param {import('./integration-authoring.type.mjs').IntegrationAddThemeOptions} [options]+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}+ */+export async function integrationAddTheme(name, options = {}) {+ const {cwd = process.cwd(), dryRun = false} = options;+ const packageDir = findPackageDir(cwd);+ const packageFile = path.join(packageDir, 'package.json');+ let pkg;+ try {+ pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(+ `Cannot read package.json: ${message}`,+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ const owner = typeof pkg.name === 'string' ? pkg.name : '(local integration)';+ const identity = themeIdentity(name);+ let manifestFile;+ let manifestExists;+ /** @type {import('../../authoring/integration/type').AstryxIntegration} */+ let manifest = {};+ try {+ const existingManifest = findLocalIntegrationManifestOrNull(packageDir);+ manifestExists = existingManifest != null;+ manifestFile =+ existingManifest ?? path.join(packageDir, 'astryx.integration.mjs');+ if (manifestExists) {+ manifest = await loadManifestObject(+ manifestFile,+ `Integration manifest ${path.basename(manifestFile)}`,+ {fresh: true},+ );+ }+ } catch (error) {+ throw new AstryxError(+ error instanceof Error ? error.message : String(error),+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }++ const rootPath = manifest.themes ?? DEFAULT_THEMES_ROOT;+ let root;+ try {+ root = assertWithin(rootPath, packageDir, {label: 'themes root'});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }++ let rootReceipt;+ try {+ rootReceipt = await patchIntegrationRoot(packageDir, 'themes', rootPath, {+ dryRun: true,+ createIfMissing: true,+ });+ } catch (error) {+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ throw new AstryxError(+ error instanceof Error ? error.message : String(error),+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }++ const themeDir = assertWithin(identity.slug, root, {+ label: 'theme directory',+ });+ 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',+ });+ /** @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) {+ throw new AstryxError(+ error instanceof Error ? error.message : String(error),+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ }+ 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(+ {path: sourceFile, contents: themeSource(identity), createOnly: true},+ {+ path: catalogFile,+ contents: `${JSON.stringify(catalog, null, 2)}\n`,+ createOnly: catalogOriginal == null,+ expectedOriginal: catalogOriginal ?? undefined,+ },+ );+ const packageUpdate = packageJsonUpdate(+ packageFile,+ rootPath,+ path.basename(manifestFile),+ );+ if (packageUpdate != null) {+ plans.push({+ path: packageFile,+ contents: packageUpdate.contents,+ createOnly: false,+ expectedOriginal: packageUpdate.expectedOriginal,+ });+ }++ const writtenFiles = plans.map(plan =>+ projectPath(path.relative(packageDir, plan.path)),+ );+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));++ if (!dryRun) {+ let rollback = () => {};+ try {+ rollback = applyWrites(plans);+ rootReceipt = await patchIntegrationRoot(packageDir, 'themes', rootPath, {+ createIfMissing: true,+ verify: () =>+ verifyThemeContribution(+ packageDir,+ manifestFile,+ owner,+ identity.slug,+ ),+ });+ } catch (error) {+ rollback();+ if (error instanceof IntegrationRootConflictError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,+ );+ }+ if (error instanceof AstryxError) throw error;+ throw new AstryxError(+ `Failed to write theme contribution: ${error instanceof Error ? error.message : String(error)}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ }+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {+ writtenFiles.push(manifestPath);+ }++ return {+ type: 'integration.add',+ data: {+ kind: 'theme',+ name: identity.slug,+ root: rootReceipt,+ manifest: manifestPath,+ files: writtenFiles,+ written: !dryRun,+ dryRun,+ },+ };+}diff --git a/packages/cli/api/integration/add-theme.test.mjs b/packages/cli/api/integration/add-theme.test.mjsnew file mode 100644index 0000000000..cbc570eb82--- /dev/null+++ b/packages/cli/api/integration/add-theme.test.mjs@@ -0,0 +1,194 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {integrationAddTheme} from './add-theme.mjs';+import {validateLocalIntegration} from './validate-integration.mjs';++let tmpDir;++function setup({+ manifest = 'export default {};\n',+ files = ['dist'],+ includeFiles = true,+} = {}) {+ /** @type {{name: string, version: string, files?: string[]}} */+ const pkg = {name: '@acme/themes', version: '1.0.0'};+ if (includeFiles) pkg.files = files;+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify(pkg, null, 2)}\n`,+ );+ fs.writeFileSync(path.join(tmpDir, 'astryx.integration.mjs'), manifest);+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-add-theme-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('integrationAddTheme', () => {+ it('writes a valid source theme, catalog, root, package files entry, and receipt', async () => {+ setup();+ const result = await integrationAddTheme('ocean', {cwd: tmpDir});++ expect(result).toEqual({+ type: 'integration.add',+ data: {+ kind: 'theme',+ name: 'ocean',+ root: {path: './themes', created: true},+ manifest: 'astryx.integration.mjs',+ files: [+ 'themes/ocean/oceanTheme.ts',+ 'themes/manifest.json',+ 'package.json',+ 'astryx.integration.mjs',+ ],+ written: true,+ dryRun: false,+ },+ });+ 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'],+ },+ ],+ });+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toContain("themes: './themes'");+ expect(+ JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'))+ .files,+ ).toEqual(['dist', 'themes', 'astryx.integration.mjs']);+ expect((await validateLocalIntegration(tmpDir)).issues).toEqual([]);+ });++ it('dry-runs the identical receipt without writing anything', async () => {+ setup();+ const beforeManifest = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',+ );+ const result = await integrationAddTheme('ocean', {+ cwd: tmpDir,+ dryRun: true,+ });++ expect(result.data.written).toBe(false);+ 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(fs.existsSync(path.join(tmpDir, 'themes'))).toBe(false);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toBe(beforeManifest);+ });++ it('does not create package.json files when the package had no allowlist', async () => {+ setup({includeFiles: false});+ await integrationAddTheme('ocean', {cwd: tmpDir});+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg).not.toHaveProperty('files');+ expect(pkg).not.toHaveProperty('exports');+ });++ it('uses an author-declared custom root without rewriting it', async () => {+ setup({+ manifest: `export default {themes: './src/themes'};\n`,+ files: undefined,+ });+ fs.mkdirSync(path.join(tmpDir, 'src/themes'), {recursive: true});+ const result = await integrationAddTheme('ocean', {cwd: tmpDir});++ expect(result.data.root).toEqual({path: './src/themes', created: false});+ expect(result.data.files).not.toContain('astryx.integration.mjs');+ expect(+ fs.existsSync(path.join(tmpDir, 'src/themes/ocean/oceanTheme.ts')),+ ).toBe(true);+ });++ it('refuses an invalid existing 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');++ await expect(+ integrationAddTheme('ocean', {cwd: tmpDir}),+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});+ expect(fs.readFileSync(catalog, 'utf-8')).toBe('{not-json\n');+ expect(fs.existsSync(path.join(tmpDir, 'themes', 'ocean'))).toBe(false);+ });++ it('refuses duplicate themes and existing source files', async () => {+ setup();+ await integrationAddTheme('ocean', {cwd: tmpDir});+ await expect(+ integrationAddTheme('ocean', {cwd: tmpDir}),+ ).rejects.toMatchObject({code: 'ERR_FILE_EXISTS'});+ });++ it.each(['../ocean', 'Ocean', 'ocean theme', '.ocean'])(+ 'refuses unsafe or noncanonical name %s',+ async name => {+ setup();+ await expect(+ integrationAddTheme(name, {cwd: tmpDir}),+ ).rejects.toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ });+ },+ );++ it('creates the integration manifest on the first add', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'plain', files: []}),+ );+ const result = await integrationAddTheme('ocean', {cwd: tmpDir});++ expect(result.data.manifest).toBe('astryx.integration.mjs');+ expect(+ result.data.files.filter(file => file === result.data.manifest),+ ).toHaveLength(1);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toContain("themes: './themes'");+ expect(+ JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'))+ .files,+ ).toEqual(['themes', 'astryx.integration.mjs']);+ });++ it('plans manifest creation without writing it under dry-run', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"plain"}\n');+ const result = await integrationAddTheme('ocean', {+ cwd: tmpDir,+ dryRun: true,+ });+ expect(result.data.files).toContain('astryx.integration.mjs');+ expect(fs.existsSync(path.join(tmpDir, 'astryx.integration.mjs'))).toBe(+ false,+ );+ });+});diff --git a/packages/cli/api/integration/integration-authoring.type.mjs b/packages/cli/api/integration/integration-authoring.type.mjsnew file mode 100644index 0000000000..bd130bc006--- /dev/null+++ b/packages/cli/api/integration/integration-authoring.type.mjs@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Typed requests and responses for integration authoring commands.+ */++/**+ * @typedef {'theme'|'component'|'doc'|'template'|'codemod'|'agent-doc'} IntegrationAddKind+ */++/**+ * @typedef {object} IntegrationAddBaseOptions+ * @property {string} [cwd]+ * @property {boolean} [dryRun]+ */++/** @typedef {IntegrationAddBaseOptions} IntegrationAddComponentOptions */++/**+ * @typedef {IntegrationAddBaseOptions & {+ * replaces?: string,+ * extends?: string,+ * }} IntegrationAddDocOptions+ */++/**+ * @typedef {IntegrationAddBaseOptions & {+ * type?: 'page'|'block',+ * }} IntegrationAddTemplateOptions+ */++/**+ * @typedef {IntegrationAddBaseOptions & {+ * to: string,+ * }} IntegrationAddCodemodOptions+ */++/** @typedef {IntegrationAddBaseOptions} IntegrationAddAgentDocOptions */+/** @typedef {IntegrationAddBaseOptions} IntegrationAddThemeOptions */++/**+ * Options for the generic `integrationAdd` dispatcher. Prefer a per-kind API+ * when the contribution kind is known so the accepted options stay narrow.+ *+ * @typedef {object} IntegrationAddOptions+ * @property {string} [cwd]+ * @property {boolean} [dryRun]+ * @property {'page'|'block'} [templateType]+ * @property {string} [replaces]+ * @property {string} [extends]+ * @property {string} [to]+ */++/**+ * A contribution writer receipt. `files` contains every project-relative path+ * written by this call, or every path that would be written under `dryRun`.+ * `root` is null for contribution kinds that modify a manifest field rather+ * than declaring a directory root (e.g. agent-doc).+ *+ * @typedef {object} IntegrationAddResponse+ * @property {'integration.add'} type+ * @property {IntegrationAddData} data+ */++/**+ * @typedef {object} IntegrationAddData+ * @property {'theme'|'component'|'doc'|'template'|'codemod'|'agent-doc'} kind+ * @property {string} name+ * @property {{path: string, created: boolean}|null} root+ * @property {string} manifest+ * @property {string[]} files+ * @property {boolean} written+ * @property {boolean} dryRun+ */++export {};diff --git a/packages/cli/api/integration/integration-block-exports.test.mjs b/packages/cli/api/integration/integration-block-exports.test.mjsindex a3242b1adb..6d9fbcdf8f 100644--- a/packages/cli/api/integration/integration-block-exports.test.mjs+++ b/packages/cli/api/integration/integration-block-exports.test.mjs@@ -177,6 +177,10 @@ const CANONICAL = 'import(@acme/widgets/templates/Gauge/GaugeShowcase.tsx)';const SPEC = '@acme/widgets/templates/Gauge/GaugeShowcase.tsx';describe('integration block-template exports recipe', () => {+ it('has at least one real resolver available', () => {+ expect(TSC_BIN ?? ESBUILD_BIN).not.toBeNull();+ });+it.runIf(TSC_BIN != null)(`CANONICAL: exports {"./templates/*.tsx"} + ${CANONICAL} type-checks under bundler resolution`,() => {diff --git a/packages/cli/api/integration/integrationAdd.doc.mjs b/packages/cli/api/integration/integrationAdd.doc.mjsnew file mode 100644index 0000000000..528ee003df--- /dev/null+++ b/packages/cli/api/integration/integrationAdd.doc.mjs@@ -0,0 +1,100 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationAdd',+ displayName: 'integrationAdd()',+ summary: 'Add one working contribution to an integration package.',+ description:+ 'Creates every file required by the selected contribution, creates the integration manifest on first use, updates an existing package files allowlist without creating one, and verifies the contribution through the same inventory contract used by integrationPackCheck.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationAdd(kind: IntegrationAddKind, name: string, options?: IntegrationAddOptions): Promise<IntegrationAddResponse>',+ keywords: [+ 'integration',+ 'add',+ 'author',+ 'scaffold',+ 'component',+ 'doc',+ 'template',+ 'codemod',+ 'theme',+ ],+ params: [+ {+ name: 'kind',+ type: 'IntegrationAddKind',+ description: 'Contribution kind.',+ required: true,+ },+ {+ name: 'name',+ type: 'string',+ description: 'Contribution name, or the literal agent-doc line.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description: 'Validate and return the planned receipt without writing.',+ default: 'false',+ },+ {+ name: 'options.templateType',+ type: "'page' | 'block'",+ description: 'Template type. Only valid for template.',+ default: "'page'",+ },+ {+ name: 'options.replaces',+ type: 'string',+ description: 'Existing topic to replace. Only valid for doc.',+ },+ {+ name: 'options.extends',+ type: 'string',+ description: 'Existing topic to extend. Only valid for doc.',+ },+ {+ name: 'options.to',+ type: 'string',+ description: 'Exact target semver. Required for codemod.',+ },+ ],+ returns: [+ {+ type: 'integration.add',+ description:+ 'A typed receipt naming every affected project-relative path and whether writes occurred.',+ },+ ],+ examples: [+ {+ label: 'Add a component',+ code: "await integrationAdd('component', 'AcmeWidget');",+ },+ {+ label: 'Preview a doc topic',+ code: "await integrationAdd('doc', 'deploying', {dryRun: true});",+ },+ ],+ command: 'integration add',+ related: [+ 'integrationAddComponent',+ 'integrationAddDoc',+ 'integrationAddTemplate',+ 'integrationAddCodemod',+ 'integrationAddAgentDoc',+ 'integrationAddTheme',+ 'integrationPackCheck',+ 'validateIntegration',+ ],+};diff --git a/packages/cli/api/integration/integrationAddAgentDoc.doc.mjs b/packages/cli/api/integration/integrationAddAgentDoc.doc.mjsnew file mode 100644index 0000000000..f69156371d--- /dev/null+++ b/packages/cli/api/integration/integrationAddAgentDoc.doc.mjs@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationAddAgentDoc',+ displayName: 'integrationAddAgentDoc()',+ summary: 'Append one validated agent-guidance line.',+ description:+ 'Converges the integration manifest to contain the literal guidance line exactly once while preserving comments and refusing malformed existing state.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationAddAgentDoc(line: string, options?: IntegrationAddAgentDocOptions): Promise<IntegrationAddResponse>',+ keywords: ['integration', 'agent', 'guidance', 'author', 'api'],+ params: [+ {+ name: 'line',+ type: 'string',+ description: 'Literal guidance line to append.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description: 'Return the exact write plan without changing files.',+ default: 'false',+ },+ ],+ returns: [+ {+ type: 'integration.add',+ description: 'The shared typed authoring receipt.',+ },+ ],+ examples: [+ {+ label: 'Add agent guidance',+ code: "await integrationAddAgentDoc('Use AcmeWidget for account status.');",+ },+ ],+ command: 'integration add agent-doc',+ related: ['integrationAdd', 'integrationPackCheck'],+};diff --git a/packages/cli/api/integration/integrationAddCodemod.doc.mjs b/packages/cli/api/integration/integrationAddCodemod.doc.mjsnew file mode 100644index 0000000000..99dc36dd86--- /dev/null+++ b/packages/cli/api/integration/integrationAddCodemod.doc.mjs@@ -0,0 +1,55 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationAddCodemod',+ displayName: 'integrationAddCodemod()',+ summary: 'Add a safe identity codemod at an exact target version.',+ description:+ 'Creates a non-throwing identity transform under the exact semver folder and declares the codemods root on first use.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationAddCodemod(name: string, options: IntegrationAddCodemodOptions): Promise<IntegrationAddResponse>',+ keywords: ['integration', 'codemod', 'upgrade', 'migration', 'author', 'api'],+ params: [+ {+ name: 'name',+ type: 'string',+ description: 'Lowercase kebab-case codemod id.',+ required: true,+ },+ {+ name: 'options.to',+ type: 'string',+ description: 'Exact target semver version.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description: 'Return the exact write plan without changing files.',+ default: 'false',+ },+ ],+ returns: [+ {+ type: 'integration.add',+ description: 'The shared typed authoring receipt.',+ },+ ],+ examples: [+ {+ label: 'Add a codemod',+ code: "await integrationAddCodemod('rename-status', {to: '1.2.0'});",+ },+ ],+ command: 'integration add codemod',+ related: ['integrationAdd', 'integrationPackCheck'],+};diff --git a/packages/cli/api/integration/integrationAddComponent.doc.mjs b/packages/cli/api/integration/integrationAddComponent.doc.mjsnew file mode 100644index 0000000000..5916492259--- /dev/null+++ b/packages/cli/api/integration/integrationAddComponent.doc.mjs@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationAddComponent',+ displayName: 'integrationAddComponent()',+ summary: 'Add a complete component contribution.',+ description:+ 'Creates the same-stem component source and metadata pair, declares the components root on first use, preserves existing package allowlists, and publishes an exact source subpath when the package already has an exports map.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationAddComponent(name: string, options?: IntegrationAddComponentOptions): Promise<IntegrationAddResponse>',+ keywords: ['integration', 'component', 'author', 'api', 'scaffold'],+ params: [+ {+ name: 'name',+ type: 'string',+ description: 'PascalCase component export name.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description: 'Return the exact write plan without changing files.',+ default: 'false',+ },+ ],+ returns: [+ {+ type: 'integration.add',+ description: 'The shared typed authoring receipt.',+ },+ ],+ examples: [+ {+ label: 'Add a component',+ code: "await integrationAddComponent('AcmeWidget');",+ },+ ],+ command: 'integration add component',+ related: ['integrationAdd', 'integrationPackCheck'],+};diff --git a/packages/cli/api/integration/integrationAddDoc.doc.mjs b/packages/cli/api/integration/integrationAddDoc.doc.mjsnew file mode 100644index 0000000000..d813612742--- /dev/null+++ b/packages/cli/api/integration/integrationAddDoc.doc.mjs@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationAddDoc',+ displayName: 'integrationAddDoc()',+ summary: 'Add a complete reference-doc contribution.',+ description:+ 'Creates a valid generic topic, declares the docs root on first use, and supports an intentional replaces or extends relationship.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationAddDoc(name: string, options?: IntegrationAddDocOptions): Promise<IntegrationAddResponse>',+ keywords: ['integration', 'doc', 'topic', 'author', 'api'],+ params: [+ {+ name: 'name',+ type: 'string',+ description: 'URL-safe topic name.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description: 'Return the exact write plan without changing files.',+ default: 'false',+ },+ {+ name: 'options.replaces',+ type: 'string',+ description: 'Existing topic this topic replaces.',+ },+ {+ name: 'options.extends',+ type: 'string',+ description: 'Existing topic this topic extends.',+ },+ ],+ returns: [+ {+ type: 'integration.add',+ description: 'The shared typed authoring receipt.',+ },+ ],+ examples: [+ {+ label: 'Add a replacement topic',+ code: "await integrationAddDoc('getting-started-meta', {replaces: 'getting-started'});",+ },+ ],+ command: 'integration add doc',+ related: ['integrationAdd', 'integrationPackCheck'],+};diff --git a/packages/cli/api/integration/integrationAddTemplate.doc.mjs b/packages/cli/api/integration/integrationAddTemplate.doc.mjsnew file mode 100644index 0000000000..d50eb4d845--- /dev/null+++ b/packages/cli/api/integration/integrationAddTemplate.doc.mjs@@ -0,0 +1,55 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationAddTemplate',+ displayName: 'integrationAddTemplate()',+ summary: 'Add a complete page or block template contribution.',+ description:+ 'Creates the same-stem template source and metadata pair, declares the templates root on first use, and publishes an exact source subpath when the package already has an exports map.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationAddTemplate(name: string, options?: IntegrationAddTemplateOptions): Promise<IntegrationAddResponse>',+ keywords: ['integration', 'template', 'page', 'block', 'author', 'api'],+ params: [+ {+ name: 'name',+ type: 'string',+ description: 'Lowercase kebab-case template id.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description: 'Return the exact write plan without changing files.',+ default: 'false',+ },+ {+ name: 'options.type',+ type: "'page' | 'block'",+ description: 'Template kind.',+ default: "'page'",+ },+ ],+ returns: [+ {+ type: 'integration.add',+ description: 'The shared typed authoring receipt.',+ },+ ],+ examples: [+ {+ label: 'Add a block',+ code: "await integrationAddTemplate('account-card', {type: 'block'});",+ },+ ],+ command: 'integration add template',+ related: ['integrationAdd', 'integrationPackCheck'],+};diff --git a/packages/cli/api/integration/integrationAddTheme.doc.mjs b/packages/cli/api/integration/integrationAddTheme.doc.mjsnew file mode 100644index 0000000000..f5a63708b2--- /dev/null+++ b/packages/cli/api/integration/integrationAddTheme.doc.mjs@@ -0,0 +1,85 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationAddTheme',+ 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.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationAddTheme(name: string, options?: IntegrationAddThemeOptions): Promise<IntegrationAddResponse>',+ keywords: ['integration', 'add', 'theme', 'author', 'source', 'scaffold'],+ params: [+ {+ name: 'name',+ type: 'string',+ description: 'Lowercase kebab-case theme name and catalog slug.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ {+ name: 'options.dryRun',+ type: 'boolean',+ description:+ 'Validate and return the same receipt without writing; data.written is false and data.dryRun is true.',+ default: 'false',+ },+ ],+ returns: [+ {+ type: 'integration.add',+ description:+ 'A typed receipt naming the contribution kind and name, root path and whether it was declared, manifest path, every affected project-relative path, whether writes occurred, and whether this was a dry run.',+ },+ ],+ throws: [+ {+ code: 'ERR_INVALID_ARGUMENT',+ when: 'the theme name is not lowercase kebab-case',+ },+ {+ code: 'ERR_FILE_NOT_FOUND',+ when: 'no package.json exists',+ },+ {+ code: 'ERR_FILE_EXISTS',+ when: 'the theme slug or source file already exists',+ },+ {+ code: 'ERR_PATH_TRAVERSAL',+ when: 'a declared themes root escapes the package',+ },+ {+ code: 'ERR_INTEGRATION_ROOT_CONFLICT',+ when: 'the manifest root changed to another path while the command was writing',+ },+ {+ code: 'ERR_THEME_INVALID',+ when: 'the package, integration manifest, or theme catalog is invalid',+ },+ {+ code: 'ERR_WRITE_FAILED',+ when: 'a staged write fails and prior writes are rolled back',+ },+ ],+ examples: [+ {+ label: 'Add a theme',+ code: "await integrationAddTheme('ocean');",+ },+ {+ label: 'Preview writes',+ code: "await integrationAddTheme('ocean', {dryRun: true});",+ },+ ],+ command: 'integration add',+ related: ['themeList', 'themeAdd', 'validateIntegration'],+};diff --git a/packages/cli/api/integration/integrationPackCheck.doc.mjs b/packages/cli/api/integration/integrationPackCheck.doc.mjsnew file mode 100644index 0000000000..9d7d4b9deb--- /dev/null+++ b/packages/cli/api/integration/integrationPackCheck.doc.mjs@@ -0,0 +1,35 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationPackCheck',+ displayName: 'integrationPackCheck()',+ summary: 'Prove an integration package survives npm packing.',+ description:+ "Validates the local integration, runs the package lifecycle, packs with npm, checks required files against npm's authoritative tarball list, extracts the real tarball into a scratch consumer, compares local and packed contribution inventories, and resolves every packed component through its documented public import to verify that module exports the component.",+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationPackCheck(options?: IntegrationPackCheckOptions): Promise<IntegrationPackCheckResponse>',+ keywords: ['integration', 'pack', 'check', 'publish', 'tarball', 'consumer'],+ params: [+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Directory inside the integration package.',+ },+ ],+ returns: [+ {+ type: 'integration.pack-check',+ description:+ 'Package identity, tarball facts, local and packed inventories, and issues.',+ },+ ],+ examples: [+ {label: 'Check the local package', code: 'await integrationPackCheck();'},+ ],+ command: 'integration pack',+ related: ['integrationAdd', 'validateIntegration'],+};diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsnew file mode 100644index 0000000000..096d9f2ed4--- /dev/null+++ b/packages/cli/api/integration/pack-check.mjs@@ -0,0 +1,795 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx integration pack --check` — verify an integration package is+ * ready to publish by cross-referencing its declared contributions against the+ * real npm tarball.+ *+ * Three phases:+ * 1. Structure validation — reuses `validateLocalIntegration`.+ * 2. Pack-list cross-reference — computes the static file inventory and+ * compares it against the lifecycle-produced `npm pack --json` artifact.+ * 3. Extracted-tarball validation — extracts the tarball into a scratch+ * consumer under the author's node_modules and runs the same discovery+ * functions a consumer uses, then compares identities (slugs, names,+ * topic ids) exactly.+ *+ * Contract: every contribution visible in the author's package, and every+ * file required to make it visible, must survive the real npm tarball and+ * be equally visible from an extracted node_modules consumer view.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {fileURLToPath} from 'node:url';+import {spawnSync} from 'node:child_process';+import jscodeshift from 'jscodeshift';+import {assertWithin} from '../../foundation/fs/path-safety.mjs';+import {resolvePackageDir} from '../../foundation/integrations/integrations.mjs';+import {+ discoverIntegrationComponents,+ resolveIntegrationImportPath,+} from '../../foundation/discovery/component-discovery.mjs';+import {loadComponentDoc} from '../../foundation/discovery/component-loader.mjs';+import {discoverIntegrationTemplatesForOne} from '../../foundation/discovery/template-adapter.mjs';+import {+ validateLocalIntegration,+ validateInstalledIntegration,+} from './validate-integration.mjs';+import {+ computeRequiredFiles,+ collectIdentities,+ compareIdentities,+} from '../../foundation/integrations/contribution-inventory.mjs';++/**+ * @typedef {import('../../foundation/integrations/issue').AstryxIntegrationIssue} Issue+ */++/** @param {string} code @param {string} message @returns {Issue} */+function error(code, message) {+ return {code, severity: 'error', message};+}++/** @param {string} code @param {string} message @returns {Issue} */+function warning(code, message) {+ return {code, severity: 'warning', message};+}++/**+ * Cleanup must never hide the check result or prevent the other temporary tree+ * from being removed.+ * @param {string|null} dir+ * @param {string} label+ * @param {Issue[]} issues+ */+function removeTreeBestEffort(dir, label, issues) {+ if (dir == null) return;+ try {+ fs.rmSync(dir, {recursive: true, force: true});+ } catch (err) {+ issues.push(+ warning(+ 'cleanup_failed',+ `Could not remove ${label} ${dir}: ${err instanceof Error ? err.message : String(err)}`,+ ),+ );+ }+}++/**+ * Find the nearest package.json starting from `cwd` and walking up.+ * @param {string} cwd+ * @returns {{packageDir: string, pkg: Record<string, unknown>}|null}+ */+function findPackage(cwd) {+ let dir = path.resolve(cwd);+ for (let depth = 0; depth < 50; depth++) {+ const file = path.join(dir, 'package.json');+ if (fs.existsSync(file)) {+ try {+ return {+ packageDir: dir,+ pkg: JSON.parse(fs.readFileSync(file, 'utf-8')),+ };+ } catch (err) {+ throw new Error(+ `Could not parse ${file}: ${err instanceof Error ? err.message : String(err)}`,+ {cause: err},+ );+ }+ }+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ return null;+}++/**+ * Build the empty receipt returned when no integration manifest is found.+ * @param {string|null} name+ * @param {Issue[]} issues+ * @returns {import('./pack-check.type.mjs').IntegrationPackCheckResponse}+ */+function emptyReceipt(name, issues) {+ return {+ type: 'integration.pack-check',+ data: {+ name,+ version: null,+ packable: !issues.some(i => i.severity === 'error'),+ tarball: null,+ inventory: {manifest: null, roots: [], expectedFiles: 0, packedFiles: 0},+ contributions: {local: null, packed: null},+ issues,+ },+ };+}++/**+ * Parse npm's JSON pack result into the facts the checker needs.+ * @param {string} output+ * @returns {{filename: string, fileCount: number, size: number, unpackedSize: number, packedPaths: Set<string>}}+ */+export function parseNpmPackOutput(output) {+ /** @type {Array<{filename: string, entryCount: number, size: number, unpackedSize: number, files?: Array<{path: string}>}>} */+ let parsed;+ try {+ parsed = JSON.parse(output);+ } catch {+ throw new Error('npm pack produced unparseable JSON output.');+ }+ if (!Array.isArray(parsed) || parsed.length === 0) {+ throw new Error('npm pack returned an empty result.');+ }+ const info = parsed[0];+ if (!info || !Array.isArray(info.files)) {+ throw new Error('npm pack returned a result without a files array.');+ }+ return {+ filename: info.filename,+ fileCount: info.entryCount,+ size: info.size,+ unpackedSize: info.unpackedSize,+ packedPaths: new Set(info.files.map(file => file.path)),+ };+}++/**+ * Run `npm pack --json` with output directed to `destDir` so no preexisting+ * tgz is overwritten. This intentionally runs the package lifecycle, matching+ * the artifact `npm publish` would produce. Uses spawnSync with an args array —+ * no shell — so paths with metacharacters cannot inject.+ *+ * @param {string} packageDir+ * @param {string} destDir+ * @returns {{filename: string, fileCount: number, size: number, unpackedSize: number, packedPaths: Set<string>}}+ */+function runNpmPack(packageDir, destDir) {+ const result = spawnSync(+ 'npm',+ ['pack', '--json', '--silent', `--pack-destination=${destDir}`],+ {cwd: packageDir, encoding: 'utf-8', timeout: 60_000},+ );+ if (result.error) {+ throw new Error(`Could not start npm pack: ${result.error.message}`);+ }+ if (result.status !== 0) {+ const stderr = (result.stderr || '').trim();+ throw new Error(+ `npm pack failed (exit ${result.status})${stderr ? `: ${stderr}` : ''}.`,+ );+ }+ return parseNpmPackOutput(result.stdout);+}++/**+ * Extract a tarball into `extractDir`, stripping the leading `package/`+ * directory that npm tarballs wrap files in. Uses spawnSync with an args+ * array — no shell.+ *+ * @param {string} tgzPath+ * @param {string} extractDir+ */+function extractTarball(tgzPath, extractDir) {+ fs.mkdirSync(extractDir, {recursive: true});+ const result = spawnSync(+ 'tar',+ ['xzf', tgzPath, '-C', extractDir, '--strip-components=1'],+ {encoding: 'utf-8', timeout: 30_000},+ );+ if (result.error) {+ throw new Error(`Could not start tar extraction: ${result.error.message}`);+ }+ if (result.status !== 0) {+ const stderr = (result.stderr || '').trim();+ throw new Error(+ `tar extraction failed (exit ${result.status})${stderr ? `: ${stderr}` : ''}.`,+ );+ }+}++const MODULE_EXTENSIONS = ['.mjs', '.js', '.mts', '.ts', '.tsx', '.jsx'];+const moduleParser = jscodeshift.withParser('tsx');++/** @param {unknown} specifier @param {string} fromFile */+function resolveLocalModule(specifier, fromFile) {+ if (typeof specifier !== 'string' || !specifier.startsWith('.')) return null;+ const base = path.resolve(path.dirname(fromFile), specifier);+ const candidates = [+ base,+ ...MODULE_EXTENSIONS.map(extension => `${base}${extension}`),+ ...MODULE_EXTENSIONS.map(extension => path.join(base, `index${extension}`)),+ ];+ return candidates.find(candidate => fs.existsSync(candidate)) ?? null;+}++/** @param {any} declaration @param {string} exportName */+function declarationExports(declaration, exportName) {+ if (!declaration) return false;+ if (['FunctionDeclaration', 'ClassDeclaration'].includes(declaration.type)) {+ return declaration.id?.name === exportName;+ }+ if (declaration.type !== 'VariableDeclaration') return false;+ return declaration.declarations.some(+ (/** @type {any} */ item) =>+ item.id?.type === 'Identifier' && item.id.name === exportName,+ );+}++/**+ * Check one resolved module's static export surface without executing package+ * code. Local ESM re-exports are followed recursively.+ *+ * @param {string} file+ * @param {string} exportName+ * @param {Set<string>} [seen]+ */+function moduleExportsName(file, exportName, seen = new Set()) {+ const identity = `${file}\0${exportName}`;+ if (seen.has(identity) || !fs.existsSync(file)) return false;+ seen.add(identity);++ let root;+ try {+ root = moduleParser(fs.readFileSync(file, 'utf-8'));+ } catch {+ return false;+ }++ let found = false;+ root+ .find(moduleParser.ExportNamedDeclaration)+ .forEach((/** @type {any} */ exportPath) => {+ if (found) return;+ const node = exportPath.node;+ if (declarationExports(node.declaration, exportName)) {+ found = true;+ return;+ }+ for (const specifier of node.specifiers ?? []) {+ const exported = specifier.exported?.name ?? specifier.exported?.value;+ if (exported !== exportName) continue;+ if (!node.source) {+ found = true;+ return;+ }+ const target = resolveLocalModule(node.source.value, file);+ const imported =+ specifier.local?.name ?? specifier.local?.value ?? exportName;+ if (target && moduleExportsName(target, imported, seen)) {+ found = true;+ return;+ }+ }+ });+ if (found) return true;+ if (+ exportName === 'default' &&+ root.find(moduleParser.ExportDefaultDeclaration).size() > 0+ ) {+ return true;+ }++ root+ .find(moduleParser.ExportAllDeclaration)+ .forEach((/** @type {any} */ exportPath) => {+ if (found) return;+ const target = resolveLocalModule(exportPath.node.source?.value, file);+ if (target && moduleExportsName(target, exportName, seen)) found = true;+ });+ return found;+}++/**+ * Resolve package specifiers through Node's real ESM resolver from the scratch+ * consumer. Resolution does not execute the target module, so source `.tsx`+ * exports and built `.mjs` exports are both safe to inspect.+ *+ * @param {string[]} specifiers+ * @param {string} scratchBase+ * @returns {Map<string, {url?: string, error?: string}>}+ */+function resolveConsumerSpecifiers(specifiers, scratchBase) {+ const resolver = path.join(scratchBase, '.astryx-resolve-imports.mjs');+ const source = `const specs = JSON.parse(process.argv[2]);\nconst out = {};\nfor (const specifier of specs) {\n try { out[specifier] = {url: import.meta.resolve(specifier)}; }\n catch (error) { out[specifier] = {error: error instanceof Error ? error.message : String(error)}; }\n}\nconsole.log(JSON.stringify(out));\n`;+ fs.writeFileSync(resolver, source, {flag: 'wx'});+ try {+ const result = spawnSync(+ process.execPath,+ [resolver, JSON.stringify([...new Set(specifiers)])],+ {cwd: scratchBase, encoding: 'utf-8', timeout: 30_000},+ );+ if (result.error || result.status !== 0) {+ const message = result.error?.message ?? result.stderr.trim();+ return new Map(+ specifiers.map(specifier => [+ specifier,+ {error: message || `resolver exited ${result.status}`},+ ]),+ );+ }+ const parsed = JSON.parse(result.stdout);+ return new Map(+ /** @type {Array<[string, {url?: string, error?: string}]>} */ (+ Object.entries(parsed)+ ),+ );+ } finally {+ fs.rmSync(resolver, {force: true});+ }+}++/**+ * Verify that every packed component is reachable through the exact import+ * specifier the component API gives consumers, and that the resolved module+ * statically exports the component name.+ *+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} integration+ * @param {string} scratchBase+ * @returns {Promise<Issue[]>}+ */+async function validatePackedComponentExports(integration, scratchBase) {+ const records = discoverIntegrationComponents(integration);+ /** @type {Array<{name: string, specifier: string}>} */+ const components = [];+ for (const record of records) {+ let docs;+ try {+ docs = await loadComponentDoc(record.docPath);+ } catch {+ continue;+ }+ const specifier =+ /** @type {{import?: string}} */ (docs).import ??+ resolveIntegrationImportPath(+ {+ exportsMap: integration.__packageExports,+ packageDir: integration.__packageDir,+ docPath: record.docPath,+ packageName: integration.name,+ },+ record.name,+ );+ components.push({name: record.name, specifier});+ }++ const resolved = resolveConsumerSpecifiers(+ components.map(component => component.specifier),+ scratchBase,+ );+ /** @type {Issue[]} */+ const issues = [];+ for (const {name, specifier} of components) {+ const result = resolved.get(specifier);+ if (!result?.url || result.error) {+ issues.push(+ error(+ 'component_import_unresolvable',+ `Component "${name}" advertises import "${specifier}", but a consumer cannot resolve it${result?.error ? `: ${result.error}` : '.'}`,+ ),+ );+ continue;+ }+ let target;+ try {+ target = fileURLToPath(result.url);+ } catch {+ target = null;+ }+ if (!target || !moduleExportsName(target, name)) {+ issues.push(+ error(+ 'component_export_missing',+ `Component "${name}" advertises import "${specifier}", but that packed module does not export "${name}". Add or correct the package export before publishing.`,+ ),+ );+ }+ }+ return issues;+}++/**+ * Verify that every packed template source can be imported through its exact+ * package subpath and still has a default export.+ *+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} integration+ * @param {string} scratchBase+ * @returns {Promise<Issue[]>}+ */+async function validatePackedTemplateExports(integration, scratchBase) {+ const {templates} = await discoverIntegrationTemplatesForOne(integration);+ const entries = templates.map(template => ({+ id: template.dirName,+ specifier: `${integration.name}/${path+ .relative(integration.__packageDir, template.filePath)+ .split(path.sep)+ .join('/')}`,+ }));+ const resolved = resolveConsumerSpecifiers(+ entries.map(entry => entry.specifier),+ scratchBase,+ );+ /** @type {Issue[]} */+ const issues = [];+ for (const {id, specifier} of entries) {+ const result = resolved.get(specifier);+ if (!result?.url || result.error) {+ issues.push(+ error(+ 'template_import_unresolvable',+ `Template "${id}" source is packed but its public import "${specifier}" cannot be resolved${result?.error ? `: ${result.error}` : '.'}`,+ ),+ );+ continue;+ }+ let target;+ try {+ target = fileURLToPath(result.url);+ } catch {+ target = null;+ }+ if (!target || !moduleExportsName(target, 'default')) {+ issues.push(+ error(+ 'template_export_missing',+ `Template "${id}" public import "${specifier}" does not have a default export.`,+ ),+ );+ }+ }+ return issues;+}++/**+ * Verify an integration package is ready to publish.+ *+ * Validates the local structure, cross-references every declared contribution+ * file against the real `npm pack` file list, extracts the tarball into a+ * scratch consumer, and compares local vs packed discovery results exactly.+ *+ * @param {import('./pack-check.type.mjs').IntegrationPackCheckOptions} [options]+ * @returns {Promise<import('./pack-check.type.mjs').IntegrationPackCheckResponse>}+ */+export async function integrationPackCheck(options = {}) {+ const {cwd = process.cwd()} = options;++ // ── Locate the package ──+ let found;+ try {+ found = findPackage(cwd);+ } catch (err) {+ return emptyReceipt(null, [+ error(+ 'invalid_package_json',+ err instanceof Error ? err.message : String(err),+ ),+ ]);+ }+ if (!found) {+ return emptyReceipt(null, [+ error(+ 'no_package',+ 'No package.json found. Run this command inside an integration package.',+ ),+ ]);+ }+ const {packageDir, pkg} = found;+ const pkgName = typeof pkg.name === 'string' ? pkg.name : '(unnamed package)';+ const pkgVersion = typeof pkg.version === 'string' ? pkg.version : null;++ // ── Phase 1: structure validation ──+ const localResult = await validateLocalIntegration(cwd);+ /** @type {Issue[]} */+ const issues = [...localResult.issues];++ if (!localResult.found || !localResult.integration) {+ return emptyReceipt(pkgName, [+ ...issues,+ ...(localResult.found+ ? []+ : [+ error(+ 'missing_manifest',+ 'No astryx.integration.{ts,mjs,js} found next to package.json.',+ ),+ ]),+ ]);+ }++ const loaded = localResult.integration;++ // ── Phase 2: file inventory + npm pack ──+ const fileInv = computeRequiredFiles(loaded);+ const {identities: localIdentities, errors: localDiscoveryErrors} =+ await collectIdentities(loaded);+ for (const discoveryError of localDiscoveryErrors) {+ issues.push(+ error(+ 'local_discovery_failed',+ `${discoveryError.kind}: ${discoveryError.message}`,+ ),+ );+ }+ for (const root of fileInv.roots) {+ if (root.files.length === 0) {+ issues.push(+ error(+ 'empty_contribution_root',+ `Declared ${root.kind} root "${root.path}" contains no discoverable contribution files.`,+ ),+ );+ }+ }++ // Temp resources — always cleaned up+ const tgzTmpDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-pack-check-'),+ );+ /** @type {string|null} */+ let scratchBase = null;++ try {+ // npm pack+ /** @type {ReturnType<typeof runNpmPack>} */+ let packResult;+ try {+ packResult = runNpmPack(packageDir, tgzTmpDir);+ } catch (err) {+ issues.push(error('pack_failed', /** @type {Error} */ (err).message));+ return buildReceipt(+ pkgName,+ pkgVersion,+ fileInv,+ null,+ localIdentities,+ null,+ issues,+ );+ }++ // Create the repo-local consumer AFTER packing, so it cannot enter the+ // tarball. Keeping it beside the package lets packed metadata resolve the+ // package's already-installed dependencies. The unique suffix makes+ // concurrent checks independent.+ scratchBase = fs.mkdtempSync(path.join(packageDir, '.astryx-pack-check-'));++ // Cross-reference file inventory vs pack list+ if (!packResult.packedPaths.has(fileInv.manifest)) {+ issues.push(+ error(+ 'manifest_not_packed',+ `Integration manifest "${fileInv.manifest}" is not in the npm pack list. ` ++ 'Add it to "files" in package.json.',+ ),+ );+ }++ for (const root of fileInv.roots) {+ const missing = root.files.filter(f => !packResult.packedPaths.has(f));+ if (missing.length === root.files.length && root.files.length > 0) {+ issues.push(+ error(+ 'root_not_packed',+ `Declared ${root.kind} root "${root.path}" has 0 of ${root.files.length} expected ` ++ `files in the pack list. Add "${root.path.replace(/^\.\//, '')}" to "files" in package.json.`,+ ),+ );+ } else {+ for (const file of missing) {+ issues.push(+ error(+ 'file_not_packed',+ `${root.kind} file "${file}" is not in the pack list.`,+ ),+ );+ }+ }+ }++ let tgzPath;+ try {+ tgzPath = assertWithin(packResult.filename, tgzTmpDir, {+ label: 'npm pack filename',+ });+ } catch (err) {+ issues.push(+ error(+ 'invalid_pack_result',+ err instanceof Error ? err.message : String(err),+ ),+ );+ return buildReceipt(+ pkgName,+ pkgVersion,+ fileInv,+ packResult,+ localIdentities,+ null,+ issues,+ );+ }++ // ── Phase 3: extract + identity comparison ──+ let extractDir;+ try {+ extractDir = resolvePackageDir(pkgName, scratchBase);+ } catch (err) {+ issues.push(+ error(+ 'invalid_package_name',+ err instanceof Error ? err.message : String(err),+ ),+ );+ return buildReceipt(+ pkgName,+ pkgVersion,+ fileInv,+ packResult,+ localIdentities,+ null,+ issues,+ );+ }+ try {+ extractTarball(tgzPath, extractDir);+ } catch (err) {+ issues.push(error('extract_failed', /** @type {Error} */ (err).message));+ return buildReceipt(+ pkgName,+ pkgVersion,+ fileInv,+ packResult,+ localIdentities,+ null,+ issues,+ );+ }++ // Validate the extracted tree as an installed integration+ const packedResult = await validateInstalledIntegration(+ pkgName,+ scratchBase,+ );++ for (const issue of packedResult.issues) {+ issues.push({+ code: `packed_${issue.code}`,+ severity: issue.severity,+ message: `Packed: ${issue.message}`,+ });+ }++ if (!packedResult.integration) {+ return buildReceipt(+ pkgName,+ pkgVersion,+ fileInv,+ packResult,+ localIdentities,+ null,+ issues,+ );+ }++ // Collect packed identities and compare+ const {identities: packedIdentities, errors: discoveryErrors} =+ await collectIdentities(packedResult.integration);++ for (const de of discoveryErrors) {+ issues.push(+ error('packed_discovery_failed', `${de.kind}: ${de.message}`),+ );+ }++ issues.push(...compareIdentities(localIdentities, packedIdentities));+ issues.push(+ ...(await validatePackedComponentExports(+ packedResult.integration,+ scratchBase,+ )),+ ...(await validatePackedTemplateExports(+ packedResult.integration,+ scratchBase,+ )),+ );++ return buildReceipt(+ pkgName,+ pkgVersion,+ fileInv,+ packResult,+ localIdentities,+ packedIdentities,+ issues,+ );+ } finally {+ removeTreeBestEffort(tgzTmpDir, 'temporary tarball directory', issues);+ removeTreeBestEffort(scratchBase, 'scratch consumer', issues);+ }+}++/**+ * Assemble the receipt.+ * @param {string} name+ * @param {string|null} version+ * @param {import('../../foundation/integrations/contribution-inventory.mjs').FileInventory} fileInv+ * @param {ReturnType<typeof runNpmPack>|null} packResult+ * @param {import('../../foundation/integrations/contribution-inventory.mjs').ContributionIdentities|null} localIdentities+ * @param {import('../../foundation/integrations/contribution-inventory.mjs').ContributionIdentities|null} packedIdentities+ * @param {Issue[]} issues+ * @returns {import('./pack-check.type.mjs').IntegrationPackCheckResponse}+ */+function buildReceipt(+ name,+ version,+ fileInv,+ packResult,+ localIdentities,+ packedIdentities,+ issues,+) {+ const packedPaths = packResult?.packedPaths ?? new Set();++ /** @type {import('./pack-check.type.mjs').PackCheckInventoryRoot[]} */+ const roots = fileInv.roots.map(root => {+ const missing = root.files.filter(f => !packedPaths.has(f));+ return {+ kind: root.kind,+ path: root.path,+ expectedFiles: root.files.length,+ missingFiles: missing,+ complete: missing.length === 0,+ };+ });++ const expectedFiles = fileInv.allFiles.length;+ const packedFiles = fileInv.allFiles.filter(f => packedPaths.has(f)).length;++ return {+ type: 'integration.pack-check',+ data: {+ name,+ version,+ packable: !issues.some(i => i.severity === 'error'),+ tarball: packResult+ ? {+ filename: packResult.filename,+ fileCount: packResult.fileCount,+ size: packResult.size,+ unpackedSize: packResult.unpackedSize,+ }+ : null,+ inventory: {+ manifest: fileInv.manifest,+ roots,+ expectedFiles,+ packedFiles,+ },+ contributions: {local: localIdentities, packed: packedIdentities},+ issues,+ },+ };+}diff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjsnew file mode 100644index 0000000000..b6aabd8bea--- /dev/null+++ b/packages/cli/api/integration/pack-check.test.mjs@@ -0,0 +1,569 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {spawnSync} from 'node:child_process';+import {integrationPackCheck, parseNpmPackOutput} from './pack-check.mjs';+import {+ integrationAddComponent,+ integrationAddTemplate,+} from './add-contribution.mjs';++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-pack-check-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/**+ * Write a minimal integration package into tmpDir.+ * Returns the package directory.+ */+function writePackage({+ name = '@acme/widgets',+ version = '1.0.0',+ files,+ manifest = "export default {themes: './themes'};\n",+ themes = true,+ npmignore,+ components = false,+ scripts,+} = {}) {+ const pkg = {name, version};+ if (files !== undefined) pkg.files = files;+ if (scripts !== undefined) pkg.scripts = scripts;+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify(pkg, null, 2) + '\n',+ );+ if (manifest != null) {+ fs.writeFileSync(path.join(tmpDir, 'astryx.integration.mjs'), manifest);+ }+ if (themes) {+ const root = path.join(tmpDir, 'themes');+ fs.mkdirSync(path.join(root, 'ocean'), {recursive: true});+ fs.writeFileSync(+ path.join(root, 'ocean', 'oceanTheme.ts'),+ "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',+ );+ }+ if (components) {+ const root = path.join(tmpDir, 'components');+ fs.mkdirSync(root, {recursive: true});+ fs.writeFileSync(+ path.join(root, 'Card.tsx'),+ 'export default function Card() { return null; }\n',+ );+ }+ if (npmignore) {+ fs.writeFileSync(path.join(tmpDir, '.npmignore'), npmignore);+ }+ return tmpDir;+}++describe('integrationPackCheck', () => {+ it('returns packable:true for a valid integration with themes', async () => {+ writePackage({files: ['astryx.integration.mjs', 'themes']});+ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.type).toBe('integration.pack-check');+ expect(result.data.packable).toBe(true);+ expect(result.data.name).toBe('@acme/widgets');+ expect(result.data.tarball).not.toBeNull();+ expect(result.data.inventory.manifest).toBe('astryx.integration.mjs');+ expect(result.data.contributions.local?.themes).toEqual([+ {slug: 'ocean', exportName: 'oceanTheme'},+ ]);+ expect(result.data.contributions.packed).toEqual(+ result.data.contributions.local,+ );+ expect(result.data.issues.filter(i => i.severity === 'error')).toHaveLength(+ 0,+ );+ });++ it('fails when a theme entry omits its catalog export', async () => {+ writePackage({files: ['astryx.integration.mjs', 'themes']});+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),+ 'export const anotherTheme = {};\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'invalid_theme',+ message: expect.stringContaining(+ 'entry "oceanTheme.ts" does not export "oceanTheme"',+ ),+ }),+ );+ });++ it('fails when a theme imports a file omitted from its catalog', 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});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'invalid_theme',+ message: expect.stringContaining(+ 'must resolve to a listed file inside the theme directory',+ ),+ }),+ );+ });++ it('fails when a discovered component is not exported to consumers', async () => {+ writePackage({+ manifest: "export default {components: './components'};\n",+ files: ['astryx.integration.mjs', 'components', 'index.mjs'],+ themes: false,+ });+ const pkgFile = path.join(tmpDir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));+ pkg.exports = {'.': './index.mjs'};+ fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);+ fs.writeFileSync(+ path.join(tmpDir, 'index.mjs'),+ 'export const existing = 1;\n',+ );+ fs.mkdirSync(path.join(tmpDir, 'components'));+ fs.writeFileSync(+ path.join(tmpDir, 'components', 'AcmeWidget.doc.mjs'),+ "export default {type: 'component', name: 'AcmeWidget', description: 'Widget.', props: []};\n",+ );+ fs.writeFileSync(+ path.join(tmpDir, 'components', 'AcmeWidget.tsx'),+ 'export function AcmeWidget() { return null; }\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'component_export_missing',+ message: expect.stringContaining('AcmeWidget'),+ }),+ );+ });++ it('passes a generated component through its exact packed export', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify({+ name: '@acme/widgets',+ version: '1.0.0',+ files: ['index.mjs'],+ exports: {'.': './index.mjs'},+ })}\n`,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'index.mjs'),+ 'export const existing = 1;\n',+ );+ await integrationAddComponent('AcmeWidget', {cwd: tmpDir});++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues).not.toContainEqual(+ expect.objectContaining({code: 'component_export_missing'}),+ );+ });++ it('fails when packed template source is hidden by package exports', async () => {+ writePackage({+ manifest: "export default {templates: './templates'};\n",+ files: ['astryx.integration.mjs', 'templates', 'index.mjs'],+ themes: false,+ });+ const pkgFile = path.join(tmpDir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));+ pkg.exports = {'.': './index.mjs'};+ fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);+ fs.writeFileSync(+ path.join(tmpDir, 'index.mjs'),+ 'export const existing = 1;\n',+ );+ fs.mkdirSync(path.join(tmpDir, 'templates'));+ fs.writeFileSync(+ path.join(tmpDir, 'templates', 'account-page.template.mjs'),+ "export default {type: 'page', name: 'Account page', description: 'Account page.'};\n",+ );+ fs.writeFileSync(+ path.join(tmpDir, 'templates', 'account-page.tsx'),+ 'export default function AccountPage() { return null; }\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'template_import_unresolvable',+ message: expect.stringContaining('account-page'),+ }),+ );+ });++ it('passes generated component and template source through exact packed exports', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify({+ name: '@acme/widgets',+ version: '1.0.0',+ files: ['index.mjs'],+ exports: {'.': './index.mjs'},+ })}\n`,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'index.mjs'),+ 'export const existing = 1;\n',+ );+ await integrationAddComponent('AcmeWidget', {cwd: tmpDir});+ await integrationAddTemplate('account-page', {cwd: tmpDir, type: 'page'});++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues).not.toContainEqual(+ expect.objectContaining({code: 'component_export_missing'}),+ );+ expect(result.data.issues).not.toContainEqual(+ expect.objectContaining({code: 'template_import_unresolvable'}),+ );+ });++ it('errors when a root directory is excluded from files[]', async () => {+ // Include manifest but NOT themes+ writePackage({files: ['astryx.integration.mjs']});+ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ const rootError = result.data.issues.find(+ i => i.code === 'root_not_packed',+ );+ expect(rootError).toBeDefined();+ expect(rootError.message).toContain('themes');+ });++ it('errors when .npmignore excludes a contribution', async () => {+ writePackage({npmignore: 'themes/\n'});+ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ const fileErrors = result.data.issues.filter(+ i => i.code === 'root_not_packed' || i.code === 'file_not_packed',+ );+ expect(fileErrors.length).toBeGreaterThan(0);+ });++ it('passes when package.json has no files field', async () => {+ writePackage({files: undefined});+ const result = await integrationPackCheck({cwd: tmpDir});++ // No files field → npm includes everything+ expect(result.data.packable).toBe(true);+ });++ it('detects a lifecycle script that changes the packed identity', async () => {+ 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))',+ ].join(';');+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ scripts: {prepack: `node -e "${script}"`},+ });++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(+ result.data.issues.find(issue => issue.code === 'identity_not_packed')+ ?.message,+ ).toContain('ocean');+ expect(+ result.data.issues.find(+ issue => issue.code === 'packed_identity_unexpected',+ )?.message,+ ).toContain('storm');+ });++ it('rejects a declared root with no contribution files', async () => {+ writePackage({+ manifest: "export default {docs: './docs'};\n",+ files: ['astryx.integration.mjs', 'docs'],+ themes: false,+ });+ fs.mkdirSync(path.join(tmpDir, 'docs'));++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(+ result.data.issues.some(+ issue => issue.code === 'empty_contribution_root',+ ),+ ).toBe(true);+ });++ it('handles scoped package extraction correctly', async () => {+ writePackage({+ name: '@my-org/deep-integration',+ files: ['astryx.integration.mjs', 'themes'],+ });+ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.name).toBe('@my-org/deep-integration');+ expect(result.data.packable).toBe(true);+ });++ it('reports source-only component candidates as warnings', async () => {+ writePackage({+ manifest:+ "export default {themes: './themes', components: './components'};\n",+ files: ['astryx.integration.mjs', 'themes', 'components'],+ components: true,+ });+ const result = await integrationPackCheck({cwd: tmpDir});++ const sourceWarnings = result.data.issues.filter(+ issue => issue.code === 'source_without_component_doc',+ );+ // Card.tsx is PascalCase but has no doc metadata → warning+ expect(sourceWarnings.length).toBeGreaterThanOrEqual(1);+ expect(sourceWarnings[0].severity).toBe('warning');+ expect(sourceWarnings[0].message).toContain('Card.tsx');+ });++ it('cleans up its scratch consumer when npm pack fails', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ scripts: {prepack: 'node -e "process.exit(17)"'},+ });++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues.some(issue => issue.code === 'pack_failed')).toBe(+ true,+ );+ expect(+ fs+ .readdirSync(tmpDir)+ .filter(name => name.startsWith('.astryx-pack-check-')),+ ).toEqual([]);+ });++ it('cleans up its scratch consumer after a successful check', async () => {+ writePackage({files: ['astryx.integration.mjs', 'themes']});++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(+ fs+ .readdirSync(tmpDir)+ .filter(name => name.startsWith('.astryx-pack-check-')),+ ).toEqual([]);+ });++ it('rejects malformed npm pack output without a raw TypeError', () => {+ expect(() =>+ parseNpmPackOutput(+ JSON.stringify([+ {filename: 'pkg.tgz', entryCount: 1, size: 1, unpackedSize: 1},+ ]),+ ),+ ).toThrow(/without a files array/);+ });++ it('reports npm missing from PATH as pack_failed', async () => {+ writePackage({files: ['astryx.integration.mjs', 'themes']});+ const originalPath = process.env.PATH;+ process.env.PATH = '';+ try {+ const result = await integrationPackCheck({cwd: tmpDir});+ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'pack_failed',+ message: expect.stringContaining('Could not start npm pack'),+ }),+ );+ } finally {+ process.env.PATH = originalPath;+ }+ });++ it('does not execute shell metacharacters embedded in the cwd', async () => {+ const marker = path.join(process.cwd(), 'astryx-pack-check-injected');+ fs.rmSync(marker, {force: true});+ const weirdDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-;touch astryx-pack-check-injected;#-'),+ );+ try {+ const pkg = {name: 'safe-pkg', version: '1.0.0'};+ fs.writeFileSync(+ path.join(weirdDir, 'package.json'),+ JSON.stringify(pkg),+ );+ fs.writeFileSync(+ path.join(weirdDir, 'astryx.integration.mjs'),+ 'export default {};\n',+ );+ const result = await integrationPackCheck({cwd: weirdDir});+ expect(result.type).toBe('integration.pack-check');+ expect(fs.existsSync(marker)).toBe(false);+ } finally {+ fs.rmSync(weirdDir, {recursive: true, force: true});+ fs.rmSync(marker, {force: true});+ }+ });++ it('returns early with issues for a directory without package.json', async () => {+ const emptyDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-pack-check-empty-'),+ );+ try {+ const result = await integrationPackCheck({cwd: emptyDir});+ expect(result.data.packable).toBe(false);+ expect(result.data.issues.some(i => i.code === 'no_package')).toBe(true);+ } finally {+ fs.rmSync(emptyDir, {recursive: true, force: true});+ }+ });++ it('reports malformed package.json instead of treating it as missing', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{bad-json');+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'export default {};\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({code: 'invalid_package_json'}),+ );+ });++ it('returns early with issues for a package without a manifest', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ '{"name":"bare-pkg","version":"1.0.0"}\n',+ );+ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues.some(i => i.code === 'missing_manifest')).toBe(+ true,+ );+ });+});++describe('pack-check mutation tests', () => {+ it('detects when a theme file is deleted after initial add', 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)++ const result = await integrationPackCheck({cwd: tmpDir});+ expect(result.data.packable).toBe(false);+ });++ it('detects when files[] is narrowed after add removes themes', async () => {+ // First: valid package+ writePackage({files: ['astryx.integration.mjs', 'themes']});++ // Narrow files to exclude themes+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ pkg.files = ['astryx.integration.mjs'];+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify(pkg, null, 2) + '\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});+ expect(result.data.packable).toBe(false);+ expect(result.data.issues.some(i => i.code === 'root_not_packed')).toBe(+ true,+ );+ });++ it('correctly counts packed vs expected files in inventory', async () => {+ writePackage({files: ['astryx.integration.mjs', 'themes']});+ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.inventory.expectedFiles).toBeGreaterThan(0);+ expect(result.data.inventory.packedFiles).toBe(+ result.data.inventory.expectedFiles,+ );+ for (const root of result.data.inventory.roots) {+ expect(root.complete).toBe(true);+ expect(root.missingFiles).toEqual([]);+ }+ });+});diff --git a/packages/cli/api/integration/pack-check.type.mjs b/packages/cli/api/integration/pack-check.type.mjsnew file mode 100644index 0000000000..473f3ede4b--- /dev/null+++ b/packages/cli/api/integration/pack-check.type.mjs@@ -0,0 +1,56 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated types for `astryx integration pack --check`.+ */++/**+ * @typedef {object} IntegrationPackCheckOptions+ * @property {string} [cwd]+ */++/**+ * @typedef {object} IntegrationPackCheckResponse+ * @property {'integration.pack-check'} type+ * @property {PackCheckData} data+ */++/** @typedef {IntegrationPackCheckResponse} PackCheckResponse */++/**+ * @typedef {object} PackCheckData+ * @property {string|null} name+ * @property {string|null} version+ * @property {boolean} packable — true when zero error-severity issues+ * @property {PackCheckTarball|null} tarball+ * @property {PackCheckInventory} inventory+ * @property {{local: import('../../foundation/integrations/contribution-inventory.mjs').ContributionIdentities|null, packed: import('../../foundation/integrations/contribution-inventory.mjs').ContributionIdentities|null}} contributions+ * @property {import('../../foundation/integrations/issue').AstryxIntegrationIssue[]} issues+ */++/**+ * @typedef {object} PackCheckTarball+ * @property {string} filename+ * @property {number} fileCount+ * @property {number} size+ * @property {number} unpackedSize+ */++/**+ * @typedef {object} PackCheckInventory+ * @property {string|null} manifest+ * @property {PackCheckInventoryRoot[]} roots+ * @property {number} expectedFiles+ * @property {number} packedFiles+ */++/**+ * @typedef {object} PackCheckInventoryRoot+ * @property {'themes'|'components'|'templates'|'codemods'|'docs'} kind+ * @property {string} path+ * @property {number} expectedFiles+ * @property {string[]} missingFiles+ * @property {boolean} complete+ */++export {};diff --git a/packages/cli/api/integration/public-api.test.mjs b/packages/cli/api/integration/public-api.test.mjsnew file mode 100644index 0000000000..c028e2f660--- /dev/null+++ b/packages/cli/api/integration/public-api.test.mjs@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import * as api from '../index.mjs';++describe('integration authoring public API', () => {+ it('exports the generic dispatcher, every per-kind writer, and pack-check', () => {+ for (const name of [+ 'integrationAdd',+ 'integrationAddComponent',+ 'integrationAddDoc',+ 'integrationAddTemplate',+ 'integrationAddCodemod',+ 'integrationAddAgentDoc',+ 'integrationAddTheme',+ 'integrationPackCheck',+ ]) {+ expect(api[name], name).toBeTypeOf('function');+ }+ });+});diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex e1f1a3675f..5a747cf9f0 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -33,6 +33,7 @@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 {findManifestPaths,@@ -44,6 +45,7 @@ import {import {validateLoadedIntegration,issueError as error,+ issueWarning as warning,} from '../../foundation/integrations/validate-contributions.mjs';export {validateLoadedIntegration};@@ -78,14 +80,200 @@ function findNearestPackageJson(cwd) {}}+const UNREACHABLE_SCAN_LIMIT = 5_000;+const UNREACHABLE_SKIP_DIRS = new Set([+ 'node_modules',+ '.git',+ 'dist',+ 'build',+ 'coverage',+ '.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+ */+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;+ }+ }+ return false;+}++/** @param {string} candidate @param {string} root */+function pathIsInside(candidate, root) {+ return candidate === root || candidate.startsWith(`${root}${path.sep}`);+}++/**+ * Find real contribution metadata that sits outside every declared root. The+ * scan is local-authoring-only, skips dependency/build output, never follows+ * symlinks, and parses candidates before reporting them so ordinary JS files do+ * not become noise.+ *+ * @param {string} packageDir+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} loaded+ * @returns {Promise<Issue[]>}+ */+async function findUnreachableContributionIssues(packageDir, loaded) {+ const roots = /** @type {string[]} */ (+ [+ loaded.components,+ loaded.templates,+ loaded.codemods,+ loaded.docs,+ loaded.themes,+ ].filter(Boolean)+ );+ /** @type {Issue[]} */+ const issues = [];+ let scanned = 0;+ let truncated = false;++ /** @param {string} dir */+ async function walk(dir) {+ if (roots.some(root => pathIsInside(dir, root))) return;+ const entries = fs+ .readdirSync(dir, {withFileTypes: true})+ .sort((a, b) => a.name.localeCompare(b.name));+ for (const entry of entries) {+ if (truncated) return;+ if (UNREACHABLE_SKIP_DIRS.has(entry.name)) continue;+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ await walk(full);+ continue;+ }+ if (!entry.isFile()) continue;+ scanned += 1;+ if (scanned > UNREACHABLE_SCAN_LIMIT) {+ 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;+ 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.`,+ ),+ );+ }+ }++ await walk(packageDir);+ if (truncated) {+ issues.push(+ warning(+ 'unreachable_scan_truncated',+ `Stopped unreachable-contribution scanning after ${UNREACHABLE_SCAN_LIMIT} files. Narrow the package or move generated output under dist/build.`,+ ),+ );+ }+ return issues;+}+/*** Validate a single integration given its package directory and identity.* Shared core for the local and installed entry points.* @param {string} packageDir* @param {{name: string, version?: string}} identity+ * @param {{scanUnreachable?: boolean}} [options]* @returns {Promise<ValidateResult>}*/-async function validateAtPackageDir(packageDir, identity) {+async function validateAtPackageDir(+ packageDir,+ identity,+ {scanUnreachable = false} = {},+) {/** @type {Issue[]} */const issues = [];/** @type {ValidateResult} */@@ -164,6 +352,7 @@ async function validateAtPackageDir(packageDir, identity) {templates: resolveRoot(manifest.templates),codemods: resolveRoot(manifest.codemods),docs: resolveRoot(manifest.docs),+ themes: resolveRoot(manifest.themes),issuesUrl: manifest.issuesUrl,agentDocs: manifest.agentDocs,__agentDocsError: agentDocsError,@@ -177,6 +366,11 @@ async function validateAtPackageDir(packageDir, identity) {// Roots + contribution checks are shared with validateLoadedIntegration so// the everyday-command nudge runs the exact same validators.issues.push(...(await validateLoadedIntegration(loaded)));+ if (scanUnreachable) {+ issues.push(+ ...(await findUnreachableContributionIssues(packageDir, loaded)),+ );+ }return result;}@@ -202,17 +396,30 @@ export async function validateLocalIntegration(cwd = process.cwd()) {}/** @type {{name?: string, version?: string}} */- let pkg = {};+ let pkg;try {pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));- } catch {- // Identity falls back to undefined; the manifest checks still run.+ } catch (err) {+ return {+ found: true,+ manifestFile: manifests[0],+ issues: [+ error(+ 'invalid_package_json',+ `Could not parse ${pkgJsonPath}: ${err instanceof Error ? err.message : String(err)}`,+ ),+ ],+ };}- return validateAtPackageDir(packageDir, {- name: pkg.name ?? '(local package)',- version: pkg.version,- });+ return validateAtPackageDir(+ packageDir,+ {+ name: pkg.name ?? '(local package)',+ version: pkg.version,+ },+ {scanUnreachable: true},+ );}/**@@ -244,15 +451,18 @@ export async function validateInstalledIntegration(spec, cwd = process.cwd()) {let pkg;try {pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));- } catch {+ } catch (err) {+ const exists = fs.existsSync(pkgJsonPath);return {found: true,name: spec,version: undefined,issues: [error(- 'package_not_found',- `Could not find installed integration package "${spec}" at ${pkgJsonPath}. Install it first.`,+ exists ? 'invalid_package_json' : 'package_not_found',+ exists+ ? `Could not parse ${pkgJsonPath}: ${err instanceof Error ? err.message : String(err)}`+ : `Could not find installed integration package "${spec}" at ${pkgJsonPath}. Install it first.`,),],};diff --git a/packages/cli/api/integration/validate-integration.test.mjs b/packages/cli/api/integration/validate-integration.test.mjsindex a9ac92faa5..cc09f8997f 100644--- a/packages/cli/api/integration/validate-integration.test.mjs+++ b/packages/cli/api/integration/validate-integration.test.mjs@@ -33,13 +33,19 @@ afterEach(() => {* @param {string} dir* @param {{name?: string, version?: string, manifest: string, manifestExt?: string}} opts*/-function writePackage(dir, {name = '@acme/widgets', version = '1.0.0', manifest, manifestExt = 'mjs'}) {+function writePackage(+ dir,+ {name = '@acme/widgets', version = '1.0.0', manifest, manifestExt = 'mjs'},+) {fs.mkdirSync(dir, {recursive: true});fs.writeFileSync(path.join(dir, 'package.json'),JSON.stringify({name, version}),);- fs.writeFileSync(path.join(dir, `astryx.integration.${manifestExt}`), manifest);+ fs.writeFileSync(+ path.join(dir, `astryx.integration.${manifestExt}`),+ manifest,+ );}/** Find issues by code. */@@ -116,7 +122,10 @@ describe('validate-integration API', () => {it('flags multiple manifests as multiple_manifests error', async () => {const pkgDir = path.join(tmpDir, 'pkg');writePackage(pkgDir, {manifest: `export default {};\n`});- fs.writeFileSync(path.join(pkgDir, 'astryx.integration.js'), 'export default {};\n');+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.js'),+ 'export default {};\n',+ );const result = await validateLocalIntegration(pkgDir);expect(byCode(result.issues, 'multiple_manifests')).toHaveLength(1);});@@ -169,7 +178,10 @@ describe('validate-integration API', () => {const cmDir = path.join(pkgDir, 'codemods', '0.2.0');fs.mkdirSync(cmDir, {recursive: true});// Missing default export → discovery throws → invalid_codemod.- fs.writeFileSync(path.join(cmDir, 'broken.mjs'), `export const nope = 1;\n`);+ fs.writeFileSync(+ path.join(cmDir, 'broken.mjs'),+ `export const nope = 1;\n`,+ );const result = await validateLocalIntegration(pkgDir);expect(byCode(result.issues, 'invalid_codemod')).toHaveLength(1);@@ -192,6 +204,157 @@ describe('validate-integration API', () => {expect(byCode(result.issues, 'invalid_template')).toHaveLength(1);});+ it('reports no errors for a valid source-theme catalog', async () => {+ const pkgDir = path.join(tmpDir, 'pkg');+ writePackage(pkgDir, {+ manifest: `export default { themes: './themes' };\n`,+ });+ 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'],+ },+ ],+ }),+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.ts'),+ `export const oceanTheme = {};\n`,+ );++ const result = await validateLocalIntegration(pkgDir);+ expect(byCode(result.issues, 'invalid_theme')).toHaveLength(0);+ expect(summarizeIssues(result.issues).errors).toBe(0);+ });++ it('flags an unreadable source-theme catalog as invalid_theme', async () => {+ const pkgDir = path.join(tmpDir, 'pkg');+ writePackage(pkgDir, {+ manifest: `export default { themes: './themes' };\n`,+ });+ fs.mkdirSync(path.join(pkgDir, 'themes'), {recursive: true});+ fs.writeFileSync(path.join(pkgDir, 'themes', 'manifest.json'), '{not-json');++ const result = await validateLocalIntegration(pkgDir);+ expect(byCode(result.issues, 'invalid_theme')).toHaveLength(1);+ });++ it('warns when a component source has no same-stem metadata', async () => {+ const pkgDir = path.join(tmpDir, 'pkg');+ writePackage(pkgDir, {+ manifest: `export default { components: './components' };\n`,+ });+ fs.mkdirSync(path.join(pkgDir, 'components'));+ fs.writeFileSync(+ path.join(pkgDir, 'components', 'InvisibleWidget.tsx'),+ 'export function InvisibleWidget() { return null; }\n',+ );++ const result = await validateLocalIntegration(pkgDir);++ expect(byCode(result.issues, 'source_without_component_doc')).toEqual([+ expect.objectContaining({+ severity: 'warning',+ message: expect.stringContaining('InvisibleWidget.doc.mjs'),+ }),+ ]);+ });++ it('reports codemods outside semver folders and invalid folder names', async () => {+ const pkgDir = path.join(tmpDir, 'pkg');+ writePackage(pkgDir, {+ manifest: `export default { codemods: './codemods' };\n`,+ });+ fs.mkdirSync(path.join(pkgDir, 'codemods', 'v1'), {recursive: true});+ fs.writeFileSync(+ path.join(pkgDir, 'codemods', 'forgotten.mjs'),+ `export default {type: 'code', title: 'Forgotten', transform: file => file.source};\n`,+ );++ const result = await validateLocalIntegration(pkgDir);++ expect(byCode(result.issues, 'codemod_outside_version')).toHaveLength(1);+ expect(byCode(result.issues, 'invalid_codemod_version')).toHaveLength(1);+ });++ it('warns about valid contribution metadata outside every declared root', async () => {+ const pkgDir = path.join(tmpDir, 'pkg');+ writePackage(pkgDir, {manifest: 'export default {};\n'});+ fs.mkdirSync(path.join(pkgDir, 'src'));+ fs.writeFileSync(+ path.join(pkgDir, 'src', 'orphan.doc.mjs'),+ `export default ${JSON.stringify({+ type: 'generic',+ name: 'orphan',+ title: 'Orphan',+ description: 'Outside every root.',+ sections: [+ {title: 'Overview', content: [{type: 'prose', text: 'Orphan.'}]},+ ],+ })};\n`,+ );+ fs.writeFileSync(+ path.join(pkgDir, 'src', 'not-a-doc.doc.mjs'),+ 'export default {nope: true};\n',+ );+ fs.mkdirSync(path.join(pkgDir, 'dist'));+ fs.writeFileSync(+ path.join(pkgDir, 'dist', 'built.doc.mjs'),+ `export default ${JSON.stringify({+ type: 'generic',+ name: 'built',+ title: 'Built',+ description: 'Generated output.',+ sections: [+ {title: 'Overview', content: [{type: 'prose', text: 'Built.'}]},+ ],+ })};\n`,+ );++ const result = await validateLocalIntegration(pkgDir);++ const unreachable = byCode(result.issues, 'unreachable_contribution');+ expect(unreachable).toHaveLength(1);+ expect(unreachable[0].message).toContain('src/orphan.doc.mjs');+ });++ it('never executes unreachable metadata while diagnosing it', async () => {+ const pkgDir = path.join(tmpDir, 'pkg');+ const marker = path.join(tmpDir, 'executed');+ writePackage(pkgDir, {manifest: 'export default {};\n'});+ fs.mkdirSync(path.join(pkgDir, 'src'));+ fs.writeFileSync(+ path.join(pkgDir, 'src', 'danger.doc.mjs'),+ `import fs from 'node:fs';\nfs.writeFileSync(${JSON.stringify(marker)}, 'ran');\nexport default {type: 'generic', name: 'danger', title: 'Danger', description: 'Static only.', sections: []};\n`,+ );++ const result = await validateLocalIntegration(pkgDir);++ expect(byCode(result.issues, 'unreachable_contribution')).toHaveLength(1);+ expect(fs.existsSync(marker)).toBe(false);+ });++ it('reports malformed local package.json instead of losing package identity', async () => {+ const pkgDir = path.join(tmpDir, 'pkg');+ writePackage(pkgDir, {manifest: 'export default {};\n'});+ fs.writeFileSync(path.join(pkgDir, 'package.json'), '{bad-json');++ const result = await validateLocalIntegration(pkgDir);++ expect(byCode(result.issues, 'invalid_package_json')).toHaveLength(1);+ });+it('validates an installed package resolved from node_modules', async () => {const consumer = path.join(tmpDir, 'consumer');fs.mkdirSync(consumer, {recursive: true});@@ -206,7 +369,10 @@ describe('validate-integration API', () => {manifest: `export default { templates: './gone' };\n`,});- const result = await validateInstalledIntegration('@acme/widgets', consumer);+ const result = await validateInstalledIntegration(+ '@acme/widgets',+ consumer,+ );expect(result.found).toBe(true);expect(result.name).toBe('@acme/widgets');expect(result.version).toBe('2.0.0');@@ -224,6 +390,24 @@ describe('validate-integration API', () => {expect(byCode(result.issues, 'package_not_found')).toHaveLength(1);});+ it('reports malformed installed package.json distinctly from not found', async () => {+ const consumer = path.join(tmpDir, 'consumer');+ const pkgDir = path.join(consumer, 'node_modules', '@acme', 'widgets');+ writePackage(pkgDir, {+ name: '@acme/widgets',+ manifest: 'export default {};\n',+ });+ fs.writeFileSync(path.join(pkgDir, 'package.json'), '{bad-json');++ const result = await validateInstalledIntegration(+ '@acme/widgets',+ consumer,+ );++ expect(byCode(result.issues, 'invalid_package_json')).toHaveLength(1);+ expect(byCode(result.issues, 'package_not_found')).toHaveLength(0);+ });+it('reports no errors for a valid component (doc + same-stem source)', async () => {const pkgDir = path.join(tmpDir, 'pkg');writePackage(pkgDir, {diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjsindex dfc2a6208d..e7d8a16eb7 100644--- a/packages/cli/api/integration/validateIntegration.doc.mjs+++ b/packages/cli/api/integration/validateIntegration.doc.mjs@@ -19,8 +19,8 @@ export const doc = {'Validates exactly ONE integration at a time: the local package rooted at ' +'cwd (no `pkg`), or an installed package resolved from cwd/node_modules ' +'(`pkg` given). It loads and schema-checks the manifest, verifies each ' +- 'declared contribution root exists, and runs the codemod/template/component ' +- 'validators, returning every finding as an AstryxIntegrationIssue. A missing ' ++ 'declared contribution root exists, and runs the codemod/template/component/' ++ 'docs/theme validators, returning every finding as an AstryxIntegrationIssue. A missing ' +'local manifest is guidance (name null, no issues), not an error, so callers ' +'can stay exit-0 in a non-integration directory.',importPath: '@astryxdesign/cli/api',diff --git a/packages/cli/api/theme/_adapter.mjs b/packages/cli/api/theme/_adapter.mjsindex 227c41ea6a..294790fe1c 100644--- a/packages/cli/api/theme/_adapter.mjs+++ b/packages/cli/api/theme/_adapter.mjs@@ -1,63 +1,126 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Shared data layer for the `theme` command's `add`/`list` leaves — reads- * the bundled-theme manifest (`templates/themes/manifest.json`, generated by- * scripts/generate-cli-themes.mjs) and resolves a theme by slug. Both leaves- * sit on this; neither reads the manifest itself.+ * @file Shared data layer for `theme list` and `theme add`.+ *+ * `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.*/-import * as fs from 'node:fs';-import * as path from 'node:path';-import {CLI_ROOT} from '../../foundation/fs/paths.mjs';+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';-/** Directory holding the generated theme bundle. */-export const THEMES_DIR = path.join(CLI_ROOT, 'assets', 'templates', 'themes');-/** The bundle manifest that lists every theme (+ its files). */-export const MANIFEST_PATH = path.join(THEMES_DIR, 'manifest.json');+export {BUNDLED_THEME_PACKAGE, MANIFEST_PATH, THEMES_DIR};/**- * A single bundled theme entry from `templates/themes/manifest.json`.- * @typedef {object} BundledTheme- * @property {string} slug- * @property {string} displayName- * @property {string} description- * @property {boolean} maintained- * @property {string} entry- * @property {string} exportName- * @property {string[]} files+ * A bundled theme entry kept for the historical public `listThemes()` helper.+ * @typedef {Pick<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme, 'slug' | 'displayName' | 'description' | 'maintained' | 'entry' | 'exportName' | 'files'>} BundledTheme*//**- * Parsed `themes` array from the bundle manifest (empty if not generated).+ * The themes bundled in this CLI build. Kept synchronous for compatibility with+ * programmatic callers that use this low-level helper directly.* @returns {BundledTheme[]}*/export function listThemes() {- if (!fs.existsSync(MANIFEST_PATH)) return [];- /** @type {{themes?: BundledTheme[]}} */- let manifest;+ return availableBundledThemes().map(theme => ({+ slug: theme.slug,+ displayName: theme.displayName,+ description: theme.description,+ maintained: theme.maintained,+ entry: theme.entry,+ exportName: theme.exportName,+ files: theme.files,+ }));+}++/** @returns {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} */+function availableBundledThemes() {try {- manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf-8'));- } catch (err) {- throw new AstryxError(- `Theme bundle manifest is unreadable (${MANIFEST_PATH}): ${/** @type {any} */ (err).message}`,- undefined,- ERROR_CODES.ERR_NO_SOURCE,- );+ return discoverBundledThemes();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_NO_SOURCE);+ }+}++/**+ * 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.+ * @param {string} cwd+ * @returns {Promise<{themes: import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[], issues: Array<import('../../foundation/integrations/issue').AstryxIntegrationIssue & {package: string}>}>}+ */+async function availableThemeState(cwd) {+ try {+ const project = await Project.load(cwd);+ const themes = await project.themes();+ return {themes, issues: await project.issues()};+ } catch {+ return {themes: availableBundledThemes(), issues: []};}- return Array.isArray(manifest.themes) ? manifest.themes : [];}/**- * Resolve a bundled theme by slug (case-insensitive). `undefined` when the slug- * is empty or unknown.+ * Bundled themes plus source themes from integrations installed in `cwd`.+ * A project/config load failure degrades to the bundled catalog, preserving the+ * command's historical usefulness outside a configured project.+ * @param {string} [cwd]+ * @returns {Promise<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]>}+ */+export async function listAvailableThemes(cwd = process.cwd()) {+ return (await availableThemeState(cwd)).themes;+}++/**+ * Resolve an available theme by case-insensitive slug and optional owner package.+ * Duplicate slugs fail closed until the caller selects an owner.* @param {string} [slug]- * @returns {BundledTheme | undefined}+ * @param {{cwd?: string, package?: string}} [options]+ * @returns {Promise<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme | undefined>}*/-export function findTheme(slug) {+export async function findTheme(slug, options = {}) {if (!slug) return undefined;- const lc = String(slug).toLowerCase();- return listThemes().find(t => t.slug.toLowerCase() === lc);+ const {themes, issues} = await availableThemeState(+ options.cwd ?? process.cwd(),+ );+ const normalized = String(slug).toLowerCase();+ const matches = themes.filter(+ theme =>+ theme.slug.toLowerCase() === normalized &&+ (options.package == null || theme.package === options.package),+ );+ if (matches.length === 0 && options.package != null) {+ const packageIssue = issues.find(+ issue => issue.package === options.package && issue.severity === 'error',+ );+ if (packageIssue) {+ throw new AstryxError(+ `Theme package "${options.package}" is installed but unavailable: ${packageIssue.message}`,+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ }+ if (matches.length > 1) {+ throw new AstryxError(+ `Theme "${slug}" is provided by more than one package. Select one with --package.`,+ matches.map(theme => ({+ name: `${theme.slug} --package ${theme.package}`,+ reason: theme.bundled+ ? 'bundled theme'+ : `provided by ${theme.package}`,+ })),+ ERROR_CODES.ERR_AMBIGUOUS_THEME,+ );+ }+ return matches[0];}diff --git a/packages/cli/api/theme/add/add.mjs b/packages/cli/api/theme/add/add.mjsindex 60a5667d0e..2bc4116e43 100644--- a/packages/cli/api/theme/add/add.mjs+++ b/packages/cli/api/theme/add/add.mjs@@ -1,18 +1,20 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file `astryx theme add` leaf — copies a bundled theme's source- * (`templates/themes/<slug>/`) into the consumer's project so they own it,- * without needing the theme package. Which theme is resolved by ../_adapter.mjs;+ * @file `astryx theme add` leaf — copies an available theme's source from the+ * CLI bundle or an installed integration into the consumer's project so they own it.* this leaf owns the copy I/O + path-safety and returns a `theme.add` receipt.*/import * as fs from 'node:fs';import * as path from 'node:path';-import {assertWithin, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';+import {+ assertWithin,+ PathSafetyError,+} from '../../../foundation/fs/path-safety.mjs';import {AstryxError} from '../../error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';-import {THEMES_DIR, listThemes, findTheme} from '../_adapter.mjs';+import {listAvailableThemes, findTheme} from '../_adapter.mjs';// Scaffolded files must not carry our repo boilerplate into a consumer's tree.import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';@@ -32,25 +34,33 @@ function defaultTargetDir(slug) {* file (without `overwrite`), a missing bundled file, or a write failure.** @param {string} slug- * @param {{targetPath?: string, overwrite?: boolean, cwd?: string}} [options]+ * @param {{targetPath?: string, overwrite?: boolean, cwd?: string, package?: string}} [options]* @returns {Promise<import('../theme.type.mjs').ThemeAddResponse>}*/export async function themeAdd(slug, options = {}) {- const {targetPath, overwrite = false, cwd = process.cwd()} = options;+ const {+ targetPath,+ overwrite = false,+ cwd = process.cwd(),+ package: packageName,+ } = options;- const match = findTheme(slug);+ const match = await findTheme(slug, {cwd, package: packageName});if (!match) {+ const available = await listAvailableThemes(cwd);throw new AstryxError(- `Unknown theme "${slug}"`,- listThemes().map(t => ({- name: t.slug,- reason: t.maintained ? 'maintained theme' : 'example theme',+ `Unknown theme "${slug}"${packageName ? ` in package "${packageName}"` : ''}`,+ available.map(theme => ({+ name: `${theme.slug} --package ${theme.package}`,+ reason: theme.bundled+ ? 'bundled theme'+ : `provided by ${theme.package}`,})),ERROR_CODES.ERR_UNKNOWN_THEME,);}- const themeSrcDir = path.join(THEMES_DIR, match.slug);+ const themeSrcDir = match.sourceDir;// Path-safe destination; reject traversal outside cwd.const rawTarget = targetPath || defaultTargetDir(match.slug);@@ -106,6 +116,7 @@ export async function themeAdd(slug, options = {}) {try {fs.mkdirSync(resolvedDir, {recursive: true});for (const w of writes) {+ fs.mkdirSync(path.dirname(w.dest), {recursive: true});const tmp = `${w.dest}.${process.pid}.tmp`;const contents = stripCopyrightHeader(fs.readFileSync(w.src, 'utf-8'));fs.writeFileSync(tmp, contents);@@ -136,6 +147,7 @@ export async function themeAdd(slug, options = {}) {slug: match.slug,displayName: match.displayName,maintained: match.maintained,+ package: match.package,outputDir: relDir,entry: match.entry,exportName: match.exportName,diff --git a/packages/cli/api/theme/add/add.test.mjs b/packages/cli/api/theme/add/add.test.mjsindex d7cd79bb62..5aa2a31e44 100644--- a/packages/cli/api/theme/add/add.test.mjs+++ b/packages/cli/api/theme/add/add.test.mjs@@ -28,6 +28,7 @@ describe('themeAdd (api/theme/add)', () => {const result = await themeAdd('neutral', {cwd: tmpDir});expect(result.type).toBe('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);for (const f of result.data.files) {diff --git a/packages/cli/api/theme/integration-themes.test.mjs b/packages/cli/api/theme/integration-themes.test.mjsnew file mode 100644index 0000000000..3606c97f9e--- /dev/null+++ b/packages/cli/api/theme/integration-themes.test.mjs@@ -0,0 +1,154 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {themeAdd} from './add/add.mjs';++let tmpDir;++function installThemeIntegration(+ packageName,+ slug,+ source = 'export const oceanTheme = {};\n',+ extraFiles = {},+) {+ const packageDir = path.join(+ tmpDir,+ 'node_modules',+ ...packageName.split('/'),+ );+ const themeDir = path.join(packageDir, 'themes', slug);+ fs.mkdirSync(themeDir, {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: packageName, version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ `export default {themes: './themes'};\n`,+ );+ 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)],+ },+ ],+ }),+ );+ 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});+ fs.writeFileSync(file, contents);+ }+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-theme-integration-'),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ dependencies: {'@acme/themes': '^1.0.0'},+ }),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('themeAdd with integration themes', () => {+ it('copies source from an installed integration and records its owner', async () => {+ installThemeIntegration('@acme/themes', 'ocean');+ const result = await themeAdd('ocean', {cwd: tmpDir});++ expect(result.data.package).toBe('@acme/themes');+ expect(result.data.outputDir).toBe(path.join('src', 'themes', 'ocean'));+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.ts'),+ 'utf-8',+ ),+ ).toContain('oceanTheme');+ });++ it('copies nested files listed by an integration theme catalog', async () => {+ installThemeIntegration(+ '@acme/themes',+ 'ocean',+ "import {oceanBlue} from './tokens/colors';\nexport const oceanTheme = {oceanBlue};\n",+ {'tokens/colors.ts': "export const oceanBlue = '#0064e0';\n"},+ );++ const result = await themeAdd('ocean', {cwd: tmpDir});++ expect(result.data.files).toEqual(['oceanTheme.ts', 'tokens/colors.ts']);+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'tokens', 'colors.ts'),+ 'utf-8',+ ),+ ).toContain('oceanBlue');+ });++ it('fails closed on a duplicate slug and resolves it with package scope', async () => {+ installThemeIntegration('@acme/themes', 'neutral');++ await expect(themeAdd('neutral', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_AMBIGUOUS_THEME',+ });+ const result = await themeAdd('neutral', {+ cwd: tmpDir,+ package: '@acme/themes',+ });+ expect(result.data.package).toBe('@acme/themes');+ });++ it('reports a selected installed package with a corrupted theme catalog', async () => {+ installThemeIntegration(+ '@acme/themes',+ 'ocean',+ "export {oceanBlue} from './tokens/colors';\n",+ {'tokens/colors.ts': "export const oceanBlue = '#0064e0';\n"},+ );+ fs.rmSync(+ path.join(+ tmpDir,+ 'node_modules',+ '@acme',+ 'themes',+ 'themes',+ 'ocean',+ 'tokens',+ 'colors.ts',+ ),+ );++ await expect(+ themeAdd('ocean', {cwd: tmpDir, package: '@acme/themes'}),+ ).rejects.toMatchObject({+ code: 'ERR_THEME_INVALID',+ message: expect.stringContaining('tokens/colors.ts'),+ });+ });++ it('reports an unknown package selection without falling back to another owner', async () => {+ installThemeIntegration('@acme/themes', 'ocean');+ await expect(+ themeAdd('ocean', {cwd: tmpDir, package: '@other/themes'}),+ ).rejects.toMatchObject({code: 'ERR_UNKNOWN_THEME'});+ });+});diff --git a/packages/cli/api/theme/list/list.mjs b/packages/cli/api/theme/list/list.mjsindex 0c5740d22f..ca59bd028a 100644--- a/packages/cli/api/theme/list/list.mjs+++ b/packages/cli/api/theme/list/list.mjs@@ -1,25 +1,46 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file `astryx theme list` leaf — projects the bundled-theme manifest into the- * `theme.list` envelope. Data source: ../_adapter.mjs (listThemes).+ * @file Theme-list projections. `themeList()` retains its historical synchronous+ * bundled-only API contract. `themeListAvailable()` is the project-aware command+ * seam that adds installed integration themes and owner packages.*/-import {listThemes} from '../_adapter.mjs';+import {listAvailableThemes, listThemes} from '../_adapter.mjs';/**- * List the themes bundled with this CLI build (the ones `theme add` can- * scaffold). Pure projection of the manifest; no I/O beyond the adapter read.+ * List themes bundled with this CLI build.* @returns {import('../theme.type.mjs').ThemeListResponse}*/export function themeList() {return {type: 'theme.list',- data: listThemes().map(t => ({- slug: t.slug,- displayName: t.displayName,- description: t.description,- maintained: t.maintained,+ data: listThemes().map(theme => ({+ slug: theme.slug,+ displayName: theme.displayName,+ description: theme.description,+ maintained: theme.maintained,})),};}++/**+ * List bundled and installed integration themes available to this project.+ * @param {{cwd?: string, package?: string}} [options]+ * @returns {Promise<import('../theme.type.mjs').ThemeListResponse>}+ */+export async function themeListAvailable(options = {}) {+ const themes = await listAvailableThemes(options.cwd);+ return {+ type: 'theme.list',+ data: themes+ .filter(theme => options.package == null || theme.package === options.package)+ .map(theme => ({+ slug: theme.slug,+ displayName: theme.displayName,+ description: theme.description,+ maintained: theme.maintained,+ package: theme.package,+ })),+ };+}diff --git a/packages/cli/api/theme/list/list.test.mjs b/packages/cli/api/theme/list/list.test.mjsindex a108eefa2d..97a6ac8aee 100644--- a/packages/cli/api/theme/list/list.test.mjs+++ b/packages/cli/api/theme/list/list.test.mjs@@ -1,41 +1,120 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file Direct-API tests for the `theme list` leaf. Runs against the real- * bundled-theme manifest (committed under templates/themes/), so it doubles as a- * guard that the bundle stays readable and shaped as `theme.list` expects.- */+import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {themeList, themeListAvailable} from './list.mjs';+import {BUNDLED_THEME_PACKAGE} from '../../../foundation/discovery/theme-discovery.mjs';-import {describe, it, expect} from 'vitest';-import {themeList} from './list.mjs';+let tmpDir;-describe('themeList (api/theme/list)', () => {- it('returns a theme.list envelope of the bundled themes', () => {+function installThemeIntegration(packageName = '@acme/themes', slug = 'ocean') {+ const packageDir = path.join(tmpDir, 'node_modules', ...packageName.split('/'));+ const themeDir = path.join(packageDir, 'themes', slug);+ fs.mkdirSync(themeDir, {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: packageName, version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ `export default {themes: './themes'};\n`,+ );+ 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'],+ },+ ],+ }),+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',+ );+}++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'}}),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('themeList (bundled compatibility API)', () => {+ it('stays synchronous and preserves the original entry shape', () => {const result = themeList();expect(result.type).toBe('theme.list');- expect(Array.isArray(result.data)).toBe(true);expect(result.data.length).toBeGreaterThan(0);- for (const t of result.data) {- expect(typeof t.slug).toBe('string');- expect(typeof t.displayName).toBe('string');- expect(typeof t.description).toBe('string');- expect(typeof t.maintained).toBe('boolean');- }+ expect(Object.keys(result.data[0]).sort()).toEqual([+ 'description',+ 'displayName',+ 'maintained',+ 'slug',+ ]);+ });+});++describe('themeListAvailable (project-aware API)', () => {+ it('returns bundled themes with owner package', async () => {+ const result = await themeListAvailable({cwd: tmpDir});+ expect(result.type).toBe('theme.list');+ expect(result.data.length).toBeGreaterThan(0);+ expect(+ result.data.some(theme => theme.package === BUNDLED_THEME_PACKAGE),+ ).toBe(true);+ });++ it('surfaces a maintained installed integration theme', async () => {+ installThemeIntegration();+ const result = await themeListAvailable({cwd: tmpDir});+ expect(result.data).toContainEqual({+ slug: 'ocean',+ displayName: 'Ocean',+ description: 'Blue and calm.',+ maintained: true,+ package: '@acme/themes',+ });});- it('surfaces the maintained neutral theme', () => {- const neutral = themeList().data.find(t => t.slug === 'neutral');- expect(neutral).toBeTruthy();- expect(neutral?.maintained).toBe(true);+ it('filters by exact owner package', async () => {+ installThemeIntegration();+ const result = await themeListAvailable({+ cwd: tmpDir,+ package: '@acme/themes',+ });+ expect(result.data).toEqual([+ {+ slug: 'ocean',+ displayName: 'Ocean',+ description: 'Blue and calm.',+ maintained: true,+ package: '@acme/themes',+ },+ ]);});- it('projects only the list fields (no entry/exportName/files leak)', () => {- const [first] = themeList().data;- expect(first).toBeTruthy();+ it('projects only public list fields', async () => {+ const [first] = (await themeListAvailable({cwd: tmpDir})).data;expect(Object.keys(first ?? {}).sort()).toEqual(['description','displayName','maintained',+ 'package','slug',]);});diff --git a/packages/cli/api/theme/listThemes.doc.mjs b/packages/cli/api/theme/listThemes.doc.mjsindex bda1da3754..ae639c83a1 100644--- a/packages/cli/api/theme/listThemes.doc.mjs+++ b/packages/cli/api/theme/listThemes.doc.mjs@@ -1,11 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file FunctionDoc for the `listThemes()` helper. Colocated with the theme- * command's shared data layer (`_adapter.mjs`); the BundledTheme shape lives- * there. This helper has no CLI command of its own — themeList and themeAdd- * sit on it.- * @position packages/cli/api/theme — function documentation+ * @file FunctionDoc for the synchronous bundled-theme compatibility helper.*//** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */@@ -14,12 +10,9 @@ export const doc = {kind: 'api',name: 'listThemes',displayName: 'listThemes()',- summary: 'Read the bundled-theme manifest and return its raw entries.',+ summary: 'Read the CLI bundled-theme manifest.',description:- "The shared data layer behind theme list/add: reads the CLI's bundled-theme manifest " +- '(templates/themes/manifest.json, generated by scripts/generate-cli-themes.mjs) and returns ' +- 'the parsed entries. themeList() projects this into the theme.list envelope; themeAdd() ' +- 'resolves a slug against it. Returns synchronously.',+ '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.',importPath: '@astryxdesign/cli/api',signature: 'listThemes(): BundledTheme[]',keywords: ['theme', 'themes', 'manifest', 'bundled', 'adapter', 'list'],@@ -28,17 +21,17 @@ export const doc = {{type: 'BundledTheme[]',description:- 'The parsed themes array from the bundle manifest: each BundledTheme has slug, displayName, description, maintained, entry, exportName, and files. Empty when the manifest has not been generated.',+ 'The bundled manifest entries: slug, displayName, description, maintained, entry, exportName, and files.',},],throws: [{code: 'ERR_NO_SOURCE',- when: 'the manifest file exists but cannot be read or parsed as JSON',+ when: 'the bundled catalog is missing, invalid, or references missing source files',},],examples: [- {label: 'Read the manifest', code: 'const themes = listThemes();'},+ {label: 'Read bundled entries', code: 'const themes = listThemes();'},],related: ['themeList', 'themeAdd', 'themeBuild'],};diff --git a/packages/cli/api/theme/theme.mjs b/packages/cli/api/theme/theme.mjsindex 303985be1b..dd93f15947 100644--- a/packages/cli/api/theme/theme.mjs+++ b/packages/cli/api/theme/theme.mjs@@ -23,5 +23,5 @@ export {parseStopList,validateStops,} from './palette/generate/generator.mjs';-export {themeList} from './list/list.mjs';+export {themeList, themeListAvailable} from './list/list.mjs';export {listThemes} from './_adapter.mjs';diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjsindex f6d15cc2a7..3a605dfec6 100644--- a/packages/cli/api/theme/theme.type.mjs+++ b/packages/cli/api/theme/theme.type.mjs@@ -55,6 +55,7 @@* @property {string} displayName* @property {string} description* @property {boolean} maintained+ * @property {string} [package] owner package for project-aware listings*//**@@ -68,7 +69,7 @@* xds --json theme add <slug>* @typedef {object} ThemeAddResponse* @property {'theme.add'} type- * @property {{slug: string, displayName: string, maintained: boolean, outputDir: string, entry: string, exportName: string, files: string[]}} data+ * @property {{slug: string, displayName: string, maintained: boolean, package: string, outputDir: string, entry: string, exportName: string, files: string[]}} data*//**diff --git a/packages/cli/api/theme/themeAdd.doc.mjs b/packages/cli/api/theme/themeAdd.doc.mjsindex f6d156bfac..4ba6e0af35 100644--- a/packages/cli/api/theme/themeAdd.doc.mjs+++ b/packages/cli/api/theme/themeAdd.doc.mjs@@ -1,10 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file FunctionDoc for `themeAdd()` / `astryx theme add`. Colocated with the- * API function it documents; the response-shape source of truth stays in- * `theme.type.mjs`.- * @position packages/cli/api/theme — function documentation+ * @file FunctionDoc for `themeAdd()` / `astryx theme add`.*//** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */@@ -13,80 +10,83 @@ export const doc = {kind: 'api',name: 'themeAdd',displayName: 'themeAdd()',- summary: 'Scaffold a bundled theme into a project as editable source.',+ summary: 'Copy an available theme into a project as editable source.',description:- "Copies a bundled theme's source (from the CLI's templates/themes/<slug>) into the " +- "consumer's project so they own it, no theme package needed. Writes are staged to temp " +- 'files then renamed, rolling back partials on failure so a failed write never leaves a ' +- 'half-written theme. Returns a theme.add receipt describing where the files landed and how ' +- 'to import them.',+ '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.',importPath: '@astryxdesign/cli/api',signature:- 'themeAdd(slug: string, options?: {targetPath?: string, overwrite?: boolean, cwd?: string}): Promise<ThemeAddResponse>',- keywords: ['theme', 'add', 'scaffold', 'copy', 'eject', 'starter'],+ 'themeAdd(slug: string, options?: {targetPath?: string, overwrite?: boolean, cwd?: string, package?: string}): Promise<ThemeAddResponse>',+ keywords: ['theme', 'add', 'integration', 'scaffold', 'copy', 'eject'],params: [{name: 'slug',type: 'string',description:- 'Slug of the bundled theme to scaffold (matched case-insensitively).',+ 'Slug of the available theme to copy (matched case-insensitively).',required: true,},{name: 'options.targetPath',type: 'string',description:- 'Destination directory for the copied files. Must resolve within cwd.',+ 'Destination directory for copied files. Must resolve within cwd.',default: "'src/themes/<slug>'",},{name: 'options.overwrite',type: 'boolean',- description:- 'Replace existing files instead of refusing when a destination file already exists.',+ description: 'Replace existing files instead of refusing.',default: 'false',},{name: 'options.cwd',type: 'string',- description: 'Directory the target path resolves against.',+ description:+ 'Project directory used for integration discovery and target paths.',+ },+ {+ name: 'options.package',+ type: 'string',+ description: 'Exact owner package used to disambiguate a shared slug.',},],returns: [{type: 'theme.add',description:- 'Scaffold receipt: the resolved slug, displayName, whether the theme is maintained, the outputDir the copy landed in (relative to cwd), the theme entry file, its exportName, and the list of files written.',+ 'Copy receipt with slug, displayName, maintained flag, owner package, outputDir, entry, exportName, and files.',},{type: 'theme.list',description:- 'The `theme add` command also lists: a bare `astryx theme add` (no slug) or `--list` routes to themeList() and returns every bundled theme (slug, displayName, description, maintained).',+ 'The CLI list affordance routes a bare `astryx theme add` or `--list` to themeListAvailable() and returns every available theme with its owner.',},],throws: [- {code: 'ERR_UNKNOWN_THEME', when: 'no bundled theme matches the slug'},- {code: 'ERR_PATH_TRAVERSAL', when: 'the target path escapes cwd'},{- code: 'ERR_NO_SOURCE',- when: 'a bundled file for the theme is missing from this CLI build',+ code: 'ERR_UNKNOWN_THEME',+ when: 'no available theme matches the slug and package',},+ {code: 'ERR_AMBIGUOUS_THEME', when: 'more than one package owns the slug'},{- code: 'ERR_FILE_EXISTS',- when: 'a destination file already exists and overwrite is not set',+ code: 'ERR_THEME_INVALID',+ when: 'the selected installed package has a blocking integration or theme-catalog 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_WRITE_FAILED',- when: 'writing the files fails (staged temp files are rolled back)',+ code: 'ERR_FILE_EXISTS',+ when: 'a destination exists and overwrite is not set',},+ {code: 'ERR_WRITE_FAILED', when: 'writing files fails'},],examples: [- {label: 'Scaffold a theme', code: "const r = await themeAdd('ocean');"},+ {label: 'Copy a bundled theme', code: "await themeAdd('ocean');"},{- label: 'Custom target + overwrite',- code: "await themeAdd('ocean', {targetPath: 'src/theme', overwrite: true});",+ label: 'Copy an integration theme',+ code: "await themeAdd('ocean', {package: '@acme/themes'});",},],command: 'theme add',- related: ['themeList', 'listThemes', 'themeBuild'],+ related: ['themeList', 'listThemes'],};diff --git a/packages/cli/api/theme/themeList.doc.mjs b/packages/cli/api/theme/themeList.doc.mjsindex 19c42d1d86..c2100012f0 100644--- a/packages/cli/api/theme/themeList.doc.mjs+++ b/packages/cli/api/theme/themeList.doc.mjs@@ -1,10 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file FunctionDoc for `themeList()` / `astryx theme list`. Colocated with the- * API function it documents; the response-shape source of truth stays in- * `theme.type.mjs`.- * @position packages/cli/api/theme — function documentation+ * @file FunctionDoc for the synchronous bundled-theme compatibility API.*//** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */@@ -13,11 +10,9 @@ export const doc = {kind: 'api',name: 'themeList',displayName: 'themeList()',- summary: 'List the themes bundled with this CLI build.',+ summary: 'List themes bundled with this CLI build.',description:- 'Projects the bundled-theme manifest into the theme.list envelope: the themes that themeAdd ' +- 'can scaffold. A pure projection of the manifest read by listThemes(); no I/O beyond that read, ' +- 'and it returns synchronously.',+ '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.',importPath: '@astryxdesign/cli/api',signature: 'themeList(): ThemeListResponse',keywords: ['theme', 'list', 'themes', 'bundled', 'available'],@@ -26,18 +21,15 @@ export const doc = {{type: 'theme.list',description:- 'Every bundled theme as a ThemeListEntry[]: each entry has slug, displayName, description, and a maintained flag.',+ 'Every bundled theme as ThemeListEntry[]: slug, displayName, description, and maintained flag.',},],throws: [{code: 'ERR_NO_SOURCE',- when: 'the bundled-theme manifest exists but cannot be read or parsed',+ when: 'the bundled-theme manifest cannot be read or parsed',},],- examples: [- {label: 'List bundled themes', code: 'const {data} = themeList();'},- ],- command: 'theme list',- related: ['themeAdd', 'listThemes', 'themeBuild'],+ 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.mjsnew file mode 100644index 0000000000..30192ff63b--- /dev/null+++ b/packages/cli/api/theme/themeListAvailable.doc.mjs@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file FunctionDoc for the project-aware `astryx theme list` API.+ */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'themeListAvailable',+ 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.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'themeListAvailable(options?: {cwd?: string, package?: string}): Promise<ThemeListResponse>',+ keywords: ['theme', 'list', 'themes', 'integration', 'available', 'package'],+ params: [+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Project directory whose installed integrations contribute themes.',+ },+ {+ name: 'options.package',+ type: 'string',+ description: 'Optional exact owner-package filter.',+ },+ ],+ returns: [+ {+ type: 'theme.list',+ description:+ 'Every available theme as ThemeListEntry[]: slug, displayName, description, maintained flag, and owner package.',+ },+ ],+ throws: [+ {+ code: 'ERR_NO_SOURCE',+ when: 'the CLI bundled-theme manifest cannot be read or parsed',+ },+ ],+ examples: [+ {+ label: 'List project themes',+ code: 'const {data} = await themeListAvailable();',+ },+ {+ label: 'List one package',+ code: "await themeListAvailable({package: '@acme/themes'});",+ },+ ],+ command: 'theme list',+ related: ['themeList', 'themeAdd'],+};diff --git a/packages/cli/assets/docs/cli-integrations.doc.mjs b/packages/cli/assets/docs/cli-integrations.doc.mjsindex 4d93eba18c..6071bb2d5d 100644--- a/packages/cli/assets/docs/cli-integrations.doc.mjs+++ b/packages/cli/assets/docs/cli-integrations.doc.mjs@@ -7,7 +7,7 @@ export const docs = {title: 'CLI Integrations',category: 'guide',description:- 'Author an npm package that contributes components, templates, and upgrade codemods to Astryx.',+ 'Author an npm package that contributes components, templates, themes, docs, and upgrade codemods to Astryx.',sections: [{@@ -16,15 +16,15 @@ export const docs = {content: [{type: 'prose',- text: 'An integration is an npm package that contributes components, templates, doc topics, and/or upgrade codemods to a consumer\'s design-system workflow. Consumers install the package and add it to their `astryx.config`; from then on the integration\'s contributions show up alongside core\'s in the same CLI commands.',+ text: "An integration is an npm package that contributes components, templates, source themes, doc topics, agent guidance, and/or upgrade codemods to a consumer's design-system workflow. Consumers install the package as a direct dependency and Astryx autolinks it; an explicit `astryx.config` entry remains available when the app needs to control ordering.",},{type: 'prose',- text: 'The system runs on two files. The consumer writes `astryx.config.{ts,mjs,js}` at their project root to list which packages to load. The author writes `astryx.integration.{ts,mjs,js}` at the package root to declare what the package contributes. This page is the author\'s guide. For the consumer side, run `npx astryx docs getting-started`.',+ text: 'The authoring CLI owns the integration file. The first `astryx integration add` creates `astryx.integration.mjs`; each later add declares its root only after writing a valid contribution behind it. Identity (name and version) still comes from package.json. For the consumer side, run `npx astryx docs getting-started`.',},{type: 'prose',- text: 'On the consumer side, adding your package is one line:',+ text: 'A consumer can still name the package explicitly when order or precedence matters:',},{type: 'code',@@ -33,7 +33,7 @@ export const docs = {},{type: 'prose',- text: 'Your components and templates then appear next to core\'s:',+ text: "Your components and templates then appear next to core's:",},{type: 'code',@@ -42,18 +42,80 @@ export const docs = {},],},+ {+ title: 'Authoring with the CLI',+ category: 'guide',+ content: [+ {+ type: 'prose',+ text: 'Do not start by hand-editing a manifest. Add the contribution you mean to ship; Astryx creates the manifest, writes every required file, preserves an existing custom root, and updates an existing package.json files allowlist without creating one.',+ },+ {+ type: 'code',+ lang: 'bash',+ code: "astryx integration add component AcmeCarousel\nastryx integration add doc deploying\nastryx integration add template dashboard --type page\nastryx integration add codemod rename-prop --to 1.2.0\nastryx integration add agent-doc 'Use AcmeCarousel for rotating content.'\nastryx integration add theme ocean",+ },+ {+ type: 'prose',+ text: 'The package self-resolves while you author it. Run `astryx component --list`, `astryx docs`, `astryx template --list`, or `astryx theme list` from the package and its local contributions appear with the package name. You do not publish or build a throwaway app to see your own work.',+ },+ {+ type: 'prose',+ text: 'Every add is non-interactive, refuses to overwrite authored files, supports --dry-run, and verifies the generated contribution through the same discovery rules a consumer uses. Before publishing, run the package gate:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'astryx integration pack --check',+ },+ {+ type: 'prose',+ text: 'The gate runs the package lifecycle, creates the real npm tarball, checks every required contribution file against the pack list, extracts it into a scratch consumer, and compares the local and packed contribution inventories. `astryx doctor integration` remains the read-only diagnostic surface when something is not found.',+ },+ ],+ },+ {+ title: 'Theme Package Walkthrough',+ category: 'guide',+ content: [+ {+ type: 'prose',+ text: 'A useful theme package usually ships more than colors. Start with the source theme, then add the guides its consumers need. Each command writes a complete contribution and keeps the package manifest in sync.',+ },+ {+ type: 'code',+ lang: 'bash',+ label: 'In the provider package',+ code: 'astryx integration add theme ocean\nastryx theme palette generate palette.config.json --out themes/ocean/tokens/ocean.palette.ts\nastryx integration add doc brand-theme\nastryx integration add doc theme-migration\nastryx theme list --package @acme/brand-integration\nastryx docs brand-theme\nastryx integration pack --check\nnpm pack',+ },+ {+ type: 'prose',+ text: 'Edit the generated theme and guide files before publishing. Palette generation writes an importable TypeScript candidate and a reproducibility receipt; import the candidate from the theme and list both nested files in that theme catalog entry. `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.',+ },+ {+ type: 'code',+ lang: 'bash',+ label: 'In a separate consumer app',+ code: 'npm install @astryxdesign/core ../brand-integration/acme-brand-integration-1.0.0.tgz\nastryx theme list --package @acme/brand-integration\nastryx docs brand-theme\nastryx docs theme-migration\nastryx theme add ocean --package @acme/brand-integration\nastryx theme build src/themes/ocean/oceanTheme.ts',+ },+ {+ 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.',+ },+ ],+ },{title: 'The Integration File',category: 'guide',content: [{type: 'prose',- text: 'To register your package as an integration, add an `astryx.integration.{ts,mjs,js}` file as a sibling of your `package.json`. It tells the CLI where to find your components, templates, doc topics, and codemods. Identity (name, version) comes from your `package.json`, not this file.',+ text: 'The CLI creates one `astryx.integration.mjs` beside package.json and adds a root only when that same operation writes a real contribution. The file tells consumers where each contribution kind lives; this example is the resulting shape, not a setup step:',},{type: 'code',lang: 'typescript',- code: "// astryx.integration.ts\nexport default {\n components: './components',\n templates: './templates',\n codemods: './codemods',\n docs: './docs',\n issuesUrl: 'https://github.com/acme/widgets/issues',\n};",+ code: "// astryx.integration.ts\nexport default {\n components: './components',\n templates: './templates',\n themes: './themes',\n codemods: './codemods',\n docs: './docs',\n issuesUrl: 'https://github.com/acme/widgets/issues',\n};",},{type: 'prose',@@ -86,7 +148,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 stamped with `type: \'page\'` (full pages) or `type: \'block\'` (smaller chunks) in a `.template.{ts,mjs,js}` file next to the source, for example `AcmeLandingPage.tsx` and `AcmeLandingPage.template.ts`.',+ 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 stamped with `type: 'page'` (full pages) or `type: 'block'` (smaller chunks) in a `.template.{ts,mjs,js}` file next to the source, for example `AcmeLandingPage.tsx` and `AcmeLandingPage.template.ts`.",},{type: 'prose',@@ -99,21 +161,7 @@ export const docs = {},{type: 'prose',- text: 'The CLI needs the template source at consume time, so make sure it is included in your published package. This is typically done via the `exports` key in `package.json`. It also lets the docsite render template previews in the future.',- },- {- type: 'code',- lang: 'jsonc',- code: '{\n "exports": {\n // ...\n "./templates/*.tsx": "./templates/*.tsx"\n }\n}',- },- {- type: 'prose',- text: 'To verify it resolves, try importing the template component with its `.tsx` extension. An extensionless specifier will not resolve under `moduleResolution: bundler`, and the extensionful export above is what lets this type-check without consumers enabling `allowImportingTsExtensions`.',- },- {- type: 'code',- lang: 'typescript',- code: "import('@acme/astryx-widgets/templates/AcmeLandingPage.tsx');",+ text: 'The CLI needs both files at consume time. `integration add` includes the templates root when package.json already has a files allowlist. It never creates an exports map, because doing that can make previously-open deep imports private; when a map already exists, it adds the generated source subpath without replacing author-owned entries. `integration pack --check` proves the source and metadata survive the tarball and verifies every component through the public import its metadata advertises.',},],},@@ -148,14 +196,46 @@ export const docs = {style: 'unordered',items: ['A topic name is a CLI argument and a docsite path, so it may hold only letters, digits, `_` and `-`.',- "A name that collides with an existing topic and declares neither `replaces` nor `extends` is an error, not a silent override; the CLI will not guess which one you meant.",- '`replaces` and `extends` are exclusive: a topic either takes another\'s place or merges onto it.',+ 'A name that collides with an existing topic and declares neither `replaces` nor `extends` is an error, not a silent override; the CLI will not guess which one you meant.',+ "`replaces` and `extends` are exclusive: a topic either takes another's place or merges onto it.",'Two integrations replacing one topic is a warning, and the one configured later in `astryx.config` wins.','`astryx doctor integration docs <package>` classifies Core overlaps as intentional replacements, intentional extensions, or accidental same-name conflicts.',],},],},+ {+ title: 'Themes',+ category: 'guide',+ 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.",+ },+ {+ type: 'code',+ lang: 'text',+ code: 'themes/\n manifest.json\n ocean/\n oceanTheme.ts',+ },+ {+ type: 'prose',+ text: "The root catalog uses the same entry contract as Astryx's bundled themes: `slug`, `displayName`, `description`, `maintained`, `entry`, `exportName`, and `files`. `entry` and every file are relative to `themes/<slug>/`; `exportName` identifies a named runtime export in the entry source. Astryx parses that source without executing it, requires every local static import and re-export to name a file in `files`, 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.",\n "maintained": true,\n "entry": "oceanTheme.ts",\n "exportName": "oceanTheme",\n "files": ["oceanTheme.ts"]\n }]\n}',+ },+ {+ type: 'prose',+ text: 'After a consumer installs the package, `astryx theme list` shows its themes with the owner package, and `astryx theme add <slug> --package <package>` copies the selected source into the app. If two packages use one slug, an unscoped add fails instead of choosing one silently.',+ },+ {+ type: 'prose',+ text: "Compatibility is additive. A CLI released before the `themes` field ignores that unknown key with a warning and continues loading the integration's older contribution kinds, but it cannot list or add the contributed theme. Upgrade `@astryxdesign/cli` in the consumer to use it.",+ },+ ],+ },{title: 'Agent Docs',category: 'guide',@@ -185,7 +265,7 @@ export const docs = {content: [{type: 'prose',- text: 'Ship codemods so `astryx upgrade` can migrate consumers across breaking changes in your package. Point the integration file\'s `codemods` field at your codemods root, and author each one as a plain object stamped with `type: \'code\'` (transforms source files) or `type: \'config\'` (rewrites the consumer\'s `astryx.config`).',+ text: "Ship codemods so `astryx upgrade` can migrate consumers across breaking changes in your package. Point the integration file's `codemods` field at your codemods root, and author each one as a plain object stamped with `type: 'code'` (transforms source files) or `type: 'config'` (rewrites the consumer's `astryx.config`).",},{type: 'code',@@ -213,7 +293,7 @@ export const docs = {},{type: 'prose',- text: 'The event is the same `DebugEvent` a consumer receives from `debug` in their own `astryx.config`, and both run: an app that sets its own handler still reaches yours, and yours never displaces theirs. The app handler is called first, then each integration in the order the config lists them. Every handler is called in isolation with its own copy of the event — one that throws, prints, or calls `process.exit` cannot change the command\'s output or exit code, and cannot stop the others.',+ text: "The event is the same `DebugEvent` a consumer receives from `debug` in their own `astryx.config`, and both run: an app that sets its own handler still reaches yours, and yours never displaces theirs. The app handler is called first, then each integration in the order the config lists them. Every handler is called in isolation with its own copy of the event — one that throws, prints, or calls `process.exit` cannot change the command's output or exit code, and cannot stop the others.",},{type: 'prose',@@ -227,7 +307,7 @@ export const docs = {content: [{type: 'prose',- text: 'Every CLI command loads the consumer\'s `astryx.config`, resolves each listed integration\'s manifest from `node_modules`, and discovers its contributions. Each file is parsed at the load boundary through `@astryxdesign/cli/authoring` — when the CLI loads it, not when you author it. A field of the wrong type fails there. A field this CLI does not know is ignored with a warning naming it, so a manifest written against a newer CLI still contributes everything this one understands. There are no factories; you write a plain object and stamp its `type`.',+ text: "Every CLI command loads the consumer's `astryx.config`, resolves each listed integration's manifest from `node_modules`, and discovers its contributions. Each file is parsed at the load boundary through `@astryxdesign/cli/authoring` — when the CLI loads it, not when you author it. A field of the wrong type fails there. A field this CLI does not know is ignored with a warning naming it, so a manifest written against a newer CLI still contributes everything this one understands. There are no factories; you write a plain object and stamp its `type`.",},{type: 'prose',diff --git a/packages/cli/assets/docs/getting-started.doc.mjs b/packages/cli/assets/docs/getting-started.doc.mjsindex 932a39d7f4..a5fd1abac1 100644--- a/packages/cli/assets/docs/getting-started.doc.mjs+++ b/packages/cli/assets/docs/getting-started.doc.mjs@@ -31,7 +31,7 @@ export const docs = {type: 'code',lang: 'text',label: 'Give it a look',- code: "Ask me what look and feel this app should have. Run `npx @astryxdesign/cli theme list` and start from the closest shipped theme with `theme add <slug>`, which copies it in as editable source; if none of them fit, run `npx @astryxdesign/cli theme template` and fill in the annotated template it writes. Default to neutral if I have no preference, and show me the result before moving on.",+ code: "Ask me what look and feel this app should have. Run `npx @astryxdesign/cli theme list` and start from the closest available theme with `theme add <slug>`; the list includes bundled themes and themes from installed integrations, with each owner shown. Use `--package` if owners share a slug. The command copies the theme in as editable source. If none fit, run `npx @astryxdesign/cli theme template` and fill in the annotated template it writes. Default to neutral if I have no preference, and show me the result before moving on.",},],},diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjsindex 7c157dfee6..d4f41c1a03 100644--- a/packages/cli/assets/docs/theme.doc.dense.mjs+++ b/packages/cli/assets/docs/theme.doc.dense.mjs@@ -38,7 +38,7 @@ export const docsDense = {content: [{type: 'prose',- text: '`theme list` + `theme add <slug>` to start from a shipped theme, or defineTheme from scratch. only override tokens that differ.',+ text: '`theme list` + `theme add <slug>` to start from a bundled or installed integration theme; use `--package` for a shared slug. Or defineTheme from scratch. only override tokens that differ.',},null,{diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjsindex dc8dab6b23..add15d8257 100644--- a/packages/cli/assets/docs/theme.doc.mjs+++ b/packages/cli/assets/docs/theme.doc.mjs@@ -136,19 +136,39 @@ function App() {},],},+ {+ title: 'Using a Theme from an Integration',+ category: 'guide',+ content: [+ {+ type: 'prose',+ text: 'Install the integration as a direct dependency and Astryx discovers its source themes and guide topics without an `astryx.config` file. Install Core too because the copied source imports `defineTheme` from `@astryxdesign/core/theme`.',+ },+ {+ type: 'code',+ lang: 'bash',+ label: 'Install, inspect, copy, and build',+ code: 'npm install @astryxdesign/core @acme/brand-integration\nastryx theme list --package @acme/brand-integration\nastryx docs brand-theme\nastryx theme add ocean --package @acme/brand-integration\nastryx theme build src/themes/ocean/oceanTheme.ts',+ },+ {+ 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`.',+ },+ ],+ },{title: 'Creating a Custom Theme',category: 'guide',content: [{type: 'prose',- text: 'Start from a theme we ship, or write one from scratch with defineTheme. Only override tokens that differ from defaults; omitted tokens use the design system defaults.',+ text: 'Start from a bundled theme or one contributed by an installed integration, or write one from scratch with defineTheme. `theme list` names each owner; when packages share a slug, pass `--package`. Only override tokens that differ from defaults; omitted tokens use the design system defaults.',},{type: 'code',lang: 'bash',label: 'Browse, then copy a theme in as editable source',- code: 'astryx theme list\nastryx theme add stone',+ code: 'astryx theme list\nastryx theme add stone\nastryx theme add ocean --package @acme/themes',},{type: 'prose',diff --git a/packages/cli/assets/docs/theme.doc.zh.mjs b/packages/cli/assets/docs/theme.doc.zh.mjsindex 58392b697e..88684ebff0 100644--- a/packages/cli/assets/docs/theme.doc.zh.mjs+++ b/packages/cli/assets/docs/theme.doc.zh.mjs@@ -8,7 +8,7 @@ export const docsZh = {{ section: 'Quick Start', title: '快速开始', content: [null, null, null, null, { type: 'prose', text: '默认导入使用运行时样式注入。/built 导入使用预编译 CSS(需配合 theme.css)。' }] },{ section: 'Available Themes', title: '可用主题', content: [null, null, { type: 'prose', text: '已发布主题:neutral(推荐起点)、butter、chocolate、gothic(仅暗色)、matcha、stone、y2k。@astryxdesign/theme-{name} = 源码版(运行时注入)。@astryxdesign/theme-{name}/built = 优化版(配合 theme.css)。' }] },{ section: 'Theme Props', title: 'Theme 属性', content: [null] },- { section: 'Creating a Custom Theme', title: '创建自定义主题', content: [{ type: 'prose', text: '用 `theme list` + `theme add <slug>` 从内置主题开始,或用 defineTheme 从零编写。只覆盖与默认值不同的令牌。' }, null, { type: 'prose', text: '`astryx theme template` 会写入 theme.template.ts:带注释的完整参考,涵盖每个 defineTheme 字段、令牌族和覆盖语法,并标明打印各自参考的 CLI 命令。' }] },+ { section: 'Creating a Custom Theme', title: '创建自定义主题', content: [{ type: 'prose', text: '用 `theme list` + `theme add <slug>` 从内置主题或已安装集成提供的主题开始;重名时传 `--package`。也可以用 defineTheme 从零编写。只覆盖与默认值不同的令牌。' }, null, { type: 'prose', text: '`astryx theme template` 会写入 theme.template.ts:带注释的完整参考,涵盖每个 defineTheme 字段、令牌族和覆盖语法,并标明打印各自参考的 CLI 命令。' }] },{ section: 'defineTheme', title: 'defineTheme', content: [{ type: 'prose', text: '支持比例配置(color、typography、radius、motion)+ 显式令牌覆盖 + 组件覆盖。color 通过 HCT 从 accent 派生完整调色板;accent 接受单个十六进制值或 [light, dark] 元组(每个模式使用各自的种子色)。tokens 覆盖按令牌逐个生效;--color-on-accent 始终由 color.accent 计算得出,因此优先使用元组 accent 而不是覆盖 --color-accent。' }, null, null] },{ section: 'Building Themes for Production', title: '生产构建', content: [{ type: 'prose', text: 'astryx theme build 将 defineTheme 编译为静态 CSS。输出 .css + .js(__built:true)+ .d.ts。' }, null, null, null, { type: 'prose', text: '当前 theme build 仅在检测到 icons: 字段使用的具名导入时,才在生成的模块中导入图标注册表;它不会编译注册表模块。defineTheme 在运行时接受的内联注册表(包括本地常量)目前会在构建产物中被省略。使用此构建流程时,请把注册表移到独立模块并使用具名导入。以下示例适用于使用 React 和 lucide-react 的注册表。' }, null, { type: 'prose', text: '上例中生成的主题从 dist 导入 ./icons.mjs。如果跳过第二条命令,theme build 仍可能成功,但加载或打包生成的模块都会因缺少 dist/icons.mjs 而失败。--icons-specifier 只更改生成的导入,不会创建或验证目标文件。路径应相对于生成的 JS 文件可解析。将 react 和图标库标记为 external,避免在注册表中重复打包这些依赖。' }, { type: 'prose', text: '不传 --icons-specifier 时,会原样保留检测到的源码导入路径。默认不传 --out 时,打包器可以把无扩展名的 ./icons 解析为旁边的 icons.tsx;Node ESM 不执行这种查找,会报 ERR_MODULE_NOT_FOUND。用 --out 移动输出位置也会改变相对导入的解析位置;使用打包器并不意味着它能自动找到原来的源码。' }, null, null, null] },{ section: 'Runtime vs Built Themes', title: '运行时 vs 构建', content: [{ type: 'prose', text: '运行时:useInsertionEffect 在客户端注入样式。构建:静态 CSS 在首次渲染时就存在。SSR 应用请使用 /built + theme.css。' }, null, null, null] },diff --git a/packages/cli/authoring/doctypes/_schema.mjs b/packages/cli/authoring/doctypes/_schema.mjsindex 59da06d234..8e86c19648 100644--- a/packages/cli/authoring/doctypes/_schema.mjs+++ b/packages/cli/authoring/doctypes/_schema.mjs@@ -46,6 +46,7 @@ const BaseDocFields = {displayName: z.string().optional(),description: z.string().optional(),usage: z.unknown().optional(),+ import: z.string().min(1).optional(),group: z.string().optional(),category: z.string().optional(),keywords: z.array(z.string()).optional(),@@ -139,7 +140,11 @@ export const SchemaDocKindSchema = zappliesTo: z.string().optional(),fields: z.array(SchemaFieldSchema),examples: z- .array(z.object({label: z.string().optional(), code: z.string()}).passthrough())+ .array(+ z+ .object({label: z.string().optional(), code: z.string()})+ .passthrough(),+ ).optional(),notes: z.array(z.unknown()).optional(),})diff --git a/packages/cli/authoring/doctypes/component/component.doc.mjs b/packages/cli/authoring/doctypes/component/component.doc.mjsindex c07c24cf0b..2bb83a9258 100644--- a/packages/cli/authoring/doctypes/component/component.doc.mjs+++ b/packages/cli/authoring/doctypes/component/component.doc.mjs@@ -46,6 +46,12 @@ export const doc = {description:'Optional public registry identity. The converter derives a stable kebab-case slug from `name`; set `slug` only to override it, and keep prior relative paths in `aliases` after a published rename.',},+ {+ name: 'import',+ type: 'string',+ description:+ 'Exact public package specifier consumers use to import an integration-owned component. The packed-package gate resolves this specifier and verifies it exports the component name.',+ },{name: 'keywords',type: 'string[]',diff --git a/packages/cli/authoring/doctypes/component/type.ts b/packages/cli/authoring/doctypes/component/type.tsindex e3689bf91e..46f1d0ed28 100644--- a/packages/cli/authoring/doctypes/component/type.ts+++ b/packages/cli/authoring/doctypes/component/type.ts@@ -45,6 +45,8 @@ export interface ComponentBaseDoc {* regex derivation. Backfill with* `apps/docsite/scripts/backfill-display-name.mjs`. */displayName: string;+ /** Exact consumer import specifier for integration-owned components. */+ import?: string;/** Search keywords for CLI discovery. Terms a developer might type when* looking for this component: synonyms, related UI concepts, and common* names from other design systems (MUI, Chakra, Radix, shadcn).diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjsindex a197675f03..81f4a76274 100644--- a/packages/cli/authoring/integration/integration.doc.mjs+++ b/packages/cli/authoring/integration/integration.doc.mjs@@ -15,8 +15,8 @@ export const doc = {description:'The astryx.integration.* manifest that sits beside an integration ' +"package's package.json. Points the CLI at the package's components, " +- 'templates, codemods, doc topics, and managed agent guidance, and where to ' +- 'file issues. Every field is optional.',+ 'templates, codemods, doc topics, source themes, and managed agent guidance, ' ++ 'and where to file issues. Every field is optional.',appliesTo: 'astryx.integration.{ts,mjs,js}',fields: [{@@ -46,6 +46,13 @@ export const doc = {'Relative path to the reference-docs (topics) root (resolved to absolute). Every {topic}.doc.{ts,mjs,js} under it is served by `astryx docs` beside the built-in topics; a topic may also declare `replaces` or `extends` to take the place of a built-in one or merge onto it.',example: "'./docs'",},+ {+ 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`.',+ example: "'./themes'",+ },{name: 'agentDocs',type: '{ append?: readonly string[] }',@@ -68,6 +75,7 @@ export const doc = {templates: './src/templates',codemods: './codemods',docs: './docs',+ themes: './themes',agentDocs: {append: ['Run acme verify before finishing.'],},@@ -92,6 +100,10 @@ export const doc = {'text. The configured project may contain at most 32 integration lines ' +'total.',},+ {+ type: 'prose',+ text: 'A themes root is forward-compatible but version-gated: a CLI released before this field ignores it with a warning and continues loading every contribution kind it understands. That older CLI cannot list or add the contributed themes.',+ },{type: 'prose',text:diff --git a/packages/cli/authoring/integration/parse.test.mjs b/packages/cli/authoring/integration/parse.test.mjsindex 99d4db80c7..fdb03e0771 100644--- a/packages/cli/authoring/integration/parse.test.mjs+++ b/packages/cli/authoring/integration/parse.test.mjs@@ -28,6 +28,9 @@ describe('parseIntegration (load boundary)', () => {components: './src',});expect(parseIntegration({docs: './docs'})).toEqual({docs: './docs'});+ expect(parseIntegration({themes: './themes'})).toEqual({+ themes: './themes',+ });expect(() =>parseIntegration({components: './c', issuesUrl: 'https://example.com/i'}),).not.toThrow();@@ -38,12 +41,14 @@ describe('parseIntegration (load boundary)', () => {// integration is published once and installed against many CLI versions.// Rejecting the manifest took the whole package's contributions down with// it, silently, on every older consumer (#5119).- expect(parseIntegration({components: './src', futureRoot: './future'})).toEqual({+ expect(+ parseIntegration({components: './src', futureRoot: './future'}),+ ).toEqual({components: './src',});- expect(unknownIntegrationKeys({components: './src', futureRoot: './future'})).toEqual([- 'futureRoot',- ]);+ expect(+ unknownIntegrationKeys({components: './src', futureRoot: './future'}),+ ).toEqual(['futureRoot']);expect(unknownIntegrationKeys({components: './src'})).toEqual([]);// Not a manifest at all — nothing to report, and the parser owns the error.expect(unknownIntegrationKeys(null)).toEqual([]);diff --git a/packages/cli/authoring/integration/schema.mjs b/packages/cli/authoring/integration/schema.mjsindex cf10f460b1..f035211b98 100644--- a/packages/cli/authoring/integration/schema.mjs+++ b/packages/cli/authoring/integration/schema.mjs@@ -70,6 +70,7 @@ export const integrationBaseSchema = z.object({templates: z.string().optional(),codemods: z.string().optional(),docs: z.string().optional(),+ themes: z.string().optional(),issuesUrl: z.string().url().optional(),});diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.tsindex 1aacb32ef1..6802600a74 100644--- a/packages/cli/authoring/integration/type.ts+++ b/packages/cli/authoring/integration/type.ts@@ -26,6 +26,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. */+ themes?: string;/** Static package guidance appended to the CLI-owned managed agent block. */agentDocs?: {append?: readonly string[];diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjsindex afec3af87a..a909add0e0 100644--- a/packages/cli/clients/cli/commands/build-theme.mjs+++ b/packages/cli/clients/cli/commands/build-theme.mjs@@ -35,9 +35,11 @@ import {emit, section, text, list, code} from '../formatters/index.mjs';import {logger} from '../../../api/logger.mjs';import {cliError} from '../lib/cli-error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {Project} from '../../../foundation/config/project.mjs';+import {warnOnIntegrationIssues} from '../../../foundation/integrations/integration-warnings.mjs';import {themeAdd} from '../../../api/theme/add/add.mjs';import {themeTemplate} from '../../../api/theme/template/template.mjs';-import {themeList} from '../../../api/theme/list/list.mjs';+import {themeListAvailable} from '../../../api/theme/list/list.mjs';import {themeTargets} from '../../../api/theme/targets/targets.mjs';import {serializePaletteCandidate,@@ -55,7 +57,7 @@ import {doc as themeTargetsCommand} from './theme-targets.doc.mjs';import {doc as themePaletteGroup} from './theme-palette.doc.mjs';import {doc as themePaletteGenerateCommand} from './theme-palette-generate.doc.mjs';import {doc as themeBuildFn} from '../../../api/theme/themeBuild.doc.mjs';-import {doc as themeListFn} from '../../../api/theme/themeList.doc.mjs';+import {doc as themeListFn} from '../../../api/theme/themeListAvailable.doc.mjs';import {doc as themeAddFn} from '../../../api/theme/themeAdd.doc.mjs';import {doc as themeTemplateFn} from '../../../api/theme/themeTemplate.doc.mjs';import {doc as themeTargetsFn} from '../../../api/theme/themeTargets.doc.mjs';@@ -181,14 +183,28 @@ async function runThemeBuildWatch(entries, options) {}/**- * Emit the bundled themes as a bulleted list plus the `theme add` usage hint —- * the human projection of a `theme.list` envelope. Shared by `theme list` and- * the list affordance of `theme add` (bare `theme add` / `--list`).+ * Print the standard integration issue nudge without changing command results.+ * @param {boolean} json+ */+async function warnOnThemeIntegrationIssues(json) {+ try {+ const project = await Project.load(process.cwd());+ await project.themes();+ await warnOnIntegrationIssues(project.loadedIntegrations, {json});+ } catch {+ // Never let the nudge break the command.+ }+}++/**+ * Emit available themes as a bulleted list plus the `theme add` usage hint —+ * the human projection of a `theme.list` envelope. Each row names its owner so+ * duplicate slugs are distinguishable.* @param {import('../../../api/theme/theme.type.mjs').ThemeListEntry[]} themes*/function printThemeList(themes) {if (themes.length === 0) {- emit(text('No themes are bundled with this CLI build.'));+ emit(text('No themes are available in this project.'));return;}const run = getCliInvocation();@@ -196,7 +212,8 @@ function printThemeList(themes) {section('Themes'),list(themes.map(t => {- const head = t.maintained ? `${t.slug} (maintained)` : t.slug;+ const status = t.maintained ? 'maintained' : 'example';+ const head = `${t.slug} (${status}, ${t.package})`;return t.description ? [head, t.description] : head;}),),@@ -523,12 +540,15 @@ export function registerTheme(program) {defineCommand(theme, themeListCommand, {fn: themeListFn,- action: async () => {+ action: async (/** @type {{package?: string}} */ options) => {const json = program.opts().json || false;/** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse} */let result;try {- result = themeList();+ result = await themeListAvailable({+ cwd: process.cwd(),+ package: options.package,+ });} catch (e) {const err =/** @type {import('../../../api/error.mjs').AstryxError} */ (e);@@ -538,6 +558,7 @@ export function registerTheme(program) {});}+ await warnOnThemeIntegrationIssues(json);const answered = resultSet({count: result.data.length,resultKind: 'theme',@@ -557,7 +578,7 @@ export function registerTheme(program) {action: async (/** @type {string | undefined} */ slug,/** @type {string | undefined} */ targetPath,- /** @type {{list?: boolean, overwrite?: boolean}} */ options,+ /** @type {{list?: boolean, overwrite?: boolean, package?: string}} */ options,) => {const json = program.opts().json || false;@@ -570,11 +591,12 @@ export function registerTheme(program) {try {result =options.list || !slug- ? themeList()+ ? await themeListAvailable({cwd: process.cwd(), package: options.package}): await themeAdd(slug, {targetPath,overwrite: options.overwrite,cwd: process.cwd(),+ package: options.package,});} catch (e) {const err =@@ -585,7 +607,8 @@ export function registerTheme(program) {});}- // `--list` (or no slug) browses the bundled themes; naming one copies it+ await warnOnThemeIntegrationIssues(json);+ // `--list` (or no slug) browses all available themes; naming one copies it// into the project, which is an effect with nothing to count.const answered =result.type === 'theme.list'@@ -603,13 +626,20 @@ export function registerTheme(program) {}// theme.add — print where files landed + how to use the theme.- const {displayName, outputDir, entry, exportName, files} = result.data;+ const {+ displayName,+ outputDir,+ entry,+ exportName,+ files,+ package: owner,+ } = result.data;const entryModule = importSpecifier(outputDir,entry.replace(/\.tsx?$/, ''),);emit(- text(`[ok] Added ${displayName} theme to ${outputDir}/`),+ text(`[ok] Added ${displayName} theme from ${owner} to ${outputDir}/`),list(files.map(f => `${outputDir}/${f}`)),text('Use it in your app (import path is relative to a file in src/ — adjust if yours lives elsewhere):',diff --git a/packages/cli/clients/cli/commands/doctor-integration.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration.doc.mjsindex 309b96a55c..dec0a1eb65 100644--- a/packages/cli/clients/cli/commands/doctor-integration.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration.doc.mjs@@ -14,7 +14,7 @@ export const doc = {description:'The integration-authoring diagnostics group. Validate a manifest and all ' +'contributions with `validate`, or check templates, components, and docs ' +- 'against built-in Core identities before publishing.',+ 'against built-in Core identities before publishing. Theme catalogs are checked by validate.',subcommands: ['validate', 'templates', 'components', 'docs'],examples: [{diff --git a/packages/cli/clients/cli/commands/integration-add.doc.mjs b/packages/cli/clients/cli/commands/integration-add.doc.mjsnew file mode 100644index 0000000000..5ad4ca7635--- /dev/null+++ b/packages/cli/clients/cli/commands/integration-add.doc.mjs@@ -0,0 +1,88 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'integration add',+ displayName: 'astryx integration add',+ namespace: 'cli',+ 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.',+ fn: 'integrationAdd',+ args: [+ {+ name: 'kind',+ param: 'kind',+ required: true,+ description: 'component, doc, template, codemod, agent-doc, or theme',+ },+ {+ name: 'name',+ param: 'name',+ required: true,+ description:+ 'Contribution name; for agent-doc this is the literal guidance line',+ },+ ],+ options: [+ {+ flag: '--dry-run',+ param: 'options.dryRun',+ description: 'Validate and show planned writes without changing files',+ },+ {+ flag: '--type <type>',+ param: 'options.templateType',+ choices: ['page', 'block'],+ description: 'Template type (page or block); only valid for template',+ },+ {+ flag: '--replaces <topic>',+ param: 'options.replaces',+ description: 'Replace an existing doc topic; only valid for doc',+ },+ {+ flag: '--extends <topic>',+ param: 'options.extends',+ description: 'Extend an existing doc topic; only valid for doc',+ },+ {+ flag: '--to <version>',+ param: 'options.to',+ description: 'Target version for a codemod; required for codemod',+ },+ ],+ examples: [+ {+ label: 'Add a component',+ cli: 'astryx integration add component AcmeWidget',+ },+ {label: 'Add a doc topic', cli: 'astryx integration add doc deploying'},+ {+ label: 'Add a page template',+ cli: 'astryx integration add template dashboard',+ },+ {+ label: 'Add a codemod',+ cli: 'astryx integration add codemod rename-widget --to 1.2.0',+ },+ {+ label: 'Add agent guidance',+ cli: "astryx integration add agent-doc 'Run acme verify before finishing.'",+ },+ {label: 'Add a source theme', cli: 'astryx integration add theme ocean'},+ {+ label: 'Preview',+ cli: 'astryx integration add component AcmeWidget --dry-run --json',+ },+ ],+ exitCodes: [+ {code: 0, when: 'the contribution is written or the dry run succeeds'},+ {+ code: 1,+ when: 'the kind, name, options, package, or target files are invalid or conflict',+ },+ ],+ related: ['integration pack', 'doctor integration validate', 'theme add'],+};diff --git a/packages/cli/clients/cli/commands/integration-authoring.test.mjs b/packages/cli/clients/cli/commands/integration-authoring.test.mjsnew file mode 100644index 0000000000..b51de6d637--- /dev/null+++ b/packages/cli/clients/cli/commands/integration-authoring.test.mjs@@ -0,0 +1,177 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {runCli} from '../../../test-utils/run-cli.mjs';++let tmpDir;++function parseEnvelope(stdout) {+ return JSON.parse(stdout.trim());+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-integration-authoring-cli-'),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify({+ name: '@acme/widgets',+ version: '1.0.0',+ files: [],+ })}\n`,+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('integration authoring CLI', () => {+ it('dry-runs and writes through the same generic add command', async () => {+ const planned = await runCli(+ ['integration', 'add', 'component', 'AcmeWidget', '--dry-run', '--json'],+ tmpDir,+ );+ expect(planned.status).toBe(0);+ const plan = parseEnvelope(planned.stdout);+ expect(plan).toMatchObject({+ type: 'integration.add',+ data: {+ kind: 'component',+ name: 'AcmeWidget',+ written: false,+ dryRun: true,+ },+ });+ expect(fs.existsSync(path.join(tmpDir, 'components'))).toBe(false);++ const written = await runCli(+ ['integration', 'add', 'component', 'AcmeWidget', '--json'],+ tmpDir,+ );+ expect(written.status).toBe(0);+ const receipt = parseEnvelope(written.stdout);+ expect(receipt).toMatchObject({+ type: 'integration.add',+ data: {+ kind: 'component',+ name: 'AcmeWidget',+ root: {path: './components', created: true},+ manifest: 'astryx.integration.mjs',+ written: true,+ dryRun: false,+ },+ });+ expect(receipt.data.files).toEqual(plan.data.files);+ });++ it('makes generated contributions visible without publishing or a config', async () => {+ for (const args of [+ ['component', 'AcmeWidget'],+ ['doc', 'local-guide'],+ ['template', 'local-page'],+ ['theme', 'ocean'],+ ]) {+ const added = await runCli(+ ['integration', 'add', ...args, '--json'],+ tmpDir,+ );+ expect(added.status).toBe(0);+ }++ const components = parseEnvelope(+ (await runCli(['component', '--list', '--json'], tmpDir)).stdout,+ );+ expect(+ Object.values(components.data.components)+ .flat()+ .some(+ component =>+ component.name === 'AcmeWidget' &&+ component.package === '@acme/widgets',+ ),+ ).toBe(true);++ const docs = parseEnvelope(+ (await runCli(['docs', 'local-guide', '--json'], tmpDir)).stdout,+ );+ expect(docs.data).toMatchObject({+ name: 'local-guide',+ });++ const templates = parseEnvelope(+ (await runCli(['template', '--list', '--json'], tmpDir)).stdout,+ );+ expect(templates.data).toContainEqual(+ expect.objectContaining({+ id: 'local-page',+ package: '@acme/widgets',+ }),+ );++ const themes = parseEnvelope(+ (await runCli(['theme', 'list', '--json'], tmpDir)).stdout,+ );+ expect(themes.data).toContainEqual(+ expect.objectContaining({slug: 'ocean', package: '@acme/widgets'}),+ );+ });++ it('packs the generated contribution and proves the consumer inventory', async () => {+ const added = await runCli(+ ['integration', 'add', 'component', 'AcmeWidget', '--json'],+ tmpDir,+ );+ expect(added.status).toBe(0);++ const checked = await runCli(+ ['integration', 'pack', '--check', '--json'],+ tmpDir,+ );+ expect(checked.status).toBe(0);+ expect(parseEnvelope(checked.stdout)).toMatchObject({+ type: 'integration.pack-check',+ data: {+ name: '@acme/widgets',+ version: '1.0.0',+ packable: true,+ contributions: {+ local: {components: ['AcmeWidget']},+ packed: {components: ['AcmeWidget']},+ },+ },+ });+ });++ it('requires the explicit --check gate on pack', async () => {+ const result = await runCli(['integration', 'pack', '--json'], tmpDir);+ expect(result.status).not.toBe(0);+ expect(parseEnvelope(result.stdout)).toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ error: 'Pass --check to verify the integration tarball.',+ });+ });++ it('refuses kind-specific options on another kind', async () => {+ const result = await runCli(+ [+ 'integration',+ 'add',+ 'component',+ 'AcmeWidget',+ '--to',+ '1.0.0',+ '--json',+ ],+ tmpDir,+ );+ expect(result.status).not.toBe(0);+ expect(parseEnvelope(result.stdout)).toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ error: 'Option "to" does not apply to integration kind "component".',+ });+ });+});diff --git a/packages/cli/clients/cli/commands/integration-pack.doc.mjs b/packages/cli/clients/cli/commands/integration-pack.doc.mjsnew file mode 100644index 0000000000..77120fe33e--- /dev/null+++ b/packages/cli/clients/cli/commands/integration-pack.doc.mjs@@ -0,0 +1,34 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'integration pack',+ displayName: 'astryx integration pack',+ namespace: 'cli',+ 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.',+ fn: 'integrationPackCheck',+ options: [+ {+ flag: '--check',+ description: 'Run the packed-package verification gate',+ },+ ],+ examples: [+ {label: 'Verify before publishing', cli: 'astryx integration pack --check'},+ {+ label: 'Machine-readable result',+ cli: 'astryx integration pack --check --json',+ },+ ],+ exitCodes: [+ {code: 0, when: 'the packed package exposes the same valid contributions'},+ {+ code: 1,+ when: '--check is omitted or the tarball is incomplete or invalid',+ },+ ],+ related: ['integration add', 'doctor integration validate'],+};diff --git a/packages/cli/clients/cli/commands/integration-real-world.test.mjs b/packages/cli/clients/cli/commands/integration-real-world.test.mjsnew file mode 100644index 0000000000..b6c281d0f8--- /dev/null+++ b/packages/cli/clients/cli/commands/integration-real-world.test.mjs@@ -0,0 +1,464 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Real package-boundary coverage for integration authoring. Authors a+ * provider through the CLI, packs it, installs the tarball into a separate+ * no-config consumer, then exercises the contributed docs and source theme.+ */++import {afterEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {spawnSync} from 'node:child_process';+import {runCli} from '../../../test-utils/run-cli.mjs';++let rootDir;++function parseEnvelope(stdout) {+ return JSON.parse(stdout.trim());+}++function writeJson(file, value) {+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);+}++function runNpm(args, cwd) {+ const command = process.platform === 'win32' ? 'npm.cmd' : 'npm';+ const result = spawnSync(command, args, {+ cwd,+ encoding: 'utf-8',+ timeout: 60_000,+ env: {+ ...process.env,+ npm_config_audit: 'false',+ npm_config_fund: 'false',+ npm_config_update_notifier: 'false',+ npm_config_cache: path.join(rootDir, '.npm-cache'),+ },+ });+ if (result.error || result.status !== 0) {+ throw new Error(+ `npm ${args[0]} failed: ${result.error?.message ?? result.stderr.trim()}`,+ );+ }+ return result.stdout;+}++afterEach(() => {+ if (rootDir) fs.rmSync(rootDir, {recursive: true, force: true});+ rootDir = undefined;+});++describe('integration authoring across a real npm package boundary', () => {+ it('authors, packs, installs, discovers, copies, and builds a theme with guides', async () => {+ rootDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-theme-provider-consumer-'),+ );+ const providerDir = path.join(rootDir, 'provider');+ const consumerDir = path.join(rootDir, 'consumer');+ const packDir = path.join(rootDir, 'packed');+ fs.mkdirSync(providerDir);+ fs.mkdirSync(consumerDir);+ fs.mkdirSync(packDir);++ writeJson(path.join(providerDir, 'package.json'), {+ name: '@acme/brand-integration',+ version: '1.0.0',+ type: 'module',+ files: ['README.md'],+ });+ fs.writeFileSync(+ path.join(providerDir, 'README.md'),+ '# Acme brand integration\n',+ );++ for (const [kind, name] of [+ ['theme', 'ocean'],+ ['doc', 'brand-theme'],+ ['doc', 'theme-migration'],+ ]) {+ const added = await runCli(+ ['integration', 'add', kind, name, '--json'],+ providerDir,+ );+ expect(added.status, added.stderr).toBe(0);+ expect(parseEnvelope(added.stdout)).toMatchObject({+ type: 'integration.add',+ data: {kind, name, written: true, dryRun: false},+ });+ }++ const themeDir = path.join(providerDir, 'themes', 'ocean');+ const paletteConfig = path.join(providerDir, 'palette.config.json');+ writeJson(paletteConfig, {+ modeStrategy: 'light-and-dark',+ stops: [20, 50, 80],+ families: [{id: 'blue', seed: '#0074e2'}],+ });+ const paletteOutput = path.join(+ 'themes',+ 'ocean',+ 'tokens',+ 'ocean.palette.ts',+ );+ const generatedPalette = await runCli(+ [+ 'theme',+ 'palette',+ 'generate',+ 'palette.config.json',+ '--out',+ paletteOutput,+ '--json',+ ],+ providerDir,+ );+ expect(generatedPalette.status, generatedPalette.stderr).toBe(0);+ expect(parseEnvelope(generatedPalette.stdout)).toMatchObject({+ type: 'theme.palette.generate',+ data: {+ output: paletteOutput,+ receipt: path.join(+ 'themes',+ 'ocean',+ 'tokens',+ 'ocean.palette.receipt.json',+ ),+ written: true,+ },+ });++ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.ts'),+ `import {defineTheme} from '@astryxdesign/core/theme';+import {palette} from './tokens/ocean.palette';++export const oceanTheme = defineTheme({+ name: 'ocean',+ tokens: {'--color-accent': palette.blue.light[50]},+});+`,+ );+ 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'),+ );+ expect(providerPackage.files).toEqual([+ 'README.md',+ 'themes',+ 'astryx.integration.mjs',+ 'docs',+ ]);++ const checked = await runCli(+ ['integration', 'pack', '--check', '--json'],+ providerDir,+ );+ expect(checked.status, checked.stderr).toBe(0);+ const checkReceipt = parseEnvelope(checked.stdout);+ expect(checkReceipt).toMatchObject({+ type: 'integration.pack-check',+ data: {+ name: '@acme/brand-integration',+ packable: true,+ contributions: {+ local: {+ themes: [{slug: 'ocean', exportName: 'oceanTheme'}],+ docs: ['brand-theme', 'theme-migration'],+ },+ },+ },+ });+ expect(checkReceipt.data.contributions.packed).toEqual(+ checkReceipt.data.contributions.local,+ );++ const packOutput = JSON.parse(+ runNpm(+ ['pack', '--json', '--silent', `--pack-destination=${packDir}`],+ providerDir,+ ),+ );+ const tarball = path.join(packDir, packOutput[0].filename);+ expect(fs.existsSync(tarball)).toBe(true);++ writeJson(path.join(consumerDir, 'package.json'), {+ name: 'theme-consumer',+ version: '1.0.0',+ private: true,+ type: 'module',+ });+ runNpm(+ [+ 'install',+ '--ignore-scripts',+ '--offline',+ '--no-audit',+ '--no-fund',+ '--package-lock=false',+ tarball,+ ],+ consumerDir,+ );++ const alternateProviderDir = path.join(rootDir, 'alternate-provider');+ fs.mkdirSync(alternateProviderDir);+ writeJson(path.join(alternateProviderDir, 'package.json'), {+ name: '@acme/alternate-brand',+ version: '1.0.0',+ type: 'module',+ files: [],+ });+ const alternateAdded = await runCli(+ ['integration', 'add', 'theme', 'ocean', '--json'],+ alternateProviderDir,+ );+ expect(alternateAdded.status, alternateAdded.stderr).toBe(0);+ const alternatePack = JSON.parse(+ runNpm(+ ['pack', '--json', '--silent', `--pack-destination=${packDir}`],+ alternateProviderDir,+ ),+ );+ runNpm(+ [+ 'install',+ '--ignore-scripts',+ '--offline',+ '--no-audit',+ '--no-fund',+ '--package-lock=false',+ path.join(packDir, alternatePack[0].filename),+ ],+ consumerDir,+ );++ const installedDir = path.join(+ consumerDir,+ 'node_modules',+ '@acme',+ 'brand-integration',+ );+ expect(fs.lstatSync(installedDir).isSymbolicLink()).toBe(false);+ const alternateInstalledDir = path.join(+ consumerDir,+ 'node_modules',+ '@acme',+ 'alternate-brand',+ );+ expect(fs.lstatSync(alternateInstalledDir).isSymbolicLink()).toBe(false);++ // The consumer installs both providers from tarballs. Link this checkout's+ // Core package as the consumer's normal app dependency so the copied source+ // can resolve the same peer it would get from `npm install @astryxdesign/core`.+ const coreScope = path.join(consumerDir, 'node_modules', '@astryxdesign');+ const coreLink = path.join(coreScope, 'core');+ fs.mkdirSync(coreScope, {recursive: true});+ fs.symlinkSync(+ path.join(process.cwd(), 'packages', 'core'),+ coreLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ fs.rmSync(providerDir, {recursive: true, force: true});+ fs.rmSync(alternateProviderDir, {recursive: true, force: true});++ const consumerPackageFile = path.join(consumerDir, 'package.json');+ const consumerPackage = JSON.parse(+ fs.readFileSync(consumerPackageFile, 'utf-8'),+ );+ const providerSpec =+ consumerPackage.dependencies['@acme/brand-integration'];+ delete consumerPackage.dependencies['@acme/brand-integration'];+ writeJson(consumerPackageFile, consumerPackage);+ const undeclared = await runCli(+ ['theme', 'list', '--package', '@acme/brand-integration', '--json'],+ consumerDir,+ );+ expect(undeclared.status, undeclared.stderr).toBe(0);+ expect(parseEnvelope(undeclared.stdout).data).toEqual([]);++ consumerPackage.devDependencies = {+ '@acme/brand-integration': providerSpec,+ };+ writeJson(consumerPackageFile, consumerPackage);+ const devLinked = await runCli(+ ['theme', 'list', '--package', '@acme/brand-integration', '--json'],+ consumerDir,+ );+ expect(devLinked.status, devLinked.stderr).toBe(0);+ expect(parseEnvelope(devLinked.stdout).data).toContainEqual(+ expect.objectContaining({+ slug: 'ocean',+ package: '@acme/brand-integration',+ }),+ );++ delete consumerPackage.devDependencies;+ consumerPackage.optionalDependencies = {+ '@acme/brand-integration': providerSpec,+ };+ writeJson(consumerPackageFile, consumerPackage);+ const optionalLinked = await runCli(+ ['theme', 'list', '--package', '@acme/brand-integration', '--json'],+ consumerDir,+ );+ expect(optionalLinked.status, optionalLinked.stderr).toBe(0);+ expect(parseEnvelope(optionalLinked.stdout).data).toContainEqual(+ expect.objectContaining({+ slug: 'ocean',+ package: '@acme/brand-integration',+ }),+ );++ delete consumerPackage.optionalDependencies;+ consumerPackage.dependencies['@acme/brand-integration'] = providerSpec;+ writeJson(consumerPackageFile, consumerPackage);++ const listed = await runCli(['theme', 'list', '--json'], consumerDir);+ expect(listed.status, listed.stderr).toBe(0);+ expect(parseEnvelope(listed.stdout).data).toContainEqual(+ expect.objectContaining({+ slug: 'ocean',+ package: '@acme/brand-integration',+ }),+ );++ for (const topic of ['brand-theme', 'theme-migration']) {+ const guide = await runCli(['docs', topic, '--json'], consumerDir);+ expect(guide.status, guide.stderr).toBe(0);+ expect(parseEnvelope(guide.stdout).data).toMatchObject({name: topic});+ }++ const ambiguous = await runCli(+ ['theme', 'add', 'ocean', 'src/themes/ambiguous', '--json'],+ consumerDir,+ );+ expect(ambiguous.status).not.toBe(0);+ expect(parseEnvelope(ambiguous.stdout)).toMatchObject({+ code: 'ERR_AMBIGUOUS_THEME',+ });++ const target = path.join('src', 'themes', 'acme-ocean');+ const copied = await runCli(+ [+ 'theme',+ 'add',+ 'ocean',+ target,+ '--package',+ '@acme/brand-integration',+ '--json',+ ],+ consumerDir,+ );+ expect(copied.status, copied.stderr).toBe(0);+ expect(parseEnvelope(copied.stdout)).toMatchObject({+ type: 'theme.add',+ data: {+ slug: 'ocean',+ package: '@acme/brand-integration',+ outputDir: target,+ files: [+ 'oceanTheme.ts',+ 'tokens/ocean.palette.ts',+ 'tokens/ocean.palette.receipt.json',+ ],+ },+ });+ expect(+ fs.readFileSync(+ path.join(consumerDir, target, 'tokens', 'ocean.palette.ts'),+ 'utf-8',+ ),+ ).toContain('export const palette');+ expect(+ JSON.parse(+ fs.readFileSync(+ path.join(+ consumerDir,+ target,+ 'tokens',+ 'ocean.palette.receipt.json',+ ),+ 'utf-8',+ ),+ ).recipe,+ ).toBe('astryx-oklch-v1');++ const copiedEntry = path.join(target, 'oceanTheme.ts');+ const built = await runCli(+ ['theme', 'build', copiedEntry, '--json'],+ consumerDir,+ );+ expect(built.status, `${built.stdout}\n${built.stderr}`).toBe(0);+ const buildReceipt = parseEnvelope(built.stdout);+ expect(buildReceipt).toMatchObject({+ type: 'theme.build',+ data: {name: 'ocean'},+ });+ for (const output of Object.values(buildReceipt.data.outputs)) {+ expect(fs.existsSync(path.join(consumerDir, output))).toBe(true);+ }++ const duplicate = await runCli(+ [+ 'theme',+ 'add',+ 'ocean',+ target,+ '--package',+ '@acme/brand-integration',+ '--json',+ ],+ consumerDir,+ );+ expect(duplicate.status).not.toBe(0);+ expect(parseEnvelope(duplicate.stdout)).toMatchObject({+ code: 'ERR_FILE_EXISTS',+ });+ const overwritten = await runCli(+ [+ 'theme',+ 'add',+ 'ocean',+ target,+ '--package',+ '@acme/brand-integration',+ '--overwrite',+ '--json',+ ],+ consumerDir,+ );+ expect(overwritten.status, overwritten.stderr).toBe(0);+ expect(parseEnvelope(overwritten.stdout).type).toBe('theme.add');++ fs.rmSync(+ path.join(installedDir, 'themes', 'ocean', 'tokens', 'ocean.palette.ts'),+ );+ const corruptedInstall = await runCli(+ [+ 'theme',+ 'add',+ 'ocean',+ 'src/themes/corrupted',+ '--package',+ '@acme/brand-integration',+ '--json',+ ],+ consumerDir,+ );+ expect(corruptedInstall.status).not.toBe(0);+ expect(parseEnvelope(corruptedInstall.stdout)).toMatchObject({+ code: 'ERR_THEME_INVALID',+ error: expect.stringContaining('ocean.palette.ts'),+ });+ }, 120_000);+});diff --git a/packages/cli/clients/cli/commands/integration.doc.mjs b/packages/cli/clients/cli/commands/integration.doc.mjsnew file mode 100644index 0000000000..681c9199f8--- /dev/null+++ b/packages/cli/clients/cli/commands/integration.doc.mjs@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'integration',+ displayName: 'astryx integration',+ namespace: 'cli',+ 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.',+ subcommands: ['add', 'pack'],+ examples: [+ {+ label: 'Add a component',+ cli: 'astryx integration add component AcmeWidget',+ },+ {+ label: 'Check the package tarball',+ cli: 'astryx integration pack --check',+ },+ ],+ exitCodes: [+ {code: 0, when: 'help is shown or a subcommand succeeds'},+ {code: 1, when: 'an unknown subcommand is provided'},+ ],+ related: ['doctor integration', 'theme add'],+};diff --git a/packages/cli/clients/cli/commands/integration.mjs b/packages/cli/clients/cli/commands/integration.mjsnew file mode 100644index 0000000000..4db8108b4d--- /dev/null+++ b/packages/cli/clients/cli/commands/integration.mjs@@ -0,0 +1,153 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CLI bindings for integration authoring and package verification. */++import {integrationAdd} from '../../../api/integration/add-contribution.mjs';+import {integrationPackCheck} from '../../../api/integration/pack-check.mjs';+import {jsonOut} from '../../../foundation/response/json.mjs';+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {NO_RESULT_SET} from '../../../foundation/debug/index.mjs';+import {emit, list, section, text} from '../formatters/index.mjs';+import {cliError} from '../lib/cli-error.mjs';+import {defineCommand} from '../lib/define-command.mjs';+import {doc as integrationGroup} from './integration.doc.mjs';+import {doc as integrationAddCommand} from './integration-add.doc.mjs';+import {doc as integrationPackCommand} from './integration-pack.doc.mjs';+import {doc as integrationAddFn} from '../../../api/integration/integrationAdd.doc.mjs';+import {doc as integrationPackCheckFn} from '../../../api/integration/integrationPackCheck.doc.mjs';++/**+ * @param {import('commander').Command} command+ * @param {string} label+ * @param {unknown} options+ * @param {import('commander').Command} invoked+ */+function showGroupOrUnknown(command, label, options, invoked) {+ const extras = invoked?.args ?? [];+ if (extras.length > 0) {+ return cliError(`unknown subcommand '${label} ${String(extras[0])}'`, {+ suggestions: (command.commands ?? []).map(child => ({+ name: child.name(),+ reason: 'available subcommand',+ })),+ code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND,+ });+ }+ command.outputHelp();+ return NO_RESULT_SET;+}++/** @param {import('commander').Command} program */+export function registerIntegration(program) {+ /** @type {import('commander').Command} */+ let integration;+ integration = defineCommand(program, integrationGroup, {+ action: (options, command) =>+ showGroupOrUnknown(integration, 'integration', options, command),+ });++ defineCommand(integration, integrationAddCommand, {+ fn: integrationAddFn,+ action: async (kind, name, options) => {+ const json = program.opts().json || false;+ let result;+ try {+ result = await integrationAdd(kind, name, {+ cwd: process.cwd(),+ dryRun: options.dryRun,+ templateType: options.type,+ replaces: options.replaces,+ extends: options.extends,+ to: options.to,+ });+ } catch (error) {+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (error);+ return cliError(err.message, {+ suggestions: err.suggestions ?? [],+ code: err.code,+ });+ }++ if (json) {+ jsonOut(result);+ return NO_RESULT_SET;+ }++ const {root, manifest, files, written, dryRun} = result.data;+ const state = dryRun ? 'plan' : written ? 'ok' : 'unchanged';+ const blocks = [+ section(+ dryRun+ ? `${kind} contribution plan`+ : written+ ? `${kind} contribution added`+ : `${kind} contribution unchanged`,+ ),+ text(`[${state}] ${result.data.name}`),+ ];+ if (root != null) {+ blocks.push(+ text(+ `${root.created ? 'Declare' : 'Use'} ${kind} root ${root.path} in ${manifest}.`,+ ),+ );+ } else {+ blocks.push(text(`Update ${manifest}.`));+ }+ if (files.length > 0) blocks.push(list(files));+ emit(...blocks);+ return NO_RESULT_SET;+ },+ });++ defineCommand(integration, integrationPackCommand, {+ fn: integrationPackCheckFn,+ action: async options => {+ if (!options.check) {+ return cliError('Pass --check to verify the integration tarball.', {+ code: ERROR_CODES.ERR_INVALID_ARGUMENT,+ });+ }++ const result = await integrationPackCheck({cwd: process.cwd()});+ if (program.opts().json) {+ jsonOut(result);+ } else {+ const {name, version, packable, tarball, inventory, issues} =+ result.data;+ const identity = [name, version].filter(Boolean).join('@');+ const blocks = [+ section(+ packable+ ? 'Integration package ready'+ : 'Integration package check failed',+ ),+ text(+ `${packable ? '[ok]' : '[fail]'} ${identity || 'local package'}`,+ ),+ ];+ if (tarball != null) {+ blocks.push(+ text(+ `${tarball.fileCount} packed files; ${inventory.packedFiles}/${inventory.expectedFiles} required files present.`,+ ),+ );+ }+ if (issues.length > 0) {+ blocks.push(+ list(+ issues.map(+ issue =>+ `[${issue.severity === 'error' ? 'fail' : 'warn'}] ${issue.message}`,+ ),+ ),+ );+ }+ emit(...blocks);+ }+ if (!result.data.packable) process.exitCode = 1;+ return NO_RESULT_SET;+ },+ });+}diff --git a/packages/cli/clients/cli/commands/theme-add.doc.mjs b/packages/cli/clients/cli/commands/theme-add.doc.mjsindex c017f3d7a6..063ecfaf6c 100644--- a/packages/cli/clients/cli/commands/theme-add.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-add.doc.mjs@@ -16,9 +16,9 @@ export const doc = {namespace: 'cli',summary: 'Scaffold a theme into your project as editable source',description:- "Copies a bundled theme's source into your project so you own it, no theme package " +- 'needed. Writes are staged then renamed, rolling back on failure. Running it with no ' +- 'slug, or with --list, lists the bundled themes instead.',+ "Copies a bundled or installed integration theme's source into your project so you own it. " ++ 'Writes are staged then renamed, rolling back on failure. Running it with no slug, or with ' ++ '--list, lists available themes; use --package when more than one owner provides the slug.',fn: 'themeAdd',args: [{name: 'slug', param: 'slug', required: false},@@ -31,19 +31,24 @@ export const doc = {description: 'Overwrite existing files without prompting',},{flag: '--list', description: 'List available themes'},+ {+ flag: '--package <package>',+ param: 'options.package',+ description: 'Select the package that owns the theme',+ },],examples: [{label: 'Scaffold a theme', cli: 'astryx theme add matcha'},{- label: 'Custom target path',- cli: 'astryx theme add matcha ./src/themes/matcha',+ label: 'Select an integration theme',+ cli: 'astryx theme add ocean --package @acme/themes',},],exitCodes: [{code: 0, when: 'success'},{code: 1,- when: 'unknown theme, a path escape, a missing bundled file, or an existing file without --overwrite',+ when: 'unknown or ambiguous theme, a path escape, a missing catalog file, or an existing file without --overwrite',},],related: ['theme list', 'theme build'],diff --git a/packages/cli/clients/cli/commands/theme-list.doc.mjs b/packages/cli/clients/cli/commands/theme-list.doc.mjsindex cf81d2f35d..7d67e0f503 100644--- a/packages/cli/clients/cli/commands/theme-list.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-list.doc.mjs@@ -16,13 +16,29 @@ export const doc = {namespace: 'cli',summary: 'List themes available to add',description:- 'Lists the themes bundled with this CLI build (the ones theme add can scaffold), ' +- 'each with its slug, display name, description, and maintained flag.',- fn: 'themeList',- examples: [{label: 'List bundled themes', cli: 'astryx theme list --json'}],+ 'Lists themes bundled with this CLI and source themes contributed by installed integrations, ' ++ 'each with its slug, display name, description, maintained flag, and owner package.',+ fn: 'themeListAvailable',+ options: [+ {+ flag: '--package <package>',+ param: 'options.package',+ description: 'Show only themes owned by this package',+ },+ ],+ examples: [+ {label: 'List available themes', cli: 'astryx theme list --json'},+ {+ label: 'List one integration package',+ cli: 'astryx theme list --package @acme/themes',+ },+ ],exitCodes: [{code: 0, when: 'success'},- {code: 1, when: 'the bundled-theme manifest cannot be read'},+ {+ code: 1,+ when: 'the bundled-theme manifest or an installed theme catalog cannot be read',+ },],related: ['theme add', 'theme build'],};diff --git a/packages/cli/clients/cli/commands/theme.doc.mjs b/packages/cli/clients/cli/commands/theme.doc.mjsindex a75eab59c2..bfbda085e9 100644--- a/packages/cli/clients/cli/commands/theme.doc.mjs+++ b/packages/cli/clients/cli/commands/theme.doc.mjs@@ -18,11 +18,11 @@ export const doc = {'The theme command group. Running astryx theme with no subcommand prints the ' +'subcommand list; the work happens in the subcommands: compile a theme (build), ' +'scaffold one into your project (add), start a custom one from the annotated template (template), ' +- 'list the bundled themes (list), generate a palette candidate (palette), or list the ' ++ 'list the bundled and installed integration themes (list), generate a palette candidate (palette), or list the ' +'component theming targets a theme can override (targets).',subcommands: ['build', 'add', 'list', 'template', 'palette', 'targets'],examples: [- {label: 'List bundled themes', cli: 'astryx theme list'},+ {label: 'List available themes', cli: 'astryx theme list'},{label: 'Scaffold a theme', cli: 'astryx theme add matcha'},{label: 'Generate a palette candidate',diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex 60ddf1964e..c1594949c2 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -93,6 +93,8 @@ export const JSON_SUPPORTED = new Set(['theme template','theme targets','theme palette generate',+ 'integration add',+ 'integration pack','upgrade','manifest','doctor',@@ -263,6 +265,7 @@ const commands = [{name: 'layout', path: './commands/layout.mjs', register: 'registerLayout'},{name: 'upgrade', path: './commands/upgrade.mjs', register: 'registerUpgrade'},{name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},+ {name: 'integration', path: './commands/integration.mjs', register: 'registerIntegration'},{name: 'hook', path: './commands/hook/index.mjs', register: 'registerHook'},{name: 'discover', path: './commands/discover.mjs', register: 'registerDiscover'},{name: 'search', path: './commands/search.mjs', register: 'registerSearch'},diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjsindex d07c731a7b..3991af94f8 100644--- a/packages/cli/clients/cli/lib/manifest.mjs+++ b/packages/cli/clients/cli/lib/manifest.mjs@@ -80,6 +80,8 @@ export const RESPONSE_TYPES = {'theme template': ['theme.template'],'theme targets': ['theme.targets'],'theme palette generate': ['theme.palette.generate'],+ 'integration add': ['integration.add'],+ 'integration pack': ['integration.pack-check'],upgrade: ['upgrade.list', 'upgrade.status', 'upgrade.run'],manifest: ['manifest'],doctor: ['doctor'],@@ -134,6 +136,11 @@ const EXAMPLES = {'astryx theme palette generate palette.config.json','astryx theme palette generate palette.config.json --out ocean.palette.json',],+ 'integration add': [+ 'astryx integration add component AcmeWidget',+ 'astryx integration add doc deploying --dry-run --json',+ ],+ 'integration pack': ['astryx integration pack --check --json'],upgrade: ['astryx upgrade --json'],manifest: ['astryx manifest --json', 'astryx --json'],doctor: ['astryx doctor', 'astryx doctor --json'],diff --git a/packages/cli/foundation/config/project-themes.test.mjs b/packages/cli/foundation/config/project-themes.test.mjsnew file mode 100644index 0000000000..310bbefe6f--- /dev/null+++ b/packages/cli/foundation/config/project-themes.test.mjs@@ -0,0 +1,127 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {Project} from './project.mjs';+import {BUNDLED_THEME_PACKAGE} from '../discovery/theme-discovery.mjs';++let tmpDir;++function installThemeIntegration(packageName, slug) {+ const packageDir = path.join(+ tmpDir,+ 'node_modules',+ ...packageName.split('/'),+ );+ const themeDir = path.join(packageDir, 'themes', slug);+ fs.mkdirSync(themeDir, {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: packageName, version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ `export default {themes: './themes'};\n`,+ );+ 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'],+ },+ ],+ }),+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.ts'),+ `export const oceanTheme = {};\n`,+ );+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-project-themes-'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ dependencies: {'@acme/themes': '^1.0.0'},+ }),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('Project themes', () => {+ it('combines bundled and autolinked integration themes with owners', async () => {+ installThemeIntegration('@acme/themes', 'ocean');+ const project = await Project.load(tmpDir);+ const themes = await project.themes();++ expect(themes.some(theme => theme.package === BUNDLED_THEME_PACKAGE)).toBe(+ true,+ );+ expect(themes).toContainEqual(+ expect.objectContaining({+ slug: 'ocean',+ package: '@acme/themes',+ sourceDir: path.join(+ tmpDir,+ 'node_modules',+ '@acme',+ 'themes',+ 'themes',+ 'ocean',+ ),+ }),+ );+ });++ it('keeps duplicate slugs from different owners for scoped resolution', async () => {+ installThemeIntegration('@acme/themes', 'neutral');+ const project = await Project.load(tmpDir);+ const matches = (await project.themes()).filter(+ theme => theme.slug === 'neutral',+ );+ expect(matches.map(theme => theme.package)).toEqual([+ BUNDLED_THEME_PACKAGE,+ '@acme/themes',+ ]);+ });++ it('records an invalid integration theme catalog as an issue', async () => {+ installThemeIntegration('@acme/themes', 'ocean');+ fs.rmSync(+ path.join(+ tmpDir,+ 'node_modules',+ '@acme',+ 'themes',+ 'themes',+ 'ocean',+ 'oceanTheme.ts',+ ),+ );+ const project = await Project.load(tmpDir);+ const themes = await project.themes();++ expect(themes.some(theme => theme.package === '@acme/themes')).toBe(false);+ expect(await project.issues()).toContainEqual(+ expect.objectContaining({+ package: '@acme/themes',+ code: 'invalid_theme',+ severity: 'error',+ }),+ );+ });+});diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 56921d231d..cd5bfbfeb9 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -6,7 +6,7 @@* `Project` is the one entry point a command uses to read everything it needs* about a consumer's project: the validated config surface, the configured* integrations, and the resolved discovery sets (components, templates,- * codemods, docs) — plus issue routing (issuesUrl) and the accumulated+ * codemods, docs, themes) — plus issue routing (issuesUrl) and the accumulated* integration issues. It replaces the old `loadConfig(cwd)` plain-object loader* and the per-command fan-out into the various discovery helpers.*@@ -14,9 +14,9 @@* - `Project.load(cwd, {cache})` is the async factory (constructors can't be* 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 nothing more.- * Discovery is LAZY.- * - Discovery methods (components/templates/codemods/docs) are MEMOIZED per+ * plus autolink the installed ones no config names, and self-resolve the+ * package being authored when it carries a manifest. 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.* - SKIP + WARN policy: as a discovery method runs, per-integration work is@@ -35,7 +35,10 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {findPresentFiles, loadModuleWithParser} from '../fs/module-loader.mjs';import {parseConfig} from '../../authoring/config/parse.mjs';-import {loadIntegrations} from '../integrations/integrations.mjs';+import {+ loadIntegrations,+ loadLocalIntegration,+} from '../integrations/integrations.mjs';import {autolinkIntegrations} from '../integrations/autolink.mjs';import {setProject as setDebugProject,@@ -56,6 +59,10 @@ import {DocsCatalog,discoverIntegrationDocs,} from '../discovery/docs-discovery.mjs';+import {+ discoverBundledThemes,+ discoverIntegrationThemes,+} from '../discovery/theme-discovery.mjs';import {getTransformsBetween} from '../../assets/codemods/registry.mjs';import {discoverIntegrationCodemods,@@ -289,6 +296,20 @@ export class Project {})),];+ // The package being authored is the one package that cannot install itself.+ // When it carries a manifest, resolve its working bytes directly so every+ // existing consumer command doubles as the author's preview. A local copy+ // replaces the same installed package in place, preserving configured+ // precedence while making the source being edited authoritative.+ const localIntegration = await loadLocalIntegration(projectDir, {fresh});+ if (localIntegration) {+ const existing = loadedIntegrations.findIndex(+ integration => integration.name === localIntegration.name,+ );+ if (existing === -1) loadedIntegrations.push(localIntegration);+ else loadedIntegrations[existing] = localIntegration;+ }+// The debug recorder resolves its settings synchronously, long before any// command gets here, so this is where a project's `debug` block gets a// turn. The event is not written until process exit, so settings applied@@ -349,8 +370,9 @@ export class Project {}/**- * Every resolved integration (lib/integrations.mjs shape), configured ones- * first, then the autolinked ones (`__autolinked`).+ * Every resolved integration (lib/integrations.mjs shape): configured first,+ * then autolinked (`__autolinked`), with the local authoring package+ * (`__local`) replacing the same installed package or appended last.* @returns {import('../integrations/integrations.mjs').LoadedIntegration[]}*/get loadedIntegrations() {@@ -575,6 +597,38 @@ export class Project {});}+ /**+ * Bundled source themes plus themes contributed by installed integrations.+ * Each record keeps its package owner and source directory so callers can+ * both list and copy it without reconstructing paths. A broken integration's+ * themes are skipped under the same issue policy as every other kind.+ *+ * @returns {Promise<import('../discovery/theme-discovery.mjs').DiscoveredTheme[]>}+ */+ async themes() {+ return this.#memo('themes', async () => {+ const themes = discoverBundledThemes();++ for (const integration of this.#loadedIntegrations) {+ await this.#collectIssues(integration);+ const pkg = this.#pkgLabel(integration);+ if (this.#hasBlockingContributionIssue(pkg)) continue;+ if (!integration?.themes) continue;+ try {+ themes.push(...(await discoverIntegrationThemes(integration)));+ } catch (err) {+ this.#pushIssue(pkg, {+ code: 'invalid_theme',+ severity: 'error',+ message: errorMessage(err),+ });+ }+ }++ return themes;+ });+ }+/*** The CLI's own doc topics plus the ones the configured integrations* contribute, resolved into one catalog: additions, replacements (with the@@ -703,7 +757,7 @@ export class Project {* When called directly, also validates any configured integration not yet* visited by a discovery call, so the returned set is complete on demand.*- * @returns {Promise<import('../integrations/issue').AstryxIntegrationIssue[]>}+ * @returns {Promise<ProjectIntegrationIssue[]>}*/async issues() {for (const integration of this.#loadedIntegrations) {diff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjsindex 8818cc65ab..04eff568f1 100644--- a/packages/cli/foundation/config/project.test.mjs+++ b/packages/cli/foundation/config/project.test.mjs@@ -128,11 +128,81 @@ function topicDoc(fields) {name: 'deploying',title: 'Deploying',description: 'How to ship it.',- sections: [{title: 'Overview', content: [{type: 'prose', text: 'Ship it.'}]}],+ sections: [+ {title: 'Overview', content: [{type: 'prose', text: 'Ship it.'}]},+ ],...fields,};}+/** Scaffold the package being authored, with no config and no installation. */+function scaffoldLocalPackage({name = '@acme/local'} = {}) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name, version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export default {+ components: './components',+ templates: './templates',+ docs: './docs',+ themes: './themes',+ };\n`,+ );++ fs.mkdirSync(path.join(tmpDir, 'components'));+ fs.writeFileSync(+ path.join(tmpDir, 'components', 'LocalWidget.doc.mjs'),+ `export default {type: 'component', name: 'LocalWidget', props: []};\n`,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'components', 'LocalWidget.tsx'),+ `export function LocalWidget() { return null; }\n`,+ );++ fs.mkdirSync(path.join(tmpDir, 'templates'));+ fs.writeFileSync(+ path.join(tmpDir, 'templates', 'local-page.template.mjs'),+ `export default {type: 'page', name: 'Local page', description: 'Local page.'};\n`,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'templates', 'local-page.tsx'),+ `export default function LocalPage() { return null; }\n`,+ );++ fs.mkdirSync(path.join(tmpDir, 'docs'));+ fs.writeFileSync(+ path.join(tmpDir, 'docs', 'local-guide.doc.mjs'),+ `export default ${JSON.stringify(+ topicDoc({name: 'local-guide', title: 'Local guide'}),+ )};\n`,+ );++ 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'],+ },+ ],+ }),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),+ `export const oceanTheme = {};\n`,+ );+}+beforeEach(() => {originalCwd = process.cwd();tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-project-test-'));@@ -158,6 +228,52 @@ describe('Project.load', () => {expect(project.cwd).toBe(tmpDir);});+ it('self-resolves the package being authored through every consumer surface', async () => {+ scaffoldLocalPackage();++ const project = await Project.load(tmpDir);++ expect(project.loadedIntegrations).toHaveLength(1);+ expect(project.loadedIntegrations[0]).toMatchObject({+ name: '@acme/local',+ __local: true,+ });+ expect(+ (await project.components()).some(+ component =>+ component.name === 'LocalWidget' &&+ component.package === '@acme/local',+ ),+ ).toBe(true);+ expect(+ (await project.templates()).some(+ template =>+ template.dirName === 'local-page' &&+ template.package === '@acme/local',+ ),+ ).toBe(true);+ expect((await project.docs()).resolve('local-guide')).toMatchObject({+ package: '@acme/local',+ });+ expect(await project.themes()).toContainEqual(+ expect.objectContaining({slug: 'ocean', package: '@acme/local'}),+ );+ });++ it('prefers local bytes over an installed copy of the same package', async () => {+ scaffold();+ scaffoldLocalPackage({name: '@acme/widgets'});++ const project = await Project.load(tmpDir);++ expect(project.loadedIntegrations).toHaveLength(1);+ expect(project.loadedIntegrations[0].__local).toBe(true);+ const owned = (await project.components()).filter(+ component => component.package === '@acme/widgets',+ );+ expect(owned.map(component => component.name)).toEqual(['LocalWidget']);+ });+it('exposes the validated config surface and loaded integrations', async () => {scaffold({issuesUrl: 'https://example.com/issues'});const project = await Project.load(tmpDir);@@ -194,7 +310,9 @@ describe('findConfigPath', () => {path.join(tmpDir, 'astryx.config.js'),`module.exports = {};\n`,);- expect(() => findConfigPath(tmpDir)).toThrow(/Multiple Astryx config files/);+ expect(() => findConfigPath(tmpDir)).toThrow(+ /Multiple Astryx config files/,+ );});});@@ -265,7 +383,9 @@ describe('Project discovery', () => {const catalog = await project.docs();expect(catalog.resolve('deploying')).toBeUndefined();const issues = await project.issues();- expect(issues.some(i => i.code === 'invalid_doc' && i.severity === 'error')).toBe(true);+ expect(+ issues.some(i => i.code === 'invalid_doc' && i.severity === 'error'),+ ).toBe(true);});it('keeps regular contributions when agentDocs is invalid', async () => {@@ -323,8 +443,12 @@ describe('Project forward compatibility', () => {const project = await Project.load(tmpDir);const comps = await project.components();- expect(comps.some(c => c.name === 'Widget' && c.package === '@acme/widgets')).toBe(true);- expect((await project.templates()).some(t => t.package === '@acme/widgets')).toBe(true);+ expect(+ comps.some(c => c.name === 'Widget' && c.package === '@acme/widgets'),+ ).toBe(true);+ expect(+ (await project.templates()).some(t => t.package === '@acme/widgets'),+ ).toBe(true);const {integration} = await project.codemods('0.1.0', '0.2.0');expect(integration).toHaveLength(1);@@ -376,7 +500,9 @@ describe('Project issues (skip + warn)', () => {const b = await project.issues();expect(a).toEqual(b);// No duplicate (package, code, message) tuples.- const seen = new Set(a.map(i => `${i.package}\u0000${i.code}\u0000${i.message}`));+ const seen = new Set(+ a.map(i => `${i.package}\u0000${i.code}\u0000${i.message}`),+ );expect(seen.size).toBe(a.length);});diff --git a/packages/cli/foundation/discovery/theme-discovery.mjs b/packages/cli/foundation/discovery/theme-discovery.mjsnew file mode 100644index 0000000000..ff1b4feba8--- /dev/null+++ b/packages/cli/foundation/discovery/theme-discovery.mjs@@ -0,0 +1,650 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Theme catalog 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.+ *+ * @input a bundled or integration-owned theme root+ * @output validated source-theme records with package ownership+ * @position packages/cli/foundation/discovery — shared theme discovery+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+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);++/**+ * @typedef {object} DiscoveredTheme+ * @property {string} slug+ * @property {string} displayName+ * @property {string} description+ * @property {boolean} maintained+ * @property {string} entry+ * @property {string} exportName+ * @property {string[]} files+ * @property {string} package+ * @property {string} sourceDir absolute directory holding this theme's files+ * @property {boolean} bundled+ */++/** @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.+ * @param {string} value+ * @param {string} root+ * @param {string} label+ */+function resolveThemePath(value, root, label) {+ if (+ path.posix.isAbsolute(value) ||+ path.win32.isAbsolute(value) ||+ value.split(/[\\/]/u).some(segment => segment === '..' || segment === '.')+ ) {+ throw new Error(+ `Invalid ${label} "${value}": it must stay inside the theme directory.`,+ );+ }+ try {+ return assertWithin(value, root, {label});+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new Error(error.message, {cause: error});+ }+ throw error;+ }+}++const THEME_MODULE_EXTENSIONS = ['.mjs', '.js', '.mts', '.ts', '.tsx', '.jsx'];++/**+ * 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) {+ if (typeof specifier !== 'string' || !specifier.startsWith('.')) return null;+ const base = path.resolve(path.dirname(fromFile), specifier);+ const candidates = [+ base,+ ...THEME_MODULE_EXTENSIONS.map(extension => `${base}${extension}`),+ ...THEME_MODULE_EXTENSIONS.map(extension =>+ path.join(base, `index${extension}`),+ ),+ ];+ for (const candidate of candidates) {+ try {+ if (!fs.statSync(candidate).isFile()) continue;+ const confined = assertWithin(candidate, themeDir, {+ allowAbsolute: true,+ label: 'theme module',+ });+ if (allowedFiles.has(confined)) return confined;+ } catch {+ // Missing, non-file, escaped, and unlisted candidates are not reachable.+ }+ }+ return null;+}++class ThemeModuleReferenceError extends Error {}++/**+ * 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 {Set<string>} [seen]+ */+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';+ const j = jscodeshift.withParser(parser);+ const root = j(fs.readFileSync(file, 'utf-8'));+ /** @type {string[]} */+ const specifiers = [];+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ importPath) => {+ if (typeof importPath.node.source?.value === 'string') {+ specifiers.push(importPath.node.source.value);+ }+ });+ root+ .find(j.ExportNamedDeclaration)+ .forEach((/** @type {any} */ exportPath) => {+ if (typeof exportPath.node.source?.value === 'string') {+ specifiers.push(exportPath.node.source.value);+ }+ });+ root.find(j.ExportAllDeclaration).forEach((/** @type {any} */ exportPath) => {+ if (typeof exportPath.node.source?.value === 'string') {+ specifiers.push(exportPath.node.source.value);+ }+ });+ root.find(j.CallExpression).forEach((/** @type {any} */ callPath) => {+ if (+ callPath.node.callee?.type === 'Import' &&+ typeof callPath.node.arguments?.[0]?.value === 'string'+ ) {+ specifiers.push(callPath.node.arguments[0].value);+ }+ });+ root.find(j.ImportExpression).forEach((/** @type {any} */ importPath) => {+ if (typeof importPath.node.source?.value === 'string') {+ specifiers.push(importPath.node.source.value);+ }+ });++ for (const specifier of specifiers) {+ if (!specifier.startsWith('.')) continue;+ const target = resolveLocalThemeModule(+ specifier,+ file,+ themeDir,+ allowedFiles,+ );+ if (!target) {+ throw new ThemeModuleReferenceError(+ `Theme catalog for ${owner} entry "${entry}" references local module "${specifier}" that must resolve to a listed file inside the theme directory.`,+ );+ }+ if (THEME_MODULE_EXTENSIONS.includes(path.extname(target))) {+ validateThemeModuleGraph(+ target,+ jscodeshift,+ themeDir,+ allowedFiles,+ owner,+ entry,+ seen,+ );+ }+ }+}++/** @param {any} declaration @param {string} exportName */+function declarationExportsName(declaration, exportName) {+ if (!declaration || declaration.declare === true) return false;+ if (+ (declaration.type === 'FunctionDeclaration' ||+ declaration.type === 'ClassDeclaration') &&+ declaration.id?.name === exportName+ ) {+ return true;+ }+ return (+ declaration.type === 'VariableDeclaration' &&+ declaration.declarations.some(+ (/** @type {any} */ declarationItem) =>+ declarationItem.id?.type === 'Identifier' &&+ declarationItem.id.name === exportName,+ )+ );+}++/**+ * Resolve a source-less export specifier to a real top-level runtime binding.+ * @param {any[]} statements+ * @param {string} localName+ * @param {string} file+ * @param {any} jscodeshift+ * @param {string} themeDir+ * @param {Set<string>} allowedFiles+ * @param {Set<string>} seen+ */+function hasRuntimeBinding(+ statements,+ localName,+ file,+ jscodeshift,+ themeDir,+ allowedFiles,+ seen,+) {+ if (+ statements.some((/** @type {any} */ statement) =>+ declarationExportsName(statement, localName),+ )+ ) {+ return true;+ }++ for (const statement of statements) {+ if (+ statement.type !== 'ImportDeclaration' ||+ statement.importKind === 'type'+ ) {+ continue;+ }+ for (const specifier of statement.specifiers ?? []) {+ if (+ specifier.local?.name !== localName ||+ specifier.importKind === 'type'+ ) {+ continue;+ }+ const source = statement.source?.value;+ if (typeof source !== 'string') return false;+ if (!source.startsWith('.')) return true;+ const target = resolveLocalThemeModule(+ source,+ file,+ themeDir,+ allowedFiles,+ );+ if (!target) return false;+ if (specifier.type === 'ImportNamespaceSpecifier') return true;+ const importedName =+ specifier.type === 'ImportDefaultSpecifier'+ ? 'default'+ : (specifier.imported?.name ?? specifier.imported?.value);+ return (+ typeof importedName === 'string' &&+ moduleExportsName(+ target,+ importedName,+ jscodeshift,+ themeDir,+ allowedFiles,+ seen,+ )+ );+ }+ }+ return false;+}++/** @param {any} declaration */+function isRuntimeDefaultDeclaration(declaration) {+ return (+ declaration != null &&+ declaration.declare !== true &&+ ![+ 'TSDeclareFunction',+ 'TSInterfaceDeclaration',+ 'TSTypeAliasDeclaration',+ ].includes(declaration.type)+ );+}++/**+ * Prove a named runtime export without executing the module. Local ESM+ * re-exports are followed recursively.+ * @param {string} file+ * @param {string} exportName+ * @param {any} jscodeshift+ * @param {string} themeDir+ * @param {Set<string>} allowedFiles+ * @param {Set<string>} [seen]+ */+function moduleExportsName(+ file,+ exportName,+ jscodeshift,+ themeDir,+ allowedFiles,+ seen = new Set(),+) {+ const identity = `${file}\0${exportName}`;+ if (seen.has(identity) || !allowedFiles.has(file) || !fs.existsSync(file)) {+ return false;+ }+ seen.add(identity);++ const parser = /\.(?:ts|tsx|mts)$/u.test(file) ? 'tsx' : 'babel';+ const j = jscodeshift.withParser(parser);+ const root = j(fs.readFileSync(file, 'utf-8'));+ const statements = root.find(j.Program).nodes()[0]?.body ?? [];+ let found = false;+ root+ .find(j.ExportNamedDeclaration)+ .forEach((/** @type {any} */ exportPath) => {+ if (found || exportPath.node.exportKind === 'type') return;+ if (declarationExportsName(exportPath.node.declaration, exportName)) {+ found = true;+ return;+ }+ for (const specifier of exportPath.node.specifiers ?? []) {+ if (+ specifier.type !== 'ExportSpecifier' ||+ specifier.exportKind === 'type' ||+ (specifier.exported?.name ?? specifier.exported?.value) !== exportName+ ) {+ continue;+ }+ if (!exportPath.node.source) {+ const localName = specifier.local?.name ?? specifier.local?.value;+ if (+ typeof localName === 'string' &&+ hasRuntimeBinding(+ statements,+ localName,+ file,+ jscodeshift,+ themeDir,+ allowedFiles,+ seen,+ )+ ) {+ found = true;+ return;+ }+ continue;+ }+ const target = resolveLocalThemeModule(+ exportPath.node.source.value,+ file,+ themeDir,+ allowedFiles,+ );+ const imported =+ specifier.local?.name ?? specifier.local?.value ?? exportName;+ if (+ target &&+ moduleExportsName(+ target,+ imported,+ jscodeshift,+ themeDir,+ allowedFiles,+ seen,+ )+ ) {+ found = true;+ return;+ }+ }+ });+ if (found) return true;+ if (+ exportName === 'default' &&+ statements.some(+ (/** @type {any} */ statement) =>+ statement.type === 'ExportDefaultDeclaration' &&+ isRuntimeDefaultDeclaration(statement.declaration),+ )+ ) {+ return true;+ }++ root.find(j.ExportAllDeclaration).forEach((/** @type {any} */ exportPath) => {+ if (found || exportPath.node.exportKind === 'type') return;+ const target = resolveLocalThemeModule(+ exportPath.node.source?.value,+ file,+ themeDir,+ allowedFiles,+ );+ if (+ target &&+ moduleExportsName(+ target,+ exportName,+ jscodeshift,+ themeDir,+ allowedFiles,+ seen,+ )+ ) {+ found = true;+ }+ });+ return found;+}++/**+ * 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[]}+ */+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}`,+ );+ }++ const manifestPath = resolveThemePath(+ THEME_MANIFEST_BASENAME,+ themeRoot,+ 'theme catalog manifest',+ );+ if (!fs.existsSync(manifestPath) || !fs.statSync(manifestPath).isFile()) {+ throw new Error(+ `Theme root for ${owner} must contain ${THEME_MANIFEST_BASENAME}.`,+ );+ }++ /** @type {unknown} */+ let parsed;+ try {+ parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(`Theme catalog for ${owner} is unreadable: ${message}`, {+ cause: error,+ });+ }++ if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error(`Theme catalog for ${owner} must be a JSON object.`);+ }+ const catalog = /** @type {{version?: unknown, themes?: unknown}} */ (parsed);+ if (catalog.version !== 1) {+ throw new Error(`Theme catalog for ${owner} must use version 1.`);+ }+ if (!Array.isArray(catalog.themes)) {+ throw new Error(`Theme catalog for ${owner} must contain a themes array.`);+ }++ /** @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)) {+ throw new Error(+ `Theme catalog for ${owner} has invalid slug "${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}".`,+ );+ }+ slugs.add(normalizedSlug);++ const displayName = requiredString(+ entry.displayName,+ `theme "${slug}" displayName`,+ owner,+ );+ if (typeof entry.description !== 'string') {+ throw new Error(+ `Theme catalog for ${owner} has an invalid description for "${slug}".`,+ );+ }+ if (typeof entry.maintained !== 'boolean') {+ throw new Error(+ `Theme catalog for ${owner} has an invalid maintained flag for "${slug}".`,+ );+ }+ const entryFile = requiredString(+ entry.entry,+ `theme "${slug}" entry`,+ owner,+ );+ const exportName = requiredString(+ entry.exportName,+ `theme "${slug}" exportName`,+ owner,+ );+ if (!/^[$A-Z_a-z][$\w]*$/u.test(exportName)) {+ throw new Error(+ `Theme catalog for ${owner} has invalid exportName "${exportName}".`,+ );+ }+ if (!Array.isArray(entry.files) || entry.files.length === 0) {+ throw new Error(+ `Theme catalog for ${owner} theme "${slug}" must list at least one file.`,+ );+ }++ const files = entry.files.map((file, fileIndex) =>+ requiredString(file, `theme "${slug}" files[${fileIndex}]`, owner),+ );+ if (new Set(files).size !== files.length) {+ throw new Error(+ `Theme catalog for ${owner} theme "${slug}" lists a file more than once.`,+ );+ }+ if (!files.includes(entryFile)) {+ throw new Error(+ `Theme catalog for ${owner} theme "${slug}" must include entry "${entryFile}" in files.`,+ );+ }+ if (!/\.(?:ts|tsx|mjs|js)$/u.test(entryFile)) {+ throw new Error(+ `Theme catalog for ${owner} theme "${slug}" entry must be source code.`,+ );+ }++ const sourceDir = resolveThemePath(+ slug,+ themeRoot,+ `theme "${slug}" directory`,+ );+ if (!fs.existsSync(sourceDir) || !fs.statSync(sourceDir).isDirectory()) {+ throw new Error(+ `Theme catalog for ${owner} is missing directory "${slug}".`,+ );+ }+ for (const file of files) {+ const source = resolveThemePath(file, sourceDir, `theme "${slug}" file`);+ if (!fs.existsSync(source) || !fs.statSync(source).isFile()) {+ throw new Error(+ `Theme catalog for ${owner} theme "${slug}" is missing file "${file}".`,+ );+ }+ }++ themes.push({+ slug,+ displayName,+ description: entry.description,+ maintained: entry.maintained,+ entry: entryFile,+ exportName,+ files,+ package: owner,+ sourceDir,+ bundled,+ });+ }++ return themes;+}++/** @returns {DiscoveredTheme[]} */+export function discoverBundledThemes() {+ return discoverThemeCatalog(THEMES_DIR, BUNDLED_THEME_PACKAGE, {+ bundled: true,+ });+}++/**+ * @param {import('../integrations/integrations.mjs').LoadedIntegration} integration+ * @returns {Promise<DiscoveredTheme[]>}+ */+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`,+ );+ let exportsName;+ 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},+ );+ }+ if (!exportsName) {+ throw new Error(+ `Theme catalog for ${theme.package} entry "${theme.entry}" does not export "${theme.exportName}".`,+ );+ }+ }+ return themes;+}diff --git a/packages/cli/foundation/discovery/theme-discovery.test.mjs b/packages/cli/foundation/discovery/theme-discovery.test.mjsnew file mode 100644index 0000000000..42fad05962--- /dev/null+++ b/packages/cli/foundation/discovery/theme-discovery.test.mjs@@ -0,0 +1,375 @@+// 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 {+ BUNDLED_THEME_PACKAGE,+ discoverBundledThemes,+ discoverIntegrationThemes,+ discoverThemeCatalog,+} 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`);+ }+ }+ fs.writeFileSync(+ path.join(tmpDir, 'manifest.json'),+ JSON.stringify({version: 1, themes: entries}),+ );+}++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-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('theme catalog discovery', () => {+ it('reads the existing bundled catalog 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);+ });++ it('reads the canonical manifest-plus-slug-directory shape', () => {+ writeCatalog([ocean]);+ expect(discoverThemeCatalog(tmpDir, '@acme/themes')).toEqual([+ expect.objectContaining({+ ...ocean,+ package: '@acme/themes',+ sourceDir: path.join(tmpDir, 'ocean'),+ 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",+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toEqual([+ expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),+ ]);+ });++ it('rejects an entry that does not export the catalog name', async () => {+ writeCatalog([ocean]);+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'oceanTheme.ts'),+ 'export const anotherTheme = {};\n',+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).rejects.toThrow(+ 'Theme catalog for @acme/themes entry "oceanTheme.ts" does not export "oceanTheme".',+ );+ });++ it('rejects a type-only export of the catalog name', async () => {+ writeCatalog([ocean]);+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'oceanTheme.ts'),+ '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 () => {+ writeCatalog([ocean]);+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'oceanTheme.ts'),+ 'export {oceanTheme};\n',+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).rejects.toThrow(+ /could not be parsed: Export 'oceanTheme' is not defined/u,+ );+ });++ 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',+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toEqual([+ expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),+ ]);+ });++ 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',+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toEqual([+ expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),+ ]);+ });++ 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",+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toEqual([+ expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),+ ]);+ });++ 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',+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toEqual([+ expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),+ ]);+ });++ 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",+ );+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'theme.ts'),+ "throw new Error('theme source executed');\nexport const oceanTheme = {};\n",+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toEqual([+ expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),+ ]);+ });++ 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",+ );+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'tokens', 'ocean.palette.ts'),+ "throw new Error('palette source executed');\nexport const oceanPalette = {};\n",+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).resolves.toEqual([+ expect.objectContaining({slug: 'ocean', exportName: 'oceanTheme'}),+ ]);+ });++ it('rejects a direct import from an unlisted theme file', async () => {+ writeCatalog([ocean]);+ fs.mkdirSync(path.join(tmpDir, 'ocean', 'tokens'), {recursive: true});+ 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',+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).rejects.toThrow(+ /must resolve to a listed file inside the theme directory/u,+ );+ });++ it('rejects a direct import outside the theme directory', async () => {+ writeCatalog([ocean]);+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'oceanTheme.ts'),+ "import {oceanPalette} from '../outside';\nexport const oceanTheme = {oceanPalette};\n",+ );+ fs.writeFileSync(+ path.join(tmpDir, 'outside.ts'),+ 'export const oceanPalette = {};\n',+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).rejects.toThrow(+ /must resolve to a listed file inside the theme directory/u,+ );+ });++ it('rejects a literal dynamic import from an unlisted file', async () => {+ const mjsTheme = {+ ...ocean,+ entry: 'oceanTheme.mjs',+ files: ['oceanTheme.mjs'],+ };+ writeCatalog([mjsTheme]);+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'oceanTheme.mjs'),+ "void import('./extra.mjs');\nexport const oceanTheme = {};\n",+ );+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'extra.mjs'),+ 'export const extra = {};\n',+ );++ await expect(+ discoverIntegrationThemes({name: '@acme/themes', themes: tmpDir}),+ ).rejects.toThrow(+ /must resolve to a listed file inside the theme directory/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",+ );+ fs.writeFileSync(+ 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,+ );+ });++ 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",+ );+ fs.writeFileSync(+ path.join(tmpDir, 'ocean', 'theme.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,+ );+ });++ it('rejects duplicate slugs case-insensitively', () => {+ writeCatalog([ocean, {...ocean, slug: 'OCEAN'}]);+ expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(+ /invalid slug|duplicate slug/u,+ );+ });++ 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',+ );+ fs.writeFileSync(+ path.join(tmpDir, 'manifest.json'),+ JSON.stringify({+ version: 1,+ themes: [+ {+ ...ocean,+ entry: '../outside.ts',+ files: ['../outside.ts'],+ },+ ],+ }),+ );+ expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(+ /must stay inside/u,+ );+ });++ it('rejects a missing catalog file and a missing listed source', () => {+ expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(+ /must contain manifest\.json/u,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'manifest.json'),+ JSON.stringify({version: 1, themes: [ocean]}),+ );+ expect(() => discoverThemeCatalog(tmpDir, '@acme/themes')).toThrow(+ /missing directory "ocean"/u,+ );+ });++ 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,+ );+ });+});diff --git a/packages/cli/foundation/integrations/contribution-inventory.mjs b/packages/cli/foundation/integrations/contribution-inventory.mjsnew file mode 100644index 0000000000..917a0d82f2--- /dev/null+++ b/packages/cli/foundation/integrations/contribution-inventory.mjs@@ -0,0 +1,497 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Contribution inventory for integration pack-check.+ *+ * Enumerates the files and contribution identities an integration package+ * declares, for cross-referencing against the npm tarball. The file inventory+ * is computed statically (no module imports); the identity inventory runs+ * the same discovery functions a consumer uses.+ *+ * @position packages/cli/foundation/integrations — shared contribution inventory+ */++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 {discoverIntegrationComponents} from '../discovery/component-discovery.mjs';+import {loadComponentDoc} from '../discovery/component-loader.mjs';+import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';+import {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';+import {discoverIntegrationDocs} from '../discovery/docs-discovery.mjs';++// ── File-walk helpers (no module imports, no execution) ──────────++const TEMPLATE_RE = /\.(?:template|doc)\.(?:ts|mjs|js)$/u;+const COMPONENT_DOC_RE = /\.doc\.(?:ts|mjs|js)$/u;+const CODEMOD_RE = /\.(?:ts|mjs|js)$/u;+const CODEMOD_TEST_RE = /\.(?:test|spec|fixture)\.(?:ts|mjs|js)$/u;+const DOC_RE = /\.doc\.(?:ts|mjs|js)$/u;+const SKIP_DIRS = new Set([+ 'node_modules',+ '.git',+ '__tests__',+ '__fixtures__',+]);++/**+ * Recursively collect files under `dir` that satisfy `filter`, excluding+ * `node_modules` and `.git`. Returns sorted absolute paths.+ * @param {string} dir+ * @param {(name: string) => boolean} filter+ * @returns {string[]}+ */+function walkDir(dir, filter) {+ if (!dir || !fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return [];+ /** @type {string[]} */+ const out = [];+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ if (SKIP_DIRS.has(entry.name)) continue;+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) out.push(...walkDir(full, filter));+ else if (filter(entry.name)) out.push(full);+ }+ return out.sort();+}++/** @param {string} packageDir @param {string} file */+function rel(packageDir, file) {+ return path.relative(packageDir, file).split(path.sep).join('/');+}++// ── Per-kind file enumeration ────────────────────────────────────++/** @param {string} root @param {string} pkgDir */+function enumerateThemeFiles(root, pkgDir) {+ /** @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)));+ }+ }+ }+ } catch {+ /* Phase 1 catches structural issues */+ }+ return files;+}++/** @param {string} root @param {string} pkgDir */+function enumerateComponentFiles(root, pkgDir) {+ const files = [];+ for (const doc of walkDir(root, name => COMPONENT_DOC_RE.test(name))) {+ files.push(rel(pkgDir, doc));+ const source = `${doc.replace(COMPONENT_DOC_RE, '')}.tsx`;+ if (fs.existsSync(source)) files.push(rel(pkgDir, source));+ }+ return files;+}++/** @param {string} root @param {string} pkgDir */+function enumerateTemplateFiles(root, pkgDir) {+ const files = [];+ for (const tmpl of walkDir(root, n => TEMPLATE_RE.test(n))) {+ files.push(rel(pkgDir, tmpl));+ const stem = tmpl.replace(TEMPLATE_RE, '');+ const source = `${stem}.tsx`;+ if (fs.existsSync(source)) files.push(rel(pkgDir, source));+ }+ return files;+}++/** @param {string} root @param {string} pkgDir */+function enumerateCodemodFiles(root, pkgDir) {+ return walkDir(+ root,+ name => CODEMOD_RE.test(name) && !CODEMOD_TEST_RE.test(name),+ ).map(file => rel(pkgDir, file));+}++/** @param {string} root @param {string} pkgDir */+function enumerateDocFiles(root, pkgDir) {+ return walkDir(root, n => DOC_RE.test(n)).map(f => rel(pkgDir, f));+}++/** @type {Record<FileInventoryRoot['kind'], (root: string, pkgDir: string) => string[]>} */+const ENUMERATORS = {+ themes: enumerateThemeFiles,+ components: enumerateComponentFiles,+ templates: enumerateTemplateFiles,+ codemods: enumerateCodemodFiles,+ docs: enumerateDocFiles,+};+const ROOT_KINDS = /** @type {const} */ ([+ 'themes',+ 'components',+ 'templates',+ 'codemods',+ 'docs',+]);++// ── Public: static file inventory ────────────────────────────────++/**+ * @typedef {object} FileInventoryRoot+ * @property {'themes'|'components'|'templates'|'codemods'|'docs'} kind+ * @property {string} path — project-relative root path+ * @property {string[]} files — project-relative required file paths+ */++/**+ * @typedef {object} FileInventory+ * @property {string} manifest — project-relative manifest path+ * @property {FileInventoryRoot[]} roots+ * @property {string[]} allFiles — deduplicated flat list+ */++/**+ * Compute the files the tarball must contain for an integration's+ * contributions to be visible. Reads catalogs and walks directories;+ * never imports or executes authored modules.+ *+ * @param {import('./integrations.mjs').LoadedIntegration} loaded+ * @returns {FileInventory}+ */+export function computeRequiredFiles(loaded) {+ const pkgDir = loaded.__packageDir;+ const manifestRel = rel(pkgDir, loaded.__manifestFile);+ /** @type {FileInventoryRoot[]} */+ const roots = [];+ const allFiles = [manifestRel];++ for (const kind of ROOT_KINDS) {+ const root = loaded[kind];+ if (!root) continue;+ const files = ENUMERATORS[kind](root, pkgDir);+ roots.push({+ kind,+ path: rel(pkgDir, root),+ files,+ });+ allFiles.push(...files);+ }++ return {manifest: manifestRel, roots, allFiles: [...new Set(allFiles)]};+}++// ── Public: identity collection ──────────────────────────────────++/**+ * @typedef {object} ContributionIdentities+ * @property {{slug: string, exportName: string}[]} themes+ * @property {string[]} components+ * @property {{id: string, type: string, name: string}[]} templates+ * @property {{version: string, id: string}[]} codemods+ * @property {string[]} docs+ * @property {string[]} agentDocsAppend+ */++/**+ * The resolved fields needed to discover contribution identities.+ * @typedef {object} IdentitySource+ * @property {string} name+ * @property {string} [themes]+ * @property {string} [components]+ * @property {string} [templates]+ * @property {string} [codemods]+ * @property {string} [docs]+ * @property {{append?: readonly string[]}} [agentDocs]+ */++/**+ * Run the same discovery functions a consumer uses to collect every+ * contribution identity from a loaded integration.+ *+ * @param {IdentitySource} loaded+ * @returns {Promise<{identities: ContributionIdentities, errors: Array<{kind: string, message: string}>}>}+ */+export async function collectIdentities(loaded) {+ /** @type {ContributionIdentities} */+ const identities = {+ themes: [],+ components: [],+ templates: [],+ codemods: [],+ docs: [],+ agentDocsAppend: loaded.agentDocs?.append+ ? [...loaded.agentDocs.append]+ : [],+ };+ /** @type {Array<{kind: string, message: string}>} */+ const errors = [];++ if (loaded.themes && fs.existsSync(loaded.themes)) {+ try {+ const themes = await discoverIntegrationThemes(+ /** @type {import('./integrations.mjs').LoadedIntegration} */ (loaded),+ );+ identities.themes = themes+ .map(t => ({slug: t.slug, exportName: t.exportName}))+ .sort((a, b) => a.slug.localeCompare(b.slug));+ } catch (err) {+ errors.push({+ kind: 'themes',+ message: /** @type {Error} */ (err).message,+ });+ }+ }++ if (loaded.components && fs.existsSync(loaded.components)) {+ try {+ const records = discoverIntegrationComponents(loaded) ?? [];+ for (const record of records) {+ try {+ await loadComponentDoc(record.docPath);+ identities.components.push(record.name);+ } catch (err) {+ errors.push({+ kind: 'components',+ message: `${path.relative(loaded.components, record.docPath)}: ${+ /** @type {Error} */ (err).message+ }`,+ });+ }+ }+ identities.components.sort();+ } catch (err) {+ errors.push({+ kind: 'components',+ message: /** @type {Error} */ (err).message,+ });+ }+ }++ if (loaded.templates && fs.existsSync(loaded.templates)) {+ try {+ const {templates, errors: templateErrors} =+ await discoverIntegrationTemplatesForOne(loaded);+ for (const templateError of templateErrors) {+ errors.push({kind: 'templates', message: templateError.message});+ }+ identities.templates = templates+ .map(t => ({id: t.dirName, type: t.type, name: t.name}))+ .sort((a, b) => a.id.localeCompare(b.id));+ } catch (err) {+ errors.push({+ kind: 'templates',+ message: /** @type {Error} */ (err).message,+ });+ }+ }++ if (loaded.codemods && fs.existsSync(loaded.codemods)) {+ try {+ const byVersion = await discoverIntegrationCodemods([loaded]);+ /** @type {{version: string, id: string}[]} */+ const entries = [];+ for (const [version, codemods] of byVersion) {+ for (const cm of codemods) entries.push({version, id: cm.id});+ }+ identities.codemods = entries.sort((a, b) =>+ `${a.version}/${a.id}`.localeCompare(`${b.version}/${b.id}`),+ );+ } catch (err) {+ errors.push({+ kind: 'codemods',+ message: /** @type {Error} */ (err).message,+ });+ }+ }++ if (loaded.docs && fs.existsSync(loaded.docs)) {+ try {+ const {records, errors: docErrors} =+ await discoverIntegrationDocs(loaded);+ for (const docError of docErrors) {+ errors.push({kind: 'docs', message: docError.message});+ }+ identities.docs = records.map(r => r.name).sort();+ } catch (err) {+ errors.push({kind: 'docs', message: /** @type {Error} */ (err).message});+ }+ }++ return {identities, errors};+}++/**+ * Prove that one contribution is visible through the same inventory seam the+ * packed-package checker uses. This is the shared postcondition for every add+ * handler, not a second set of per-writer rules.+ *+ * @param {IdentitySource} loaded+ * @param {'theme'|'component'|'template'|'codemod'|'doc'|'agent-doc'} kind+ * @param {string} name+ * @param {{version?: string}} [options]+ * @returns {Promise<void>}+ */+export async function assertContributionVisible(+ loaded,+ kind,+ name,+ {version} = {},+) {+ const {identities, errors} = await collectIdentities(loaded);+ const errorKind =+ kind === 'theme'+ ? 'themes'+ : kind === 'component'+ ? 'components'+ : kind === 'template'+ ? 'templates'+ : kind === 'codemod'+ ? 'codemods'+ : kind === 'doc'+ ? 'docs'+ : 'agentDocs';+ const relevantError = errors.find(error => error.kind === errorKind);+ if (relevantError) throw new Error(relevantError.message);++ const visible =+ kind === 'theme'+ ? identities.themes.some(theme => theme.slug === name)+ : kind === 'component'+ ? identities.components.includes(name)+ : kind === 'template'+ ? identities.templates.some(template => template.id === name)+ : kind === 'codemod'+ ? identities.codemods.some(+ codemod => codemod.id === name && codemod.version === version,+ )+ : kind === 'doc'+ ? identities.docs.includes(name)+ : identities.agentDocsAppend.includes(name);+ if (!visible) {+ const qualifier = version == null ? '' : ` under version ${version}`;+ throw new Error(+ `${kind} contribution "${name}" was not visible${qualifier} after writing.`,+ );+ }+}++// ── Public: identity comparison ──────────────────────────────────++/**+ * @typedef {import('./issue').AstryxIntegrationIssue} Issue+ */++/**+ * Compare local and packed identities. Anything discoverable locally but+ * missing from the packed tarball is an error.+ *+ * @param {ContributionIdentities} local+ * @param {ContributionIdentities} packed+ * @returns {Issue[]}+ */+export function compareIdentities(local, packed) {+ /** @type {Issue[]} */+ const issues = [];++ /**+ * Compare one identity list in both directions, then compare the complete+ * record for matching keys. A packed-only identity is just as suspicious as a+ * missing one: npm shipped bytes the local authoring view did not expose.+ * @param {string} kind+ * @param {unknown[]} localItems+ * @param {unknown[]} packedItems+ * @param {(item: any) => string} keyOf+ */+ function compareKind(kind, localItems, packedItems, keyOf) {+ const localByKey = new Map(localItems.map(item => [keyOf(item), item]));+ const packedByKey = new Map(packedItems.map(item => [keyOf(item), item]));+ for (const [key, item] of localByKey) {+ if (!packedByKey.has(key)) {+ issues.push({+ code: 'identity_not_packed',+ severity: 'error',+ message: `${kind} "${key}" is discoverable locally but missing from the packed tarball.`,+ });+ continue;+ }+ const packedItem = packedByKey.get(key);+ if (!isDeepStrictEqual(item, packedItem)) {+ issues.push({+ code: 'identity_mismatch',+ severity: 'error',+ message: `${kind} "${key}" resolves differently from the packed tarball.`,+ });+ }+ }+ for (const key of packedByKey.keys()) {+ if (!localByKey.has(key)) {+ issues.push({+ code: 'packed_identity_unexpected',+ severity: 'error',+ message: `${kind} "${key}" exists only in the packed tarball.`,+ });+ }+ }+ }++ compareKind('Theme', local.themes, packed.themes, item => item.slug);+ compareKind('Component', local.components, packed.components, item => item);+ compareKind('Template', local.templates, packed.templates, item => item.id);+ compareKind(+ 'Codemod',+ local.codemods,+ packed.codemods,+ item => `${item.version}/${item.id}`,+ );+ compareKind('Doc topic', local.docs, packed.docs, item => item);++ if (+ JSON.stringify(local.agentDocsAppend) !==+ JSON.stringify(packed.agentDocsAppend)+ ) {+ issues.push({+ code: 'agent_docs_mismatch',+ severity: 'error',+ message:+ 'agentDocs.append lines differ between local and packed manifests.',+ });+ }++ return issues;+}++// ── Public: source-only candidate detection ──────────────────────++const PASCAL_CASE_TSX = /^([A-Z][A-Za-z0-9]+)\.tsx$/u;++/**+ * Find top-level PascalCase `.tsx` files under a components root that are+ * NOT registered as integration components. These are candidates that+ * Astryx will ignore — surfaced as a warning so the author knows.+ *+ * Scans only direct children of the root (not recursive) and never+ * enters node_modules.+ *+ * @param {string|undefined} componentsRoot absolute path+ * @param {string[]} registeredNames names already returned by discovery+ * @returns {string[]} unregistered PascalCase names+ */+export function findSourceOnlyCandidates(componentsRoot, registeredNames) {+ if (!componentsRoot || !fs.existsSync(componentsRoot)) return [];+ const known = new Set(registeredNames);+ /** @type {string[]} */+ const candidates = [];+ for (const entry of fs.readdirSync(componentsRoot, {withFileTypes: true})) {+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;+ const match = entry.name.match(PASCAL_CASE_TSX);+ if (!match) continue;+ if (!known.has(match[1])) candidates.push(match[1]);+ }+ return candidates.sort();+}diff --git a/packages/cli/foundation/integrations/contribution-inventory.test.mjs b/packages/cli/foundation/integrations/contribution-inventory.test.mjsnew file mode 100644index 0000000000..6b967da30e--- /dev/null+++ b/packages/cli/foundation/integrations/contribution-inventory.test.mjs@@ -0,0 +1,361 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ computeRequiredFiles,+ compareIdentities,+ findSourceOnlyCandidates,+} from './contribution-inventory.mjs';++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-ci-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/** Build a minimal LoadedIntegration-shaped object from fixture contents. */+function loaded(overrides = {}) {+ const manifestFile = path.join(tmpDir, 'astryx.integration.mjs');+ if (!fs.existsSync(manifestFile)) {+ fs.writeFileSync(manifestFile, 'export default {};\n');+ }+ return {+ name: '@acme/widgets',+ version: '1.0.0',+ __spec: '@acme/widgets',+ __packageDir: tmpDir,+ __manifestFile: manifestFile,+ ...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 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');+ return root;+}++describe('computeRequiredFiles', () => {+ it('enumerates manifest + theme catalog files', () => {+ const root = writeTheme('ocean', ['oceanTheme.ts', 'tokens.ts']);+ const inv = computeRequiredFiles(loaded({themes: root}));++ expect(inv.manifest).toBe('astryx.integration.mjs');+ expect(inv.roots).toHaveLength(1);+ expect(inv.roots[0].kind).toBe('themes');+ expect(inv.roots[0].files).toEqual(+ expect.arrayContaining([+ 'themes/manifest.json',+ 'themes/ocean/oceanTheme.ts',+ 'themes/ocean/tokens.ts',+ ]),+ );+ expect(inv.allFiles).toContain('astryx.integration.mjs');+ expect(inv.allFiles).toContain('themes/manifest.json');+ });++ it('enumerates paired component metadata and source files', () => {+ const root = path.join(tmpDir, 'components');+ fs.mkdirSync(root, {recursive: true});+ for (const name of ['Card', 'Button']) {+ fs.writeFileSync(path.join(root, `${name}.tsx`), `// ${name}\n`);+ fs.writeFileSync(+ path.join(root, `${name}.doc.mjs`),+ `export default {type: 'component', name: '${name}', props: []};\n`,+ );+ }+ fs.writeFileSync(path.join(root, 'PrivateHelper.tsx'), '// unpaired\n');+ fs.writeFileSync(path.join(root, 'utils.ts'), '// not a component\n');+ const inv = computeRequiredFiles(loaded({components: root}));++ expect(inv.roots[0].kind).toBe('components');+ expect(inv.roots[0].files).toEqual(+ expect.arrayContaining([+ 'components/Button.doc.mjs',+ 'components/Button.tsx',+ 'components/Card.doc.mjs',+ 'components/Card.tsx',+ ]),+ );+ expect(inv.roots[0].files).not.toContain('components/PrivateHelper.tsx');+ expect(inv.roots[0].files).not.toContain('components/utils.ts');+ });++ it('includes symlinked component metadata and source paths', () => {+ const root = path.join(tmpDir, 'components');+ const shared = path.join(tmpDir, 'shared');+ fs.mkdirSync(root);+ fs.mkdirSync(shared);+ fs.writeFileSync(+ path.join(shared, 'LinkedWidget.doc.mjs'),+ "export default {type: 'component', name: 'LinkedWidget', props: []};\n",+ );+ fs.writeFileSync(+ path.join(shared, 'LinkedWidget.tsx'),+ 'export function LinkedWidget() { return null; }\n',+ );+ fs.symlinkSync(+ path.relative(root, path.join(shared, 'LinkedWidget.doc.mjs')),+ path.join(root, 'LinkedWidget.doc.mjs'),+ );+ fs.symlinkSync(+ path.relative(root, path.join(shared, 'LinkedWidget.tsx')),+ path.join(root, 'LinkedWidget.tsx'),+ );++ const inventory = computeRequiredFiles(loaded({components: root}));++ expect(inventory.roots[0].files).toEqual([+ 'components/LinkedWidget.doc.mjs',+ 'components/LinkedWidget.tsx',+ ]);+ });++ it('enumerates template files with paired sources', () => {+ const root = path.join(tmpDir, 'templates');+ fs.mkdirSync(path.join(root, 'dashboard'), {recursive: true});+ fs.writeFileSync(+ path.join(root, 'dashboard', 'dashboard.template.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',+ );+ expect(inv.roots[0].files).toContain('templates/dashboard/dashboard.tsx');+ });++ it('enumerates legacy .doc template 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',+ );+ 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.tsx',+ ]);+ });++ it('enumerates codemod files under version dirs', () => {+ const root = path.join(tmpDir, 'codemods');+ fs.mkdirSync(path.join(root, '0.2.0'), {recursive: true});+ fs.writeFileSync(path.join(root, '0.2.0', 'rename-prop.mjs'), '// cm\n');+ const inv = computeRequiredFiles(loaded({codemods: root}));++ expect(inv.roots[0].files).toContain('codemods/0.2.0/rename-prop.mjs');+ });++ it('enumerates doc files', () => {+ const root = path.join(tmpDir, 'docs');+ fs.mkdirSync(root, {recursive: true});+ fs.writeFileSync(path.join(root, 'theming.doc.mjs'), '// doc\n');+ const inv = computeRequiredFiles(loaded({docs: root}));++ expect(inv.roots[0].files).toContain('docs/theming.doc.mjs');+ });++ it('returns empty contributions for a bare manifest', () => {+ const inv = computeRequiredFiles(loaded());+ expect(inv.roots).toEqual([]);+ expect(inv.allFiles).toEqual(['astryx.integration.mjs']);+ });++ it('handles missing root directories gracefully', () => {+ const inv = computeRequiredFiles(+ loaded({themes: path.join(tmpDir, 'nonexistent')}),+ );+ expect(inv.roots[0].files).toEqual([]);+ });+});++describe('compareIdentities', () => {+ const base = () => ({+ themes: [],+ components: [],+ templates: [],+ codemods: [],+ docs: [],+ agentDocsAppend: [],+ });++ it('returns no issues when identities match exactly', () => {+ const local = {+ ...base(),+ themes: [{slug: 'ocean', exportName: 'oceanTheme'}],+ components: ['Card'],+ };+ const packed = {+ ...base(),+ themes: [{slug: 'ocean', exportName: 'oceanTheme'}],+ components: ['Card'],+ };+ expect(compareIdentities(local, packed)).toEqual([]);+ });++ it('errors when a theme slug is missing from packed', () => {+ const local = {+ ...base(),+ themes: [+ {slug: 'ocean', exportName: 'oceanTheme'},+ {slug: 'forest', exportName: 'forestTheme'},+ ],+ };+ const packed = {+ ...base(),+ themes: [{slug: 'ocean', exportName: 'oceanTheme'}],+ };+ const issues = compareIdentities(local, packed);+ expect(issues).toHaveLength(1);+ expect(issues[0]).toMatchObject({+ code: 'identity_not_packed',+ severity: 'error',+ });+ expect(issues[0].message).toContain('forest');+ });++ it('errors when a component name is missing from packed', () => {+ const local = {...base(), components: ['Card', 'Button']};+ const packed = {...base(), components: ['Card']};+ const issues = compareIdentities(local, packed);+ expect(issues).toHaveLength(1);+ expect(issues[0].message).toContain('Button');+ });++ it('errors when a template id is missing from packed', () => {+ const local = {+ ...base(),+ templates: [{id: 'dash', type: 'page', name: 'Dashboard'}],+ };+ const packed = {...base()};+ const issues = compareIdentities(local, packed);+ expect(issues).toHaveLength(1);+ expect(issues[0].message).toContain('dash');+ });++ it('errors when a codemod is missing from packed', () => {+ const local = {+ ...base(),+ codemods: [{version: '0.2.0', id: 'rename-prop'}],+ };+ const packed = {...base()};+ const issues = compareIdentities(local, packed);+ expect(issues).toHaveLength(1);+ expect(issues[0].message).toContain('rename-prop');+ });++ it('errors when a doc topic is missing from packed', () => {+ const local = {...base(), docs: ['theming']};+ const packed = {...base()};+ const issues = compareIdentities(local, packed);+ expect(issues).toHaveLength(1);+ expect(issues[0].message).toContain('theming');+ });++ it('errors when packed contains an identity absent locally', () => {+ const local = {...base()};+ const packed = {...base(), docs: ['surprise']};+ const issues = compareIdentities(local, packed);+ expect(issues).toEqual([+ expect.objectContaining({+ code: 'packed_identity_unexpected',+ message: expect.stringContaining('surprise'),+ }),+ ]);+ });++ it('errors when a matching identity resolves to different metadata', () => {+ const local = {+ ...base(),+ templates: [{id: 'dash', type: 'page', name: 'Dashboard'}],+ };+ const packed = {+ ...base(),+ templates: [{id: 'dash', type: 'block', name: 'Dashboard'}],+ };+ const issues = compareIdentities(local, packed);+ expect(issues).toEqual([+ expect.objectContaining({+ code: 'identity_mismatch',+ message: expect.stringContaining('dash'),+ }),+ ]);+ });++ it('errors when agentDocs lines differ', () => {+ const local = {...base(), agentDocsAppend: ['Install via npm.']};+ const packed = {...base(), agentDocsAppend: []};+ const issues = compareIdentities(local, packed);+ expect(issues).toHaveLength(1);+ expect(issues[0].code).toBe('agent_docs_mismatch');+ });+});++describe('findSourceOnlyCandidates', () => {+ it('finds PascalCase .tsx without metadata', () => {+ const root = path.join(tmpDir, 'components');+ fs.mkdirSync(root);+ fs.writeFileSync(path.join(root, 'Card.tsx'), '// Card\n');+ fs.writeFileSync(path.join(root, 'Button.tsx'), '// Button\n');+ fs.writeFileSync(path.join(root, 'helper.tsx'), '// lowercase\n');+ const candidates = findSourceOnlyCandidates(root, ['Card']);+ expect(candidates).toEqual(['Button']);+ });++ it('includes a symlinked PascalCase source candidate', () => {+ const root = path.join(tmpDir, 'components');+ fs.mkdirSync(root);+ fs.writeFileSync(path.join(root, 'source.tsx'), '// source\n');+ fs.symlinkSync('source.tsx', path.join(root, 'LinkedWidget.tsx'));+ expect(findSourceOnlyCandidates(root, [])).toEqual(['LinkedWidget']);+ });++ it('returns empty when all are registered', () => {+ const root = path.join(tmpDir, 'components');+ fs.mkdirSync(root);+ fs.writeFileSync(path.join(root, 'Card.tsx'), '// Card\n');+ expect(findSourceOnlyCandidates(root, ['Card'])).toEqual([]);+ });++ it('returns empty for missing root', () => {+ expect(findSourceOnlyCandidates(undefined, [])).toEqual([]);+ });++ it('ignores nested directories', () => {+ const root = path.join(tmpDir, 'components');+ fs.mkdirSync(path.join(root, 'sub'), {recursive: true});+ fs.writeFileSync(path.join(root, 'sub', 'Deep.tsx'), '// nested\n');+ expect(findSourceOnlyCandidates(root, [])).toEqual([]);+ });+});diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex d76e7264c3..74badd287e 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -6,7 +6,7 @@* Integrations are PACKAGE NAMES listed in astryx.config.{ts,mjs,js}. Each* package declares a single conventional root manifest sibling to its* package.json — astryx.integration.{ts,mjs,js} — which contributes- * components/templates/codemods/docs roots and an optional issuesUrl. Identity+ * components/templates/codemods/docs/themes roots and an optional issuesUrl. Identity* (name, version) comes from the package's package.json, not the manifest.*/@@ -25,8 +25,8 @@ import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';/*** A fully-resolved, loaded integration. Identity (`name`, `version`) comes from- * the package's package.json; the `components`/`templates`/`codemods`/`docs`- * roots are absolute paths resolved from the manifest. The `__`-prefixed fields+ * the package's package.json; the `components`/`templates`/`codemods`/`docs`/+ * `themes` roots are absolute paths resolved from the manifest. The `__`-prefixed fields* are internal bookkeeping used by Doctor integration validation and Project.* @typedef {object} LoadedIntegration* @property {string} name@@ -35,6 +35,7 @@ import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';* @property {string} [templates]* @property {string} [codemods]* @property {string} [docs]+ * @property {string} [themes]* @property {string} [issuesUrl]* @property {{append?: readonly string[]}} [agentDocs]* @property {string} [__agentDocsError] contribution-specific validation@@ -52,6 +53,8 @@ import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';* @property {boolean} [__autolinked] loaded because the project declares the* package as a dependency and it ships a manifest, with no astryx.config* entry naming it — see foundation/integrations/autolink.mjs+ * @property {boolean} [__local] loaded from the package containing the current+ * working directory, so an author sees the exact bytes they are editing* @property {string} [__dependencyField] for an autolinked integration, the* package.json field that declared it (`dependencies`, `devDependencies`,* `optionalDependencies`)@@ -181,7 +184,9 @@ export function resolvePackageDir(packageName, cwd = process.cwd()) {const nodeModules = path.resolve(cwd, 'node_modules');const dir = path.resolve(nodeModules, ...packageName.split('/'));if (dir !== nodeModules && !dir.startsWith(nodeModules + path.sep)) {- throw new Error(`Integration "${packageName}" resolves outside node_modules.`);+ throw new Error(+ `Integration "${packageName}" resolves outside node_modules.`,+ );}return dir;}@@ -210,6 +215,94 @@ function resolveManifestPath(packageDir, spec) {return present[0];}+/**+ * Load the integration package rooted at `packageDir` directly, without first+ * installing or publishing it. This is the self-resolution seam: an author in+ * a package with a manifest sees the same contributions a consumer installs.+ *+ * A missing manifest returns null. A broken manifest returns the same load-error+ * marker as an installed integration, so Project issues stay truthful.+ *+ * @param {string} packageDir+ * @param {{fresh?: boolean}} [options]+ * @returns {Promise<LoadedIntegration|null>}+ */+export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {+ const manifests = findManifestPaths(packageDir);+ if (manifests.length === 0) return null;++ const pkgPath = path.join(packageDir, 'package.json');+ let pkg;+ try {+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));+ } catch {+ throw new Error(+ `Could not read the local integration package at ${pkgPath}.`,+ );+ }+ const spec =+ typeof pkg.name === 'string' && pkg.name.length > 0+ ? pkg.name+ : '(local integration)';+ const manifestFile = resolveManifestPath(packageDir, spec);++ let manifest;+ /** @type {string[]} */+ let unknownKeys;+ /** @type {import('../../authoring/debug/type').DebugEventHandler | undefined} */+ let debugHandler;+ /** @type {string | undefined} */+ let agentDocsError;+ try {+ ({+ manifest,+ unknownKeys,+ debug: debugHandler,+ agentDocsError,+ } = await loadManifest(manifestFile, `Integration ${spec}`, {fresh}));+ } catch (err) {+ return {+ name: spec,+ version: pkg.version,+ __spec: spec,+ __packageDir: packageDir,+ __manifestFile: manifestFile,+ __loadError: err instanceof Error ? err.message : String(err),+ __local: true,+ };+ }++ /** @param {string | null | undefined} value */+ const resolveRoot = value => {+ if (value == null) return undefined;+ try {+ return assertWithin(value, packageDir, {label: 'contribution root'});+ } catch {+ return undefined;+ }+ };++ return {+ name: spec,+ version: pkg.version,+ components: resolveRoot(manifest.components),+ templates: resolveRoot(manifest.templates),+ codemods: resolveRoot(manifest.codemods),+ docs: resolveRoot(manifest.docs),+ themes: resolveRoot(manifest.themes),+ issuesUrl: manifest.issuesUrl,+ agentDocs: manifest.agentDocs,+ __agentDocsError: agentDocsError,+ __unknownKeys: unknownKeys,+ __debug: debugHandler,+ __spec: spec,+ __packageDir: packageDir,+ __packageExports: pkg.exports ?? null,+ __manifestFile: manifestFile,+ __local: true,+ };+}+/*** Load configured integrations.*@@ -289,6 +382,7 @@ export async function loadIntegrations(templates: resolveRoot(manifest.templates),codemods: resolveRoot(manifest.codemods),docs: resolveRoot(manifest.docs),+ themes: resolveRoot(manifest.themes),issuesUrl: manifest.issuesUrl,agentDocs: manifest.agentDocs,__agentDocsError: agentDocsError,diff --git a/packages/cli/foundation/integrations/manifest-writer.mjs b/packages/cli/foundation/integrations/manifest-writer.mjsnew file mode 100644index 0000000000..df1b6cce28--- /dev/null+++ b/packages/cli/foundation/integrations/manifest-writer.mjs@@ -0,0 +1,328 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Shared writer for adding one contribution root to an existing Astryx+ * integration manifest without replacing any author-owned field.+ *+ * The function is intentionally independent of every contribution kind. Theme,+ * component, template, doc, and codemod writers all need the same operation and+ * must not grow separate source-rewrite implementations.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {randomUUID} from 'node:crypto';+import jscodeshift from 'jscodeshift';+import {assertWithin} from '../fs/path-safety.mjs';+import {findManifestPaths, loadManifestObject} from './integrations.mjs';++export class IntegrationRootConflictError extends Error {+ /** @param {string} kind @param {string} current @param {string} requested */+ constructor(kind, current, requested) {+ super(+ `Integration manifest already declares ${kind}: "${current}"; refusing to replace it with "${requested}".`,+ );+ this.name = 'IntegrationRootConflictError';+ this.code = 'INTEGRATION_ROOT_CONFLICT';+ this.kind = kind;+ this.current = current;+ this.requested = requested;+ }+}++/**+ * Find the one local integration manifest, or null when none exists.+ * @param {string} packageDir+ * @returns {string|null}+ */+export function findLocalIntegrationManifestOrNull(packageDir) {+ const manifests = findManifestPaths(packageDir);+ if (manifests.length === 0) return null;+ if (manifests.length > 1) {+ throw new Error(+ `Multiple integration manifests found (${manifests+ .map(file => path.basename(file))+ .join(', ')}). Keep exactly one.`,+ );+ }+ return manifests[0];+}++/**+ * Find the one local integration manifest.+ * @param {string} packageDir+ * @returns {string}+ */+export function findLocalIntegrationManifest(packageDir) {+ const manifest = findLocalIntegrationManifestOrNull(packageDir);+ if (manifest == null) {+ throw new Error('No astryx.integration.{ts,mjs,js} file found.');+ }+ return manifest;+}++/** @param {any} node */+export function unwrapManifestExpression(node) {+ let current = node;+ while (+ current &&+ [+ 'TSAsExpression',+ 'TSSatisfiesExpression',+ 'TypeCastExpression',+ 'ParenthesizedExpression',+ ].includes(current.type)+ ) {+ current = current.expression;+ }+ return current;+}++/** @param {any} property @param {string} name */+function propertyNamed(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)+ );+}++/**+ * Find the object literal an integration manifest exports.+ * @param {ReturnType<typeof jscodeshift.withParser>} j+ * @param {ReturnType<ReturnType<typeof jscodeshift.withParser>>} ast+ * @returns {any|null}+ */+export function findManifestObject(j, ast) {+ const exports = ast.find(j.ExportDefaultDeclaration);+ if (exports.size() !== 1) return null;+ let declaration = unwrapManifestExpression(exports.nodes()[0].declaration);++ if (j.Identifier.check(declaration)) {+ const bindings = ast.find(j.VariableDeclarator, {+ id: {type: 'Identifier', name: declaration.name},+ });+ if (bindings.size() !== 1) return null;+ declaration = unwrapManifestExpression(bindings.nodes()[0].init);+ }++ if (j.CallExpression.check(declaration) && declaration.arguments.length > 0) {+ declaration = unwrapManifestExpression(declaration.arguments[0]);+ }++ return j.ObjectExpression.check(declaration) ? declaration : null;+}++/** @param {string} file */+function removeTemporary(file) {+ try {+ fs.rmSync(file, {force: true});+ } catch {+ // Best effort. The transaction error remains the actionable failure.+ }+}++/**+ * Atomically replace one text file while preserving its mode.+ * @param {string} file+ * @param {string} contents+ * @param {string} [expectedContents] bytes read during preflight+ */+function replaceFile(file, contents, expectedContents) {+ const expected =+ expectedContents === undefined ? null : Buffer.from(expectedContents);+ const assertUnchanged = () => {+ if (expected != null && !fs.readFileSync(file).equals(expected)) {+ throw new Error(`File changed while writing: ${file}`);+ }+ };+ const temporary = path.join(+ path.dirname(file),+ `.${path.basename(file)}.tmp-${randomUUID()}`,+ );+ let descriptor;+ try {+ assertUnchanged();+ const mode = fs.statSync(file).mode;+ descriptor = fs.openSync(temporary, 'wx', mode);+ fs.writeFileSync(descriptor, contents, 'utf-8');+ fs.closeSync(descriptor);+ descriptor = undefined;+ assertUnchanged();+ fs.renameSync(temporary, file);+ } catch (error) {+ if (descriptor != null) fs.closeSync(descriptor);+ removeTemporary(temporary);+ throw error;+ }+}++/**+ * Atomically create one text file without replacing a racing writer.+ * @param {string} file+ * @param {string} contents+ */+function createFile(file, contents) {+ const temporary = path.join(+ path.dirname(file),+ `.${path.basename(file)}.tmp-${randomUUID()}`,+ );+ let descriptor;+ let linked = false;+ try {+ descriptor = fs.openSync(temporary, 'wx', 0o666);+ fs.writeFileSync(descriptor, contents, 'utf-8');+ fs.closeSync(descriptor);+ descriptor = undefined;+ fs.linkSync(temporary, file);+ linked = true;+ removeTemporary(temporary);+ } catch (error) {+ if (descriptor != null) fs.closeSync(descriptor);+ if (linked) {+ try {+ removeFileIfUnchanged(file, contents);+ } catch {+ // Preserve a concurrent edit rather than forcing cleanup.+ }+ }+ removeTemporary(temporary);+ throw error;+ }+}++/** @param {string} file @param {string} expectedContents */+function removeFileIfUnchanged(file, expectedContents) {+ if (fs.lstatSync(file).isSymbolicLink()) {+ throw new Error(`File changed before rollback: ${file}`);+ }+ if (!fs.readFileSync(file).equals(Buffer.from(expectedContents))) {+ throw new Error(`File changed before rollback: ${file}`);+ }+ fs.rmSync(file);+}++/**+ * Add a contribution root to an integration manifest, creating the manifest+ * when requested and none exists.+ *+ * If the key already has `rootPath`, this is an idempotent no-op. A different+ * author-owned value is a typed refusal. `dryRun` performs every read and+ * source-shape check but writes nothing. `createIfMissing` creates a minimal+ * `.mjs` manifest as part of the same verified operation.+ *+ * @param {string} packageDir+ * @param {string} kind+ * @param {string} rootPath+ * @param {{dryRun?: boolean, verify?: () => void | Promise<void>, createIfMissing?: boolean}} [options]+ * @returns {Promise<{path: string, created: boolean}>}+ */+export async function patchIntegrationRoot(+ packageDir,+ kind,+ rootPath,+ {dryRun = false, verify, createIfMissing = false} = {},+) {+ if (!/^[A-Za-z_$][\w$]*$/u.test(kind)) {+ throw new Error(`Invalid integration root key "${kind}".`);+ }+ assertWithin(rootPath, packageDir, {label: `${kind} root`});++ const existingManifest = findLocalIntegrationManifestOrNull(packageDir);+ const manifestExists = existingManifest != null;+ if (!manifestExists && !createIfMissing) {+ throw new Error('No astryx.integration.{ts,mjs,js} file found.');+ }+ const manifestFile =+ existingManifest ?? path.join(packageDir, 'astryx.integration.mjs');+ let writableManifestFile = manifestFile;+ if (manifestExists && fs.lstatSync(manifestFile).isSymbolicLink()) {+ writableManifestFile = assertWithin(+ fs.realpathSync(manifestFile),+ packageDir,+ {+ allowAbsolute: true,+ label: 'integration manifest symlink target',+ },+ );+ }++ /** @type {Record<string, unknown>} */+ let manifest = {};+ if (manifestExists) {+ manifest = /** @type {Record<string, unknown>} */ (+ await loadManifestObject(+ manifestFile,+ `Integration manifest ${path.basename(manifestFile)}`,+ {fresh: true},+ )+ );+ }+ const current = manifest[kind];+ if (current !== undefined) {+ if (current !== rootPath) {+ throw new IntegrationRootConflictError(kind, String(current), rootPath);+ }+ if (!dryRun && verify) await verify();+ return {path: rootPath, created: false};+ }++ const source = manifestExists+ ? fs.readFileSync(manifestFile, 'utf-8')+ : 'export default {};\n';+ const j = jscodeshift.withParser('tsx');+ let ast;+ try {+ ast = j(source);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(+ `Could not parse ${path.basename(manifestFile)}: ${message}`,+ {cause: error},+ );+ }+ const object = findManifestObject(j, ast);+ if (!object) {+ throw new Error(+ `Could not update ${path.basename(manifestFile)} safely: its default export is not a static object literal.`,+ );+ }++ if (+ object.properties.some((/** @type {any} */ property) =>+ propertyNamed(property, kind),+ )+ ) {+ throw new Error(+ `${path.basename(manifestFile)} changed while preparing ${kind}. Run the command again.`,+ );+ }++ object.properties.push(+ j.objectProperty(j.identifier(kind), j.stringLiteral(rootPath)),+ );+ let next = ast.toSource({quote: 'single', reuseWhitespace: true});+ if (source.endsWith('\n') && !next.endsWith('\n')) next += '\n';+ if (!dryRun) {+ if (manifestExists) replaceFile(writableManifestFile, next, source);+ else createFile(manifestFile, next);+ try {+ if (verify) await verify();+ } catch (error) {+ if (manifestExists) replaceFile(writableManifestFile, source, next);+ else removeFileIfUnchanged(manifestFile, next);+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(`Post-write verification failed: ${message}`, {+ cause: error,+ });+ }+ }+ return {path: rootPath, created: true};+}diff --git a/packages/cli/foundation/integrations/manifest-writer.test.mjs b/packages/cli/foundation/integrations/manifest-writer.test.mjsnew file mode 100644index 0000000000..6e9844ff6c--- /dev/null+++ b/packages/cli/foundation/integrations/manifest-writer.test.mjs@@ -0,0 +1,229 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ findLocalIntegrationManifest,+ findLocalIntegrationManifestOrNull,+ IntegrationRootConflictError,+ patchIntegrationRoot,+} from './manifest-writer.mjs';++let tmpDir;++function manifest(source = 'export default {};\n', ext = 'mjs') {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"fixture"}\n');+ const file = path.join(tmpDir, `astryx.integration.${ext}`);+ fs.writeFileSync(file, source);+ return file;+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-manifest-writer-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('patchIntegrationRoot', () => {+ it('creates a minimal manifest when requested', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"fixture"}\n');+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes', {+ createIfMissing: true,+ }),+ ).resolves.toEqual({path: './themes', created: true});+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toContain("themes: './themes'");+ });++ it('plans manifest creation without writing it', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"fixture"}\n');+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes', {+ createIfMissing: true,+ dryRun: true,+ }),+ ).resolves.toEqual({path: './themes', created: true});+ expect(findLocalIntegrationManifestOrNull(tmpDir)).toBeNull();+ });++ it('adds a root to a direct default export and preserves other fields', async () => {+ const file = manifest(+ `// Keep this note.\nexport default {components: './components'};\n`,+ );+ const result = await patchIntegrationRoot(tmpDir, 'themes', './themes');+ const source = fs.readFileSync(file, 'utf-8');++ expect(result).toEqual({path: './themes', created: true});+ expect(source).toContain('// Keep this note.');+ expect(source).toContain("components: './components'");+ expect(source).toContain("themes: './themes'");+ });++ it('handles a typed satisfies expression', async () => {+ const file = manifest(+ `import type {AstryxIntegration} from '@astryxdesign/cli/authoring';\nexport default {} satisfies AstryxIntegration;\n`,+ 'ts',+ );+ await patchIntegrationRoot(tmpDir, 'themes', './themes');+ expect(fs.readFileSync(file, 'utf-8')).toContain("themes: './themes'");+ });++ it('is an idempotent no-op when the root already matches', async () => {+ const file = manifest(`export default {themes: './themes'};\n`);+ const before = fs.readFileSync(file, 'utf-8');+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes'),+ ).resolves.toEqual({path: './themes', created: false});+ expect(fs.readFileSync(file, 'utf-8')).toBe(before);+ });++ it('returns a typed refusal instead of replacing an author-owned root', async () => {+ manifest(`export default {themes: './src/themes'};\n`);+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes'),+ ).rejects.toBeInstanceOf(IntegrationRootConflictError);+ });++ it('runs read-back for an already-correct root', async () => {+ manifest(`export default {themes: './themes'};\n`);+ let verified = 0;+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes', {+ verify: () => {+ verified += 1;+ },+ }),+ ).resolves.toEqual({path: './themes', created: false});+ expect(verified).toBe(1);+ });++ it('restores the manifest when post-write verification fails', async () => {+ const file = manifest(`export default {components: './components'};\n`);+ const before = fs.readFileSync(file, 'utf-8');+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes', {+ verify: () => {+ throw new Error('not visible');+ },+ }),+ ).rejects.toThrow(/Post-write verification failed: not visible/u);+ expect(fs.readFileSync(file, 'utf-8')).toBe(before);+ });++ it('does not clobber a concurrent manifest edit during rollback', async () => {+ const file = manifest(`export default {components: './components'};\n`);+ const concurrent = `export default {components: './components', docs: './docs'};\n`;+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes', {+ verify: () => {+ fs.writeFileSync(file, concurrent);+ throw new Error('not visible');+ },+ }),+ ).rejects.toThrow(/File changed while writing/u);+ expect(fs.readFileSync(file, 'utf-8')).toBe(concurrent);+ });++ it('removes a newly created manifest when verification fails', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"fixture"}\n');+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes', {+ createIfMissing: true,+ verify: () => {+ throw new Error('not visible');+ },+ }),+ ).rejects.toThrow(/Post-write verification failed: not visible/u);+ expect(findLocalIntegrationManifestOrNull(tmpDir)).toBeNull();+ });++ it('preserves a concurrent edit to a newly created manifest on rollback', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"fixture"}\n');+ const file = path.join(tmpDir, 'astryx.integration.mjs');+ const concurrent = `export default {docs: './docs'};\n`;+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes', {+ createIfMissing: true,+ verify: () => {+ fs.writeFileSync(file, concurrent);+ throw new Error('not visible');+ },+ }),+ ).rejects.toThrow(/File changed before rollback/u);+ expect(fs.readFileSync(file, 'utf-8')).toBe(concurrent);+ });++ it('dry-runs the same patch without changing bytes', async () => {+ const file = manifest();+ const before = fs.readFileSync(file, 'utf-8');+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes', {dryRun: true}),+ ).resolves.toEqual({path: './themes', created: true});+ expect(fs.readFileSync(file, 'utf-8')).toBe(before);+ });++ it('refuses a root key that is not a JavaScript identifier', async () => {+ manifest();+ await expect(+ patchIntegrationRoot(tmpDir, 'not-a-key', './root'),+ ).rejects.toThrow(/Invalid integration root key/);+ });++ it('refuses a root that escapes the package', async () => {+ manifest();+ await expect(+ patchIntegrationRoot(tmpDir, 'themes', '../themes'),+ ).rejects.toThrow(/outside the project root/u);+ });++ it('preserves a manifest symlink and updates its in-package target', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"fixture"}\n');+ fs.mkdirSync(path.join(tmpDir, 'config'));+ const target = path.join(tmpDir, 'config', 'integration.mjs');+ const manifestFile = path.join(tmpDir, 'astryx.integration.mjs');+ fs.writeFileSync(target, 'export default {};\n');+ fs.symlinkSync(target, manifestFile);++ await patchIntegrationRoot(tmpDir, 'themes', './themes');++ expect(fs.lstatSync(manifestFile).isSymbolicLink()).toBe(true);+ expect(fs.readFileSync(target, 'utf-8')).toContain("themes: './themes'");+ });++ it('refuses a manifest symlink whose target escapes the package', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"fixture"}\n');+ const outside = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-manifest-outside-'),+ );+ try {+ const target = path.join(outside, 'integration.mjs');+ fs.writeFileSync(target, 'export default {};\n');+ fs.symlinkSync(target, path.join(tmpDir, 'astryx.integration.mjs'));++ await expect(+ patchIntegrationRoot(tmpDir, 'themes', './themes'),+ ).rejects.toThrow(/outside the project root|symlink/u);+ expect(fs.readFileSync(target, 'utf-8')).toBe('export default {};\n');+ } finally {+ fs.rmSync(outside, {recursive: true, force: true});+ }+ });++ it('finds zero or exactly one conventional manifest', () => {+ expect(findLocalIntegrationManifestOrNull(tmpDir)).toBeNull();+ const file = manifest();+ expect(findLocalIntegrationManifest(tmpDir)).toBe(file);+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.js'),+ 'export default {};\n',+ );+ expect(() => findLocalIntegrationManifest(tmpDir)).toThrow(+ /Multiple integration manifests/u,+ );+ });+});diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjsindex d4ea333a41..9ba85d6c21 100644--- a/packages/cli/foundation/integrations/validate-contributions.mjs+++ b/packages/cli/foundation/integrations/validate-contributions.mjs@@ -13,7 +13,7 @@* did that. Optional contributions such as `agentDocs` carry their own error* marker so a bad contribution is reported without withdrawing valid roots.* What is re-checked is the on-disk contributions (roots +- * codemods/templates/components), because those regress independently of the+ * codemods/templates/components/docs/themes), because those regress independently of the* manifest: a deleted directory, a template that lost its source file.** @input a loaded-integration-shaped object (absolute contribution roots + identity)@@ -22,10 +22,14 @@*/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 {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';import * as componentDiscovery from '../discovery/component-discovery.mjs';import {discoverIntegrationDocs} from '../discovery/docs-discovery.mjs';+import {discoverIntegrationThemes} from '../discovery/theme-discovery.mjs';/*** @typedef {import('./issue').AstryxIntegrationIssue} Issue@@ -77,12 +81,18 @@ function checkUnknownKeys(integration, issues) {/*** Verify each declared contribution root exists on disk. A declared-but-missing* root is a `missing_root` error.- * @param {{components?: string, templates?: string, codemods?: string, docs?: string}} resolved+ * @param {{components?: string, templates?: string, codemods?: string, docs?: string, themes?: string}} resolved* absolute resolved roots (undefined when not declared)* @param {Issue[]} issues*/function checkRoots(resolved, issues) {- const kinds = /** @type {const} */ (['components', 'templates', 'codemods', 'docs']);+ const kinds = /** @type {const} */ ([+ 'components',+ 'templates',+ 'codemods',+ 'docs',+ 'themes',+ ]);for (const kind of kinds) {const root = resolved[kind];if (root == null) continue;@@ -106,10 +116,42 @@ function checkRoots(resolved, issues) {*/async function checkCodemods(integration, issues) {if (!integration.codemods || !fs.existsSync(integration.codemods)) return;+ 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)+ ) {+ 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.`,+ ),+ );+ }+ if (+ entry.isDirectory() &&+ !['node_modules', '.git', '__tests__', '__fixtures__'].includes(+ entry.name,+ ) &&+ !isValidSemver(entry.name)+ ) {+ issues.push(+ issueError(+ 'invalid_codemod_version',+ `Codemod folder "${entry.name}" is not an exact semver version such as 1.2.0.`,+ ),+ );+ }+ }try {await discoverIntegrationCodemods([integration]);} catch (err) {- issues.push(issueError('invalid_codemod', /** @type {any} */ (err).message));+ issues.push(+ issueError('invalid_codemod', /** @type {any} */ (err).message),+ );}}@@ -127,7 +169,9 @@ async function checkTemplates(integration, issues) {issues.push(issueError('invalid_template', e.message));}} catch (err) {- issues.push(issueError('invalid_template', /** @type {any} */ (err).message));+ issues.push(+ issueError('invalid_template', /** @type {any} */ (err).message),+ );}}@@ -159,8 +203,21 @@ async function checkComponents(integration, issues) {);}}+ for (const name of findSourceOnlyCandidates(+ integration.components,+ records.map(record => record.name),+ )) {+ issues.push(+ issueWarning(+ 'source_without_component_doc',+ `Component source "${name}.tsx" has no same-stem metadata file ${name}.doc.mjs, so Astryx ignores it.`,+ ),+ );+ }} catch (err) {- issues.push(issueError('invalid_component', /** @type {any} */ (err).message));+ issues.push(+ issueError('invalid_component', /** @type {any} */ (err).message),+ );}}@@ -189,6 +246,22 @@ async function checkDocs(integration, issues) {}}+/**+ * Validate the integration's source-theme catalog. The same discovery function+ * powers Project and theme list/add, so validation cannot accept a shape that+ * consumers later fail to use.+ * @param {LoadedIntegration} integration+ * @param {Issue[]} issues+ */+async function checkThemes(integration, issues) {+ if (!integration.themes || !fs.existsSync(integration.themes)) return;+ try {+ await discoverIntegrationThemes(integration);+ } catch (err) {+ issues.push(issueError('invalid_theme', /** @type {any} */ (err).message));+ }+}+/*** Run every contribution validator against a loaded-integration-shaped object.* @param {LoadedIntegration} integration@@ -199,6 +272,7 @@ async function runContributionChecks(integration, issues) {await checkTemplates(integration, issues);await checkComponents(integration, issues);await checkDocs(integration, issues);+ await checkThemes(integration, issues);}/**@@ -232,6 +306,7 @@ export async function validateLoadedIntegration(loaded) {templates: loaded.templates,codemods: loaded.codemods,docs: loaded.docs,+ themes: loaded.themes,},issues,);diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjsindex bcf908c164..410fd68263 100644--- a/packages/cli/foundation/response/error-codes.doc.mjs+++ b/packages/cli/foundation/response/error-codes.doc.mjs@@ -113,10 +113,25 @@ export const doc = {description:'A component name is owned by more than one package (narrow with --package).',},+ {+ value: 'ERR_AMBIGUOUS_THEME',+ description:+ 'A theme slug is owned by more than one package (narrow with --package).',+ },{value: 'ERR_UNKNOWN_THEME',description: 'No theme matched the requested slug (theme add).',},+ {+ value: 'ERR_INTEGRATION_ROOT_CONFLICT',+ description:+ 'An integration manifest already declares a different path for the requested contribution root.',+ },+ {+ value: 'ERR_INTEGRATION_EXPORT_CONFLICT',+ description:+ 'A package export already maps a generated contribution subpath to a different target.',+ },{value: 'ERR_UNKNOWN_PACKAGE',description: 'No package matched the requested name (discover).',@@ -189,7 +204,7 @@ export const doc = {{value: 'ERR_THEME_INVALID',description:- 'A theme definition was missing a required property (e.g. `name`).',+ 'A theme definition or contributed theme catalog is invalid.',},{value: 'ERR_THEME_LOAD',diff --git a/packages/cli/foundation/response/error-codes.mjs b/packages/cli/foundation/response/error-codes.mjsindex aabdc614fc..1ed15a065c 100644--- a/packages/cli/foundation/response/error-codes.mjs+++ b/packages/cli/foundation/response/error-codes.mjs@@ -55,7 +55,10 @@* | 'ERR_UNKNOWN_TEMPLATE'* | 'ERR_AMBIGUOUS_TEMPLATE'* | 'ERR_AMBIGUOUS_COMPONENT'+ * | 'ERR_AMBIGUOUS_THEME'* | 'ERR_UNKNOWN_THEME'+ * | 'ERR_INTEGRATION_ROOT_CONFLICT'+ * | 'ERR_INTEGRATION_EXPORT_CONFLICT'* | 'ERR_UNKNOWN_PACKAGE'* | 'ERR_UNKNOWN_AGENT'* | 'ERR_UNKNOWN_FEATURE'@@ -140,8 +143,14 @@ export const ERROR_CODES = Object.freeze({ERR_AMBIGUOUS_TEMPLATE: 'ERR_AMBIGUOUS_TEMPLATE',/** A component name is owned by more than one package (narrow with --package). */ERR_AMBIGUOUS_COMPONENT: 'ERR_AMBIGUOUS_COMPONENT',+ /** A theme slug is owned by more than one package (narrow with --package). */+ ERR_AMBIGUOUS_THEME: 'ERR_AMBIGUOUS_THEME',/** No theme matched the requested slug (theme add). */ERR_UNKNOWN_THEME: 'ERR_UNKNOWN_THEME',+ /** An integration root already points somewhere other than the requested path. */+ ERR_INTEGRATION_ROOT_CONFLICT: 'ERR_INTEGRATION_ROOT_CONFLICT',+ /** A package export already maps a generated contribution subpath elsewhere. */+ ERR_INTEGRATION_EXPORT_CONFLICT: 'ERR_INTEGRATION_EXPORT_CONFLICT',/** No package matched the requested name (discover). */ERR_UNKNOWN_PACKAGE: 'ERR_UNKNOWN_PACKAGE',/** An unrecognized `--agent` value was passed to agent-docs/init. */@@ -176,7 +185,7 @@ export const ERROR_CODES = Object.freeze({ERR_WRITE_FAILED: 'ERR_WRITE_FAILED',// ── Theme build ──────────────────────────────────────────────────- /** A theme definition was missing a required property (e.g. `name`). */+ /** A theme definition or contributed theme catalog 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 60432f741e..ee355f1f17 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -197,12 +197,12 @@ export const doc = {{value: 'theme.list',description:- 'Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag.',+ 'Every bundled or installed integration theme as a ThemeListEntry[]: each with slug, displayName, description, maintained flag, and owner package.',},{value: 'theme.add',description:- 'A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written.',+ 'A scaffold receipt: resolved slug, displayName, maintained flag, owner package, outputDir (relative to cwd), the theme entry file, its exportName, and the files written.',},{value: 'theme.template',@@ -252,6 +252,16 @@ export const doc = {},// integration authoring+ {+ value: 'integration.add',+ description:+ 'A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun.',+ },+ {+ value: 'integration.pack-check',+ description:+ 'The packed-package check: package identity, tarball facts, local and packed contribution inventories, and issues.',+ },{value: 'integration.validate',description: