An open source design system that's fully customizable and agent ready
TypeScript
[CLI] Add opt-in app theme imports (#6874)
Joey71cf6cd06273
diff --git a/.changeset/app-themes-import-built.md b/.changeset/app-themes-import-built.mdnew file mode 100644index 0000000000..42aff1f503--- /dev/null+++ b/.changeset/app-themes-import-built.md@@ -0,0 +1,19 @@+---+'@astryxdesign/cli': patch+---++[feat] Apps can opt into package-managed themes with `astryx theme add <slug> --import`. The command records the theme in one generated app module with its production CSS, optional font CSS, and default slug. Use `theme remove` and `theme use` to manage that record, and pass `themes[defaultThemeSlug]` to `<Theme>`.++Plain `astryx theme add` keeps its released source-copy behavior, options, stdout, exit status, and every `theme.add` data field. It now warns that `theme eject` is the explicit source-fork command and `theme add --import` is the way to use the package-managed theme. Its machine result adds the `DEP-0005` deprecation entry; the cleanup is `CLN-0005` in a later scheduled minor.++Use `defineTheme({extends: importedTheme, ...})` for ordinary customization. `theme eject` creates an independent local fork with its descriptor. JSON callers receive `theme.app` from import, remove, and use, or `theme.eject` from eject.++Existing bundled source copies stay where they are and keep their bytes. Run `astryx upgrade --from 0.6.4 --path . --apply` to add the missing unmaintained descriptor beside each bundled copy in `src/themes`. Until then, theme commands skip those copies and `theme list` and doctor name them as unmigrated. Package integration themes keep their released complete-directory copy, including the authoring descriptor.++`ASTRYX_THEME` is no longer read. In a project with a generated app theme module, component metadata reads that record's default built theme. Without the module, the released `package.json#astryx.theme` lookup keeps its meaning. Doctor loads every recorded built module through the same theme adapter, so a broken runtime import fails `theme-owners` instead of passing.++`theme build` also writes `<out>.css.d.ts` so TypeScript accepts generated CSS imports. Check mode stays compatible with released output sets that do not have this new stub yet.++Integration themes can export built modules and stylesheets. `astryx integration add theme` creates those exports, and `integration verify` checks the exported paths against the packed package and source. Missing partner exports alone do not block packing. Every declared export must resolve; staleness is a warning for an incomplete set and an error for the complete importable module and stylesheet pair.++@josephfarinadiff --git a/.changeset/search-quality-scoring-tie.md b/.changeset/search-quality-scoring-tie.mdindex 74ac799a24..47c0a3bbe6 100644--- a/.changeset/search-quality-scoring-tie.md+++ b/.changeset/search-quality-scoring-tie.md@@ -15,9 +15,10 @@ keyword + prose. The `theme` doc also gains consumer-facing keywords so itsurfaces for questions like "how to use a theme" and "how to apply a theme".Themes are now a search domain: bundled and integration-provided themes appear-in results with their slug, displayName, package, and the `astryx theme add`-command. `--type theme` filters to them. Like `--type doc`, it works outside an-app, where an open search now covers the docs and themes. Search help, the-manifest, and the API reference list the new domain and its result fields.+in results with their slug, displayName, package, and the command+`astryx theme add --import <slug>`. `--type theme` filters to them. Like+`--type doc`, it works outside an app, where an open search now covers the docs+and themes. Search help, the manifest, and the API reference list the new domain+and its result fields.@josephfarinadiff --git a/.changeset/theme-font-stylesheets.md b/.changeset/theme-font-stylesheets.mdnew file mode 100644index 0000000000..1aa116fbf8--- /dev/null+++ b/.changeset/theme-font-stylesheets.md@@ -0,0 +1,13 @@+---+'@astryxdesign/theme-butter': patch+'@astryxdesign/theme-chocolate': patch+'@astryxdesign/theme-gothic': patch+'@astryxdesign/theme-matcha': patch+'@astryxdesign/theme-neutral': patch+'@astryxdesign/theme-stone': patch+'@astryxdesign/theme-y2k': patch+---++[feat] Each theme package now exports `/fonts.css` beside `/built` and `/theme.css`. Import it when the theme uses non-system fonts.++@josephfarinadiff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjsindex b83f5d47c2..af76eb1d5e 100644--- a/.github/scripts/api-cli-parity-test.mjs+++ b/.github/scripts/api-cli-parity-test.mjs@@ -226,7 +226,7 @@ add('integration add theme (dry run)',add('theme list', ['theme', 'list'],() => apiCall(api.themeListAvailable, {cwd: ROOT}));add('theme add --list', ['theme', 'add', '--list'],- () => apiCall(api.themeListAvailable, {cwd: ROOT}));+ () => apiCall(api.themeListCopySources, {cwd: ROOT}));add('theme add nonexistent', ['theme', 'add', 'nonexistent99'],() => apiCall(api.themeAdd, 'nonexistent99', {cwd: ROOT}));diff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.mdindex 48f60e3d9f..1388ab74a2 100644--- a/docs/architecture/cli-surface.md+++ b/docs/architecture/cli-surface.md@@ -173,19 +173,29 @@ and remains available through explicit Core package selection.Invalid template and component files do not hide valid siblings. Apackage-scoped theme lookup still surfaces that package's blocking catalogerror instead of misreporting the theme as unknown.-- **INV19 — Integration themes are packaged editable source.** The manifest's- `themes` root contains one directory per slug. Every theme source has a mandatory- same-stem, strongly typed `ThemeDoc`; there is no root item catalog. Discovery- derives the source entry and required named runtime export from the shared stem,- parses source without executing it, and rejects escaped local imports and missing- or type-only runtime exports. The theme directory is the recursive copy and pack- boundary; dot entries and files npm never publishes belong to no theme. A- dot-folder, or a folder holding neither a descriptor nor a `<name>Theme`- source, is not a theme and is neither read nor packed, and doctor warns about- one that looks like a theme; a folder with a theme source and no descriptor- fails. `theme list` retains package- ownership, and `theme add --package` copies the complete directory before- `theme build` compiles the consumer-owned copy.+- **INV19 — Integration themes are importable packages; editable source is an+ explicit eject.** The manifest's `themes` root contains one directory per slug.+ Every theme source has a mandatory same-stem, strongly typed `ThemeDoc`; there+ is no root item catalog. Discovery derives the source entry and required named+ export from the shared stem, parses source without executing it, and rejects+ escaped local imports and missing or type-only exports. The theme directory is+ the recursive copy and pack boundary; dot entries and files npm never publishes+ belong to no theme. A dot-folder, or a folder holding neither a descriptor nor+ a `<name>Theme` source, is not a theme and is neither read nor packed, and doctor+ warns about one that looks like a theme; a folder with a theme source and no+ descriptor fails. The one exception is the project's local `src/themes` root:+ a source copy made by the released `theme add` without its descriptor is+ reported as unmigrated, skipped without failing theme commands, and remains+ unmanaged until upgrade adds its missing descriptor. `integration add theme`+ creates public built-module and stylesheet exports and keeps CSS side effectful.+ A package may also export a font stylesheet. `integration verify` rebuilds+ source, compares the local built module and stylesheet, and proves every+ declared theme export resolves from the packed package. `theme list` retains+ package ownership, and `theme add --import` records that owner and imports only built+ outputs. The deprecated plain `theme add` keeps copying source until its scheduled+ cleanup. `theme eject` is the explicit source fork; it copies the complete+ theme directory and same-stem descriptor, with the local descriptor marked as+ not maintained by the package owner.- **INV20 — A command's API subject has one layout.** A command's behavior livesin `api/<subject>/`. `<subject>.mjs` is the subject's entry, and `api/index.mjs`re-exports what it exports. A subject with more than one operation puts each indiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 006b5b2b80..8727647c2d 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -78,24 +78,24 @@ Options:<!-- BEGIN GENERATED: commands -->-| Command | Description |-| ------------- | --------------------------------------------------------------------------------------------- |-| `blog` | Read the Astryx blog from the published feed |-| `build` | Build a page: the template to start from, or the workflow playbook (no query) |-| `component` | List components or print component docs |-| `discover` | Browse and search integrations: the ones you have and the ones you could add |-| `docs` | Print reference docs |-| `doctor` | Diagnose Astryx projects and integration packages |-| `gap-report` | Report a missing component or feature to the package that owns it |-| `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, templates, and themes in one ranked list |-| `swizzle` | Copy component source for customization |-| `template` | List, show, or scaffold page and block templates |-| `theme` | Create and build themes: add a shipped one, compile to CSS, or list what a theme can override |-| `upgrade` | Update your code after upgrading Astryx, and refresh ShadCN-copied components |+| Command | Description |+| ------------- | ----------------------------------------------------------------------------- |+| `blog` | Read the Astryx blog from the published feed |+| `build` | Build a page: the template to start from, or the workflow playbook (no query) |+| `component` | List components or print component docs |+| `discover` | Browse and search integrations: the ones you have and the ones you could add |+| `docs` | Print reference docs |+| `doctor` | Diagnose Astryx projects and integration packages |+| `gap-report` | Report a missing component or feature to the package that owns it |+| `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, templates, and themes in one ranked list |+| `swizzle` | Copy component source for customization |+| `template` | List, show, or scaffold page and block templates |+| `theme` | Add, switch, build, and author themes |+| `upgrade` | Update your code after upgrading Astryx, and refresh ShadCN-copied components |<!-- END GENERATED: commands --><!-- Generated by scripts/generate-cli-readme.mjs from `astryx manifest`. Run `pnpm -F @astryxdesign/cli readme`. -->@@ -458,11 +458,13 @@ Every response has a `type` discriminant. The full set is below (generated from| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. || `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. || `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |-| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |+| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). || `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 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.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. |+| `theme.add` | The released source-copy receipt: slug, displayName, maintained flag, owner package, outputDir, source entry, exportName, and files. Its additive meta.deprecations entry names DEP-0005 and the source-fork/import replacements. |+| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. |+| `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. || `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, componentCount, and targets, one per theming target — {key, className, component, props, states, deprecatedFor?}, where props and states are its legal override keys and deprecatedFor names the canonical replacement key. || `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |diff --git a/packages/cli/api/doctor/_adapter.mjs b/packages/cli/api/doctor/_adapter.mjsnew file mode 100644index 0000000000..07f46b567a--- /dev/null+++ b/packages/cli/api/doctor/_adapter.mjs@@ -0,0 +1,142 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Environment adapter for app-theme doctor evidence. */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {Project} from '../../foundation/config/project.mjs';+import {+ discoverUnmigratedThemeCopies,+ themeImportPackage,+} from '../../foundation/discovery/theme-discovery.mjs';+import {resolveThemeImports} from '../../foundation/discovery/theme-imports.mjs';+import {findCoreDir, findInstalledPackage} from '../../foundation/fs/paths.mjs';+export {+ isLocalThemeOwner,+ planThemeAppWrite,+ readThemeState,+ resolveThemeModule,+} from '../../foundation/config/theme-state.mjs';+export {themeBuild, validateThemePrivateInputs} from '../theme/build/build.mjs';+export {resolveRecordedTheme} from '../theme/theme.mjs';+export {collectUnloadedFonts} from '../theme/build/font-warning.mjs';++/**+ * Package written to the generated app record for one discovered theme.+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme+ */+export function themeRecordOwner(theme) {+ return themeImportPackage(theme);+}++export const SOURCE_EXTENSIONS = new Set([+ '.js',+ '.jsx',+ '.mjs',+ '.cjs',+ '.ts',+ '.tsx',+ '.mts',+ '.cts',+]);++const SKIP_DIRS = new Set([+ '.git',+ '.next',+ 'build',+ 'coverage',+ 'dist',+ 'node_modules',+]);++/** @param {string} file */+export function readTextFile(file) {+ return fs.readFileSync(file, 'utf-8');+}++/** @param {string} file */+export function readTextFileIfExists(file) {+ if (!fs.existsSync(file)) return null;+ try {+ return readTextFile(file);+ } catch {+ return null;+ }+}++/**+ * A bounded app-source walk that excludes dependencies, generated output, and+ * links. The doctor parses the returned bytes without executing app code.+ * @param {string} root+ * @param {string} generatedModule+ */+export function listProjectSourceFiles(root, generatedModule) {+ /** @type {string[]} */+ const files = [];+ /** @type {string[]} */+ const queue = [root];+ while (queue.length > 0 && files.length < 5000) {+ const dir = /** @type {string} */ (queue.shift());+ let entries;+ try {+ entries = fs.readdirSync(dir, {withFileTypes: true});+ } catch {+ continue;+ }+ for (const entry of entries) {+ if (entry.isSymbolicLink()) continue;+ const file = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.astryx-')) {+ queue.push(file);+ }+ } else if (+ entry.isFile() &&+ file !== generatedModule &&+ SOURCE_EXTENSIONS.has(path.extname(entry.name))+ ) {+ files.push(file);+ }+ }+ }+ return files;+}++/** @param {string} projectDir */+export async function discoverDoctorThemes(projectDir) {+ const project = await Project.load(projectDir);+ return project.themes();+}++/**+ * Resolve one discovered theme's built module and stylesheets.+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme+ * @param {{cwd: string, ownerThemeCount: number}} options+ */+export function resolveDoctorThemeImports(theme, options) {+ return resolveThemeImports(theme, options);+}++/** @param {string} projectDir */+export function discoverDoctorUnmigratedCopies(projectDir) {+ return discoverUnmigratedThemeCopies(projectDir);+}++/** @param {string} projectDir */+export function findDoctorCoreDir(projectDir) {+ return findCoreDir(projectDir);+}++/** @param {string} projectDir @param {string} packageName */+export function findDoctorInstalledPackage(projectDir, packageName) {+ return findInstalledPackage(projectDir, packageName);+}++/** @param {string} file */+export function readPackageJson(file) {+ try {+ return JSON.parse(readTextFile(file));+ } catch {+ return null;+ }+}diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjsindex f0f3b350e3..37934371aa 100644--- a/packages/cli/api/doctor/doctor.doc.mjs+++ b/packages/cli/api/doctor/doctor.doc.mjs@@ -23,9 +23,7 @@ export const doc = {'integration provider identity and contribution issues, agent docs, the ' +'detected package manager, and the health of the docs the CLI reads (authoring ' +'and CLI docs, the docs tree, doc size), and returns a structured ' +- 'report. It only reads (never installs, writes, or mutates), apart from ' +- "importing astryx.config, which runs that file's top-level code, so it is safe " +- 'as a CI gate and for agents to invoke.',+ 'report. Theme checks run when the generated app module exists; without one, doctor reports that the CLI manages no themes and names theme add --import. Earlier descriptor-less copies are a non-failing upgrade warning. It never installs, writes, or mutates. It imports astryx.config, executes every added theme source while validating private inputs, and loads every recorded built theme module to prove its runtime imports work, including themes from installed packages. Local theme source also runs during build-freshness checks. Stylesheets are parsed without execution. Config and theme top-level code therefore run, so use doctor only with project code you trust.',importPath: '@astryxdesign/cli/api',signature: 'doctor(options?: DoctorOptions): Promise<DoctorResponse>',keywords: ['doctor', 'diagnose', 'health', 'check', 'verify', 'environment'],diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex d396e82697..1b598a3db3 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -50,6 +50,7 @@ import {import {typedEdges} from '../docs/node/node.mjs';import {detailView, indexView} from '../../foundation/doc-compiler/lenses.mjs';import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs';+import {checkAppThemes} from './theme-checks.mjs';/*** @typedef {'pass'|'warn'|'fail'|'info'} DoctorStatus@@ -70,7 +71,6 @@ import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env* @property {string} nodeVersion - Running Node version.* @property {string|null} coreDir - Resolved core package directory, or null.* @property {string|null} configPath - Resolved astryx.config.mjs path, or null.- * @property {string|null} configTheme - theme value read from config, or null.* @property {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]|null} [integrations]* Every integration the project loaded, or null when the project could not be* read at all.@@ -113,77 +113,6 @@ function pkgVersion(dir) {return pkg?.version ?? null;}-/**- * Walk up from `startDir` to locate the nearest node_modules directory.- * @param {string} startDir- * @returns {string|null}- */-function findNodeModules(startDir) {- let dir = startDir;- for (let i = 0; i < 6; i++) {- const candidate = path.join(dir, 'node_modules');- if (fs.existsSync(candidate)) return candidate;- const parent = path.dirname(dir);- if (parent === dir) break;- dir = parent;- }- return null;-}--/**- * Find every installed @astryxdesign/theme-* package under node_modules.- * @param {string} cwd- * @returns {Array<{name: string, version: string|null}>}- */-function findThemePackages(cwd) {- const nm = findNodeModules(cwd);- /** @type {Array<{name: string, version: string|null}>} */- const found = [];- if (!nm) return found;- const scopeDir = path.join(nm, '@astryxdesign');- if (!fs.existsSync(scopeDir)) return found;- let entries;- try {- entries = fs.readdirSync(scopeDir, {withFileTypes: true});- } catch {- return found;- }- for (const entry of entries) {- if (!entry.name.startsWith('theme-')) continue;- const dir = path.join(scopeDir, entry.name);- // pnpm installs packages as symlinks into node_modules/.pnpm, and a- // symlink dirent reports isDirectory() as false — stat the target instead.- let isDir = entry.isDirectory();- if (!isDir && entry.isSymbolicLink()) {- try {- isDir = fs.statSync(dir).isDirectory();- } catch {- isDir = false;- }- }- if (!isDir) continue;- const name = `@astryxdesign/${entry.name}`;- found.push({name, version: pkgVersion(dir)});- }- return found;-}--/**- * Detect whether a theme appears to be wired up via the ASTRYX_THEME env var or- * an `xds.theme` field in the nearest package.json. Config-based wiring is- * handled by the caller (ctx.configTheme). This only inspects static signals.- * @param {string} cwd- * @returns {{wired: boolean, source: string|null}}- */-function detectThemeWiring(cwd) {- if (process.env.ASTRYX_THEME) return {wired: true, source: 'ASTRYX_THEME env var'};- const nm = findNodeModules(cwd);- const projectDir = nm ? path.dirname(nm) : cwd;- const pkg = readPkg(path.join(projectDir, 'package.json'));- if (pkg?.astryx?.theme) return {wired: true, source: 'package.json astryx.theme'};- return {wired: false, source: null};-}-/* ── individual checks ────────────────────────────────────────────────── *//**@@ -284,47 +213,6 @@ export function checkVersionAlignment(ctx) {};}-/**- * Check 4 — at least one @astryxdesign/theme-* is installed and a theme is wired.- * @param {DoctorContext} ctx- * @returns {DoctorCheck}- */-export function checkThemes(ctx) {- const themes = findThemePackages(ctx.cwd);- const wiring = detectThemeWiring(ctx.cwd);- const hasConfigTheme = Boolean(ctx.configTheme);- const wired = wiring.wired || hasConfigTheme;-- if (themes.length === 0) {- return {- id: 'themes',- label: 'Theme packages',- status: 'warn',- message: 'No @astryxdesign/theme-* packages are installed.',- fix: 'Install a theme, e.g. `npm install @astryxdesign/theme-neutral`, then import its CSS or set astryx.theme.',- };- }-- const names = themes.map(t => t.name).join(', ');- if (!wired) {- return {- id: 'themes',- label: 'Theme packages',- status: 'warn',- message: `Theme package(s) installed (${names}) but no theme appears wired.`,- fix: 'Wire a theme via the `astryx.theme` field in package.json, the ASTRYX_THEME env var, or your astryx.config.mjs.',- };- }-- const source = hasConfigTheme ? 'astryx.config.mjs theme' : wiring.source;- return {- id: 'themes',- label: 'Theme packages',- status: 'pass',- message: `Theme package(s) installed (${names}); wired via ${source}.`,- };-}-/*** Check 5 — astryx.config.mjs (if present) loads and has a valid shape.* @param {DoctorContext} ctx@@ -1219,7 +1107,6 @@ export const SYNC_CHECKS = [checkNodeVersion,checkCoreInstalled,checkVersionAlignment,- checkThemes,checkImplicitIntegrations,checkProviderIdentity,checkIntegrationIssues,@@ -1249,9 +1136,7 @@ export async function runChecks(options = {}) {configError = /** @type {Error} */ (err);}- // Resolve a possible theme key from config, and the integrations the project- // actually loaded (best-effort; never throws).- let configTheme = null;+ // Resolve integrations the project actually loaded (best-effort; never throws)./** @type {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]|null} */let integrations = null;// A docs read falls back to the built-in topics when the project cannot be@@ -1268,8 +1153,6 @@ export async function runChecks(options = {}) {let autolinkFailures = null;try {const project = await Project.load(cwd);- configTheme =- /** @type {{theme?: string}} */ (project.config ?? {}).theme ?? null;integrations = project.loadedIntegrations;// An installed dependency whose manifest cannot be loaded is kept out of// loadedIntegrations on purpose. The provider ledger still records it.@@ -1294,7 +1177,7 @@ export async function runChecks(options = {}) {}integrationIssues = await project.issues();} catch {- // Best-effort: a missing/invalid config leaves configTheme null.+ // Best-effort: a missing or invalid config leaves integrations unavailable.}/** @type {DoctorContext} */@@ -1303,7 +1186,6 @@ export async function runChecks(options = {}) {nodeVersion: process.versions.node,coreDir,configPath,- configTheme,integrations,docsCatalog,docsCatalogIssues,@@ -1315,10 +1197,11 @@ export async function runChecks(options = {}) {/** @type {DoctorCheck[]} */const checks = [];- // checkConfig is async; run it in its declared slot (after themes).+ // Run the app-theme checks and config check after the environment checks.for (const fn of SYNC_CHECKS) {checks.push(fn(ctx));- if (fn === checkThemes) {+ if (fn === checkVersionAlignment) {+ checks.push(...(await checkAppThemes(cwd)));checks.push(await checkConfig(ctx));}}diff --git a/packages/cli/api/doctor/theme-checks.mjs b/packages/cli/api/doctor/theme-checks.mjsnew file mode 100644index 0000000000..2b71c0fc32--- /dev/null+++ b/packages/cli/api/doctor/theme-checks.mjs@@ -0,0 +1,1117 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Positive-evidence checks for the app theme record.+ *+ * Each AST-050 check has its own stable result. Missing app-theme state is+ * informational. A check passes only after its specific evidence is read.+ */++import * as path from 'node:path';+import {parse} from '@babel/parser';+import postcss from 'postcss';+import {+ collectUnloadedFonts,+ discoverDoctorThemes,+ discoverDoctorUnmigratedCopies,+ findDoctorCoreDir,+ findDoctorInstalledPackage,+ isLocalThemeOwner,+ listProjectSourceFiles,+ planThemeAppWrite,+ readPackageJson,+ readTextFile,+ readTextFileIfExists,+ readThemeState,+ resolveDoctorThemeImports,+ resolveRecordedTheme,+ resolveThemeModule,+ SOURCE_EXTENSIONS,+ themeBuild,+ themeRecordOwner,+ validateThemePrivateInputs,+} from './_adapter.mjs';+import {getCliInvocation} from '../../foundation/env/package-manager.mjs';+import {satisfiesRange} from '../../foundation/env/semver.mjs';+import {logger} from '../logger.mjs';++/** @typedef {import('./doctor.mjs').DoctorCheck} DoctorCheck */+/** @typedef {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} DiscoveredTheme */+/** @typedef {import('../../foundation/config/theme-state.mjs').ResolvedAppTheme} ResolvedAppTheme */++const CHECKS = [+ ['theme-owners', 'Theme owners and built imports'],+ ['theme-module', 'Generated theme module'],+ ['theme-module-import', 'App imports the theme module'],+ ['theme-stylesheet-imports', 'Built theme stylesheet imports'],+ ['theme-local-builds', 'Local theme build freshness'],+ ['theme-private-variables', 'Private theme variables'],+ ['theme-core-peers', 'Theme Core peer compatibility'],+ ['theme-default', 'Default added theme'],+ ['theme-fonts', 'Theme font loading'],+ ['theme-global-rules', 'Cross-theme global CSS rules'],+];++/**+ * @param {string} message+ * @param {Error|null} [moduleError]+ * @returns {DoctorCheck[]}+ */+function unavailableChecks(message, moduleError = null) {+ return CHECKS.map(([id, label]) => ({+ id,+ label,+ status: moduleError && id === 'theme-module' ? 'fail' : 'info',+ message:+ moduleError && id === 'theme-module' ? moduleError.message : message,+ ...(moduleError && id === 'theme-module'+ ? {+ fix: 'Keep one CLI-generated astryx-themes.ts or astryx-themes.js file, then run `astryx theme add <slug> --import`.',+ }+ : {}),+ }));+}++/** @param {string} value */+function projectPath(value) {+ return value.split(path.sep).join('/');+}++/** @param {string} root @param {string} file */+function relative(root, file) {+ return projectPath(path.relative(root, file));+}++/**+ * The concrete command that revalidates one recorded theme after its source or+ * package is corrected.+ * @param {string} projectDir+ * @param {string} run+ * @param {DiscoveredTheme[]} available+ * @param {string} slug+ * @param {string} owner+ */+function refreshThemeCommand(projectDir, run, available, slug, owner) {+ const theme = available.find(+ candidate =>+ candidate.slug === slug && themeRecordOwner(candidate) === owner,+ );+ if (!isLocalThemeOwner(owner)) {+ const selector = theme?.package ?? owner;+ return `npm install ${owner}@latest; ${run} theme add ${slug} --import --package ${selector}`;+ }+ const source = theme+ ? relative(projectDir, path.join(theme.sourceDir, theme.entry))+ : projectPath(path.join(owner, slug, `${slug}Theme.ts`));+ return `${run} theme build ${source}; ${run} theme add ${slug} --import`;+}++/** @param {string} source */+function parseModule(source) {+ return parse(source, {+ sourceType: 'unambiguous',+ plugins: ['typescript', 'jsx', 'decorators-legacy', 'importAttributes'],+ });+}++/** @param {unknown} value @param {(node: any) => void} visit */+function walkAst(value, visit) {+ if (value == null || typeof value !== 'object') return;+ if (Array.isArray(value)) {+ for (const item of value) walkAst(item, visit);+ return;+ }+ const node = /** @type {Record<string, unknown>} */ (value);+ if (typeof node.type === 'string') visit(node);+ for (const [key, child] of Object.entries(node)) {+ if (['loc', 'start', 'end', 'extra'].includes(key)) continue;+ walkAst(child, visit);+ }+}++/** @param {string} source */+function moduleSpecifiers(source) {+ const values = new Set();+ walkAst(parseModule(source), node => {+ if (+ [+ 'ImportDeclaration',+ 'ExportNamedDeclaration',+ 'ExportAllDeclaration',+ ].includes(node.type) &&+ typeof node.source?.value === 'string'+ ) {+ values.add(node.source.value);+ }+ if (+ node.type === 'ImportExpression' &&+ typeof node.source?.value === 'string'+ ) {+ values.add(node.source.value);+ }+ if (+ node.type === 'CallExpression' &&+ (node.callee?.type === 'Import' || node.callee?.name === 'require') &&+ typeof node.arguments?.[0]?.value === 'string'+ ) {+ values.add(node.arguments[0].value);+ }+ });+ return values;+}++/** @param {string} specifier @param {string} fromFile @param {string} target */+function specifierTargets(specifier, fromFile, target) {+ if (!specifier.startsWith('.')) return false;+ const base = path.resolve(path.dirname(fromFile), specifier);+ const candidates = [+ base,+ ...[...SOURCE_EXTENSIONS].map(extension => `${base}${extension}`),+ ...[...SOURCE_EXTENSIONS].map(extension =>+ path.join(base, `index${extension}`),+ ),+ ];+ return candidates.some(+ candidate => path.resolve(candidate) === path.resolve(target),+ );+}++/** @param {string} root @param {string} generatedModule */+function sourceImportEvidence(root, generatedModule) {+ let parseFailures = 0;+ for (const file of listProjectSourceFiles(root, generatedModule)) {+ try {+ const source = readTextFile(file);+ if (+ [...moduleSpecifiers(source)].some(specifier =>+ specifierTargets(specifier, file, generatedModule),+ )+ ) {+ return {found: true, parseFailures};+ }+ } catch {+ parseFailures += 1;+ }+ }+ return {found: false, parseFailures};+}++/**+ * Find a source file that imports one added built module without its paired CSS.+ * @param {string} root+ * @param {string} generatedModule+ * @param {ResolvedAppTheme[]} themes+ */+function themeImportPairEvidence(root, generatedModule, themes) {+ const files = [+ generatedModule,+ ...listProjectSourceFiles(root, generatedModule),+ ];+ const unpaired = [];+ const unproven = [];+ for (const file of files) {+ let source;+ try {+ source = readTextFile(file);+ } catch {+ continue;+ }+ const candidates = themes.filter(theme =>+ source.includes(+ theme.source === 'local'+ ? path.basename(theme.moduleFile)+ : theme.module,+ ),+ );+ if (candidates.length === 0) continue;+ let specifiers;+ try {+ specifiers = moduleSpecifiers(source);+ } catch {+ unproven.push(relative(root, file));+ continue;+ }+ for (const theme of candidates) {+ const importsModule = [...specifiers].some(specifier =>+ theme.source === 'local'+ ? specifierTargets(specifier, file, theme.moduleFile)+ : specifier === theme.module,+ );+ if (!importsModule) continue;+ const importsStylesheet = [...specifiers].some(specifier =>+ theme.source === 'local'+ ? specifierTargets(specifier, file, theme.stylesheetFile)+ : specifier === theme.stylesheet,+ );+ if (!importsStylesheet) {+ unpaired.push({+ slug: theme.slug,+ file: relative(root, file),+ stylesheet: theme.stylesheet || relative(root, theme.stylesheetFile),+ });+ }+ }+ }+ return {unpaired, unproven};+}++/** @param {string} value */+function normalizeFontName(value) {+ return value+ .trim()+ .replace(/^(['"])(.*)\1$/u, '$2')+ .replace(/\s+/gu, ' ');+}++/** @param {string[]} files */+function namedThemeFonts(files) {+ const names = new Map();+ for (const file of files) {+ const source = readTextFileIfExists(file);+ if (source == null) continue;+ try {+ walkAst(parseModule(source), node => {+ if (node.type !== 'ObjectProperty' && node.type !== 'Property') return;+ const key = node.key?.name ?? node.key?.value;+ const value = node.value?.value;+ if (typeof key !== 'string' || typeof value !== 'string') return;+ /** @type {string[]} */+ let found = [];+ if (key.startsWith('--font-family-')) {+ found = collectUnloadedFonts({tokens: {[key]: value}});+ } else if (key === 'family') {+ found = collectUnloadedFonts({typography: {body: {family: value}}});+ } else if (key === 'fontFamily') {+ found = collectUnloadedFonts({+ components: {probe: {base: {fontFamily: value}}},+ });+ }+ for (const name of found) {+ const normalized = name.toLowerCase();+ if (!names.has(normalized)) names.set(normalized, name);+ }+ });+ } catch {+ // The source-to-built checks report parse or build problems separately.+ }+ }+ return new Set(names.values());+}++/** @param {string} css */+function fontStylesheetEvidence(css) {+ const loaded = new Set();+ let external = false;+ const root = postcss.parse(css);+ root.walkAtRules(atRule => {+ if (atRule.name.toLowerCase() === 'import') external = true;+ if (atRule.name.toLowerCase() !== 'font-face') return;+ atRule.walkDecls(/^font-family$/iu, declaration => {+ loaded.add(normalizeFontName(declaration.value).toLowerCase());+ });+ });+ return {loaded, external};+}++/** @param {import('postcss').Rule} rule @param {string} slug */+function scopedToTheme(rule, slug) {+ const needles = [+ `[data-astryx-theme="${slug}"]`,+ `[data-astryx-theme='${slug}']`,+ ];+ if (needles.some(needle => rule.selector.includes(needle))) return true;+ /** @type {import('postcss').Node|undefined} */+ let parent = rule.parent;+ while (parent) {+ if (parent.type === 'atrule') {+ const atRule = /** @type {import('postcss').AtRule} */ (parent);+ const params = atRule.params;+ if (needles.some(needle => String(params).includes(needle))) return true;+ }+ parent = parent.parent;+ }+ return false;+}++/** @param {string} css @param {string} slug */+function globalRules(css, slug) {+ const rules = new Map();+ const root = postcss.parse(css);+ root.walkRules(rule => {+ if (scopedToTheme(rule, slug)) return;+ /** @type {import('postcss').Node|undefined} */+ let parent = rule.parent;+ while (parent) {+ if (+ parent.type === 'atrule' &&+ /keyframes$/iu.test(+ /** @type {import('postcss').AtRule} */ (parent).name,+ )+ )+ return;+ parent = parent.parent;+ }+ /** @type {string[]} */+ const declarations = [];+ rule.walkDecls(declaration => {+ declarations.push(+ `${declaration.prop.trim()}:${declaration.value.trim()}${declaration.important ? '!important' : ''}`,+ );+ });+ rules.set(rule.selector.trim(), declarations.sort().join(';'));+ });+ return rules;+}++/**+ * Report source copies made by the released `theme add` before it copied+ * descriptors. This is a migration notice, not one of the ten setup checks.+ * @param {string} projectDir+ * @returns {DoctorCheck|null}+ */+function unmigratedCopyCheck(projectDir) {+ const copies = discoverDoctorUnmigratedCopies(projectDir);+ if (copies.length === 0) return null;+ const shown = copies+ .map(copy => relative(projectDir, copy.sourceDir))+ .join(', ');+ const command = `${getCliInvocation(projectDir)} upgrade --from 0.6.4 --path . --apply`;+ return {+ id: 'theme-unmigrated-copies',+ label: 'Earlier copied themes',+ status: 'warn',+ message: `${copies.length} source theme copy or copies are not managed themes yet: ${shown}.`,+ fix: `Write their missing descriptors with \`${command}\`.`,+ };+}++/**+ * Run all ten app-theme checks.+ * @param {string} cwd+ * @returns {Promise<DoctorCheck[]>}+ */+export async function checkAppThemes(cwd) {+ let state;+ try {+ state = readThemeState(cwd);+ } catch (error) {+ const err = error instanceof Error ? error : new Error(String(error));+ if (/No package\.json found/u.test(err.message)) {+ return unavailableChecks('No app theme record found.');+ }+ return unavailableChecks(+ 'Skipped because the generated theme module could not be read.',+ err,+ );+ }++ if (!state.configured) {+ try {+ resolveThemeModule(state.projectDir, {forWrite: true});+ } catch (error) {+ return unavailableChecks(+ 'Skipped because the generated theme module is unavailable.',+ error instanceof Error ? error : new Error(String(error)),+ );+ }+ const run = getCliInvocation(state.projectDir);+ /** @type {DoctorCheck[]} */+ const report = [+ {+ id: 'theme-management',+ label: 'CLI-managed app themes',+ status: 'info',+ message: state.legacyTheme+ ? `The CLI manages no themes. The released package.json astryx.theme value ${JSON.stringify(state.legacyTheme)} remains active.`+ : 'The CLI manages no themes because this project has no generated theme module.',+ fix: `Start managing app themes with \`${run} theme add <slug> --import\`.`,+ },+ ];+ const migration = unmigratedCopyCheck(state.projectDir);+ if (migration) report.push(migration);+ return report;+ }++ const run = getCliInvocation(state.projectDir);+ const ownerEntries = Object.entries(state.themes);+ /** @type {DiscoveredTheme[]} */+ let available = [];+ let discoveryError = null;+ try {+ available = await discoverDoctorThemes(state.projectDir);+ } catch (error) {+ discoveryError = error instanceof Error ? error : new Error(String(error));+ }++ /** @type {ResolvedAppTheme[]} */+ const resolved = [];+ /** @type {Array<{slug: string, owner: string, message: string}>} */+ const resolutionProblems = [];+ const ownerCounts = new Map();+ for (const theme of available) {+ const owner = themeRecordOwner(theme);+ ownerCounts.set(owner, (ownerCounts.get(owner) ?? 0) + 1);+ }+ if (!discoveryError) {+ for (const [slug, owner] of ownerEntries) {+ const theme = available.find(+ candidate =>+ candidate.slug === slug && themeRecordOwner(candidate) === owner,+ );+ if (!theme) {+ resolutionProblems.push({+ slug,+ owner,+ message: `Theme "${slug}" from ${owner} is unavailable.`,+ });+ continue;+ }+ /** @type {ResolvedAppTheme} */+ let resolvedTheme;+ try {+ resolvedTheme = resolveDoctorThemeImports(theme, {+ cwd: state.projectDir,+ ownerThemeCount: ownerCounts.get(owner) ?? 1,+ });+ } catch (error) {+ resolutionProblems.push({+ slug,+ owner,+ message: error instanceof Error ? error.message : String(error),+ });+ continue;+ }+ try {+ const loaded = await resolveRecordedTheme(state.projectDir, slug);+ if (!loaded.module) {+ resolutionProblems.push({+ slug,+ owner,+ message: `Theme "${slug}" from ${owner} could not load its built module: ${loaded.problem ?? `${loaded.specifier} does not resolve`}.`,+ });+ continue;+ }+ } catch (error) {+ const detail =+ error instanceof Error+ ? error.message.split('\n', 1)[0]?.trim() || error.name+ : String(error);+ resolutionProblems.push({+ slug,+ owner,+ message: `Theme "${slug}" from ${owner} could not load its built module: ${detail}.`,+ });+ continue;+ }+ resolved.push(resolvedTheme);+ }+ }++ const incompleteResolution =+ discoveryError != null ||+ resolutionProblems.length > 0 ||+ resolved.length !== ownerEntries.length;++ /** @type {ReturnType<typeof planThemeAppWrite>|null} */+ let prepared = null;+ if (+ !discoveryError &&+ resolutionProblems.length === 0 &&+ resolved.length === ownerEntries.length &&+ state.defaultSlug != null &&+ Object.hasOwn(state.themes, state.defaultSlug)+ ) {+ try {+ prepared = planThemeAppWrite(+ state,+ state.themes,+ state.defaultSlug,+ resolved,+ );+ } catch {+ prepared = null;+ }+ }++ /** @type {DoctorCheck[]} */+ const checks = [];++ if (ownerEntries.length === 0) {+ checks.push({+ id: 'theme-owners',+ label: 'Theme owners and built imports',+ status: 'fail',+ message: 'The generated record has no added themes.',+ fix: `${run} theme add <slug> --import`,+ });+ } else if (discoveryError) {+ checks.push({+ id: 'theme-owners',+ label: 'Theme owners and built imports',+ status: 'fail',+ message: discoveryError.message,+ fix: `${run} theme add <slug> --import`,+ });+ } else if (resolutionProblems.length > 0) {+ checks.push({+ id: 'theme-owners',+ label: 'Theme owners and built imports',+ status: 'fail',+ message: resolutionProblems.map(problem => problem.message).join(' '),+ fix: resolutionProblems+ .map(problem =>+ refreshThemeCommand(+ state.projectDir,+ run,+ available,+ problem.slug,+ problem.owner,+ ),+ )+ .join(' '),+ });+ } else {+ checks.push({+ id: 'theme-owners',+ label: 'Theme owners and built imports',+ status: 'pass',+ message: `${resolved.length} added theme${resolved.length === 1 ? '' : 's'} resolve to built modules and stylesheets, and every built module loads.`,+ });+ }++ const currentModule = state.module.expectedOriginal?.toString('utf-8') ?? '';+ if (!prepared) {+ checks.push({+ id: 'theme-module',+ label: 'Generated theme module',+ status: 'info',+ message:+ 'Could not regenerate the module until its owners, imports, and default are valid.',+ });+ } else if (currentModule !== prepared.moduleContents) {+ checks.push({+ id: 'theme-module',+ label: 'Generated theme module',+ status: 'fail',+ message: `${state.module.path} differs from the exact module generated from its own record.`,+ fix: `${run} theme use ${state.defaultSlug}`,+ });+ } else {+ checks.push({+ id: 'theme-module',+ label: 'Generated theme module',+ status: 'pass',+ message: `${state.module.path} has the generated marker and exactly matches its record.`,+ });+ }++ const importEvidence = sourceImportEvidence(+ state.projectDir,+ state.module.file,+ );+ if (importEvidence.found) {+ checks.push({+ id: 'theme-module-import',+ label: 'App imports the theme module',+ status: 'pass',+ message: `Project source imports ${state.module.path}.`,+ });+ } else {+ checks.push({+ id: 'theme-module-import',+ label: 'App imports the theme module',+ status: 'warn',+ message: `Could not prove that project source imports ${state.module.path}${importEvidence.parseFailures ? `; ${importEvidence.parseFailures} source file(s) could not be parsed` : ''}.`,+ fix: `Import {themes, defaultThemeSlug} from the generated module and render <Theme theme={themes[defaultThemeSlug]}>.`,+ });+ }++ if (discoveryError || resolutionProblems.length > 0) {+ checks.push({+ id: 'theme-stylesheet-imports',+ label: 'Built theme stylesheet imports',+ status: 'info',+ message:+ 'Could not prove module and stylesheet pairs until every built import resolves.',+ });+ } else {+ const pairEvidence = themeImportPairEvidence(+ state.projectDir,+ state.module.file,+ prepared?.entries ?? resolved,+ );+ if (pairEvidence.unpaired.length > 0) {+ checks.push({+ id: 'theme-stylesheet-imports',+ label: 'Built theme stylesheet imports',+ status: 'fail',+ message: pairEvidence.unpaired+ .map(+ problem =>+ `${problem.file} imports ${problem.slug} without ${problem.stylesheet}`,+ )+ .join('; '),+ fix: `Import the named stylesheet beside each built module, then run ${run} theme use ${state.defaultSlug}.`,+ });+ } else if (pairEvidence.unproven.length > 0) {+ checks.push({+ id: 'theme-stylesheet-imports',+ label: 'Built theme stylesheet imports',+ status: 'info',+ message: `Could not parse theme imports in ${pairEvidence.unproven.join(', ')}.`,+ });+ } else {+ checks.push({+ id: 'theme-stylesheet-imports',+ label: 'Built theme stylesheet imports',+ status: 'pass',+ message:+ 'Every added built module import is paired with its stylesheet import.',+ });+ }+ }++ const localThemes = resolved.filter(theme => theme.source === 'local');+ if (incompleteResolution) {+ checks.push({+ id: 'theme-local-builds',+ label: 'Local theme build freshness',+ status: 'info',+ message:+ 'Could not check local build freshness until every local output resolves.',+ });+ } else if (localThemes.length === 0) {+ checks.push({+ id: 'theme-local-builds',+ label: 'Local theme build freshness',+ status: 'pass',+ message: 'No added local themes need a freshness check.',+ });+ } else {+ const stale = [];+ const previousSilent = logger.silent;+ logger.setSilent(true);+ try {+ for (const theme of localThemes) {+ const availableTheme = available.find(+ candidate =>+ candidate.slug === theme.slug &&+ themeRecordOwner(candidate) === theme.owner,+ );+ if (!availableTheme) continue;+ try {+ const receipt = await themeBuild(+ path.join(availableTheme.sourceDir, availableTheme.entry),+ {check: true},+ {cwd: state.projectDir},+ );+ if (+ receipt == null ||+ receipt.type !== 'theme.build.check' ||+ !receipt.data.upToDate+ ) {+ stale.push(theme.slug);+ }+ } catch {+ stale.push(theme.slug);+ }+ }+ } finally {+ logger.setSilent(previousSilent);+ }+ checks.push(+ stale.length > 0+ ? {+ id: 'theme-local-builds',+ label: 'Local theme build freshness',+ status: 'fail',+ message: `Local theme outputs are missing or stale: ${stale.join(', ')}.`,+ fix: stale+ .map(slug =>+ refreshThemeCommand(+ state.projectDir,+ run,+ available,+ slug,+ state.themes[slug],+ ),+ )+ .join(' '),+ }+ : {+ id: 'theme-local-builds',+ label: 'Local theme build freshness',+ status: 'pass',+ message: 'Every added local theme output matches its source.',+ },+ );+ }++ const privateProblems = [];+ for (const theme of resolved) {+ const availableTheme = available.find(+ candidate =>+ candidate.slug === theme.slug &&+ themeRecordOwner(candidate) === theme.owner,+ );+ if (!availableTheme) continue;+ try {+ const errors = await validateThemePrivateInputs(+ path.join(availableTheme.sourceDir, availableTheme.entry),+ {cwd: state.projectDir},+ );+ if (errors.length > 0) {+ privateProblems.push({theme, message: errors.join('; ')});+ }+ } catch (error) {+ privateProblems.push({+ theme,+ message: `input could not be inspected: ${error instanceof Error ? error.message : String(error)}`,+ });+ }+ }+ checks.push(+ incompleteResolution+ ? {+ id: 'theme-private-variables',+ label: 'Private theme variables',+ status: 'info',+ message:+ 'Could not inspect every theme input until built imports resolve.',+ }+ : privateProblems.length > 0+ ? {+ id: 'theme-private-variables',+ label: 'Private theme variables',+ status: 'fail',+ message: `Added theme inputs set private --_* variables directly (${privateProblems+ .map(problem => `${problem.theme.slug}: ${problem.message}`)+ .join('; ')}).`,+ fix: `Remove the direct private input keys, then ${privateProblems+ .map(problem =>+ refreshThemeCommand(+ state.projectDir,+ run,+ available,+ problem.theme.slug,+ problem.theme.owner,+ ),+ )+ .join(' ')}`,+ }+ : {+ id: 'theme-private-variables',+ label: 'Private theme variables',+ status: 'pass',+ message:+ 'No added theme input sets a private --_* variable directly.',+ },+ );++ const coreDir = findDoctorCoreDir(state.projectDir);+ const coreVersion = coreDir+ ? readPackageVersion(path.join(coreDir, 'package.json'))+ : null;+ const peerProblems = [];+ for (const [slug, owner] of ownerEntries) {+ if (isLocalThemeOwner(owner)) continue;+ const packageDir = findDoctorInstalledPackage(state.projectDir, owner);+ const pkg = packageDir+ ? readPackageJson(path.join(packageDir, 'package.json'))+ : null;+ const range = pkg?.peerDependencies?.['@astryxdesign/core'];+ if (+ !coreVersion ||+ typeof range !== 'string' ||+ !satisfiesRange(coreVersion, range)+ ) {+ peerProblems.push({+ slug,+ owner,+ range: typeof range === 'string' ? range : null,+ message: `${slug}: ${owner} requires ${typeof range === 'string' ? range : 'an undeclared Core range'}, installed ${coreVersion ?? 'none'}`,+ });+ }+ }+ checks.push(+ incompleteResolution+ ? {+ id: 'theme-core-peers',+ label: 'Theme Core peer compatibility',+ status: 'info',+ message:+ 'Could not prove Core peer compatibility until every added theme resolves.',+ }+ : peerProblems.length > 0+ ? {+ id: 'theme-core-peers',+ label: 'Theme Core peer compatibility',+ status: 'fail',+ message: peerProblems.map(problem => problem.message).join('; '),+ fix: peerProblems+ .map(problem =>+ problem.range+ ? `npm install '@astryxdesign/core@${problem.range}'; ${run} doctor`+ : refreshThemeCommand(+ state.projectDir,+ run,+ available,+ problem.slug,+ problem.owner,+ ),+ )+ .join(' '),+ }+ : {+ id: 'theme-core-peers',+ label: 'Theme Core peer compatibility',+ status: 'pass',+ message:+ 'Every added package theme accepts the installed @astryxdesign/core version.',+ },+ );++ const validDefault =+ state.defaultSlug != null && Object.hasOwn(state.themes, state.defaultSlug);+ checks.push(+ validDefault+ ? {+ id: 'theme-default',+ label: 'Default added theme',+ status: 'pass',+ message: `Default theme "${state.defaultSlug}" is added.`,+ }+ : {+ id: 'theme-default',+ label: 'Default added theme',+ status: 'fail',+ message: `Default theme "${state.defaultSlug ?? ''}" is not one of the added themes.`,+ fix:+ ownerEntries.length > 0+ ? `${run} theme use ${ownerEntries[0][0]}`+ : `${run} theme add <slug> --import`,+ },+ );++ const fontFailures = [];+ const externalFontWarnings = [];+ const missingFontWarnings = [];+ let generatedImports = null;+ try {+ generatedImports = moduleSpecifiers(currentModule);+ } catch {+ // The generated-module check owns the parse failure. This check stays+ // evidence-driven and refuses to pass without readable imports.+ }+ for (const theme of resolved) {+ const availableTheme = available.find(+ candidate =>+ candidate.slug === theme.slug &&+ themeRecordOwner(candidate) === theme.owner,+ );+ const files = [theme.moduleFile];+ if (availableTheme) {+ files.push(path.join(availableTheme.sourceDir, availableTheme.entry));+ }+ const names = namedThemeFonts(files);+ if (names.size === 0) continue;+ const importedTheme =+ prepared?.entries.find(entry => entry.slug === theme.slug) ?? theme;+ if (!theme.fontStylesheetFile || !importedTheme.fontStylesheet) {+ const problem = {+ theme,+ message: `${[...names].join(', ')} (font stylesheet is not imported)`,+ };+ missingFontWarnings.push(problem);+ continue;+ }+ if (!generatedImports?.has(importedTheme.fontStylesheet)) {+ fontFailures.push({+ theme,+ message: `${[...names].join(', ')} (font stylesheet is not imported)`,+ });+ continue;+ }+ try {+ const evidence = fontStylesheetEvidence(+ readTextFile(theme.fontStylesheetFile),+ );+ const missing = [...names].filter(+ name => !evidence.loaded.has(name.toLowerCase()),+ );+ if (missing.length === 0) continue;+ if (evidence.external) {+ externalFontWarnings.push(`${theme.slug}: ${missing.join(', ')}`);+ } else {+ fontFailures.push({theme, message: missing.join(', ')});+ }+ } catch {+ fontFailures.push({+ theme,+ message: 'font stylesheet could not be parsed',+ });+ }+ }+ const fontWarningMessages = [];+ const fontWarningFixes = [];+ if (missingFontWarnings.length > 0) {+ fontWarningMessages.push(+ `Added themes name font families but import no font stylesheet (${missingFontWarnings+ .map(problem => `${problem.theme.slug}: ${problem.message}`)+ .join('; ')}).`,+ );+ const localWarnings = missingFontWarnings.filter(+ problem => problem.theme.source === 'local',+ );+ const packageWarnings = missingFontWarnings.filter(+ problem => problem.theme.source !== 'local',+ );+ if (localWarnings.length > 0) {+ fontWarningFixes.push(+ `Add <slug>.fonts.css beside each built local theme output, then ${localWarnings+ .map(problem => `${run} theme add ${problem.theme.slug} --import`)+ .join('; ')}.`,+ );+ }+ if (packageWarnings.length > 0) {+ fontWarningFixes.push(+ 'Load the named package fonts in app HTML, or install a package version that exports <slug>.fonts.css (or fonts.css for a single-theme package).',+ );+ }+ }+ if (externalFontWarnings.length > 0) {+ fontWarningMessages.push(+ `External font imports prevent proof for ${externalFontWarnings.join('; ')}.`,+ );+ fontWarningFixes.push(+ 'Confirm the font service stylesheet loads each named family.',+ );+ }+ checks.push(+ incompleteResolution+ ? {+ id: 'theme-fonts',+ label: 'Theme font loading',+ status: 'info',+ message:+ 'Could not prove font loading until every added theme resolves.',+ }+ : fontFailures.length > 0+ ? {+ id: 'theme-fonts',+ label: 'Theme font loading',+ status: 'fail',+ message: `Named font families have no proven loader (${fontFailures+ .map(problem => `${problem.theme.slug}: ${problem.message}`)+ .join('; ')}).`,+ fix: `Add the missing font stylesheet export or local <slug>.fonts.css, then ${fontFailures+ .map(problem =>+ refreshThemeCommand(+ state.projectDir,+ run,+ available,+ problem.theme.slug,+ problem.theme.owner,+ ),+ )+ .join(' ')}`,+ }+ : fontWarningMessages.length > 0+ ? {+ id: 'theme-fonts',+ label: 'Theme font loading',+ status: 'warn',+ message: fontWarningMessages.join(' '),+ fix: fontWarningFixes.join(' '),+ }+ : {+ id: 'theme-fonts',+ label: 'Theme font loading',+ status: 'pass',+ message:+ 'Every named non-system font has a local @font-face loader.',+ },+ );++ const globalBySelector = new Map();+ const globalProblems = [];+ for (const theme of resolved) {+ try {+ for (const [selector, declarations] of globalRules(+ readTextFile(theme.stylesheetFile),+ theme.slug,+ )) {+ const prior = globalBySelector.get(selector);+ if (prior && prior.declarations !== declarations) {+ globalProblems.push({+ message: `${selector}: ${prior.theme.slug}, ${theme.slug}`,+ themes: [prior.theme, theme],+ });+ } else if (!prior) {+ globalBySelector.set(selector, {theme, declarations});+ }+ }+ } catch {+ globalProblems.push({+ message: `${theme.slug}: stylesheet could not be parsed`,+ themes: [theme],+ });+ }+ }+ /** @type {Map<string, ResolvedAppTheme>} */+ const globalRepairThemes = new Map();+ for (const problem of globalProblems) {+ for (const theme of problem.themes) {+ globalRepairThemes.set(`${theme.owner}\u0000${theme.slug}`, theme);+ }+ }+ checks.push(+ incompleteResolution+ ? {+ id: 'theme-global-rules',+ label: 'Cross-theme global CSS rules',+ status: 'info',+ message:+ 'Could not compare global CSS until every added stylesheet resolves.',+ }+ : globalProblems.length > 0+ ? {+ id: 'theme-global-rules',+ label: 'Cross-theme global CSS rules',+ status: 'fail',+ message: `Added themes write different global rules for the same selector (${globalProblems+ .map(problem => problem.message)+ .join('; ')}).`,+ fix: `Scope each conflicting rule under its [data-astryx-theme] selector, then ${[+ ...globalRepairThemes.values(),+ ]+ .map(theme =>+ refreshThemeCommand(+ state.projectDir,+ run,+ available,+ theme.slug,+ theme.owner,+ ),+ )+ .join(' ')}`,+ }+ : {+ id: 'theme-global-rules',+ label: 'Cross-theme global CSS rules',+ status: 'pass',+ message:+ 'No added themes write different rules for the same selector outside their own scope.',+ },+ );++ const migration = unmigratedCopyCheck(state.projectDir);+ if (migration) checks.push(migration);+ return checks;+}++/** @param {string} file */+function readPackageVersion(file) {+ const pkg = readPackageJson(file);+ return typeof pkg?.version === 'string' ? pkg.version : null;+}diff --git a/packages/cli/api/doctor/theme-checks.test.mjs b/packages/cli/api/doctor/theme-checks.test.mjsnew file mode 100644index 0000000000..5322ba8083--- /dev/null+++ b/packages/cli/api/doctor/theme-checks.test.mjs@@ -0,0 +1,483 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Fault-injection coverage for all ten app-theme doctor checks. */++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 {checkAppThemes} from './theme-checks.mjs';+import {themeAdd} from '../theme/add/add.mjs';+import {themeEject} from '../theme/eject/eject.mjs';+import {themeBuild} from '../theme/build/build.mjs';+import {parseThemeModuleRecord} from '../../foundation/config/theme-state.mjs';++/** @type {string[]} */+const dirs = [];+const REPO_ROOT = path.resolve(import.meta.dirname, '../../../..');++/** @param {string} file @param {string} content */+function write(file, content) {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, content);+}++/**+ * @param {Array<{slug: string, css?: string, fontFamily?: string, fontCss?: string}>} themeSpecs+ * @param {{peerRange?: string, importModule?: boolean}} [options]+ */+async function fixture(themeSpecs = [{slug: 'ocean'}], options = {}) {+ const dir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-doctor-themes-'),+ );+ dirs.push(dir);+ fs.mkdirSync(path.join(dir, 'src'), {recursive: true});+ write(path.join(dir, 'tsconfig.json'), '{}\n');+ write(+ path.join(dir, 'package.json'),+ JSON.stringify({+ name: 'doctor-app',+ private: true,+ dependencies: {+ '@acme/themes': '1.0.0',+ '@astryxdesign/core': '1.0.0',+ },+ }),+ );+ write(+ path.join(dir, 'node_modules/@astryxdesign/core/package.json'),+ JSON.stringify({name: '@astryxdesign/core', version: '1.0.0'}),+ );++ const packageDir = path.join(dir, 'node_modules/@acme/themes');+ const exportsMap = {};+ for (const spec of themeSpecs) {+ exportsMap[`./themes/${spec.slug}`] = `./dist/${spec.slug}.js`;+ exportsMap[`./themes/${spec.slug}.css`] = `./dist/${spec.slug}.css`;+ if (spec.fontCss != null) {+ exportsMap[`./themes/${spec.slug}.fonts.css`] =+ `./dist/${spec.slug}.fonts.css`;+ }+ }+ write(+ path.join(packageDir, 'package.json'),+ JSON.stringify({+ name: '@acme/themes',+ version: '1.0.0',+ type: 'module',+ peerDependencies: {+ '@astryxdesign/core': options.peerRange ?? '^1.0.0',+ },+ exports: exportsMap,+ }),+ );+ write(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );++ for (const spec of themeSpecs) {+ const exportName = `${spec.slug}Theme`;+ const sourceDir = path.join(packageDir, 'themes', spec.slug);+ const fontProperty = spec.fontFamily+ ? `, fontFamily: ${JSON.stringify(spec.fontFamily)}`+ : '';+ write(+ path.join(sourceDir, `${exportName}.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: '${spec.slug}', displayName: '${spec.slug}', description: '${spec.slug} theme.', maintained: true};\n`,+ );+ write(+ path.join(sourceDir, `${exportName}.ts`),+ `export const ${exportName} = {name: '${spec.slug}', tokens: {}${fontProperty}};\n`,+ );+ write(+ path.join(packageDir, `dist/${spec.slug}.js`),+ `export const ${exportName} = {name: '${spec.slug}', tokens: {}${fontProperty}};\n`,+ );+ write(+ path.join(packageDir, `dist/${spec.slug}.css`),+ spec.css ??+ `[data-astryx-theme="${spec.slug}"] { --color-text: black; }\n`,+ );+ if (spec.fontCss != null) {+ write(path.join(packageDir, `dist/${spec.slug}.fonts.css`), spec.fontCss);+ }+ await themeAdd(spec.slug, {+ cwd: dir,+ import: true,+ package: '@acme/themes',+ });+ }++ if (options.importModule !== false) {+ write(+ path.join(dir, 'src/index.tsx'),+ "import {themes, defaultThemeSlug} from './astryx-themes';\nvoid themes[defaultThemeSlug];\n",+ );+ }+ return {dir, packageDir, moduleFile: path.join(dir, 'src/astryx-themes.ts')};+}++/** @param {Awaited<ReturnType<typeof checkAppThemes>>} checks @param {string} id */+function check(checks, id) {+ const result = checks.find(item => item.id === id);+ if (!result) throw new Error(`Missing doctor check ${id}`);+ return result;+}++/** @param {string} dir */+function runDoctor(dir) {+ return spawnSync(+ process.execPath,+ [path.join(REPO_ROOT, 'packages/cli/clients/cli/bin/astryx.mjs'), 'doctor'],+ {cwd: dir, encoding: 'utf-8', timeout: 30_000},+ );+}++afterEach(() => {+ while (dirs.length > 0) {+ fs.rmSync(dirs.pop(), {recursive: true, force: true});+ }+});++describe('app-theme doctor checks', () => {+ it('returns ten positive passes for a healthy package theme', async () => {+ const {dir} = await fixture();+ const checks = await checkAppThemes(dir);++ expect(checks.map(item => item.id)).toEqual([+ 'theme-owners',+ 'theme-module',+ 'theme-module-import',+ 'theme-stylesheet-imports',+ 'theme-local-builds',+ 'theme-private-variables',+ 'theme-core-peers',+ 'theme-default',+ 'theme-fonts',+ 'theme-global-rules',+ ]);+ expect(checks.map(item => item.status)).toEqual(Array(10).fill('pass'));+ expect(check(checks, 'theme-owners').message).toContain(+ 'every built module loads',+ );+ });++ it('fails theme-owners when a recorded module has a missing dependency', async () => {+ const {dir, packageDir} = await fixture();+ write(+ path.join(packageDir, 'dist/ocean.js'),+ `import '@acme/definitely-missing-dep';\nexport const oceanTheme = {name: 'ocean', tokens: {}};\n`,+ );++ const result = check(await checkAppThemes(dir), 'theme-owners');++ expect(result).toMatchObject({id: 'theme-owners', status: 'fail'});+ expect(result.message).toContain('Theme "ocean"');+ expect(result.message).toContain('@acme/definitely-missing-dep');+ expect(result.message).not.toMatch(/\n\s+at /u);+ const cli = runDoctor(dir);+ expect(cli.status).toBe(1);+ expect(cli.stdout).not.toContain('No failures');+ expect(cli.stdout).toContain('Theme owners and built imports');+ expect(cli.stdout).toContain('@acme/definitely-missing-dep');+ expect(cli.stderr).not.toMatch(/\n\s+at /u);+ }, 30_000);++ it('fails theme-owners when a recorded module is malformed', async () => {+ const {dir, packageDir} = await fixture();+ write(+ path.join(packageDir, 'dist/ocean.js'),+ 'export const oceanTheme = ;\n',+ );++ const result = check(await checkAppThemes(dir), 'theme-owners');++ expect(result).toMatchObject({id: 'theme-owners', status: 'fail'});+ expect(result.message).toContain('Theme "ocean"');+ expect(result.message).toContain('does not export "oceanTheme"');+ expect(result.message).not.toMatch(/\n\s+at /u);+ });++ it('fails theme-owners for an ambiguous multi-theme record', async () => {+ const {dir, packageDir} = await fixture([{slug: 'ocean'}, {slug: 'reef'}]);+ const packageFile = path.join(packageDir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ delete pkg.exports['./themes/ocean'];+ write(packageFile, JSON.stringify(pkg));++ const result = check(await checkAppThemes(dir), 'theme-owners');++ expect(result).toMatchObject({id: 'theme-owners', status: 'fail'});+ expect(result.message).toContain('ocean');+ expect(result.message).not.toMatch(/\n\s+at /u);+ });++ it.each([+ 'theme-local-builds',+ 'theme-private-variables',+ 'theme-core-peers',+ 'theme-fonts',+ 'theme-global-rules',+ ])('%s cannot pass when theme discovery throws', async id => {+ const {dir} = await fixture();+ write(+ path.join(dir, 'astryx.config.mjs'),+ "throw new Error('fixture discovery failure');\n",+ );++ expect(check(await checkAppThemes(dir), id)).toMatchObject({+ status: 'info',+ });+ });++ it('lets the static default check pass when discovery throws', async () => {+ const {dir} = await fixture();+ write(+ path.join(dir, 'astryx.config.mjs'),+ "throw new Error('fixture discovery failure');\n",+ );++ expect(check(await checkAppThemes(dir), 'theme-default')).toMatchObject({+ status: 'pass',+ });+ });++ it('check 1 fails when a recorded built stylesheet no longer resolves', async () => {+ const {dir, packageDir} = await fixture();+ fs.rmSync(path.join(packageDir, 'dist/ocean.css'));++ expect(check(await checkAppThemes(dir), 'theme-owners')).toMatchObject({+ status: 'fail',+ fix: expect.stringContaining('theme add ocean --import'),+ });+ });++ it('check 2 fails when the generated module is hand-edited', async () => {+ const {dir, moduleFile} = await fixture();+ fs.appendFileSync(moduleFile, '// hand edit\n');++ expect(check(await checkAppThemes(dir), 'theme-module')).toMatchObject({+ status: 'fail',+ fix: expect.stringContaining('theme use ocean'),+ });+ });++ it('check 3 warns when no project source imports the generated module', async () => {+ const {dir} = await fixture([{slug: 'ocean'}], {importModule: false});++ expect(+ check(await checkAppThemes(dir), 'theme-module-import'),+ ).toMatchObject({+ status: 'warn',+ fix: expect.stringContaining('themes[defaultThemeSlug]'),+ });+ });++ it('check 4 fails when a built module import loses its stylesheet pair', async () => {+ const {dir, moduleFile} = await fixture();+ const source = fs+ .readFileSync(moduleFile, 'utf-8')+ .replace('import "@acme/themes/themes/ocean.css";\n', '');+ fs.writeFileSync(moduleFile, source);++ expect(+ check(await checkAppThemes(dir), 'theme-stylesheet-imports'),+ ).toMatchObject({+ status: 'fail',+ fix: expect.stringContaining('theme use ocean'),+ });+ });++ it('check 5 fails when an added local theme cannot reproduce its outputs', async () => {+ const {dir} = await fixture();+ await themeEject('ocean', {cwd: dir, package: '@acme/themes'});+ const localDir = path.join(dir, 'src/themes/ocean');+ const sourceFile = path.join(localDir, 'oceanTheme.ts');+ fs.writeFileSync(+ sourceFile,+ "const oceanTheme = {name: 'ocean', tokens: {'--color-bg': '#000'}};\nexport {oceanTheme};\nexport default oceanTheme;\n",+ );+ await themeBuild(sourceFile, {}, {cwd: dir});+ await themeAdd('ocean', {cwd: dir, import: true});+ expect(+ parseThemeModuleRecord(+ fs.readFileSync(path.join(dir, 'src/astryx-themes.ts'), 'utf-8'),+ ),+ ).toMatchObject({themes: {ocean: './src/themes'}});+ fs.appendFileSync(path.join(localDir, 'ocean.css'), '\n.injected {}\n');++ expect(+ check(await checkAppThemes(dir), 'theme-local-builds'),+ ).toMatchObject({+ status: 'fail',+ fix: expect.stringContaining('theme build'),+ });+ });++ it('check 6 ignores private variables generated from guaranteed component properties', async () => {+ const {dir, packageDir} = await fixture([+ {+ slug: 'ocean',+ css: '[data-astryx-theme="ocean"] { --_button-radius: var(--radius-full); }\n',+ },+ ]);+ write(+ path.join(packageDir, 'themes/ocean/oceanTheme.ts'),+ "export const oceanTheme = {name: 'ocean', tokens: {}, components: {button: {base: {borderRadius: 'var(--radius-full)'}}}};\n",+ );++ expect(+ check(await checkAppThemes(dir), 'theme-private-variables'),+ ).toMatchObject({status: 'pass'});+ });++ it('check 6 fails on a private --_* key in theme input', async () => {+ const {dir, packageDir} = await fixture();+ write(+ path.join(packageDir, 'themes/ocean/oceanTheme.ts'),+ "export const oceanTheme = {name: 'ocean', tokens: {}, components: {button: {base: {'--_button-radius': '2px'}}}};\n",+ );++ const result = check(await checkAppThemes(dir), 'theme-private-variables');+ expect(result).toMatchObject({status: 'fail'});+ expect(result.message).toContain('--_button-radius');+ });++ it('check 7 fails when a theme peer range rejects installed Core', async () => {+ const {dir} = await fixture([{slug: 'ocean'}], {peerRange: '^9.0.0'});++ const result = check(await checkAppThemes(dir), 'theme-core-peers');+ expect(result).toMatchObject({+ status: 'fail',+ fix: expect.stringContaining('npm install'),+ });+ expect(result.message).toContain('^9.0.0');+ });++ it('check 8 fails when the static default is not an added slug', async () => {+ const {dir, moduleFile} = await fixture();+ const source = fs+ .readFileSync(moduleFile, 'utf-8')+ .replace('"defaultThemeSlug":"ocean"', '"defaultThemeSlug":"ghost"');+ fs.writeFileSync(moduleFile, source);++ expect(check(await checkAppThemes(dir), 'theme-default')).toMatchObject({+ status: 'fail',+ fix: expect.stringContaining('theme use ocean'),+ });+ });++ it('check 9 warns when a named font has no stylesheet loader', async () => {+ const {dir} = await fixture([{slug: 'ocean', fontFamily: 'Ocean Sans'}]);++ const checks = await checkAppThemes(dir);+ const result = check(checks, 'theme-fonts');+ expect(result).toMatchObject({+ status: 'warn',+ fix: expect.stringContaining('fonts.css'),+ });+ expect(result.message).toContain('Ocean Sans');+ expect(checks.some(item => item.status === 'fail')).toBe(false);+ });++ it('check 9 warns when a local theme has no font stylesheet', async () => {+ const {dir} = await fixture([{slug: 'ocean', fontFamily: 'Ocean Sans'}]);+ await themeEject('ocean', {cwd: dir, package: '@acme/themes'});+ const sourceFile = path.join(dir, 'src/themes/ocean/oceanTheme.ts');+ await themeBuild(sourceFile, {}, {cwd: dir});+ await themeAdd('ocean', {cwd: dir, import: true});++ const checks = await checkAppThemes(dir);+ expect(check(checks, 'theme-fonts')).toMatchObject({+ status: 'warn',+ message: expect.stringContaining('Ocean Sans'),+ fix: expect.stringContaining('<slug>.fonts.css'),+ });+ expect(checks.some(item => item.status === 'fail')).toBe(false);+ });++ it('check 9 passes when a local @font-face proves the named family', async () => {+ const {dir} = await fixture([+ {+ slug: 'ocean',+ fontFamily: 'Ocean Sans',+ fontCss:+ '@font-face { font-family: "Ocean Sans"; src: url("./ocean.woff2"); }\n',+ },+ ]);++ expect(check(await checkAppThemes(dir), 'theme-fonts')).toMatchObject({+ status: 'pass',+ });+ });++ it('check 9 warns when an external import cannot prove the named family', async () => {+ const {dir} = await fixture([+ {+ slug: 'ocean',+ fontFamily: 'Ocean Sans',+ fontCss: '@import url("https://fonts.example/ocean.css");\n',+ },+ ]);++ expect(check(await checkAppThemes(dir), 'theme-fonts')).toMatchObject({+ status: 'warn',+ message: expect.stringContaining('Ocean Sans'),+ });+ });++ it('check 10 fails on conflicting unscoped rules across added themes', async () => {+ const {dir} = await fixture([+ {slug: 'ocean', css: 'body { color: blue; }\n'},+ {slug: 'sunset', css: 'body { color: red; }\n'},+ ]);++ const result = check(await checkAppThemes(dir), 'theme-global-rules');+ expect(result).toMatchObject({status: 'fail'});+ expect(result.message).toContain('body');+ });++ it('reports one information check when the CLI manages no themes', async () => {+ const dir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-doctor-empty-'),+ );+ dirs.push(dir);+ write(path.join(dir, 'package.json'), '{"name":"empty"}\n');++ const checks = await checkAppThemes(dir);+ expect(checks).toEqual([+ expect.objectContaining({+ id: 'theme-management',+ status: 'info',+ message: expect.stringContaining('manages no themes'),+ fix: expect.stringContaining('theme add <slug> --import'),+ }),+ ]);+ });++ it('names an unmigrated copy without failing a project that has no module', async () => {+ const dir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-doctor-unmigrated-'),+ );+ dirs.push(dir);+ write(path.join(dir, 'package.json'), '{"name":"empty"}\n');+ write(+ path.join(dir, 'src/themes/ocean/oceanTheme.ts'),+ 'export const oceanTheme = {};\n',+ );++ const checks = await checkAppThemes(dir);++ expect(checks).toHaveLength(2);+ expect(checks.some(item => item.status === 'fail')).toBe(false);+ expect(checks).toContainEqual(+ expect.objectContaining({+ id: 'theme-unmigrated-copies',+ status: 'warn',+ message: expect.stringContaining('src/themes/ocean'),+ fix: expect.stringContaining('upgrade --from 0.6.4 --path . --apply'),+ }),+ );+ });+});diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjsindex f758a550bf..b270b3e105 100644--- a/packages/cli/api/index.mjs+++ b/packages/cli/api/index.mjs@@ -28,9 +28,13 @@ export {template} from './template/template.mjs';export {themeBuild,themeAdd,+ themeRemove,+ themeUse,+ themeEject,themeTemplate,themeList,themeListAvailable,+ themeListCopySources,themeTargets,themePaletteGenerate,generateTonalPalette,diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjsindex 5edb770439..d79c8f1f74 100644--- a/packages/cli/api/init/run/run.mjs+++ b/packages/cli/api/init/run/run.mjs@@ -35,11 +35,9 @@ const VALID_AGENTS = ['claude', 'cursor', 'codex', 'hermes', 'muse', 'all'];/*** Build the "Next steps" lines printed at the end of `astryx init`.*- * Theme guidance must match the runtime recommendation emitted by core's- * <Theme> component (packages/core/src/theme/Theme.tsx): the pre-built theme- * path (`/built` import + `theme.css`) plus the base CSS import, so users- * don't end up with an unstyled app or the slower runtime style-injection- * path. See https://github.com/facebook/astryx/issues/3080.+ * Theme guidance follows the generated app-module workflow. `theme add --import` records+ * installed built themes and imports their production and font stylesheets. The+ * app imports that module once and passes its default to <Theme>.** @param {string} invocation install-aware CLI invocation stem (e.g. `npx astryx`, `pnpm exec astryx`, or `npx @astryxdesign/cli` for one-off runs)* @returns {string[]} ordered list of human-facing lines@@ -53,11 +51,12 @@ export function getNextSteps(invocation) {" 2. Import base styles: import '@astryxdesign/core/reset.css'"," and import '@astryxdesign/core/astryx.css'"," 3. Import components: import { Button } from '@astryxdesign/core'",- ' 4. Optionally add a theme (use the pre-built path for performance):',- " import { neutralTheme } from '@astryxdesign/theme-neutral/built'",- " import '@astryxdesign/theme-neutral/theme.css'",- ' <Theme theme={neutralTheme}>...</Theme>',- ` For custom themes, run \`${invocation} theme build <file>\` to generate the built artifacts.`,+ ' 4. Add and wire a theme:',+ ' npm install @astryxdesign/theme-neutral',+ ` ${invocation} theme add neutral --import`,+ " import { themes, defaultThemeSlug } from './astryx-themes'",+ ' <Theme theme={themes[defaultThemeSlug]}>...</Theme>',+ ` Extend an imported theme to customize it. Run \`${invocation} theme eject <slug>\` only to fork source.`,` 5. ${invocation} --help for all commands`,'',];@@ -141,7 +140,7 @@ function applyTheme(cwd, invocation, data) {logger.error('Could not write the theme template.');}logger.log(- ` Copy it to your theme file and edit, or run \`${invocation} theme add <slug>\` to start from a shipped theme (\`${invocation} theme list\` to browse).`,+ ` Edit the blank template for a new theme, or run \`${invocation} theme add <slug> --import\` to import an installed built theme (\`${invocation} theme list\` to browse). Extend an imported theme for ordinary customization; use \`${invocation} theme eject <slug>\` only to fork source.`,);}diff --git a/packages/cli/api/integration/__fixtures__/released-0.6.5-ocean.mjs b/packages/cli/api/integration/__fixtures__/released-0.6.5-ocean.mjsnew file mode 100644index 0000000000..53717f8245--- /dev/null+++ b/packages/cli/api/integration/__fixtures__/released-0.6.5-ocean.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Published npm output kept encoded so repository headers cannot alter its bytes. */+export const released065Ocean = Object.freeze({+ artifact: 'released-0.6.5-ocean.css',+ package: '@astryxdesign/[email protected]',+ source: 'npm',+ command: 'astryx theme build oceanTheme.ts',+ workingDirectory: 'themes/ocean',+ inputSha256:+ '05ac5f9fc3eb71a0096e4fd6dcecfb0d508e403a564be49bf5c535b3c5080245',+ sha256: 'd48aa16f5a87dcaa0d851928a4be735f80c29e462d3dd223cfc38570495f6fbd',+ base64:+ 'LyoKICogQGdlbmVyYXRlZCBieSBgYXN0cnl4IHRoZW1lIGJ1aWxkYCDigJQgZG8gbm90IGVkaXQgbWFudWFsbHkuCiAqIFNvdXJjZTogb2NlYW5UaGVtZS50cwogKiBDb21tYW5kOiBhc3RyeXggdGhlbWUgYnVpbGQgb2NlYW5UaGVtZS50cwogKiBDTEk6IEBhc3RyeXhkZXNpZ24vY2xpQDAuNi41CiAqIENvcmU6IEBhc3RyeXhkZXNpZ24vY29yZUAwLjYuNQogKi8KCkBsYXllciByZXNldCB7CkBzY29wZSAoW2RhdGEtYXN0cnl4LXRoZW1lPSJvY2VhbiJdKSB0byAoW2RhdGEtYXN0cnl4LXRoZW1lXSkgewogIDp3aGVyZShoMSwgaDIsIGgzLCBoNCwgaDUsIGg2KSB7CiAgICBmb250LWZhbWlseTogdmFyKC0tZm9udC1mYW1pbHktaGVhZGluZyk7CiAgICBjb2xvcjogdmFyKC0tY29sb3ItdGV4dC1wcmltYXJ5KTsKICB9CgogIDp3aGVyZShoMSkgewogICAgZm9udC1zaXplOiB2YXIoLS10ZXh0LWhlYWRpbmctMS1zaXplKTsKICAgIGZvbnQtd2VpZ2h0OiB2YXIoLS10ZXh0LWhlYWRpbmctMS13ZWlnaHQpOwogICAgbGluZS1oZWlnaHQ6IHZhcigtLXRleHQtaGVhZGluZy0xLWxlYWRpbmcpOwogIH0KCiAgOndoZXJlKGgyKSB7CiAgICBmb250LXNpemU6IHZhcigtLXRleHQtaGVhZGluZy0yLXNpemUpOwogICAgZm9udC13ZWlnaHQ6IHZhcigtLXRleHQtaGVhZGluZy0yLXdlaWdodCk7CiAgICBsaW5lLWhlaWdodDogdmFyKC0tdGV4dC1oZWFkaW5nLTItbGVhZGluZyk7CiAgfQoKICA6d2hlcmUoaDMpIHsKICAgIGZvbnQtc2l6ZTogdmFyKC0tdGV4dC1oZWFkaW5nLTMtc2l6ZSk7CiAgICBmb250LXdlaWdodDogdmFyKC0tdGV4dC1oZWFkaW5nLTMtd2VpZ2h0KTsKICAgIGxpbmUtaGVpZ2h0OiB2YXIoLS10ZXh0LWhlYWRpbmctMy1sZWFkaW5nKTsKICB9CgogIDp3aGVyZShoNCkgewogICAgZm9udC1zaXplOiB2YXIoLS10ZXh0LWhlYWRpbmctNC1zaXplKTsKICAgIGZvbnQtd2VpZ2h0OiB2YXIoLS10ZXh0LWhlYWRpbmctNC13ZWlnaHQpOwogICAgbGluZS1oZWlnaHQ6IHZhcigtLXRleHQtaGVhZGluZy00LWxlYWRpbmcpOwogIH0KCiAgOndoZXJlKGg1KSB7CiAgICBmb250LXNpemU6IHZhcigtLXRleHQtaGVhZGluZy01LXNpemUpOwogICAgZm9udC13ZWlnaHQ6IHZhcigtLXRleHQtaGVhZGluZy01LXdlaWdodCk7CiAgICBsaW5lLWhlaWdodDogdmFyKC0tdGV4dC1oZWFkaW5nLTUtbGVhZGluZyk7CiAgfQoKICA6d2hlcmUoaDYpIHsKICAgIGZvbnQtc2l6ZTogdmFyKC0tdGV4dC1oZWFkaW5nLTYtc2l6ZSk7CiAgICBmb250LXdlaWdodDogdmFyKC0tdGV4dC1oZWFkaW5nLTYtd2VpZ2h0KTsKICAgIGxpbmUtaGVpZ2h0OiB2YXIoLS10ZXh0LWhlYWRpbmctNi1sZWFkaW5nKTsKICB9CgogIDp3aGVyZShwKSB7CiAgICBmb250LWZhbWlseTogdmFyKC0tZm9udC1mYW1pbHktYm9keSk7CiAgICBmb250LXNpemU6IHZhcigtLXRleHQtYm9keS1zaXplKTsKICAgIGZvbnQtd2VpZ2h0OiB2YXIoLS10ZXh0LWJvZHktd2VpZ2h0KTsKICAgIGxpbmUtaGVpZ2h0OiB2YXIoLS10ZXh0LWJvZHktbGVhZGluZyk7CiAgICBjb2xvcjogdmFyKC0tY29sb3ItdGV4dC1wcmltYXJ5KTsKICB9CgogIDp3aGVyZShzbWFsbCkgewogICAgZm9udC1zaXplOiB2YXIoLS10ZXh0LXN1cHBvcnRpbmctc2l6ZSk7CiAgICBmb250LXdlaWdodDogdmFyKC0tdGV4dC1zdXBwb3J0aW5nLXdlaWdodCk7CiAgICBsaW5lLWhlaWdodDogdmFyKC0tdGV4dC1zdXBwb3J0aW5nLWxlYWRpbmcpOwogICAgY29sb3I6IHZhcigtLWNvbG9yLXRleHQtc2Vjb25kYXJ5KTsKICB9CgogIDp3aGVyZShjb2RlLCBwcmUpIHsKICAgIGZvbnQtZmFtaWx5OiB2YXIoLS1mb250LWZhbWlseS1jb2RlKTsKICAgIGZvbnQtc2l6ZTogdmFyKC0tdGV4dC1jb2RlLXNpemUpOwogICAgbGluZS1oZWlnaHQ6IHZhcigtLXRleHQtY29kZS1sZWFkaW5nKTsKICB9CgogIDp3aGVyZShocikgewogICAgYm9yZGVyOiBub25lOwogICAgYm9yZGVyLXRvcDogMXB4IHNvbGlkIHZhcigtLWNvbG9yLWJvcmRlcik7CiAgfQp9Cn0KCkBsYXllciBhc3RyeXgtYmFzZSB7Cjpyb290IHsKICAtLWNvbG9yLWRhdGEtY2F0ZWdvcmljYWwtYmx1ZTogbGlnaHQtZGFyaygjMDE3MUUzLCAjMDE3MUUzKTsKICAtLWNvbG9yLWRhdGEtY2F0ZWdvcmljYWwtb3JhbmdlOiBsaWdodC1kYXJrKCNFQjZFMDAsICNFQjZFMDApOwogIC0tY29sb3ItZGF0YS1jYXRlZ29yaWNhbC1wdXJwbGU6IGxpZ2h0LWRhcmsoIzZCMUVGRCwgIzZCMUVGRCk7CiAgLS1jb2xvci1kYXRhLWNhdGVnb3JpY2FsLWdyZWVuOiBsaWdodC1kYXJrKCMwQjk5MUYsICMwQjk5MUYpOwogIC0tY29sb3ItZGF0YS1jYXRlZ29yaWNhbC1waW5rOiBsaWdodC1kYXJrKCNGMzUxQzAsICNGMzUxQzApOwogIC0tY29sb3ItZGF0YS1jYXRlZ29yaWNhbC1jeWFuOiBsaWdodC1kYXJrKCMwMTcxQTQsICMwMTcxQTQpOwogIC0tY29sb3ItZGF0YS1jYXRlZ29yaWNhbC1yZWQ6IGxpZ2h0LWRhcmsoI0Y1Mzk0RiwgI0Y1Mzk0Rik7CiAgLS1jb2xvci1kYXRhLWNhdGVnb3JpY2FsLXRlYWw6IGxpZ2h0LWRhcmsoIzA4QTNBMywgIzA4QTNBMyk7CiAgLS1jb2xvci1kYXRhLWNhdGVnb3JpY2FsLWJyb3duOiBsaWdodC1kYXJrKCM5NjVFMDMsICM5NjVFMDMpOwogIC0tY29sb3ItZGF0YS1jYXRlZ29yaWNhbC1pbmRpZ286IGxpZ2h0LWRhcmsoIzZGOEFGRiwgIzZGOEFGRik7CiAgLS1jb2xvci1kYXRhLW5ldXRyYWw6IGxpZ2h0LWRhcmsoIzg0OTRBMywgIzhDOTM5Qik7CiAgLS1jb2xvci1kYXRhLWJsdWUtNTogbGlnaHQtZGFyaygjMDIxNjVFLCAjMDIxNjVFKTsKICAtLWNvbG9yLWRhdGEtYmx1ZS00OiBsaWdodC1kYXJrKCMwMDRDQkMsICMwMDRDQkMpOwogIC0tY29sb3ItZGF0YS1ibHVlLTM6IGxpZ2h0LWRhcmsoIzI2OTRGRSwgIzI2OTRGRSk7CiAgLS1jb2xvci1kYXRhLWJsdWUtMjogbGlnaHQtZGFyaygjNzhCRUZGLCAjNzhCRUZGKTsKICAtLWNvbG9yLWRhdGEtYmx1ZS0xOiBsaWdodC1kYXJrKCNEQkVDRkYsICNEQkVDRkYpOwogIC0tY29sb3ItZGF0YS1zaGFtcm9jay01OiBsaWdodC1kYXJrKCMwQjYwM0QsICMwQjYwM0QpOwogIC0tY29sb3ItZGF0YS1zaGFtcm9jay00OiBsaWdodC1kYXJrKCMxMzg1NDYsICMxMzg1NDYpOwogIC0tY29sb3ItZGF0YS1zaGFtcm9jay0zOiBsaWdodC1kYXJrKCMyNEJCNUUsICMyNEJCNUUpOwogIC0tY29sb3ItZGF0YS1zaGFtcm9jay0yOiBsaWdodC1kYXJrKCM4RUY3QUEsICM4RUY3QUEpOwogIC0tY29sb3ItZGF0YS1zaGFtcm9jay0xOiBsaWdodC1kYXJrKCNENkZFRTQsICNENkZFRTQpOwogIC0tY29sb3ItZGF0YS1vcmFuZ2UtNTogbGlnaHQtZGFyaygjQTEzRjA0LCAjQTEzRjA0KTsKICAtLWNvbG9yLWRhdGEtb3JhbmdlLTQ6IGxpZ2h0LWRhcmsoI0Q2NjEwMCwgI0Q2NjEwMCk7CiAgLS1jb2xvci1kYXRhLW9yYW5nZS0zOiBsaWdodC1kYXJrKCNGRDk1MzcsICNGRDk1MzcpOwogIC0tY29sb3ItZGF0YS1vcmFuZ2UtMjogbGlnaHQtZGFyaygjRkRCODc2LCAjRkRCODc2KTsKICAtLWNvbG9yLWRhdGEtb3JhbmdlLTE6IGxpZ2h0LWRhcmsoI0ZGRTZDRiwgI0ZGRTZDRik7CiAgLS1jb2xvci1kYXRhLXBpbmstNTogbGlnaHQtZGFyaygjOEUxMDczLCAjOEUxMDczKTsKICAtLWNvbG9yLWRhdGEtcGluay00OiBsaWdodC1kYXJrKCNEMTIzQTEsICNEMTIzQTEpOwogIC0tY29sb3ItZGF0YS1waW5rLTM6IGxpZ2h0LWRhcmsoI0Y5ODlEMywgI0Y5ODlEMyk7CiAgLS1jb2xvci1kYXRhLXBpbmstMjogbGlnaHQtZGFyaygjRkVBREUzLCAjRkVBREUzKTsKICAtLWNvbG9yLWRhdGEtcGluay0xOiBsaWdodC1kYXJrKCNGQ0UzRjQsICNGQ0UzRjQpOwogIC0tY29sb3ItZGF0YS1wdXJwbGUtNTogbGlnaHQtZGFyaygjM0UwNjk3LCAjM0UwNjk3KTsKICAtLWNvbG9yLWRhdGEtcHVycGxlLTQ6IGxpZ2h0LWRhcmsoIzZCMUVGRCwgIzZCMUVGRCk7CiAgLS1jb2xvci1kYXRhLXB1cnBsZS0zOiBsaWdodC1kYXJrKCM5MDgxRkYsICM5MDgxRkYpOwogIC0tY29sb3ItZGF0YS1wdXJwbGUtMjogbGlnaHQtZGFyaygjQjNCMEZFLCAjQjNCMEZFKTsKICAtLWNvbG9yLWRhdGEtcHVycGxlLTE6IGxpZ2h0LWRhcmsoI0U4RThGQiwgI0U4RThGQik7CiAgLS1jb2xvci1kYXRhLXJlZC01OiBsaWdodC1kYXJrKCM5RDA1MTksICM5RDA1MTkpOwogIC0tY29sb3ItZGF0YS1yZWQtNDogbGlnaHQtZGFyaygjRDMxMTMwLCAjRDMxMTMwKTsKICAtLWNvbG9yLWRhdGEtcmVkLTM6IGxpZ2h0LWRhcmsoI0ZCN0Q4NywgI0ZCN0Q4Nyk7CiAgLS1jb2xvci1kYXRhLXJlZC0yOiBsaWdodC1kYXJrKCNGRkIyQjgsICNGRkIyQjgpOwogIC0tY29sb3ItZGF0YS1yZWQtMTogbGlnaHQtZGFyaygjRkVFNEU2LCAjRkVFNEU2KTsKICAtLWNvbG9yLWRhdGEtdGVhbC01OiBsaWdodC1kYXJrKCMwODc2N0QsICMwODc2N0QpOwogIC0tY29sb3ItZGF0YS10ZWFsLTQ6IGxpZ2h0LWRhcmsoIzBDOTI5MywgIzBDOTI5Myk7CiAgLS1jb2xvci1kYXRhLXRlYWwtMzogbGlnaHQtZGFyaygjMERCN0FGLCAjMERCN0FGKTsKICAtLWNvbG9yLWRhdGEtdGVhbC0yOiBsaWdodC1kYXJrKCM2Q0U2RDgsICM2Q0U2RDgpOwogIC0tY29sb3ItZGF0YS10ZWFsLTE6IGxpZ2h0LWRhcmsoI0Q3RkNGOCwgI0Q3RkNGOCk7CiAgLS1jb2xvci1kYXRhLXllbGxvdy01OiBsaWdodC1kYXJrKCM4QTUwMDEsICM4QTUwMDEpOwogIC0tY29sb3ItZGF0YS15ZWxsb3ctNDogbGlnaHQtZGFyaygjRDY5ODA0LCAjRDY5ODA0KTsKICAtLWNvbG9yLWRhdGEteWVsbG93LTM6IGxpZ2h0LWRhcmsoI0ZCQ0UwMywgI0ZCQ0UwMyk7CiAgLS1jb2xvci1kYXRhLXllbGxvdy0yOiBsaWdodC1kYXJrKCNGQ0VDODUsICNGQ0VDODUpOwogIC0tY29sb3ItZGF0YS15ZWxsb3ctMTogbGlnaHQtZGFyaygjRkRGNkJBLCAjRkRGNkJBKTsKICAtLWNvbG9yLWRhdGEtZ3JheS01OiBsaWdodC1kYXJrKCMyNTM2M0YsICMzMzMzMzgpOwogIC0tY29sb3ItZGF0YS1ncmF5LTQ6IGxpZ2h0LWRhcmsoIzVENkM3QiwgIzY2NkE3Mik7CiAgLS1jb2xvci1kYXRhLWdyYXktMzogbGlnaHQtZGFyaygjQUZCOUM0LCAjQjJCOEJFKTsKICAtLWNvbG9yLWRhdGEtZ3JheS0yOiBsaWdodC1kYXJrKCNDQ0QzREIsICNEMEQzRDYpOwogIC0tY29sb3ItZGF0YS1ncmF5LTE6IGxpZ2h0LWRhcmsoI0YxRjRGNywgI0YyRjRGNik7Cn0KfQoKQGxheWVyIGFzdHJ5eC10aGVtZSB7CkBzY29wZSAoW2RhdGEtYXN0cnl4LXRoZW1lPSJvY2VhbiJdKSB0byAoW2RhdGEtYXN0cnl4LXRoZW1lXSkgewogIFtkYXRhLWFzdHJ5eC1tZWRpYT0iZGFyayJdIHsKICAgIGNvbG9yLXNjaGVtZTogZGFyazsKICAgIC0tY29sb3ItdGV4dC1wcmltYXJ5OiB2YXIoLS1jb2xvci1vbi1kYXJrKTsKICAgIC0tY29sb3ItaWNvbi1wcmltYXJ5OiB2YXIoLS1jb2xvci1vbi1kYXJrKTsKICAgIC0tY29sb3ItYWNjZW50OiB2YXIoLS1jb2xvci1vbi1kYXJrKTsKICB9CgogIFtkYXRhLWFzdHJ5eC1tZWRpYT0ibGlnaHQiXSB7CiAgICBjb2xvci1zY2hlbWU6IGxpZ2h0OwogICAgLS1jb2xvci10ZXh0LXByaW1hcnk6IHZhcigtLWNvbG9yLW9uLWxpZ2h0KTsKICAgIC0tY29sb3ItaWNvbi1wcmltYXJ5OiB2YXIoLS1jb2xvci1vbi1saWdodCk7CiAgICAtLWNvbG9yLWFjY2VudDogdmFyKC0tY29sb3Itb24tbGlnaHQpOwogIH0KfQp9Cg==',+});diff --git a/packages/cli/api/integration/add-helpers.mjs b/packages/cli/api/integration/add-helpers.mjsindex 0fab6b974d..ad050715f3 100644--- a/packages/cli/api/integration/add-helpers.mjs+++ b/packages/cli/api/integration/add-helpers.mjs@@ -60,19 +60,29 @@ export function findPackageDir(startDir) {*//**- * 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.+ * @typedef {object} PackageJsonUpdateOptions+ * @property {boolean} [createExports] create a subpath map when the package has+ * no exports field+ * @property {string[]} [sideEffects] side-effect glob patterns to preserve when+ * package.json currently declares `sideEffects: false` or a pattern array+ */++/**+ * Compute one package.json update for an existing `files` allowlist and an+ * optional exports map. An exports map is created only when `createExports` is+ * explicit because doing so makes every unlisted deep import private.** @param {string} packageFile* @param {string[]} entries project-relative files or directories* @param {PackageExportEntry[]} [publicExports]+ * @param {PackageJsonUpdateOptions} [options]* @returns {PackageJsonUpdate|null}*/export function packageJsonFilesUpdate(packageFile,entries,publicExports = [],+ {createExports = false, sideEffects = []} = {},) {const expectedOriginal = fs.readFileSync(packageFile);const original = expectedOriginal.toString('utf-8');@@ -117,11 +127,13 @@ export function packageJsonFilesUpdate(}}- if (pkg.exports !== undefined && publicExports.length > 0) {+ if ((pkg.exports !== undefined || createExports) && publicExports.length > 0) {const authored = pkg.exports;/** @type {Record<string, unknown>} */let exportsMap;- if (+ if (authored === undefined) {+ exportsMap = {};+ } else if (authored == null ||typeof authored !== 'object' ||Array.isArray(authored)@@ -160,6 +172,36 @@ export function packageJsonFilesUpdate(if (changed || exportsMap !== authored) pkg.exports = exportsMap;}+ if (sideEffects.length > 0 && pkg.sideEffects !== undefined) {+ if (pkg.sideEffects === false) {+ pkg.sideEffects = [...sideEffects];+ changed = true;+ } else if (Array.isArray(pkg.sideEffects)) {+ if (+ pkg.sideEffects.some(+ (/** @type {unknown} */ item) => typeof item !== 'string',+ )+ ) {+ throw new AstryxError(+ 'package.json sideEffects must be a boolean or an array of strings before Astryx can add theme CSS.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ for (const pattern of sideEffects) {+ if (pkg.sideEffects.includes(pattern)) continue;+ pkg.sideEffects.push(pattern);+ changed = true;+ }+ } else if (pkg.sideEffects !== true) {+ throw new AstryxError(+ 'package.json sideEffects must be a boolean or an array of strings before Astryx can add theme CSS.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ }+if (!changed) return null;const indent = original.match(/\n([ \t]+)"/u)?.[1] ?? ' ';return {@@ -176,6 +218,7 @@ export function packageJsonFilesUpdate(* @param {string} rootPath* @param {string} manifestName* @param {PackageExportEntry[]} [publicExports]+ * @param {PackageJsonUpdateOptions} [options]* @returns {PackageJsonUpdate|null}*/export function packageJsonUpdate(@@ -183,11 +226,13 @@ export function packageJsonUpdate(rootPath,manifestName,publicExports = [],+ options = {},) {return packageJsonFilesUpdate(packageFile,[rootPath, manifestName],publicExports,+ options,);}diff --git a/packages/cli/api/integration/add-theme.mjs b/packages/cli/api/integration/add-theme.mjsindex ba85dfb110..c463dda6c5 100644--- a/packages/cli/api/integration/add-theme.mjs+++ b/packages/cli/api/integration/add-theme.mjs@@ -2,8 +2,8 @@/*** @file `astryx integration add theme` — scaffold one strongly typed,- * same-stem source/descriptor pair into an integration package and declare the- * themes root on first use.+ * same-stem source/descriptor pair into an integration package, declare the+ * themes root on first use, and add the built module and stylesheet exports.** `--from <base>` forks an existing theme's source files as the starting point* instead of writing a blank `defineTheme` skeleton.@@ -528,10 +528,24 @@ export async function integrationAddTheme(name, options = {}) {];}+ const outputBase = projectPath(+ path.relative(packageDir, path.join(themeDir, identity.slug)),+ );let packageUpdate = packageJsonUpdate(packageFile,rootPath,path.basename(manifestFile),+ [+ {+ subpath: `themes/${identity.slug}`,+ target: `${outputBase}.js`,+ },+ {+ subpath: `themes/${identity.slug}.css`,+ target: `${outputBase}.css`,+ },+ ],+ {createExports: true, sideEffects: ['**/*.css']},);// A CLI older than the one that reads typed theme descriptors rejects the// themes root and withholds the package's themes and docs. Declare the CLIdiff --git a/packages/cli/api/integration/add-theme.test.mjs b/packages/cli/api/integration/add-theme.test.mjsindex fdf906e35d..be5178a4b5 100644--- a/packages/cli/api/integration/add-theme.test.mjs+++ b/packages/cli/api/integration/add-theme.test.mjs@@ -72,10 +72,14 @@ describe('integrationAddTheme', () => {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']);+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.files).toEqual(['dist', 'themes', 'astryx.integration.mjs']);+ expect(pkg.exports).toMatchObject({+ './themes/ocean': './themes/ocean/ocean.js',+ './themes/ocean.css': './themes/ocean/ocean.css',+ });expect((await validateLocalIntegration(tmpDir)).issues).toEqual([]);});@@ -107,10 +111,16 @@ describe('integrationAddTheme', () => {'export default {};\n',);const result = await integrationAddTheme('ocean', {cwd: tmpDir});- expect(result.data.files).not.toContain('package.json');+ expect(result.data.files).toContain('package.json');expect(JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8')),- ).toEqual(pkg);+ ).toMatchObject({+ ...pkg,+ exports: {+ './themes/ocean': './themes/ocean/ocean.js',+ './themes/ocean.css': './themes/ocean/ocean.css',+ },+ });});it('dry-runs the identical receipt without writing anything', async () => {@@ -135,14 +145,17 @@ describe('integrationAddTheme', () => {).toBe(beforeManifest);});- it('does not create package.json files when the package had no allowlist', async () => {+ it('creates theme exports even when the package has no files 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');+ expect(pkg.exports).toEqual({+ './themes/ocean': './themes/ocean/ocean.js',+ './themes/ocean.css': './themes/ocean/ocean.css',+ });});it('uses an author-declared custom root without rewriting it', async () => {@@ -161,13 +174,35 @@ describe('integrationAddTheme', () => {expect(fs.existsSync(path.join(tmpDir, 'src/themes/ocean/oceanTheme.doc.mjs')),).toBe(true);+ expect(+ JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'))+ .exports,+ ).toEqual({+ './themes/ocean': './src/themes/ocean/ocean.js',+ './themes/ocean.css': './src/themes/ocean/ocean.css',+ });+ });++ it('keeps generated theme CSS side-effectful', async () => {+ setup();+ const packageFile = path.join(tmpDir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ pkg.sideEffects = false;+ fs.writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);++ await integrationAddTheme('ocean', {cwd: tmpDir});++ expect(+ JSON.parse(fs.readFileSync(packageFile, 'utf-8')).sideEffects,+ ).toEqual(['**/*.css']);});- it('keeps each theme to its own folder: a second theme touches no shared file', async () => {+ it('adds one export pair per theme without touching the manifest again', async () => {setup({manifest: "export default {themes: './themes'};\n"});await integrationAddTheme('ocean', {cwd: tmpDir});- const shared = ['package.json', 'astryx.integration.mjs'].map(file =>- fs.readFileSync(path.join(tmpDir, file), 'utf-8'),+ const manifestBefore = fs.readFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'utf-8',);const result = await integrationAddTheme('reef', {cwd: tmpDir});@@ -175,16 +210,24 @@ describe('integrationAddTheme', () => {expect(result.data.files).toEqual(['themes/reef/reefTheme.ts','themes/reef/reefTheme.doc.mjs',+ 'package.json',]);expect(fs.readdirSync(path.join(tmpDir, 'themes')).sort()).toEqual(['ocean','reef',]);expect(- ['package.json', 'astryx.integration.mjs'].map(file =>- fs.readFileSync(path.join(tmpDir, file), 'utf-8'),- ),- ).toEqual(shared);+ fs.readFileSync(path.join(tmpDir, 'astryx.integration.mjs'), 'utf-8'),+ ).toBe(manifestBefore);+ expect(+ JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'))+ .exports,+ ).toEqual({+ './themes/ocean': './themes/ocean/ocean.js',+ './themes/ocean.css': './themes/ocean/ocean.css',+ './themes/reef': './themes/reef/reef.js',+ './themes/reef.css': './themes/reef/reef.css',+ });});it('refuses an obsolete central catalog without changing its bytes', async () => {@@ -350,6 +393,14 @@ describe('integrationAddTheme --from', () => {expect(descriptor).toContain("name: 'ocean'");expect(descriptor).toContain("@astryxdesign/cli/authoring').ThemeDoc");expect(descriptor).toContain('maintained: true');+ expect(result.data.files).toContain('package.json');+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ expect(pkg.exports).toMatchObject({+ './themes/ocean': './themes/ocean/ocean.js',+ './themes/ocean.css': './themes/ocean/ocean.css',+ });// The theme must validate.expect((await validateLocalIntegration(tmpDir)).issues).toEqual([]);diff --git a/packages/cli/api/integration/pack-check.lifecycle-output.test.mjs b/packages/cli/api/integration/pack-check.lifecycle-output.test.mjsindex eb319d9766..cc74cee81e 100644--- a/packages/cli/api/integration/pack-check.lifecycle-output.test.mjs+++ b/packages/cli/api/integration/pack-check.lifecycle-output.test.mjs@@ -1,6 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import {spawnSync} from 'node:child_process';import * as fs from 'node:fs';import * as path from 'node:path';import {integrationPackCheck} from './pack-check.mjs';@@ -26,6 +27,10 @@ function writeThemePackage(scripts) {files: ['astryx.integration.mjs', 'themes'],peerDependencies: {'@astryxdesign/cli': '>=0.7.0'},peerDependenciesMeta: {'@astryxdesign/cli': {optional: true}},+ exports: {+ './themes/ocean': './themes/ocean/ocean.js',+ './themes/ocean.css': './themes/ocean/ocean.css',+ },scripts,},null,@@ -48,6 +53,21 @@ function writeThemePackage(scripts) {export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Ocean theme.', maintained: true};`,);+ const built = spawnSync(+ process.execPath,+ [+ path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),+ 'theme',+ 'build',+ 'themes/ocean/oceanTheme.ts',+ ],+ {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},+ );+ if (built.status !== 0) {+ throw new Error(+ `Could not build the theme fixture: ${built.stderr || built.stdout}`,+ );+ }}describe('integrationPackCheck with lifecycle script output', () => {@@ -91,8 +111,7 @@ describe('integrationPackCheck with lifecycle script output', () => {it('keeps a failing lifecycle script output in the pack_failed issue', async () => {writeThemePackage({- prepack:- 'node -e "console.error(\'prepack exploded\'); process.exit(3)"',+ prepack: 'node -e "console.error(\'prepack exploded\'); process.exit(3)"',});const result = await integrationPackCheck({cwd: tmpDir});diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsindex 7e819cb7bb..e86a13364e 100644--- a/packages/cli/api/integration/pack-check.mjs+++ b/packages/cli/api/integration/pack-check.mjs@@ -38,6 +38,16 @@ import {discoverIntegrationDocs,loadTopicModule,} from '../../foundation/discovery/docs-discovery.mjs';+import {discoverIntegrationThemes} from '../../foundation/discovery/theme-discovery.mjs';+import {inspectPackageExport} from '../../foundation/discovery/package-exports.mjs';+import {+ ThemeImportError,+ resolveThemeImports,+} from '../../foundation/discovery/theme-imports.mjs';+import {+ normalizeThemeBuildForCompare,+ themeBuild,+} from '../theme/build/build.mjs';import {discoverIntegrationComponents,resolveIntegrationImportPath,@@ -68,6 +78,54 @@ function warning(code, message) {return {code, severity: 'warning', message};}+const GENERATED_HEADER_LINE =+ ' * @generated by `astryx theme build` — do not edit manually.';+const SOURCE_LINE = /^( \* Source: )(\S(?:.*\S)?)(\s*)$/u;+const CLI_VERSION_LINE = /^( \* CLI: @astryxdesign\/cli@)(\S+)(\s*)$/u;+const CORE_VERSION_LINE = /^( \* Core: @astryxdesign\/core@)(\S+)(\s*)$/u;++/**+ * Compare generated theme outputs without making their build directory or+ * CLI/Core version look like source drift. Normalization applies only to the+ * first generated JS or CSS comment and only when it contains exactly one+ * well-formed Source, CLI, and Core line. Missing, duplicate, malformed,+ * reordered, or any other bytes stay significant. `theme build --check`+ * deliberately stays strict.+ * @param {string} content+ */+export function normalizeThemeVerifyForCompare(content) {+ const normalized = normalizeThemeBuildForCompare(content);+ const lines = normalized.split('\n');+ if (lines[0] !== '/*' && lines[0] !== '/**') return normalized;+ const close = lines.indexOf(' */', 1);+ if (close === -1) return normalized;+ const header = lines.slice(1, close);+ if (header.filter(line => line === GENERATED_HEADER_LINE).length !== 1) {+ return normalized;+ }+ const source = header.filter(line => SOURCE_LINE.test(line));+ const cli = header.filter(line => CLI_VERSION_LINE.test(line));+ const core = header.filter(line => CORE_VERSION_LINE.test(line));+ if (source.length !== 1 || cli.length !== 1 || core.length !== 1) {+ return normalized;+ }+ return lines+ .map((line, index) => {+ if (index >= close) return line;+ if (SOURCE_LINE.test(line)) {+ return line.replace(SOURCE_LINE, '$1<source>$3');+ }+ if (CLI_VERSION_LINE.test(line)) {+ return line.replace(CLI_VERSION_LINE, '$1<version>$3');+ }+ if (CORE_VERSION_LINE.test(line)) {+ return line.replace(CORE_VERSION_LINE, '$1<version>$3');+ }+ return line;+ })+ .join('\n');+}+/*** Cleanup must never hide the check result or prevent the other temporary tree* from being removed.@@ -347,7 +405,9 @@ function moduleExportsName(file, exportName, seen = new Set()) {async function setsSectionIds(files) {for (const file of files) {if (typeof file !== 'string') continue;- const doc = /** @type {any} */ (await loadTopicModule(file).catch(() => null));+ const doc = /** @type {any} */ (+ await loadTopicModule(file).catch(() => null)+ );const sections = Array.isArray(doc?.sections) ? doc.sections : [];if (sections.some((/** @type {any} */ section) => section?.id != null)) {return true;@@ -478,6 +538,403 @@ async function validatePackedComponentExports(integration, scratchBase) {return issues;}+/** @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} integration */+function integrationPackageMetadata(integration) {+ try {+ return JSON.parse(+ fs.readFileSync(+ path.join(integration.__packageDir, 'package.json'),+ 'utf-8',+ ),+ );+ } catch {+ return {name: integration.name};+ }+}++/**+ * The exported output group selected for one theme. A complete per-theme or+ * single-theme pair wins; otherwise return the incomplete group so each path+ * can still be checked without making source-only packages fail.+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} integration+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme+ * @param {number} themeCount+ */+function declaredThemeBuildOutputs(integration, theme, themeCount) {+ const pkg = integrationPackageMetadata(integration);+ if (pkg.exports === undefined) return [];+ const groups = [+ [+ {kind: 'module', subpath: `./themes/${theme.slug}`},+ {kind: 'stylesheet', subpath: `./themes/${theme.slug}.css`},+ {kind: 'font stylesheet', subpath: `./themes/${theme.slug}.fonts.css`},+ ],+ ...(themeCount === 1+ ? [+ [+ {kind: 'module', subpath: './built'},+ {kind: 'stylesheet', subpath: './theme.css'},+ {kind: 'font stylesheet', subpath: './fonts.css'},+ ],+ ]+ : []),+ ].map(group =>+ group.map(output => ({+ ...output,+ inspected: inspectPackageExport(+ pkg,+ integration.__packageDir,+ output.subpath,+ ),+ })),+ );+ const declared = groups.map(group =>+ group.filter(output => output.inspected.exported),+ );+ return (+ declared.find(+ group =>+ group.some(output => output.kind === 'module') &&+ group.some(output => output.kind === 'stylesheet'),+ ) ??+ declared.find(group => group.length > 0) ??+ []+ );+}++/**+ * Check every declared path in an incomplete export pair without making the+ * missing partner a publication error.+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} localTheme+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} packedIntegration+ * @param {Array<{kind: string, subpath: string, inspected: import('../../foundation/discovery/package-exports.mjs').PackageExportResult}>} declared+ * @param {string} source+ * @param {string} sourceRelative+ * @param {string} packageDir+ */+async function validateIncompleteThemeExports(+ localTheme,+ packedIntegration,+ declared,+ source,+ sourceRelative,+ packageDir,+) {+ /** @type {Issue[]} */+ const issues = [+ warning(+ 'theme_exports_incomplete',+ `Theme "${localTheme.slug}" exports ${declared.map(output => output.inspected.specifier).join(', ')} without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.`,+ ),+ ];+ const packedPkg = integrationPackageMetadata(packedIntegration);+ const outputs = declared.map(output => ({+ ...output,+ packed: inspectPackageExport(+ packedPkg,+ packedIntegration.__packageDir,+ output.subpath,+ ),+ }));+ for (const output of outputs) {+ if (+ !output.inspected.target ||+ !output.packed.exported ||+ !output.packed.target+ ) {+ issues.push(+ error(+ 'theme_import_unresolvable',+ `Theme "${localTheme.slug}" declares ${output.inspected.specifier}, but that ${output.kind} does not resolve from both the source package and packed tarball.`,+ ),+ );+ }+ }+ if (issues.some(issue => issue.severity === 'error')) return issues;++ const expectedDir = fs.mkdtempSync(+ path.join(os.tmpdir(), `astryx-theme-${localTheme.slug}-`),+ );+ const expectedCss = path.join(expectedDir, `${localTheme.slug}.css`);+ try {+ if (outputs.some(output => output.kind !== 'font stylesheet')) {+ const receipt = await themeBuild(+ source,+ {out: expectedCss},+ {cwd: packageDir},+ );+ if (receipt == null || receipt.type !== 'theme.build') {+ throw new Error('the theme build produced no complete receipt');+ }+ }+ for (const output of outputs) {+ const localFile = /** @type {string} */ (output.inspected.target);+ const packedFile = /** @type {string} */ (output.packed.target);+ if (output.kind === 'font stylesheet') {+ if (!fs.readFileSync(localFile).equals(fs.readFileSync(packedFile))) {+ issues.push(+ error(+ 'packed_theme_font_stylesheet_changed',+ `Theme "${localTheme.slug}" font stylesheet changed during packing. Keep its export and bytes unchanged in the tarball.`,+ ),+ );+ }+ continue;+ }+ const expectedFile =+ output.kind === 'module'+ ? path.join(expectedDir, `${localTheme.slug}.js`)+ : expectedCss;+ const expected = normalizeThemeVerifyForCompare(+ fs.readFileSync(expectedFile, 'utf-8'),+ );+ const local = normalizeThemeVerifyForCompare(+ fs.readFileSync(localFile, 'utf-8'),+ );+ const packed = normalizeThemeVerifyForCompare(+ fs.readFileSync(packedFile, 'utf-8'),+ );+ if (expected !== local) {+ issues.push(+ warning(+ output.kind === 'module'+ ? 'theme_module_stale'+ : 'theme_stylesheet_stale',+ `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. This incomplete export remains packable, but run \`astryx theme build ${sourceRelative}\` before adding its matching export.`,+ ),+ );+ }+ if (local !== packed) {+ issues.push(+ error(+ output.kind === 'module'+ ? 'packed_theme_module_changed'+ : 'packed_theme_stylesheet_changed',+ `Theme "${localTheme.slug}" ${output.kind} changed during packing. Keep the built output unchanged in the tarball.`,+ ),+ );+ }+ }+ } catch (err) {+ issues.push(+ error(+ 'theme_build_failed',+ `Theme "${localTheme.slug}" could not be rebuilt from ${sourceRelative}: ${err instanceof Error ? err.message : String(err)} Run \`astryx theme build ${sourceRelative}\` before packing.`,+ ),+ );+ } finally {+ fs.rmSync(expectedDir, {recursive: true, force: true});+ }+ return issues;+}++/**+ * Prove local theme exports are fresh, prove the same exports resolve from the+ * tarball, and reject lifecycle changes to source or built output bytes.+ *+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} localIntegration+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} packedIntegration+ * @param {string} scratchBase+ * @returns {Promise<Issue[]>}+ */+async function validatePackedThemeExports(+ localIntegration,+ packedIntegration,+ scratchBase,+) {+ /** @type {Issue[]} */+ const issues = [];+ let localThemes;+ let packedThemes;+ try {+ localThemes = await discoverIntegrationThemes(localIntegration);+ } catch (err) {+ issues.push(+ error(+ 'theme_discovery_failed',+ `Local themes could not be validated: ${err instanceof Error ? err.message : String(err)}`,+ ),+ );+ return issues;+ }+ try {+ packedThemes = await discoverIntegrationThemes(packedIntegration);+ } catch (err) {+ issues.push(+ error(+ 'packed_theme_discovery_failed',+ `Packed themes could not be validated: ${err instanceof Error ? err.message : String(err)}`,+ ),+ );+ return issues;+ }+ const packedBySlug = new Map(packedThemes.map(theme => [theme.slug, theme]));+ for (const localTheme of localThemes) {+ const packedTheme = packedBySlug.get(localTheme.slug);+ if (!packedTheme) continue;+ const source = path.join(localTheme.sourceDir, localTheme.entry);+ const packedSource = path.join(packedTheme.sourceDir, packedTheme.entry);+ const sourceRelative = path.relative(localIntegration.__packageDir, source);++ if (!fs.readFileSync(source).equals(fs.readFileSync(packedSource))) {+ issues.push(+ error(+ 'packed_theme_source_changed',+ `Theme "${localTheme.slug}" source changed during packing. Keep ${sourceRelative} unchanged in the tarball.`,+ ),+ );+ }++ const declaredOutputs = declaredThemeBuildOutputs(+ localIntegration,+ localTheme,+ localThemes.length,+ );+ if (declaredOutputs.length === 0) {+ issues.push(+ warning(+ 'theme_exports_missing',+ `Theme "${localTheme.slug}" has no declared built exports. The package remains source-compatible. To make it importable, run \`astryx theme build ${sourceRelative}\` and export "./themes/${localTheme.slug}" plus "./themes/${localTheme.slug}.css" from package.json; \`astryx integration add theme ${localTheme.slug}\` creates those exports for a new theme.`,+ ),+ );+ continue;+ }+ if (+ !declaredOutputs.some(output => output.kind === 'module') ||+ !declaredOutputs.some(output => output.kind === 'stylesheet')+ ) {+ issues.push(+ ...(await validateIncompleteThemeExports(+ localTheme,+ packedIntegration,+ declaredOutputs,+ source,+ sourceRelative,+ localIntegration.__packageDir,+ )),+ );+ continue;+ }++ let localImports;+ let packedImports;+ try {+ localImports = resolveThemeImports(localTheme, {+ cwd: localIntegration.__packageDir,+ ownerThemeCount: localThemes.length,+ });+ packedImports = resolveThemeImports(packedTheme, {+ cwd: scratchBase,+ ownerThemeCount: packedThemes.length,+ });+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ issues.push(+ error(+ err instanceof ThemeImportError+ ? 'theme_import_unresolvable'+ : 'theme_import_invalid',+ `${message} Run \`astryx theme build ${sourceRelative}\` before packing.`,+ ),+ );+ continue;+ }++ const expectedDir = fs.mkdtempSync(+ path.join(os.tmpdir(), `astryx-theme-${localTheme.slug}-`),+ );+ const expectedCss = path.join(expectedDir, `${localTheme.slug}.css`);+ try {+ const receipt = await themeBuild(+ source,+ {out: expectedCss},+ {cwd: localIntegration.__packageDir},+ );+ if (receipt == null || receipt.type !== 'theme.build') {+ issues.push(+ error(+ 'theme_build_failed',+ `Theme "${localTheme.slug}" did not produce a complete build. Run \`astryx theme build ${sourceRelative}\` before packing.`,+ ),+ );+ continue;+ }+ const expectedModule = path.join(expectedDir, `${localTheme.slug}.js`);+ /** @type {Array<{kind: string, expected: string, local: string, packed: string, staleCode: string, packedCode: string}>} */+ const buildOutputs = [+ {+ kind: 'module',+ expected: expectedModule,+ local: localImports.moduleFile,+ packed: packedImports.moduleFile,+ staleCode: 'theme_module_stale',+ packedCode: 'packed_theme_module_changed',+ },+ {+ kind: 'stylesheet',+ expected: expectedCss,+ local: localImports.stylesheetFile,+ packed: packedImports.stylesheetFile,+ staleCode: 'theme_stylesheet_stale',+ packedCode: 'packed_theme_stylesheet_changed',+ },+ ];+ for (const output of buildOutputs) {+ const expected = normalizeThemeVerifyForCompare(+ fs.readFileSync(output.expected, 'utf-8'),+ );+ const local = normalizeThemeVerifyForCompare(+ fs.readFileSync(output.local, 'utf-8'),+ );+ const packed = normalizeThemeVerifyForCompare(+ fs.readFileSync(output.packed, 'utf-8'),+ );+ if (expected !== local) {+ issues.push(+ error(+ output.staleCode,+ `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. Run \`astryx theme build ${sourceRelative}\` before packing.`,+ ),+ );+ }+ if (local !== packed) {+ issues.push(+ error(+ output.packedCode,+ `Theme "${localTheme.slug}" ${output.kind} changed during packing. Keep the built output unchanged in the tarball.`,+ ),+ );+ }+ }+ if (+ localImports.fontStylesheet !== packedImports.fontStylesheet ||+ (localImports.fontStylesheetFile &&+ packedImports.fontStylesheetFile &&+ !fs+ .readFileSync(localImports.fontStylesheetFile)+ .equals(fs.readFileSync(packedImports.fontStylesheetFile)))+ ) {+ issues.push(+ error(+ 'packed_theme_font_stylesheet_changed',+ `Theme "${localTheme.slug}" font stylesheet changed during packing. Keep its export and bytes unchanged in the tarball.`,+ ),+ );+ }+ } catch (err) {+ issues.push(+ error(+ 'theme_build_failed',+ `Theme "${localTheme.slug}" could not be rebuilt from ${sourceRelative}: ${err instanceof Error ? err.message : String(err)} Run \`astryx theme build ${sourceRelative}\` before packing.`,+ ),+ );+ } finally {+ fs.rmSync(expectedDir, {recursive: true, force: true});+ }+ }+ return issues;+}+/*** Verify that every packed template source can be imported through its exact* package subpath and still has a default export.@@ -870,6 +1327,11 @@ export async function integrationPackCheck(options = {}) {issues.push(...compareIdentities(localIdentities, packedIdentities));issues.push(+ ...(await validatePackedThemeExports(+ loaded,+ packedResult.integration,+ scratchBase,+ )),...(await validatePackedComponentExports(packedResult.integration,scratchBase,diff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjsindex 7be7e3c55d..c209ea35bf 100644--- a/packages/cli/api/integration/pack-check.test.mjs+++ b/packages/cli/api/integration/pack-check.test.mjs@@ -5,7 +5,14 @@ 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 {createHash} from 'node:crypto';+import {+ integrationPackCheck,+ normalizeThemeVerifyForCompare,+ parseNpmPackOutput,+} from './pack-check.mjs';+import {normalizeThemeBuildForCompare} from '../theme/build/build.mjs';+import {released065Ocean} from './__fixtures__/released-0.6.5-ocean.mjs';import {integrationAddComponent,integrationAddTemplate,@@ -21,6 +28,178 @@ afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});+function generatedCssArtifact({+ source = 'themes/ocean/oceanTheme.ts',+ cli = '0.6.6',+ core = '0.6.6',+ body = ':root { color: red; }',+} = {}) {+ return `/*+ * @generated by \`astryx theme build\` — do not edit manually.+ * Source: ${source}+ * Command: astryx theme build ${source}+ * CLI: @astryxdesign/cli@${cli}+ * Core: @astryxdesign/core@${core}+ */++${body}+`;+}++function generatedJsArtifact({+ source = 'themes/ocean/oceanTheme.ts',+ cli = '0.6.6',+ core = '0.6.6',+ body = "export const oceanTheme = {name: 'ocean'};",+} = {}) {+ return `/**+ * @generated by \`astryx theme build\` — do not edit manually.+ * Source: ${source}+ * CLI: @astryxdesign/cli@${cli}+ * Core: @astryxdesign/core@${core}+ */++${body}+`;+}++describe('verify-only generated CSS header normalization', () => {+ it('ignores one source path and exact version pair but leaves build --check strict', () => {+ const current = generatedCssArtifact();+ const released = generatedCssArtifact({+ source: 'oceanTheme.ts',+ cli: '0.6.5',+ core: '0.6.5',+ });++ expect(normalizeThemeVerifyForCompare(released)).toBe(+ normalizeThemeVerifyForCompare(current),+ );+ expect(normalizeThemeBuildForCompare(released)).not.toBe(+ normalizeThemeBuildForCompare(current),+ );+ expect(released).not.toBe(current);+ });++ it.each([+ ['body change', source => source.replace('color: red', 'color: blue')],+ [+ 'Source text in the CSS body',+ source =>+ source.replace(+ ':root { color: red; }',+ ':root { color: red; }\n * Source: body.css',+ ),+ ],+ [+ 'header reordering',+ source =>+ source.replace(+ ' * CLI: @astryxdesign/[email protected]\n * Core: @astryxdesign/[email protected]',+ ' * Core: @astryxdesign/[email protected]\n * CLI: @astryxdesign/[email protected]',+ ),+ ],+ [+ 'other header change',+ source => source.replace('@generated by', '@generated with'),+ ],+ [+ 'missing version line',+ source => source.replace(' * CLI: @astryxdesign/[email protected]\n', ''),+ ],+ [+ 'duplicate version line',+ source =>+ source.replace(+ ' * CLI: @astryxdesign/[email protected]\n',+ ' * CLI: @astryxdesign/[email protected]\n * CLI: @astryxdesign/[email protected]\n',+ ),+ ],+ [+ 'malformed version line',+ source =>+ source.replace(+ 'CLI: @astryxdesign/[email protected]',+ 'CLI: malformed-version-header',+ ),+ ],+ [+ 'missing Source line',+ source => source.replace(' * Source: themes/ocean/oceanTheme.ts\n', ''),+ ],+ [+ 'duplicate Source line',+ source =>+ source.replace(+ ' * Source: themes/ocean/oceanTheme.ts\n',+ ' * Source: themes/ocean/oceanTheme.ts\n * Source: oceanTheme.ts\n',+ ),+ ],+ [+ 'malformed Source line',+ source =>+ source.replace(' * Source: themes/ocean/oceanTheme.ts', ' * Source: '),+ ],+ ])('keeps a %s significant', (_label, mutate) => {+ const current = generatedCssArtifact();+ expect(normalizeThemeVerifyForCompare(mutate(current))).not.toBe(+ normalizeThemeVerifyForCompare(current),+ );+ });++ it('normalizes one generated JavaScript header source and version pair', () => {+ const current = generatedJsArtifact();+ const fromThemeDir = generatedJsArtifact({+ source: 'oceanTheme.ts',+ cli: '0.6.5',+ core: '0.6.5',+ });+ expect(normalizeThemeVerifyForCompare(fromThemeDir)).toBe(+ normalizeThemeVerifyForCompare(current),+ );+ expect(normalizeThemeBuildForCompare(fromThemeDir)).not.toBe(+ normalizeThemeBuildForCompare(current),+ );+ });++ it.each([+ [+ 'JavaScript body change',+ source => source.replace("name: 'ocean'", "name: 'reef'"),+ ],+ [+ 'Source text in the JavaScript body',+ source =>+ source.replace(+ "export const oceanTheme = {name: 'ocean'};",+ "export const oceanTheme = {name: 'ocean'};\n * Source: body.js",+ ),+ ],+ [+ 'missing JavaScript Source line',+ source => source.replace(' * Source: themes/ocean/oceanTheme.ts\n', ''),+ ],+ [+ 'duplicate JavaScript Source line',+ source =>+ source.replace(+ ' * Source: themes/ocean/oceanTheme.ts\n',+ ' * Source: themes/ocean/oceanTheme.ts\n * Source: oceanTheme.ts\n',+ ),+ ],+ [+ 'malformed JavaScript Source line',+ source =>+ source.replace(' * Source: themes/ocean/oceanTheme.ts', ' * Source: '),+ ],+ ])('keeps a %s significant', (_label, mutate) => {+ const current = generatedJsArtifact();+ expect(normalizeThemeVerifyForCompare(mutate(current))).not.toBe(+ normalizeThemeVerifyForCompare(current),+ );+ });+});+/*** Write a minimal integration package into tmpDir.* Returns the package directory.@@ -31,6 +210,7 @@ function writePackage({files,manifest = "export default {themes: './themes'};\n",themes = true,+ themeExports = false,npmignore,components = false,scripts,@@ -40,6 +220,12 @@ function writePackage({if (themes) pkg.peerDependencies = {'@astryxdesign/cli': '>=0.6.4'};if (files !== undefined) pkg.files = files;if (scripts !== undefined) pkg.scripts = scripts;+ if (themes && themeExports) {+ pkg.exports = {+ './themes/ocean': './themes/ocean/ocean.js',+ './themes/ocean.css': './themes/ocean/ocean.css',+ };+ }fs.writeFileSync(path.join(tmpDir, 'package.json'),JSON.stringify(pkg, null, 2) + '\n',@@ -60,6 +246,23 @@ function writePackage({export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Ocean theme.', maintained: true};`,);+ if (themeExports) {+ const built = spawnSync(+ process.execPath,+ [+ path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),+ 'theme',+ 'build',+ 'themes/ocean/oceanTheme.ts',+ ],+ {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},+ );+ if (built.status !== 0) {+ throw new Error(+ `Could not build the theme fixture: ${built.stderr || built.stdout}`,+ );+ }+ }}if (components) {const root = path.join(tmpDir, 'components');@@ -75,13 +278,41 @@ export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description:return tmpDir;}+function setThemeExports(exportsMap) {+ const packageFile = path.join(tmpDir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ pkg.exports = exportsMap;+ fs.writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);+}++function runCliVerify() {+ const run = spawnSync(+ process.execPath,+ [+ path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),+ 'integration',+ 'verify',+ '--json',+ ],+ {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},+ );+ return {+ status: run.status,+ stderr: run.stderr,+ receipt: run.stdout ? JSON.parse(run.stdout) : null,+ };+}+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.packable,+ JSON.stringify(result.data.issues, null, 2),+ ).toBe(true);expect(result.data.name).toBe('@acme/widgets');expect(result.data.tarball).not.toBeNull();expect(result.data.inventory.manifest).toBe('astryx.integration.mjs');@@ -96,6 +327,26 @@ describe('integrationPackCheck', () => {);});+ it('warns but remains packable when a theme declares no built exports', async () => {+ writePackage({files: ['astryx.integration.mjs', 'themes']});++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues).toEqual([+ {+ code: 'theme_exports_missing',+ severity: 'warning',+ message:+ 'Theme "ocean" has no declared built exports. The package remains source-compatible. To make it importable, run `astryx theme build themes/ocean/oceanTheme.ts` and export "./themes/ocean" plus "./themes/ocean.css" from package.json; `astryx integration add theme ocean` creates those exports for a new theme.',+ },+ ]);+ const cli = runCliVerify();+ expect(cli.status, cli.stderr).toBe(0);+ expect(cli.receipt?.data.packable).toBe(true);+ expect(cli.receipt?.data.issues).toEqual(result.data.issues);+ });+it('fails a package that ships a theme on a CLI range that cannot read it', async () => {writePackage({files: ['astryx.integration.mjs', 'themes']});const pkgFile = path.join(tmpDir, 'package.json');@@ -128,6 +379,298 @@ describe('integrationPackCheck', () => {);});+ it('fails when a declared theme export does not resolve', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });+ fs.rmSync(path.join(tmpDir, 'themes', 'ocean', 'ocean.css'));++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'theme_import_unresolvable',+ message: expect.stringContaining('stylesheet export'),+ }),+ );+ });++ it.each([+ {+ label: 'module only',+ exportsMap: {'./built': './themes/ocean/ocean.js'},+ specifiers: ['@acme/widgets/built'],+ },+ {+ label: 'stylesheet only',+ exportsMap: {'./theme.css': './themes/ocean/ocean.css'},+ specifiers: ['@acme/widgets/theme.css'],+ },+ {+ label: 'font stylesheet only',+ exportsMap: {'./fonts.css': './themes/ocean/ocean.fonts.css'},+ specifiers: ['@acme/widgets/fonts.css'],+ fonts: true,+ },+ {+ label: 'module and font stylesheet',+ exportsMap: {+ './built': './themes/ocean/ocean.js',+ './fonts.css': './themes/ocean/ocean.fonts.css',+ },+ specifiers: ['@acme/widgets/built', '@acme/widgets/fonts.css'],+ fonts: true,+ },+ {+ label: 'stylesheet and font stylesheet',+ exportsMap: {+ './theme.css': './themes/ocean/ocean.css',+ './fonts.css': './themes/ocean/ocean.fonts.css',+ },+ specifiers: ['@acme/widgets/theme.css', '@acme/widgets/fonts.css'],+ fonts: true,+ },+ ])(+ 'warns and exits zero for an incomplete $label export set',+ async ({exportsMap, specifiers, fonts}) => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });+ if (fonts) {+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.fonts.css'),+ '@font-face { font-family: Ocean; src: url(./ocean.woff2); }\n',+ );+ }+ setThemeExports(exportsMap);+ const message = `Theme "ocean" exports ${specifiers.join(', ')} without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.`;++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues).toEqual([+ {code: 'theme_exports_incomplete', severity: 'warning', message},+ ]);+ const cli = runCliVerify();+ expect(cli.status, cli.stderr).toBe(0);+ expect(cli.receipt?.data.packable).toBe(true);+ expect(cli.receipt?.data.issues).toEqual(result.data.issues);+ },+ );++ it('keeps a published 0.6.5 stylesheet-only package packable', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });+ setThemeExports({'./theme.css': './themes/ocean/ocean.css'});+ const provenance = released065Ocean;+ const released = Buffer.from(provenance.base64, 'base64');+ expect(createHash('sha256').update(released).digest('hex')).toBe(+ provenance.sha256,+ );+ expect(provenance).toMatchObject({+ artifact: 'released-0.6.5-ocean.css',+ package: '@astryxdesign/[email protected]',+ source: 'npm',+ command: 'astryx theme build oceanTheme.ts',+ workingDirectory: 'themes/ocean',+ inputSha256:+ '05ac5f9fc3eb71a0096e4fd6dcecfb0d508e403a564be49bf5c535b3c5080245',+ sha256:+ 'd48aa16f5a87dcaa0d851928a4be735f80c29e462d3dd223cfc38570495f6fbd',+ });+ const source = fs.readFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),+ );+ expect(createHash('sha256').update(source).digest('hex')).toBe(+ provenance.inputSha256,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.css'),+ released,+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues).toEqual([+ {+ code: 'theme_exports_incomplete',+ severity: 'warning',+ message:+ 'Theme "ocean" exports @acme/widgets/theme.css without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.',+ },+ ]);+ const cli = runCliVerify();+ expect(cli.status, cli.stderr).toBe(0);+ expect(cli.receipt?.data.packable).toBe(true);+ expect(cli.receipt?.data.issues).toEqual(result.data.issues);+ });++ it('warns and exits zero for stale content in an incomplete export set', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });+ setThemeExports({'./theme.css': './themes/ocean/ocean.css'});+ fs.appendFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.css'),+ '/* stale stylesheet body */\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues).toEqual([+ {+ code: 'theme_exports_incomplete',+ severity: 'warning',+ message:+ 'Theme "ocean" exports @acme/widgets/theme.css without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.',+ },+ {+ code: 'theme_stylesheet_stale',+ severity: 'warning',+ message:+ 'Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. This incomplete export remains packable, but run `astryx theme build themes/ocean/oceanTheme.ts` before adding its matching export.',+ },+ ]);+ const cli = runCliVerify();+ expect(cli.status, cli.stderr).toBe(0);+ expect(cli.receipt?.data.packable).toBe(true);+ expect(cli.receipt?.data.issues).toEqual(result.data.issues);+ });++ it('passes a complete pair generated by the current CLI', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues).toEqual([]);+ const cli = runCliVerify();+ expect(cli.status, cli.stderr).toBe(0);+ expect(cli.receipt?.data.packable).toBe(true);+ expect(cli.receipt?.data.issues).toEqual([]);+ });++ it('passes a complete pair built from inside the theme directory', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });+ const themeDir = path.join(tmpDir, 'themes', 'ocean');+ const built = spawnSync(+ process.execPath,+ [+ path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),+ 'theme',+ 'build',+ 'oceanTheme.ts',+ ],+ {cwd: themeDir, encoding: 'utf-8', timeout: 30_000},+ );+ expect(built.status, built.stderr).toBe(0);++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues).toEqual([]);+ const cli = runCliVerify();+ expect(cli.status, cli.stderr).toBe(0);+ expect(cli.receipt?.data.issues).toEqual([]);+ });++ it('fails when a complete pair drifts from source', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });+ fs.appendFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.js'),+ '// stale module\n',+ );+ fs.appendFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.css'),+ '/* stale stylesheet */\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toEqual([+ {+ code: 'theme_module_stale',+ severity: 'error',+ message:+ 'Theme "ocean" module does not match themes/ocean/oceanTheme.ts. Run `astryx theme build themes/ocean/oceanTheme.ts` before packing.',+ },+ {+ code: 'theme_stylesheet_stale',+ severity: 'error',+ message:+ 'Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. Run `astryx theme build themes/ocean/oceanTheme.ts` before packing.',+ },+ ]);+ const cli = runCliVerify();+ expect(cli.status).toBe(1);+ expect(cli.receipt?.data.packable).toBe(false);+ expect(cli.receipt?.data.issues).toEqual(result.data.issues);+ });++ it('fails when a built module omits the descriptor export', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });+ const built = path.join(tmpDir, 'themes', 'ocean', 'ocean.js');+ fs.writeFileSync(+ built,+ fs+ .readFileSync(built, 'utf-8')+ .replace('export const oceanTheme', 'export const otherTheme'),+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'theme_import_unresolvable',+ message: expect.stringContaining('does not export "oceanTheme"'),+ }),+ );+ });++ it('fails when an exported font stylesheet is absent from the tarball', async () => {+ writePackage({npmignore: '**/*.fonts.css\n', themeExports: true});+ const packageFile = path.join(tmpDir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ pkg.exports['./themes/ocean.fonts.css'] = './themes/ocean/ocean.fonts.css';+ fs.writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.fonts.css'),+ '@import url("https://example.com/fonts.css");\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'theme_import_unresolvable',+ message: expect.stringContaining('font stylesheet does not resolve'),+ }),+ );+ });+it('fails when a theme entry omits its inferred runtime export', async () => {writePackage({files: ['astryx.integration.mjs', 'themes']});fs.writeFileSync(@@ -348,7 +891,10 @@ describe('integrationPackCheck', () => {});it('fails a package that ships a namespace doc on a CLI range that cannot read it', async () => {- writePackage({manifest: "export default {docs: './docs'};\n", themes: false});+ writePackage({+ manifest: "export default {docs: './docs'};\n",+ themes: false,+ });fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});fs.writeFileSync(path.join(tmpDir, 'docs', 'acme.doc.mjs'),@@ -382,7 +928,10 @@ describe('integrationPackCheck', () => {}, 120_000);it('fails a package with only a placed guide on a CLI range that cannot read the docs tree, and passes flat topics', async () => {- writePackage({manifest: "export default {docs: './docs'};\n", themes: false});+ writePackage({+ manifest: "export default {docs: './docs'};\n",+ themes: false,+ });fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});fs.writeFileSync(path.join(tmpDir, 'docs', 'notes.doc.mjs'),@@ -407,7 +956,10 @@ describe('integrationPackCheck', () => {}, 120_000);it('fails a package whose doc section sets id on a CLI range that rejects the field', async () => {- writePackage({manifest: "export default {docs: './docs'};\n", themes: false});+ writePackage({+ manifest: "export default {docs: './docs'};\n",+ themes: false,+ });fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});const topic = (/** @type {string} */ section) =>`export default {type: 'generic', name: 'notes', title: 'Notes', description: 'Notes.', sections: [${section}]};\n`;@@ -418,7 +970,9 @@ describe('integrationPackCheck', () => {);fs.writeFileSync(file,- topic("{title: 'Take notes', content: [{type: 'prose', text: 'Notes.'}]}"),+ topic(+ "{title: 'Take notes', content: [{type: 'prose', text: 'Notes.'}]}",+ ),);expect(await codes()).not.toContain('section_ids_need_cli');// A fresh file name: the module loader caches a path once it is imported.@@ -442,7 +996,10 @@ describe('integrationPackCheck', () => {}, 120_000);it('fails a package with a template that sets replaces on a CLI range that rejects the field', async () => {- writePackage({manifest: "export default {templates: './templates'};\n", themes: false});+ writePackage({+ manifest: "export default {templates: './templates'};\n",+ themes: false,+ });fs.mkdirSync(path.join(tmpDir, 'templates'), {recursive: true});fs.writeFileSync(path.join(tmpDir, 'templates', 'acme-shell.doc.mjs'),@@ -476,7 +1033,10 @@ describe('integrationPackCheck', () => {}, 120_000);it('fails a package with a template that sets keywords on a CLI range that rejects the field', async () => {- writePackage({manifest: "export default {templates: './templates'};\n", themes: false});+ writePackage({+ manifest: "export default {templates: './templates'};\n",+ themes: false,+ });fs.mkdirSync(path.join(tmpDir, 'templates'), {recursive: true});fs.writeFileSync(path.join(tmpDir, 'templates', 'acme-health.doc.mjs'),diff --git a/packages/cli/api/search/search.doc.mjs b/packages/cli/api/search/search.doc.mjsindex 9115972413..8f587cd940 100644--- a/packages/cli/api/search/search.doc.mjs+++ b/packages/cli/api/search/search.doc.mjs@@ -55,7 +55,7 @@ export const doc = {{type: 'search',description:- 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, `displayName` and `kind` for templates, and `displayName` for themes. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from). A theme result is one theme you can add: `name` is its slug, its command is the `astryx theme add` that copies it into the app, and `package` is the npm package that ships it (`@astryxdesign/cli` for the CLI\'s own themes).',+ 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, `displayName` and `kind` for templates, and `displayName` for themes. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from). A theme result is one theme you can import: `name` is its slug, its command is `astryx theme add --import <slug>`, and `package` is the npm package that ships it (`@astryxdesign/cli` for the CLI\'s own themes).',},],throws: [diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex c3d0db34f5..9ad7fb3d91 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -1586,7 +1586,7 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {result = {...base,displayName: c._displayName,- command: `astryx theme add ${c.name}`,+ command: `astryx theme add --import ${c.name}`,};break;default:diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjsindex 3ccd25ee23..b809d0448d 100644--- a/packages/cli/api/search/search.test.mjs+++ b/packages/cli/api/search/search.test.mjs@@ -99,7 +99,7 @@ describe('search leaf — per-domain result fields', () => {expect(['page', 'block']).toContain(res.kind);} else if (res.domain === 'theme') {expect(res.displayName).toMatch(/\S/);- expect(res.command).toMatch(/^astryx theme add /);+ expect(res.command).toBe(`astryx theme add --import ${res.name}`);}}}, SLOW);diff --git a/packages/cli/api/search/search.type.mjs b/packages/cli/api/search/search.type.mjsindex 481723e13d..4518f98706 100644--- a/packages/cli/api/search/search.type.mjs+++ b/packages/cli/api/search/search.type.mjs@@ -20,7 +20,7 @@* @property {number} score - Relevance score (higher is better).* @property {string} reason - Human-readable reason the candidate matched (e.g. `keyword "button"`).* @property {string} description - One-line description, when available.- * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add neutral` for a theme).+ * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add --import neutral` for a theme).* @property {string} [import] - Import path — present for component and hook results.* @property {string} [title] - Doc title — present for doc results.* @property {string} [section] - Section key — present when a doc result is one section of a topic; `command` reads only that section.diff --git a/packages/cli/api/theme/_adapter.mjs b/packages/cli/api/theme/_adapter.mjsindex 175532a0ad..6872af5d28 100644--- a/packages/cli/api/theme/_adapter.mjs+++ b/packages/cli/api/theme/_adapter.mjs@@ -1,24 +1,57 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Shared data layer for `theme list` and `theme add`.+ * @file Shared data and write adapter for app-theme commands.*- * `listThemes()` intentionally keeps its historical synchronous, bundled-only- * contract. Project-aware callers use `listAvailableThemes()`, which asks- * Project for the bundled themes plus every installed integration theme root.+ * Keeps the historical synchronous bundled-theme helper, resolves project-aware+ * source themes, loads recorded built artifacts through the shared runtime+ * loader, reads static generated-module state, and applies each add/remove/use+ * regeneration through the shared atomic write transaction.*/+import * as fs from 'node:fs';+import * as path from 'node:path';import {Project} from '../../foundation/config/project.mjs';import {BUNDLED_THEME_PACKAGE,THEMES_DIR,discoverBundledThemes,+ discoverIntegrationThemes,+ discoverUnmigratedThemeCopies,+ themeImportPackage,} from '../../foundation/discovery/theme-discovery.mjs';+import {+ ThemeImportError,+ resolveThemeImports,+} from '../../foundation/discovery/theme-imports.mjs';+import {+ findThemeProject,+ isLocalThemeOwner,+ ThemeStateError,+ planThemeAppWrite,+ readThemeState,+} from '../../foundation/config/theme-state.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {+ assertWithin,+ PathSafetyError,+} from '../../foundation/fs/path-safety.mjs';+import {stripCopyrightHeader} from '../../foundation/text/copyright-header.mjs';+import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';+import {importThemeArtifact} from '../../foundation/fs/module-loader.mjs';+import {applyWrites} from '../integration/add-helpers.mjs';export {BUNDLED_THEME_PACKAGE, THEMES_DIR};+/**+ * Package written to the generated app record for one discovered theme.+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme+ */+export function themeRecordOwner(theme) {+ return themeImportPackage(theme);+}+/*** 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@@ -56,40 +89,387 @@ function availableBundledThemes() {* discovering them. The issue set lets a package-scoped lookup distinguish an* absent theme from an installed package whose theme descriptors are broken.* @param {string} cwd+ * @param {{includeLocal?: boolean}} [options]* @returns {Promise<{themes: import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[], issues: Array<import('../../foundation/integrations/issue').AstryxIntegrationIssue & {package: string}>}>}*/-async function availableThemeState(cwd) {+async function availableThemeState(cwd, {includeLocal = true} = {}) {+ let project;try {- const project = await Project.load(cwd);- const themes = await project.themes();- return {themes, issues: await project.issues()};+ project = await Project.load(cwd);} catch {return {themes: availableBundledThemes(), issues: []};}+ try {+ const themes = await project.themes({includeLocal});+ return {themes, issues: await project.issues()};+ } catch (error) {+ throw asThemeError(error);+ }}/**- * Bundled themes plus source themes from integrations installed in `cwd`.- * A project/config load failure degrades to the bundled set, preserving the- * command's historical usefulness outside a configured project.+ * Bundled themes plus local and installed integration themes available to the+ * project.* @param {string} [cwd]+ * @param {{includeLocal?: boolean}} [options]* @returns {Promise<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]>}*/-export async function listAvailableThemes(cwd = process.cwd()) {- return (await availableThemeState(cwd)).themes;+export async function listAvailableThemes(cwd = process.cwd(), options = {}) {+ return (await availableThemeState(cwd, options)).themes;+}++/** @param {unknown} error */+function isMissingThemeArtifact(error) {+ return (+ error != null &&+ typeof error === 'object' &&+ 'code' in error &&+ error.code === 'ERR_THEME_ARTIFACT_NOT_FOUND'+ );+}++/** @param {unknown} error */+function isMalformedThemeArtifact(error) {+ return (+ error instanceof Error &&+ (error.name === 'ParseError' ||+ error.name === 'SyntaxError' ||+ error.message.startsWith('ParseError:') ||+ error.message.startsWith('SyntaxError:'))+ );+}++/** @param {string} specifier @param {string} cwd */+async function tryRecordedThemeArtifact(specifier, cwd) {+ try {+ return {+ module: await importThemeArtifact(specifier, cwd),+ missing: false,+ problem: null,+ };+ } catch (error) {+ if (isMissingThemeArtifact(error)) {+ return {module: null, missing: true, problem: null};+ }+ if (!isMalformedThemeArtifact(error)) throw error;+ const malformed = /** @type {Error} */ (error);+ const detail =+ malformed.message.split('\n', 1)[0]?.trim() || malformed.name;+ return {+ module: null,+ missing: false,+ problem: `could not load the recorded theme artifact "${specifier}": ${detail}`,+ };+ }+}++/**+ * Load one built theme named by the generated app record. Callers choose how to+ * present missing, ambiguous, or malformed results; unrelated loader failures+ * propagate. A missing generated module is reported as `configured: false` so+ * the released package-field path can remain separate.+ *+ * @param {string} cwd+ * @param {string} [requestedSlug] defaults to the record's default+ * @returns {Promise<{configured: boolean, slug: string|null, owner: string|null, module: Record<string, unknown>|null, specifier: string, missing?: boolean, problem: string|null}>}+ */+export async function resolveRecordedTheme(cwd, requestedSlug) {+ let state;+ try {+ state = readThemeState(cwd);+ } catch {+ return {+ configured: false,+ slug: null,+ owner: null,+ module: null,+ specifier: 'generated theme record',+ problem: null,+ };+ }+ if (!state.configured) {+ return {+ configured: false,+ slug: null,+ owner: null,+ module: null,+ specifier: 'generated theme record',+ problem: null,+ };+ }++ const slug = requestedSlug ?? state.defaultSlug;+ if (slug == null) {+ return {+ configured: true,+ slug: null,+ owner: null,+ module: null,+ specifier: 'generated theme record',+ problem: 'the generated theme record has no default theme',+ };+ }+ const owner = state.themes[slug];+ if (typeof owner !== 'string') {+ return {+ configured: true,+ slug,+ owner: null,+ module: null,+ specifier: `generated theme record (${slug})`,+ problem: `theme "${slug}" is not present in the generated theme record`,+ };+ }++ if (isLocalThemeOwner(owner)) {+ const specifier = path.join(state.projectDir, owner, slug, `${slug}.js`);+ const loaded = await tryRecordedThemeArtifact(specifier, state.projectDir);+ return {configured: true, slug, owner, ...loaded, specifier};+ }++ const perThemeSpecifier = `${owner}/themes/${slug}`;+ const perTheme = await tryRecordedThemeArtifact(+ perThemeSpecifier,+ state.projectDir,+ );+ if (perTheme.module || perTheme.problem) {+ return {+ configured: true,+ slug,+ owner,+ ...perTheme,+ specifier: perThemeSpecifier,+ };+ }++ let ownerThemeCount = null;+ try {+ const integrations = await loadIntegrations([owner], {+ cwd: state.projectDir,+ resolveProviders: false,+ });+ const integration = integrations.find(+ candidate => candidate.name === owner,+ );+ if (integration && !integration.__loadError) {+ ownerThemeCount = (await discoverIntegrationThemes(integration)).length;+ }+ } catch {+ // Bundled standalone theme packages have no integration manifest.+ }+ if (ownerThemeCount == null) {+ try {+ const available = await listAvailableThemes(state.projectDir);+ ownerThemeCount = available.filter(+ theme => themeImportPackage(theme) === owner,+ ).length;+ } catch {+ // An unavailable package cannot safely use the ambiguous shorthand.+ }+ }+ if (ownerThemeCount != null && ownerThemeCount > 1) {+ return {+ configured: true,+ slug,+ owner,+ module: null,+ specifier: perThemeSpecifier,+ problem: `theme "${slug}" is recorded from multi-theme package ${owner}, but ${perThemeSpecifier} does not resolve. Refusing to load ${owner}/built or the package root because either could be a different theme`,+ };+ }+ if (ownerThemeCount === 1) {+ for (const specifier of [`${owner}/built`, owner]) {+ const loaded = await tryRecordedThemeArtifact(+ specifier,+ state.projectDir,+ );+ if (loaded.module || loaded.problem) {+ return {configured: true, slug, owner, ...loaded, specifier};+ }+ }+ }+ return {+ configured: true,+ slug,+ owner,+ module: null,+ specifier: perThemeSpecifier,+ problem: null,+ };+}++/**+ * Source copies made by the released `theme add` before local descriptors.+ * @param {string} cwd+ */+export function listUnmigratedThemeCopies(cwd) {+ return discoverUnmigratedThemeCopies(cwd);+}++/** @param {string} slug */+function defaultEjectTarget(slug) {+ return path.join('src', 'themes', slug);+}++/**+ * Strip repository boilerplate from UTF-8 text while preserving binary bytes.+ * @param {Buffer} bytes+ * @returns {Buffer|string}+ */+function scaffoldContents(bytes) {+ const text = bytes.toString('utf-8');+ return Buffer.from(text, 'utf-8').equals(bytes)+ ? stripCopyrightHeader(text)+ : bytes;+}++/**+ * Describe an ejected theme as a new, unmaintained local fork.+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme+ */+function localThemeDescriptor(theme) {+ return `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {+ type: 'theme',+ name: ${JSON.stringify(theme.slug)},+ displayName: ${JSON.stringify(theme.displayName)},+ description: ${JSON.stringify(theme.description)},+ maintained: false,+};+`;+}++/**+ * Publish one theme's complete source inventory as an atomic local fork.+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme+ * @param {{cwd: string, targetPath?: string, overwrite?: boolean}} options+ * @returns {string} project-relative output directory+ */+export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {+ let resolvedDir;+ try {+ resolvedDir = assertWithin(+ targetPath || defaultEjectTarget(theme.slug),+ cwd,+ {label: 'theme target path'},+ );+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }++ let writes;+ try {+ writes = theme.files.map(name => ({+ name,+ src: path.join(theme.sourceDir, name),+ dest: assertWithin(name, resolvedDir, {+ label: `theme destination for ${name}`,+ }),+ }));+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ throw error;+ }++ for (const write of writes) {+ if (!fs.existsSync(write.src)) {+ throw new AstryxError(+ `Theme "${theme.slug}" is missing bundled file "${write.name}". ` ++ 'Re-run `node scripts/generate-cli-themes.mjs` to rebuild the bundle.',+ undefined,+ ERROR_CODES.ERR_NO_SOURCE,+ );+ }+ }++ if (!overwrite) {+ const existing = writes.find(write => fs.existsSync(write.dest));+ if (existing) {+ const rel = path.relative(cwd, existing.dest) || existing.dest;+ throw new AstryxError(+ `Refusing to overwrite existing file ${rel}. ` ++ 'Re-run with --overwrite (or -f) to replace it.',+ undefined,+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }+ }++ try {+ fs.mkdirSync(resolvedDir, {recursive: true});+ const plans = writes.map(write => {+ fs.mkdirSync(path.dirname(write.dest), {recursive: true});+ const dest = assertWithin(write.name, resolvedDir, {+ label: `theme destination for ${write.name}`,+ });+ return {+ path: dest,+ contents:+ path.resolve(write.src) === path.resolve(theme.docPath)+ ? localThemeDescriptor(theme)+ : scaffoldContents(fs.readFileSync(write.src)),+ createOnly: !overwrite,+ };+ });+ applyWrites(plans);+ } catch (error) {+ if (error instanceof AstryxError) throw error;+ if (error instanceof PathSafetyError) {+ throw new AstryxError(+ error.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(+ `Failed to write theme files: ${message}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }++ return path.relative(cwd, resolvedDir) || '.';+}++/** @param {unknown} error */+function asThemeError(error) {+ if (error instanceof AstryxError) return error;+ const message = error instanceof Error ? error.message : String(error);+ const code =+ error instanceof ThemeStateError &&+ message.startsWith('Refusing to replace')+ ? ERROR_CODES.ERR_FILE_EXISTS+ : ERROR_CODES.ERR_THEME_INVALID;+ return new AstryxError(message, undefined, code);}/*** Resolve an available theme by case-insensitive slug and optional owner package.- * Duplicate slugs fail closed until the caller selects an owner.+ * Without an explicit package, a local theme shadows package themes that share+ * its slug. Other duplicate slugs fail closed until the caller selects an owner.* @param {string} [slug]- * @param {{cwd?: string, package?: string}} [options]+ * @param {{cwd?: string, package?: string, includeLocal?: boolean}} [options]* @returns {Promise<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme | undefined>}*/export async function findTheme(slug, options = {}) {if (!slug) return undefined;const {themes, issues} = await availableThemeState(options.cwd ?? process.cwd(),+ {includeLocal: options.includeLocal},);const normalized = String(slug).toLowerCase();const matches = themes.filter(@@ -109,17 +489,298 @@ export async function findTheme(slug, options = {}) {);}}+ if (matches.length > 1 && options.package == null) {+ const local = matches.find(theme => theme.source === 'local');+ if (local) return local;+ }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}`,+ reason:+ theme.source === 'bundled'+ ? 'bundled theme'+ : theme.source === 'local'+ ? 'local theme'+ : `provided by ${theme.package}`,})),ERROR_CODES.ERR_AMBIGUOUS_THEME,);}return matches[0];}++/**+ * Read the generated module's app-theme record with stable CLI errors.+ * @param {string} [cwd]+ */+export function readAppThemeState(cwd = process.cwd()) {+ try {+ return readThemeState(cwd);+ } catch (error) {+ throw asThemeError(error);+ }+}++/**+ * Read the app state needed by a list operation. Outside a package project,+ * bundled themes remain listable and there is no generated app state.+ * @param {string} [cwd]+ * @returns {Pick<ReturnType<typeof readThemeState>, 'projectDir' | 'themes' | 'defaultSlug'>}+ */+export function readThemeListState(cwd = process.cwd()) {+ let projectDir;+ try {+ ({projectDir} = findThemeProject(cwd));+ } catch (error) {+ if (error instanceof ThemeStateError) {+ return {+ projectDir: path.resolve(cwd),+ themes: {},+ defaultSlug: null,+ };+ }+ throw asThemeError(error);+ }+ return readAppThemeState(projectDir);+}++/**+ * Resolve every recorded owner to built import metadata, in record order.+ * @param {ReturnType<typeof readThemeState>} state+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} available+ */+export function resolveRecordedThemes(state, available) {+ /** @type {Map<string, number>} */+ const ownerCounts = new Map();+ for (const theme of available) {+ const owner = themeImportPackage(theme);+ ownerCounts.set(owner, (ownerCounts.get(owner) ?? 0) + 1);+ }+ return Object.entries(state.themes).map(([slug, owner]) => {+ const theme = available.find(+ candidate =>+ candidate.slug === slug && themeImportPackage(candidate) === owner,+ );+ if (!theme) {+ throw new AstryxError(+ `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, then run \`astryx theme add ${slug} --import --package ${owner}\`.`,+ undefined,+ ERROR_CODES.ERR_UNKNOWN_THEME,+ );+ }+ try {+ return resolveThemeImports(theme, {+ cwd: state.projectDir,+ ownerThemeCount: ownerCounts.get(owner) ?? 1,+ });+ } catch (error) {+ if (error instanceof ThemeImportError) throw asThemeError(error);+ throw error;+ }+ });+}++/**+ * Resolve the current generated-module state without changing it.+ * @param {string} [cwd]+ */+export async function resolveThemeApp(cwd = process.cwd()) {+ const state = readAppThemeState(cwd);+ const available = await listAvailableThemes(state.projectDir);+ const entries = state.configured+ ? resolveRecordedThemes(state, available)+ : [];+ return {state, available, entries};+}++/**+ * @param {ReturnType<typeof readThemeState>} state+ * @param {Record<string, string>} themes+ * @param {string} defaultSlug+ * @param {'add'|'remove'|'use'} action+ * @param {string} slug+ * @param {boolean} changed+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} available+ * @returns {Promise<import('./theme.type.mjs').ThemeAppResponse>}+ */+async function writeThemeApp(+ state,+ themes,+ defaultSlug,+ action,+ slug,+ changed,+ available,+) {+ const finalState = {...state, themes, defaultSlug, configured: true};+ const resolved = resolveRecordedThemes(finalState, available);+ let prepared;+ try {+ prepared = planThemeAppWrite(finalState, themes, defaultSlug, resolved);+ } catch (error) {+ throw asThemeError(error);+ }+ try {+ applyWrites([prepared.plan]);+ } catch (error) {+ if (error instanceof AstryxError) throw error;+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(+ `Failed to write the generated theme module: ${message}`,+ undefined,+ ERROR_CODES.ERR_WRITE_FAILED,+ );+ }+ return {+ type: 'theme.app',+ data: {+ themes: prepared.entries.map(theme => ({+ slug: theme.slug,+ owner: theme.owner,+ module: theme.module,+ stylesheet: theme.stylesheet,+ ...(theme.fontStylesheet ? {fontStylesheet: theme.fontStylesheet} : {}),+ source: theme.source,+ })),+ default: defaultSlug,+ modulePath: prepared.module.path,+ change: {+ action,+ slug,+ changed,+ firstAdd: action === 'add' && !state.configured,+ },+ },+ };+}++/**+ * Add one available built theme to the app record.+ * @param {string} slug+ * @param {{cwd?: string, package?: string}} [options]+ * @returns {Promise<import('./theme.type.mjs').ThemeAppResponse>}+ */+export async function addThemeToApp(slug, options = {}) {+ const cwd = options.cwd ?? process.cwd();+ const match = await findTheme(slug, {cwd, package: options.package});+ if (!match) {+ const available = await listAvailableThemes(cwd);+ throw new AstryxError(+ `Unknown theme "${slug}"${options.package ? ` in package "${options.package}"` : ''}.`,+ available.map(theme => ({+ name: `${theme.slug} --package ${theme.package}`,+ reason:+ theme.source === 'bundled'+ ? 'bundled theme'+ : theme.source === 'local'+ ? 'local theme'+ : `provided by ${theme.package}`,+ })),+ ERROR_CODES.ERR_UNKNOWN_THEME,+ );+ }+ const state = readAppThemeState(cwd);+ const available = await listAvailableThemes(state.projectDir);+ const owner = themeImportPackage(match);+ const themes = {...state.themes, [match.slug]: owner};+ const changed = state.themes[match.slug] !== owner;+ const defaultSlug =+ state.configured && state.defaultSlug != null+ ? state.defaultSlug+ : match.slug;+ return writeThemeApp(+ state,+ themes,+ defaultSlug,+ 'add',+ match.slug,+ changed,+ available,+ );+}++/**+ * Canonical recorded slug for a case-insensitive command lookup.+ * @param {ReturnType<typeof readThemeState>} state+ * @param {string} slug+ */+function recordedThemeSlug(state, slug) {+ const needle = slug.toLowerCase();+ return Object.keys(state.themes).find(+ candidate => candidate.toLowerCase() === needle,+ );+}++/**+ * Remove one non-default theme from the app record.+ * @param {string} slug+ * @param {{cwd?: string}} [options]+ * @returns {Promise<import('./theme.type.mjs').ThemeAppResponse>}+ */+export async function removeThemeFromApp(slug, options = {}) {+ const state = readAppThemeState(options.cwd ?? process.cwd());+ const recordedSlug = recordedThemeSlug(state, slug);+ if (!state.configured || recordedSlug == null) {+ throw new AstryxError(+ `Theme "${slug}" is not added. Run \`astryx theme add ${slug} --import\` first.`,+ undefined,+ ERROR_CODES.ERR_UNKNOWN_THEME,+ );+ }+ if (state.defaultSlug === recordedSlug) {+ throw new AstryxError(+ `Theme "${recordedSlug}" is the default. Run \`astryx theme use <other-slug>\` before removing it.`,+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ const themes = {...state.themes};+ delete themes[recordedSlug];+ if (state.defaultSlug == null) {+ throw new AstryxError(+ 'The generated theme module has no default theme. Run `astryx theme use <slug>` first.',+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ const available = await listAvailableThemes(state.projectDir);+ return writeThemeApp(+ state,+ themes,+ state.defaultSlug,+ 'remove',+ recordedSlug,+ true,+ available,+ );+}++/**+ * Select one added theme as the app default.+ * @param {string} slug+ * @param {{cwd?: string}} [options]+ * @returns {Promise<import('./theme.type.mjs').ThemeAppResponse>}+ */+export async function useThemeInApp(slug, options = {}) {+ const state = readAppThemeState(options.cwd ?? process.cwd());+ const recordedSlug = recordedThemeSlug(state, slug);+ if (!state.configured || recordedSlug == null) {+ throw new AstryxError(+ `Theme "${slug}" is not added. Run \`astryx theme add ${slug} --import\` first.`,+ undefined,+ ERROR_CODES.ERR_UNKNOWN_THEME,+ );+ }+ const available = await listAvailableThemes(state.projectDir);+ return writeThemeApp(+ state,+ state.themes,+ recordedSlug,+ 'use',+ recordedSlug,+ state.defaultSlug !== recordedSlug,+ available,+ );+}diff --git a/packages/cli/api/theme/add/add.binary.test.mjs b/packages/cli/api/theme/add/add.binary.test.mjsindex 7462bc1109..a692d0da3c 100644--- a/packages/cli/api/theme/add/add.binary.test.mjs+++ b/packages/cli/api/theme/add/add.binary.test.mjs@@ -5,6 +5,8 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import {themeAdd} from './add.mjs';+import {themeEject} from '../eject/eject.mjs';+import {runCli} from '../../../test-utils/run-cli.mjs';const HEADER = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n';@@ -28,6 +30,7 @@ beforeEach(() => {const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'themes');const themeDir = path.join(packageDir, 'themes', 'ocean');fs.mkdirSync(path.join(themeDir, 'fonts'), {recursive: true});+ fs.mkdirSync(path.join(themeDir, 'tokens'), {recursive: true});fs.writeFileSync(path.join(packageDir, 'package.json'),JSON.stringify({name: '@acme/themes', version: '1.0.0'}),@@ -46,15 +49,23 @@ export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description:path.join(themeDir, 'oceanTheme.ts'),`${HEADER}export const oceanTheme = {};\n`,);+ fs.writeFileSync(+ path.join(themeDir, 'icons.tsx'),+ 'export const oceanIcons = {};\n',+ );fs.writeFileSync(path.join(themeDir, 'fonts', 'ocean.woff2'), FONT_BYTES);+ fs.writeFileSync(+ path.join(themeDir, 'tokens', 'colors.ts'),+ "export const oceanBlue = '#0064e0';\n",+ );});afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});-describe('themeAdd copies every file of the theme', () => {- it('copies a binary file byte for byte', async () => {+describe('themeAdd keeps the released source-copy inventory', () => {+ it('copies binary bytes and the integration authoring descriptor', async () => {const result = await themeAdd('ocean', {cwd: tmpDir,package: '@acme/themes',@@ -63,7 +74,69 @@ describe('themeAdd copies every file of the theme', () => {expect(result.data.files).toEqual(['oceanTheme.ts','fonts/ocean.woff2',+ 'icons.tsx','oceanTheme.doc.mjs',+ 'tokens/colors.ts',+ ]);+ const copied = fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'fonts', 'ocean.woff2'),+ );+ expect(copied.equals(FONT_BYTES)).toBe(true);+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.doc.mjs'),+ 'utf-8',+ ),+ ).toContain("name: 'ocean'");+ });++ it('keeps the released nested order in CLI JSON, text, and copied files', async () => {+ const expected = [+ 'oceanTheme.ts',+ 'fonts/ocean.woff2',+ 'icons.tsx',+ 'oceanTheme.doc.mjs',+ 'tokens/colors.ts',+ ];+ const json = await runCli(+ ['theme', 'add', 'ocean', '--package', '@acme/themes', '--json'],+ tmpDir,+ );+ expect(json.status, json.stderr).toBe(0);+ expect(JSON.parse(json.stdout).data.files).toEqual(expected);+ for (const file of expected) {+ expect(+ fs.existsSync(path.join(tmpDir, 'src', 'themes', 'ocean', file)),+ ).toBe(true);+ }++ fs.rmSync(path.join(tmpDir, 'src'), {recursive: true, force: true});+ const text = await runCli(+ ['theme', 'add', 'ocean', '--package', '@acme/themes'],+ tmpDir,+ );+ expect(text.status, text.stderr).toBe(0);+ const positions = expected.map(file =>+ text.stdout.indexOf(`src/themes/ocean/${file}`),+ );+ expect(positions.every(position => position >= 0)).toBe(true);+ expect(positions).toEqual([...positions].sort((a, b) => a - b));+ });+});++describe('themeEject copies every file of the theme', () => {+ it('copies a binary file byte for byte', async () => {+ const result = await themeEject('ocean', {+ cwd: tmpDir,+ package: '@acme/themes',+ });++ expect(result.data.files).toEqual([+ 'oceanTheme.ts',+ 'oceanTheme.doc.mjs',+ 'fonts/ocean.woff2',+ 'icons.tsx',+ 'tokens/colors.ts',]);const copied = fs.readFileSync(path.join(tmpDir, 'src', 'themes', 'ocean', 'fonts', 'ocean.woff2'),@@ -72,7 +145,7 @@ describe('themeAdd copies every file of the theme', () => {});it('still strips the repo header from a text source', async () => {- await themeAdd('ocean', {cwd: tmpDir, package: '@acme/themes'});+ await themeEject('ocean', {cwd: tmpDir, package: '@acme/themes'});expect(fs.readFileSync(diff --git a/packages/cli/api/theme/add/add.mjs b/packages/cli/api/theme/add/add.mjsindex f67d7ae3ed..1159e325e5 100644--- a/packages/cli/api/theme/add/add.mjs+++ b/packages/cli/api/theme/add/add.mjs@@ -1,38 +1,38 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @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.+ * @file `astryx theme add` — copy by default; import built output by opt-in.+ *+ * The released command copies source and returns `theme.add`. `--import` adds+ * the built theme to the generated app module and returns `theme.app`.*/import * as fs from 'node:fs';import * as path from 'node:path';+import {addThemeToApp, findTheme, listAvailableThemes} from '../_adapter.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 {listAvailableThemes, findTheme} from '../_adapter.mjs';import {applyWrites} from '../../integration/add-helpers.mjs';-// Scaffolded files must not carry our repo boilerplate into a consumer's tree.import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';-/**- * @param {string} slug- * @returns {string}- */+const COPY_DEPRECATION = Object.freeze({+ id: 'DEP-0005',+ replacements: ['theme eject', 'theme add --import'],+});++/** @param {string} slug */function defaultTargetDir(slug) {return path.join('src', 'themes', slug);}/**- * The bytes to write for one listed file. Only UTF-8 text loses our header;- * anything else (a font, an image) is copied verbatim, since decoding it would- * corrupt it.+ * Strip repository boilerplate from UTF-8 text while preserving binary bytes.* @param {Buffer} bytes- * @returns {Buffer | string}+ * @returns {Buffer|string}*/function scaffoldContents(bytes) {const text = bytes.toString('utf-8');@@ -42,17 +42,17 @@ function scaffoldContents(bytes) {}/**- * Copy a bundled theme's files into the consumer's project (defaults to- * `src/themes/<slug>/`). Writes are staged to temp files then renamed, rolling- * back partials on failure so a failed write never leaves a half-written theme.- * Throws AstryxError for an unknown slug, a target that escapes cwd, an existing- * file (without `overwrite`), a missing bundled file, or a write failure.+ * Bundled and package themes preserve their released copy inventories. Bundled+ * themes keep their authoring descriptor behind; integration themes copy the+ * complete directory, including the descriptor. Local themes are deliberately+ * excluded: copying `theme add` resolves only bundled and package themes, while+ * `--import` can select a built local theme.** @param {string} slug- * @param {{targetPath?: string, overwrite?: boolean, cwd?: string, package?: 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 = {}) {+async function copyThemeSource(slug, options) {const {targetPath,overwrite = false,@@ -60,120 +60,123 @@ export async function themeAdd(slug, options = {}) {package: packageName,} = options;- const match = await findTheme(slug, {cwd, package: packageName});+ const match = await findTheme(slug, {+ cwd,+ package: packageName,+ includeLocal: false,+ });if (!match) {- const available = await listAvailableThemes(cwd);+ const available = await listAvailableThemes(cwd, {includeLocal: false});throw new AstryxError(`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}`,+ reason:+ theme.source === 'bundled'+ ? 'bundled theme'+ : `provided by ${theme.package}`,})),ERROR_CODES.ERR_UNKNOWN_THEME,);}- const themeSrcDir = match.sourceDir;-- // Path-safe destination; reject traversal outside cwd.const rawTarget = targetPath || defaultTargetDir(match.slug);let resolvedDir;try {resolvedDir = assertWithin(rawTarget, cwd, {label: 'theme target path'});- } catch (err) {- if (err instanceof PathSafetyError) {+ } catch (error) {+ if (error instanceof PathSafetyError) {throw new AstryxError(- err.message,+ error.message,undefined,ERROR_CODES.ERR_PATH_TRAVERSAL,);}- throw err;+ throw error;}+ const descriptor = path+ .relative(match.sourceDir, match.docPath)+ .split(path.sep)+ .join('/');+ const copyFiles = match.bundled+ ? match.files.filter(name => name !== descriptor)+ : [match.entry, ...match.files.filter(name => name !== match.entry).sort()];let writes;try {- writes = match.files.map(name => ({+ writes = copyFiles.map(name => ({name,- src: path.join(themeSrcDir, name),+ src: path.join(match.sourceDir, name),dest: assertWithin(name, resolvedDir, {label: `theme destination for ${name}`,}),}));- } catch (err) {- if (err instanceof PathSafetyError) {+ } catch (error) {+ if (error instanceof PathSafetyError) {throw new AstryxError(- err.message,+ error.message,undefined,ERROR_CODES.ERR_PATH_TRAVERSAL,);}- throw err;+ throw error;}- for (const w of writes) {- if (!fs.existsSync(w.src)) {++ for (const write of writes) {+ if (!fs.existsSync(write.src)) {throw new AstryxError(- `Theme "${match.slug}" is missing bundled file "${w.name}". ` +- `Re-run \`node scripts/generate-cli-themes.mjs\` to rebuild the bundle.`,+ `Theme "${match.slug}" is missing bundled file "${write.name}". ` ++ 'Re-run `node scripts/generate-cli-themes.mjs` to rebuild the bundle.',undefined,ERROR_CODES.ERR_NO_SOURCE,);}}- // Refuse to clobber unless --overwrite.if (!overwrite) {- const existing = writes.find(w => fs.existsSync(w.dest));+ const existing = writes.find(write => fs.existsSync(write.dest));if (existing) {const rel = path.relative(cwd, existing.dest) || existing.dest;throw new AstryxError(`Refusing to overwrite existing file ${rel}. ` +- `Re-run with --overwrite (or -f) to replace it.`,+ 'Re-run with --overwrite (or -f) to replace it.',undefined,ERROR_CODES.ERR_FILE_EXISTS,);}}- // One transaction: every file publishes, or every replaced file gets its- // previous bytes back and every created file is removed. mkdir is inside the- // try so a failure (e.g. an ancestor is a file → EEXIST/ENOTDIR) surfaces as- // a stable ERR_WRITE_FAILED rather than leaking a raw fs errno + absolute path.try {fs.mkdirSync(resolvedDir, {recursive: true});- const plans = writes.map(w => {- fs.mkdirSync(path.dirname(w.dest), {recursive: true});- // Confine again once the directories exist: one may have been swapped- // for a link since the destination was first checked.- const dest = assertWithin(w.name, resolvedDir, {- label: `theme destination for ${w.name}`,+ const plans = writes.map(write => {+ fs.mkdirSync(path.dirname(write.dest), {recursive: true});+ const dest = assertWithin(write.name, resolvedDir, {+ label: `theme destination for ${write.name}`,});return {path: dest,- contents: scaffoldContents(fs.readFileSync(w.src)),+ contents: scaffoldContents(fs.readFileSync(write.src)),createOnly: !overwrite,};});applyWrites(plans);- } catch (err) {- if (err instanceof AstryxError) throw err;- if (err instanceof PathSafetyError) {+ } catch (error) {+ if (error instanceof AstryxError) throw error;+ if (error instanceof PathSafetyError) {throw new AstryxError(- err.message,+ error.message,undefined,ERROR_CODES.ERR_PATH_TRAVERSAL,);}+ const message = error instanceof Error ? error.message : String(error);throw new AstryxError(- `Failed to write theme files: ${/** @type {any} */ (err).message}`,+ `Failed to write theme files: ${message}`,undefined,ERROR_CODES.ERR_WRITE_FAILED,);}- const relDir = path.relative(cwd, resolvedDir) || '.';return {type: 'theme.add',data: {@@ -181,10 +184,30 @@ export async function themeAdd(slug, options = {}) {displayName: match.displayName,maintained: match.maintained,package: match.package,- outputDir: relDir,+ outputDir: path.relative(cwd, resolvedDir) || '.',entry: match.entry,exportName: match.exportName,- files: match.files,+ files: copyFiles,},+ meta: {deprecations: [COPY_DEPRECATION]},};}++/**+ * Copy one available source theme, or import its built output with `import`.+ * @param {string} slug+ * @param {{targetPath?: string, overwrite?: boolean, cwd?: string, package?: string, import?: boolean}} [options]+ * @returns {Promise<import('../theme.type.mjs').ThemeAddResponse | import('../theme.type.mjs').ThemeAppResponse>}+ */+export async function themeAdd(slug, options = {}) {+ if (!options.import) return copyThemeSource(slug, options);++ if (options.targetPath != null || options.overwrite === true) {+ throw new AstryxError(+ '`theme add --import` cannot be combined with a target path or --overwrite.',+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ return addThemeToApp(slug, options);+}diff --git a/packages/cli/api/theme/add/add.rollback.test.mjs b/packages/cli/api/theme/add/add.rollback.test.mjsindex 609468d64f..08729b0230 100644--- a/packages/cli/api/theme/add/add.rollback.test.mjs+++ b/packages/cli/api/theme/add/add.rollback.test.mjs@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * `theme add` writes a theme as one transaction: when a later file fails to+ * `theme eject` writes a theme as one transaction: when a later file fails to* publish, every file it already replaced gets its previous bytes back and* every file it created is removed. Publishing is forced to fail by wrapping* the two calls that publish a staged file: `linkSync` for a new file and@@ -61,13 +61,13 @@ vi.mock('node:fs', async importOriginal => {});const fs = await import('node:fs');-const {themeAdd} = await import('./add.mjs');+const {themeEject} = await import('../eject/eject.mjs');const {listThemes} = await import('../_adapter.mjs');let tmpDir;beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-rollback-'));+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-rollback-'));failures.publish = 0;failures.restore = false;failures.count = 0;@@ -98,12 +98,12 @@ function strays() {.filter(name => name.includes('.tmp') || name.includes('.restore-'));}-describe('themeAdd rolls back a partial write', () => {+describe('themeEject rolls back a partial write', () => {it('removes every created file when the second publish fails', async () => {const files = stoneFiles();failures.publish = 2;- await expect(themeAdd('stone', {cwd: tmpDir})).rejects.toMatchObject({+ await expect(themeEject('stone', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_WRITE_FAILED',});@@ -119,7 +119,7 @@ describe('themeAdd rolls back a partial write', () => {failures.publish = 2;await expect(- themeAdd('stone', {cwd: tmpDir, overwrite: true}),+ themeEject('stone', {cwd: tmpDir, overwrite: true}),).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});expect(fs.readFileSync(files[0]).equals(before)).toBe(true);@@ -136,7 +136,7 @@ describe('themeAdd rolls back a partial write', () => {let error;try {- await themeAdd('stone', {cwd: tmpDir, overwrite: true});+ await themeEject('stone', {cwd: tmpDir, overwrite: true});} catch (caught) {error = caught;}@@ -149,9 +149,9 @@ describe('themeAdd rolls back a partial write', () => {it('writes every file when nothing fails', async () => {const files = stoneFiles();- const result = await themeAdd('stone', {cwd: tmpDir});+ const result = await themeEject('stone', {cwd: tmpDir});- expect(result.type).toBe('theme.add');+ expect(result.type).toBe('theme.eject');for (const file of files) expect(fs.existsSync(file)).toBe(true);expect(strays()).toEqual([]);});diff --git a/packages/cli/api/theme/add/add.staging.test.mjs b/packages/cli/api/theme/add/add.staging.test.mjsindex 9206b9e4cf..c4e4840299 100644--- a/packages/cli/api/theme/add/add.staging.test.mjs+++ b/packages/cli/api/theme/add/add.staging.test.mjs@@ -4,16 +4,16 @@ 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 {themeAdd} from './add.mjs';+import {themeEject} from '../eject/eject.mjs';import {listThemes} from '../_adapter.mjs';let tmpDir;let outsideDir;beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-staging-'));+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-staging-'));outsideDir = fs.mkdtempSync(- path.join(os.tmpdir(), 'astryx-themeadd-outside-'),+ path.join(os.tmpdir(), 'astryx-themeeject-outside-'),);});@@ -23,7 +23,7 @@ afterEach(() => {});/**- * Where `theme add` writes the first file of `slug`.+ * Where `theme eject` writes the first file of `slug`.* @param {string} slug*/function firstDestination(slug) {@@ -36,14 +36,14 @@ function firstDestination(slug) {// Staging names are unpredictable and created exclusively, so an entry planted// at a predictable name beside the destination is never written through.-describe('themeAdd staging writes stay inside the project', () => {+describe('themeEject staging writes stay inside the project', () => {it('never writes through a link planted at a predictable staging name', async () => {const victim = path.join(outsideDir, 'victim.txt');fs.writeFileSync(victim, 'outside\n');const dest = firstDestination('stone');fs.symlinkSync(victim, `${dest}.${process.pid}.tmp`);- await themeAdd('stone', {cwd: tmpDir});+ await themeEject('stone', {cwd: tmpDir});expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');expect(fs.lstatSync(dest).isFile()).toBe(true);@@ -53,7 +53,7 @@ describe('themeAdd staging writes stay inside the project', () => {const victim = path.join(outsideDir, 'created.txt');fs.symlinkSync(victim, `${firstDestination('stone')}.${process.pid}.tmp`);- await themeAdd('stone', {cwd: tmpDir});+ await themeEject('stone', {cwd: tmpDir});expect(fs.existsSync(victim)).toBe(false);});@@ -65,7 +65,7 @@ describe('themeAdd staging writes stay inside the project', () => {fs.symlinkSync(victim, dest);await expect(- themeAdd('stone', {cwd: tmpDir, overwrite: true}),+ themeEject('stone', {cwd: tmpDir, overwrite: true}),).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');expect(fs.lstatSync(dest).isSymbolicLink()).toBe(true);@@ -75,7 +75,7 @@ describe('themeAdd staging writes stay inside the project', () => {const victim = path.join(outsideDir, 'created.txt');fs.symlinkSync(victim, firstDestination('stone'));- await expect(themeAdd('stone', {cwd: tmpDir})).rejects.toMatchObject({+ await expect(themeEject('stone', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL',});expect(fs.existsSync(victim)).toBe(false);diff --git a/packages/cli/api/theme/add/add.test.mjs b/packages/cli/api/theme/add/add.test.mjsindex 575ebef54b..857daa603f 100644--- a/packages/cli/api/theme/add/add.test.mjs+++ b/packages/cli/api/theme/add/add.test.mjs@@ -1,63 +1,208 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file Direct-API tests for the `theme add` leaf. Copies real bundled themes- * into a tmp cwd and asserts the receipt + on-disk effects, plus the guard rails- * (unknown slug, no-overwrite, path traversal). Uses the maintained `neutral`- * theme so the fixture stays stable.- */--import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import {afterEach, beforeEach, describe, expect, it} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';-import * as os from 'node:os';import {themeAdd} from './add.mjs';+import {themeEject} from '../eject/eject.mjs';+import {+ THEME_MODULE_MARKER,+ parseThemeModuleRecord,+} from '../../../foundation/config/theme-state.mjs';let tmpDir;+function installTheme(+ slug = 'ocean',+ packageName = '@acme/themes',+ options = {},+) {+ const packageDir = path.join(+ tmpDir,+ 'node_modules',+ ...packageName.split('/'),+ );+ const sourceDir = path.join(packageDir, 'themes', slug);+ const exportName = `${slug}Theme`;+ fs.mkdirSync(sourceDir, {recursive: true});+ fs.mkdirSync(path.join(packageDir, 'dist'), {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({+ name: packageName,+ version: '1.0.0',+ type: 'module',+ exports: {+ [`./themes/${slug}`]: `./dist/${slug}.js`,+ [`./themes/${slug}.css`]: `./dist/${slug}.css`,+ },+ }),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+ fs.writeFileSync(+ path.join(sourceDir, `${exportName}.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: '${slug}', displayName: '${slug}', description: '${slug} theme.', maintained: true};\n`,+ );+ fs.writeFileSync(+ path.join(sourceDir, `${exportName}.ts`),+ `export const ${exportName} = {};\n`,+ );+ if (!options.missingBuilt) {+ fs.writeFileSync(+ path.join(packageDir, `dist/${slug}.js`),+ `export const ${exportName} = {name: '${slug}', __built: true};\n`,+ );+ fs.writeFileSync(+ path.join(packageDir, `dist/${slug}.css`),+ `[data-astryx-theme="${slug}"] {}\n`,+ );+ }+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ pkg.dependencies[packageName] = '^1.0.0';+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify(pkg)}\n`,+ );+}++function installBuiltThemePackage(slug) {+ const packageName = `@astryxdesign/theme-${slug}`;+ const packageDir = path.join(+ tmpDir,+ 'node_modules',+ ...packageName.split('/'),+ );+ const exportName = `${slug}Theme`;+ fs.mkdirSync(path.join(packageDir, 'dist'), {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({+ name: packageName,+ version: '1.0.0',+ type: 'module',+ exports: {+ './built': './dist/built.js',+ './theme.css': './dist/theme.css',+ },+ }),+ );+ fs.writeFileSync(+ path.join(packageDir, 'dist/built.js'),+ `export const ${exportName} = {name: '${slug}', __built: true};\n`,+ );+ fs.writeFileSync(+ path.join(packageDir, 'dist/theme.css'),+ `[data-astryx-theme="${slug}"] {}\n`,+ );+ const pkg = JSON.parse(+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),+ );+ pkg.dependencies[packageName] = '^1.0.0';+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ `${JSON.stringify(pkg)}\n`,+ );+}+beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-'));+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-theme-add-app-'));+ fs.mkdirSync(path.join(tmpDir, 'src'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {}}),+ );+ fs.writeFileSync(path.join(tmpDir, 'tsconfig.json'), '{}\n');});afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});-describe('themeAdd (api/theme/add)', () => {- it('copies a theme into src/themes/<slug> and returns a theme.add receipt', async () => {+describe('themeAdd', () => {+ it('keeps the released source-copy response and works without built exports', async () => {+ installTheme('ocean', '@acme/themes', {missingBuilt: true});++ const result = await themeAdd('ocean', {+ cwd: tmpDir,+ package: '@acme/themes',+ });++ expect(result).toMatchObject({+ type: 'theme.add',+ data: {+ slug: 'ocean',+ displayName: 'ocean',+ maintained: true,+ package: '@acme/themes',+ outputDir: 'src/themes/ocean',+ entry: 'oceanTheme.ts',+ exportName: 'oceanTheme',+ files: ['oceanTheme.ts', 'oceanTheme.doc.mjs'],+ },+ meta: {+ deprecations: [+ {+ id: 'DEP-0005',+ replacements: ['theme eject', 'theme add --import'],+ },+ ],+ },+ });+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src/themes/ocean/oceanTheme.ts'),+ 'utf-8',+ ),+ ).toContain('export const oceanTheme');+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src/themes/ocean/oceanTheme.doc.mjs'),+ 'utf-8',+ ),+ ).toContain("name: 'ocean'");+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(+ false,+ );+ });++ it('keeps every released bundled copy receipt field and file', async () => {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'));- // Exactly what the bundle has always copied, in that order: the CLI's own- // descriptor stays behind.- expect(result.data.files).toEqual([- 'neutralTheme.ts',- 'icons.tsx',- 'neutralPalettes.ts',- 'neutralPalettes.generated.ts',- 'neutralPaletteRefs.generated.ts',- 'neutralPalettes.generated.receipt.json',- 'palette.config.json',- ]);++ expect(result.data).toEqual({+ slug: 'neutral',+ displayName: 'Neutral',+ maintained: true,+ package: '@astryxdesign/cli',+ outputDir: path.join('src', 'themes', 'neutral'),+ entry: 'neutralTheme.ts',+ exportName: 'neutralTheme',+ files: [+ 'neutralTheme.ts',+ 'icons.tsx',+ 'neutralPalettes.ts',+ 'neutralPalettes.generated.ts',+ 'neutralPaletteRefs.generated.ts',+ 'neutralPalettes.generated.receipt.json',+ 'palette.config.json',+ ],+ });expect(- fs.readdirSync(path.join(tmpDir, 'src', 'themes', 'neutral')).sort(),+ fs.readdirSync(path.join(tmpDir, 'src/themes/neutral')).sort(),).toEqual([...result.data.files].sort());- for (const f of result.data.files) {- expect(- fs.existsSync(path.join(tmpDir, 'src', 'themes', 'neutral', f)),- ).toBe(true);- }});- it('copies every relative import required by the scaffolded theme', async () => {+ it('keeps every relative import required by a copied theme', async () => {const result = await themeAdd('neutral', {cwd: tmpDir});const outputDir = path.join(tmpDir, result.data.outputDir);- const relativeImports = /from\s+['"](\.\.?\/[^'"]+)['"]/g;+ const relativeImports = /from\s+['"](\.\.?\/[^'"]+)['"]/gu;for (const file of result.data.files) {- if (!/\.(?:ts|tsx|mjs)$/.test(file)) continue;+ if (!/\.(?:ts|tsx|mjs)$/u.test(file)) continue;const source = fs.readFileSync(path.join(outputDir, file), 'utf-8');for (const [, specifier] of source.matchAll(relativeImports)) {const imported = path.resolve(outputDir, path.dirname(file), specifier);@@ -71,7 +216,7 @@ describe('themeAdd (api/theme/add)', () => {}});- it('strips the Meta copyright header from copied files', async () => {+ it('strips the repository copyright header from copied text', async () => {const result = await themeAdd('neutral', {cwd: tmpDir});const first = path.join(tmpDir,@@ -79,16 +224,16 @@ describe('themeAdd (api/theme/add)', () => {result.data.files[0],);expect(fs.readFileSync(first, 'utf-8')).not.toMatch(- /Copyright \(c\) Meta Platforms/,+ /Copyright \(c\) Meta Platforms/u,);});- it('resolves the slug case-insensitively', async () => {+ it('keeps case-insensitive copy lookup', async () => {const result = await themeAdd('Neutral', {cwd: tmpDir});expect(result.data.slug).toBe('neutral');});- it('honors an explicit target path (within cwd)', async () => {+ it('keeps an explicit copy target path', async () => {const result = await themeAdd('neutral', {cwd: tmpDir,targetPath: 'themes/mine',@@ -99,49 +244,310 @@ describe('themeAdd (api/theme/add)', () => {).toBe(true);});- it('throws ERR_UNKNOWN_THEME for an unknown slug (with suggestions)', async () => {+ it('keeps unknown-theme errors on the copy path', async () => {await expect(themeAdd('does-not-exist', {cwd: tmpDir}),).rejects.toMatchObject({code: 'ERR_UNKNOWN_THEME'});});- it('refuses to overwrite existing files without overwrite', async () => {+ it('keeps the copy overwrite guard and explicit replacement', async () => {await themeAdd('neutral', {cwd: tmpDir});await expect(themeAdd('neutral', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_FILE_EXISTS',});+ await expect(+ themeAdd('neutral', {cwd: tmpDir, overwrite: true}),+ ).resolves.toMatchObject({type: 'theme.add'});});- it('replaces files when overwrite is set', async () => {- await themeAdd('neutral', {cwd: tmpDir});- const result = await themeAdd('neutral', {cwd: tmpDir, overwrite: true});- expect(result.type).toBe('theme.add');- });-- it('rejects a target path that escapes cwd', async () => {+ it('keeps copy path traversal protection', async () => {await expect(themeAdd('neutral', {cwd: tmpDir, targetPath: '../escape'}),).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});});- it('surfaces ERR_WRITE_FAILED (not a raw errno) when the target path is an existing file', async () => {+ it('keeps stable write errors when a copy target is a file', async () => {fs.writeFileSync(path.join(tmpDir, 'blocker'), 'x');await expect(themeAdd('neutral', {cwd: tmpDir, targetPath: 'blocker'}),).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});});- it('surfaces ERR_WRITE_FAILED when an ancestor of the default dir is a file', async () => {- // A file named `src` blocks mkdir of src/themes/neutral (ENOTDIR).+ it('keeps stable write errors when the default copy ancestor is a file', async () => {+ fs.rmSync(path.join(tmpDir, 'src'), {recursive: true, force: true});fs.writeFileSync(path.join(tmpDir, 'src'), 'x');await expect(themeAdd('neutral', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_WRITE_FAILED',});});- it('adds into an existing empty target directory', async () => {+ it('keeps copying into an existing empty target directory', async () => {fs.mkdirSync(path.join(tmpDir, 'mydir'));- const r = await themeAdd('neutral', {cwd: tmpDir, targetPath: 'mydir'});- expect(r.data.outputDir).toBe('mydir');+ const result = await themeAdd('neutral', {+ cwd: tmpDir,+ targetPath: 'mydir',+ });+ expect(result.data.outputDir).toBe('mydir');+ });++ it('excludes local themes from the copying lookup', async () => {+ installTheme();+ const localDir = path.join(tmpDir, 'src', 'themes', 'ocean');+ fs.mkdirSync(localDir, {recursive: true});+ fs.writeFileSync(+ path.join(localDir, 'oceanTheme.doc.mjs'),+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Local ocean', description: 'Local.', maintained: false};\n",+ );+ fs.writeFileSync(+ path.join(localDir, 'oceanTheme.ts'),+ 'export const oceanTheme = {source: "local"};\n',+ );++ const result = await themeAdd('ocean', {+ cwd: tmpDir,+ targetPath: 'src/copied-ocean',+ });++ expect(result.type).toBe('theme.add');+ expect(result.data.package).toBe('@acme/themes');+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'copied-ocean', 'oceanTheme.ts'),+ 'utf-8',+ ),+ ).not.toContain('source: "local"');+ });++ it.each([+ ['a target path', {targetPath: 'src/brand'}],+ ['overwrite', {overwrite: true}],+ ])('rejects --import with %s before writing', async (_label, copyOption) => {+ installTheme();++ await expect(+ themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ ...copyOption,+ }),+ ).rejects.toMatchObject({+ code: 'ERR_THEME_INVALID',+ message: expect.stringContaining('cannot be combined'),+ });+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(+ false,+ );+ expect(fs.existsSync(path.join(tmpDir, 'src/brand'))).toBe(false);+ });++ it('records and imports a built package theme without copying source', async () => {+ installTheme();+ const packageBefore = fs.readFileSync(+ path.join(tmpDir, 'package.json'),+ 'utf-8',+ );++ const result = await themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ });++ expect(result).toMatchObject({+ type: 'theme.app',+ data: {+ default: 'ocean',+ modulePath: 'src/astryx-themes.ts',+ change: {action: 'add', slug: 'ocean', changed: true},+ themes: [+ {+ slug: 'ocean',+ owner: '@acme/themes',+ module: '@acme/themes/themes/ocean',+ stylesheet: '@acme/themes/themes/ocean.css',+ source: 'package',+ },+ ],+ },+ });+ expect(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8')).toBe(+ packageBefore,+ );+ expect(fs.existsSync(path.join(tmpDir, 'src/themes/ocean'))).toBe(false);+ const module = fs.readFileSync(+ path.join(tmpDir, 'src/astryx-themes.ts'),+ 'utf-8',+ );+ expect(module).toContain(THEME_MODULE_MARKER);+ expect(module).toContain('from "@acme/themes/themes/ocean"');+ expect(module).toContain('import "@acme/themes/themes/ocean.css"');+ expect(parseThemeModuleRecord(module)).toEqual({+ themes: {ocean: '@acme/themes'},+ defaultSlug: 'ocean',+ });+ });++ it('keeps the released CLI selector while recording the import package', async () => {+ installBuiltThemePackage('neutral');+ const result = await themeAdd('neutral', {+ cwd: tmpDir,+ import: true,+ package: '@astryxdesign/cli',+ });++ expect(result.data.themes).toEqual([+ expect.objectContaining({+ slug: 'neutral',+ owner: '@astryxdesign/theme-neutral',+ module: '@astryxdesign/theme-neutral/built',+ stylesheet: '@astryxdesign/theme-neutral/theme.css',+ source: 'bundled',+ }),+ ]);+ expect(+ parseThemeModuleRecord(+ fs.readFileSync(path.join(tmpDir, 'src/astryx-themes.ts'), 'utf-8'),+ ),+ ).toEqual({+ themes: {neutral: '@astryxdesign/theme-neutral'},+ defaultSlug: 'neutral',+ });+ });++ it('regenerates an already-added theme and reports no state change', async () => {+ installTheme();+ await themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ });+ const moduleFile = path.join(tmpDir, 'src/astryx-themes.ts');+ fs.appendFileSync(moduleFile, '\n// hand edit\n');++ const result = await themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ });++ expect(result.data.change.changed).toBe(false);+ expect(fs.readFileSync(moduleFile, 'utf-8')).not.toContain('hand edit');+ });++ it('fails before writing when the selected module path is authored', async () => {+ installTheme();+ const moduleFile = path.join(tmpDir, 'src/astryx-themes.ts');+ fs.writeFileSync(moduleFile, 'export const mine = true;\n');++ await expect(+ themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ }),+ ).rejects.toMatchObject({code: 'ERR_FILE_EXISTS'});+ expect(fs.readFileSync(moduleFile, 'utf-8')).toBe(+ 'export const mine = true;\n',+ );+ });++ it('uses a JavaScript module at the project root when there is no src', async () => {+ fs.rmSync(path.join(tmpDir, 'src'), {recursive: true});+ fs.rmSync(path.join(tmpDir, 'tsconfig.json'));+ installTheme();++ const result = await themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ });++ expect(result.data.modulePath).toBe('astryx-themes.js');+ expect(fs.existsSync(path.join(tmpDir, 'astryx-themes.js'))).toBe(true);+ });++ it('prefers a built local theme and switches the recorded owner', async () => {+ installTheme();+ await themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ });+ await themeEject('ocean', {cwd: tmpDir, package: '@acme/themes'});+ const localDir = path.join(tmpDir, 'src', 'themes', 'ocean');+ fs.writeFileSync(+ path.join(localDir, 'ocean.js'),+ 'export const oceanTheme = {name: "local-ocean", __built: true};\n',+ );+ fs.writeFileSync(path.join(localDir, 'ocean.css'), '/* local css */\n');++ const result = await themeAdd('ocean', {cwd: tmpDir, import: true});++ expect(result).toMatchObject({+ type: 'theme.app',+ data: {+ change: {action: 'add', slug: 'ocean', changed: true},+ themes: [+ {+ slug: 'ocean',+ owner: './src/themes',+ module: './themes/ocean/ocean.js',+ stylesheet: './themes/ocean/ocean.css',+ source: 'local',+ },+ ],+ },+ });+ expect(+ parseThemeModuleRecord(+ fs.readFileSync(path.join(tmpDir, 'src/astryx-themes.ts'), 'utf-8'),+ ),+ ).toEqual({+ themes: {ocean: './src/themes'},+ defaultSlug: 'ocean',+ });+ });++ it('ignores an unmigrated local copy without changing it', async () => {+ const copyDir = path.join(tmpDir, 'src', 'themes', 'ocean');+ fs.mkdirSync(copyDir, {recursive: true});+ const source = 'export const oceanTheme = {name: "copied"};\n';+ fs.writeFileSync(path.join(copyDir, 'oceanTheme.ts'), source);+ installTheme();++ const result = await themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ });++ expect(result.data.themes).toEqual([+ expect.objectContaining({slug: 'ocean', owner: '@acme/themes'}),+ ]);+ expect(fs.readFileSync(path.join(copyDir, 'oceanTheme.ts'), 'utf-8')).toBe(+ source,+ );+ expect(fs.existsSync(path.join(copyDir, 'oceanTheme.doc.mjs'))).toBe(false);+ });++ it('never falls back to package source when built exports are missing', async () => {+ installTheme('ocean', '@acme/themes', {missingBuilt: true});++ await expect(+ themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ }),+ ).rejects.toMatchObject({+ code: 'ERR_THEME_INVALID',+ message: expect.stringMatching(+ /no resolvable built module and stylesheet/i,+ ),+ });+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(+ false,+ );});});diff --git a/packages/cli/api/theme/add/add.types.test.mjs b/packages/cli/api/theme/add/add.types.test.mjsnew file mode 100644index 0000000000..7865592527--- /dev/null+++ b/packages/cli/api/theme/add/add.types.test.mjs@@ -0,0 +1,151 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file TypeScript proof for generated app modules with package and local themes. */++import {afterEach, describe, expect, it, vi} from 'vitest';+import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';++import {themeBuild} from '../build/build.mjs';+import {themeAdd} from './add.mjs';++vi.setConfig({testTimeout: 120_000});++const REPO_ROOT = path.resolve(import.meta.dirname, '../../../../..');+const TSC_BIN = path.join(REPO_ROOT, 'node_modules/typescript/bin/tsc');+/** @type {string[]} */+const dirs = [];++/** @param {string} file @param {string} contents */+function write(file, contents) {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, contents);+}++function makeProject() {+ const project = fs.mkdtempSync(path.join(REPO_ROOT, '.tmp-theme-app-types-'));+ dirs.push(project);+ write(+ path.join(project, 'package.json'),+ JSON.stringify({+ name: 'theme-app-types',+ private: true,+ type: 'module',+ dependencies: {'@acme/themes': '1.0.0'},+ }),+ );++ const packageDir = path.join(project, 'node_modules/@acme/themes');+ write(+ path.join(packageDir, 'package.json'),+ JSON.stringify({+ name: '@acme/themes',+ version: '1.0.0',+ type: 'module',+ exports: {+ './themes/ocean': {+ types: './dist/ocean.d.ts',+ import: './dist/ocean.js',+ },+ './themes/ocean.css': {+ types: './dist/ocean.css.d.ts',+ default: './dist/ocean.css',+ },+ },+ }),+ );+ write(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+ write(+ path.join(packageDir, 'themes/ocean/oceanTheme.doc.mjs'),+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Ocean theme.', maintained: true};\n",+ );+ write(+ path.join(packageDir, 'themes/ocean/oceanTheme.ts'),+ "export const oceanTheme = {name: 'ocean', tokens: {}};\n",+ );+ write(+ path.join(packageDir, 'dist/ocean.js'),+ "export const oceanTheme = {name: 'ocean', tokens: {}};\n",+ );+ write(+ path.join(packageDir, 'dist/ocean.d.ts'),+ "export declare const oceanTheme: {readonly name: 'ocean'};\n",+ );+ write(+ path.join(packageDir, 'dist/ocean.css'),+ '[data-astryx-theme="ocean"] { color: navy; }\n',+ );+ write(path.join(packageDir, 'dist/ocean.css.d.ts'), 'export {};\n');++ write(+ path.join(project, 'src/themes/stone/stoneTheme.doc.mjs'),+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'stone', displayName: 'Stone', description: 'Stone theme.', maintained: false};\n",+ );+ write(+ path.join(project, 'src/themes/stone/stoneTheme.ts'),+ "export const stoneTheme = {name: 'stone', tokens: {'--color-text': '#111'}};\nexport default stoneTheme;\n",+ );+ write(+ path.join(project, 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: {+ module: 'ESNext',+ moduleResolution: 'Bundler',+ target: 'ES2022',+ strict: true,+ noEmit: true,+ noUncheckedSideEffectImports: true,+ noUnusedLocals: true,+ skipLibCheck: true,+ },+ include: ['src/astryx-themes.ts', 'src/use-themes.ts'],+ }),+ );+ return project;+}++afterEach(() => {+ while (dirs.length > 0) {+ fs.rmSync(dirs.pop(), {recursive: true, force: true});+ }+});++describe('generated app-theme module types', () => {+ it('type-checks package and local CSS imports under strict side-effect checking', async () => {+ const project = makeProject();+ await themeBuild('src/themes/stone/stoneTheme.ts', {}, {cwd: project});+ expect(+ fs.existsSync(path.join(project, 'src/themes/stone/stone.css.d.ts')),+ ).toBe(true);++ await themeAdd('ocean', {+ cwd: project,+ import: true,+ package: '@acme/themes',+ });+ await themeAdd('stone', {cwd: project, import: true});+ write(+ path.join(project, 'src/use-themes.ts'),+ "import {defaultThemeSlug, themes} from './astryx-themes.js';\nimport type {ThemeSlug} from './astryx-themes.js';\nexport const activeTheme = themes[defaultThemeSlug];\nexport const activeSlug: ThemeSlug = defaultThemeSlug;\n",+ );++ try {+ execFileSync(+ process.execPath,+ [TSC_BIN, '--project', path.join(project, 'tsconfig.json')],+ {cwd: project, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe']},+ );+ } catch (error) {+ const failure = /** @type {{stdout?: unknown, stderr?: unknown}} */ (+ error+ );+ throw new Error(`${failure.stdout ?? ''}${failure.stderr ?? ''}`, {+ cause: error,+ });+ }+ });+});diff --git a/packages/cli/api/theme/build/build.family.test.mjs b/packages/cli/api/theme/build/build.family.test.mjsindex 2b6c3791d9..4de79e13d3 100644--- a/packages/cli/api/theme/build/build.family.test.mjs+++ b/packages/cli/api/theme/build/build.family.test.mjs@@ -16,7 +16,12 @@ import {runCli} from '../../../test-utils/run-cli.mjs';vi.setConfig({testTimeout: 120_000});const CLI_ROOT = path.resolve(import.meta.dirname, '../../..');const FAMILY_KEY = 'ocean-family';-const OUTPUTS = [`${FAMILY_KEY}.css`, `${FAMILY_KEY}.js`, `${FAMILY_KEY}.d.ts`];+const OUTPUTS = [+ `${FAMILY_KEY}.css`,+ `${FAMILY_KEY}.css.d.ts`,+ `${FAMILY_KEY}.js`,+ `${FAMILY_KEY}.d.ts`,+];/** @type {string[]} */ let dirs;beforeAll(() => ensureCoreBuilt(), 200_000);beforeEach(() => (dirs = []));@@ -121,7 +126,7 @@ describe('themeBuildFamily()', () => {expect(result?.type).toBe('theme.build');expect(result?.data.name).toBe('ocean');// prettier-ignore- expect(result?.data.outputs).toEqual({css: `themes/${FAMILY_KEY}.css`, js: `themes/${FAMILY_KEY}.js`, dts: `themes/${FAMILY_KEY}.d.ts`});+ expect(result?.data.outputs).toEqual({css: `themes/${FAMILY_KEY}.css`, cssDts: `themes/${FAMILY_KEY}.css.d.ts`, js: `themes/${FAMILY_KEY}.js`, dts: `themes/${FAMILY_KEY}.d.ts`});// prettier-ignorefor (const output of OUTPUTS) { const a = fs.readFileSync(path.join(first, 'themes', output), 'utf8'), b = fs.readFileSync(path.join(second, 'themes', output), 'utf8'); expect({output, content: a}).toEqual({output, content: b}); }const css = fs.readFileSync(@@ -258,8 +263,12 @@ describe('themeBuildFamily()', () => {await expect(build(dir, files)).rejects.toThrow(/Failed to write theme outputs/,);- expect(fs.existsSync(path.join(outputDir, `${FAMILY_KEY}.css`))).toBe(false);- expect(fs.existsSync(path.join(outputDir, `${FAMILY_KEY}.d.ts`))).toBe(false);+ expect(fs.existsSync(path.join(outputDir, `${FAMILY_KEY}.css`))).toBe(+ false,+ );+ expect(fs.existsSync(path.join(outputDir, `${FAMILY_KEY}.d.ts`))).toBe(+ false,+ );expect(fs.readdirSync(outputDir).filter(name => name.includes('.tmp-')),).toEqual([]);diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex 7026e5dcc8..456a23f8d5 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -11,6 +11,7 @@* @astryxdesign/core's shared generator (the SINGLE source of truth so the* build emits the exact CSS the `<Theme>` runtime does), writes:* - A CSS file with token overrides and component styles+ * - A CSS declaration module for strict side-effect imports* - A JS module that re-exports the built theme (+ icon registry)* - A .d.ts (plus an optional .variants.d.ts for custom prop values)*@@ -41,7 +42,9 @@* `theme.build.check` receipt listing any stale or missing outputs. This is* the CI guard for committed, generated theme CSS: the source of truth is* `<theme>.ts`, and `theme build --check` fails when the committed- * `<theme>.css`/`.js`/`.d.ts` no longer match it.+ * `<theme>.css`/`.js`/`.d.ts` no longer match it. Builds also write a+ * `<theme>.css.d.ts` import stub; check mode tolerates that one file being absent+ * so output sets from the released CLI stay valid after an upgrade.*/import * as fs from 'node:fs';@@ -62,6 +65,7 @@ import {PathSafetyError,} from '../../../foundation/fs/path-safety.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {validatePrivateVars} from '../../../foundation/config/theme-private-vars.mjs';import {AstryxError} from '../../error.mjs';import {applyWrites} from '../../integration/add-helpers.mjs';import {logger} from '../../logger.mjs';@@ -431,7 +435,7 @@ function generatedHeader(sourceFile, lang = 'js', command, versions) {* @param {string} content* @returns {string}*/-function normalizeForCompare(content) {+export function normalizeThemeBuildForCompare(content) {return content.split('\n').filter(line => {@@ -441,24 +445,36 @@ function normalizeForCompare(content) {.join('\n');}-/** @param {Array<{dest: string, content: string}>} writes @param {string} cwd @returns {Array<{path: string, reason: 'missing' | 'outdated'}>} */+/** @param {Array<{dest: string, content: string, allowMissingInCheck?: boolean}>} writes @param {string} cwd @returns {Array<{path: string, reason: 'missing' | 'outdated'}>} */function staleBuildOutputs(writes, cwd) {/** @type {Array<{path: string, reason: 'missing' | 'outdated'}>} */const stale = [];for (const write of writes) {const rel = path.relative(cwd, write.dest);if (!fs.existsSync(write.dest)) {- stale.push({path: rel, reason: 'missing'});+ if (!write.allowMissingInCheck) {+ stale.push({path: rel, reason: 'missing'});+ }continue;}const onDisk = fs.readFileSync(write.dest, 'utf8');- if (normalizeForCompare(onDisk) !== normalizeForCompare(write.content)) {+ if (+ normalizeThemeBuildForCompare(onDisk) !==+ normalizeThemeBuildForCompare(write.content)+ ) {stale.push({path: rel, reason: 'outdated'});}}return stale;}+/** @param {Array<{dest: string, allowMissingInCheck?: boolean}>} writes @param {string} cwd */+function checkedBuildOutputs(writes, cwd) {+ return writes+ .filter(write => !write.allowMissingInCheck || fs.existsSync(write.dest))+ .map(write => path.relative(cwd, write.dest));+}+/** @param {Array<{dest: string, content: string}>} writes */function writeBuildOutputs(writes) {if (writes.length === 0) return;@@ -515,8 +531,6 @@ function toIdentifier(name) {* from the cwd-relative dir (most consumers import from a file under src/) but* keeps the rest of the path (e.g. `themes/gothic`). Callers note the path is* relative to the consumer's file.- * Exported (not just used by `themeBuild`'s install instructions) because the- * thin CLI's `theme add` action reuses it for its own scaffold instructions.* @param {string} relDir* @param {string} base* @returns {string}@@ -1106,30 +1120,6 @@ function assertAdaptationCapability();}-/**- * Every `[component, rules]` pair a theme may emit, including ordered- * adaptation rules. Validators, private-variable checks, and notices must see- * rule-only values even though variant augmentation is root-owned.- *- * @param {Record<string, any>} themeDef- * @returns {[string, Record<string, any>][]}- */-function themedComponentEntries(themeDef) {- const maps = [- themeDef.components,- ...adaptationRuleValues(themeDef).map(- (/** @type {any} */ value) => value.components,- ),- ];-- /** @type {[string, Record<string, any>][]} */- const entries = [];- for (const map of maps) {- if (map) entries.push(...Object.entries(map));- }- return entries;-}-/*** Root component entries are the only surface allowed to introduce variants.* @param {Record<string, any>} themeDef@@ -1686,6 +1676,46 @@ async function extractThemeDefinition(filePath, interception, /** @type {any} */}}+/**+ * Load one theme through the build's real module loader and validate the raw+ * input captured from its defineTheme lineage. Used by doctor so it applies the+ * same direct-input rule as theme build without mistaking compiler output for+ * authored input.+ *+ * @param {string} file+ * @param {{cwd?: string}} [ctx]+ * @returns {Promise<string[]>}+ */+export async function validateThemePrivateInputs(+ file,+ {cwd = process.cwd()} = {},+) {+ const filePath = path.resolve(cwd, file);+ if (!fs.existsSync(filePath)) {+ throw new AstryxError(+ `File not found: ${filePath}`,+ undefined,+ ERROR_CODES.ERR_FILE_NOT_FOUND,+ );+ }++ const interception = interceptCore(_coreThemeModule, _coreRootModule);+ let theme;+ try {+ theme = (await extractThemeDefinition(filePath, interception)).theme;+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_LOAD);+ }++ const inputs = interception.lineageOf(theme);+ try {+ return [...new Set(inputs.flatMap(input => validatePrivateVars(input)))];+ } finally {+ interception.strip(theme);+ }+}+/*** Fallback extraction via regex + eval.* Only works for plain object literals — can't follow imports or variables.@@ -2092,48 +2122,6 @@ async function validateComponentOverrides(themeDef) {: validateComponentOverridesAgainstRegistry(themeDef, knownComponents);}-/**- * Validate that themes don't set private (--_*) CSS custom properties directly.- * Private vars are internal implementation details managed by the derived var- * expansion pipeline. Theme authors should write standard CSS properties- * (e.g. borderRadius, padding) instead.- *- * Returns array of error strings.- * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef- * @returns {string[]}- */-function validatePrivateVars(themeDef) {- /** @type {string[]} */- const errors = [];-- for (const [component, rules] of themedComponentEntries(themeDef)) {- for (const [key, styles] of Object.entries(rules)) {- /**- * @param {unknown} value- * @param {string[]} [path]- */- const visit = (value, path = []) => {- if (!value || typeof value !== 'object' || Array.isArray(value)) return;- for (const [prop, nested] of Object.entries(value)) {- if (prop.startsWith('--_')) {- errors.push(- `Component "${component}" (${[key, ...path].join(' ')}) sets private var "${prop}". ` +- `Private vars (--_*) are internal; use standard CSS properties ` +- `(e.g. borderRadius, padding) instead. The pipeline expands them automatically.`,- );- }- visit(nested, [...path, prop]);- }- };- visit(styles);- }- }-- // One entry per distinct message: a component declared both at the root and- // in one or more adaptations would otherwise report the same problem twice.- return [...new Set(errors)];-}-const BUILTIN_HEADING_TYPES = new Set(['display-1', 'display-2', 'display-3']);/**@@ -2332,8 +2320,8 @@ function validateHeadingTypeAugmentationSupport(themeDef) {}/**- * Compile a defineTheme file to CSS + JS + .d.ts (and an optional- * `.variants.d.ts`). Performs the writes and returns a `theme.build` receipt,+ * Compile a defineTheme file to CSS + CSS .d.ts + JS + JS .d.ts (and an+ * optional `.variants.d.ts`). Performs the writes and returns a `theme.build` receipt,* or `null` when the theme produced no CSS (nothing to build). Throws* AstryxError (stable code) on failure. Progress is emitted through the shared* `logger` (silent by default).@@ -2836,6 +2824,7 @@ async function themeBuildInternal(// was left as orphaned half-built output. Stage-then-commit avoids// that.const outDir = path.dirname(outPath);+ const cssDtsPath = `${outPath}.d.ts`;const jsPath = path.join(outDir, `${baseName}.js`);const dtsPath = path.join(outDir, `${baseName}.d.ts`);@@ -2859,6 +2848,9 @@ async function themeBuildInternal(// importing the theme also loads the custom-variant augmentations.const cssContent =generatedHeader(sourceRelative, 'css', buildCommand, versions) + css;+ const cssDtsContent =+ generatedHeader(sourceRelative, 'ts', buildCommand, versions) ++ 'export {};\n';const jsContent =generatedHeader(sourceRelative, 'js', buildCommand, versions) +generateBuiltModule(@@ -2900,6 +2892,7 @@ async function themeBuildInternal(const writes = [{dest: outPath, content: cssContent},+ {dest: cssDtsPath, content: cssDtsContent, allowMissingInCheck: true},{dest: jsPath, content: jsContent},{dest: dtsPath, content: dtsContent},];@@ -2933,7 +2926,7 @@ async function themeBuildInternal(name: themeDef.name,upToDate,stale,- checked: writes.map(w => path.relative(cwd, w.dest)),+ checked: checkedBuildOutputs(writes, cwd),},};}@@ -2941,6 +2934,7 @@ async function themeBuildInternal(writeBuildOutputs(writes);logger.log(`\n[ok] ${path.relative(cwd, outPath)}`);+ logger.log(`[ok] ${path.relative(cwd, cssDtsPath)}`);logger.log(` ${tokenCount} token overrides, ${componentCount} component overrides`,);@@ -3009,6 +3003,7 @@ Or with a <link> tag:sizeKB: parseFloat(size),outputs: {css: path.relative(cwd, outPath),+ cssDts: path.relative(cwd, cssDtsPath),js: path.relative(cwd, jsPath),dts: path.relative(cwd, dtsPath),...(variantDecl && variantDtsPath@@ -3174,6 +3169,7 @@ export async function themeBuildFamily(const root = members[0];const outDir = path.dirname(root.filePath);const outPath = path.join(outDir, `${baseName}.css`);+ const cssDtsPath = `${outPath}.d.ts`;const jsPath = path.join(outDir, `${baseName}.js`);const dtsPath = path.join(outDir, `${baseName}.d.ts`);const sources = new Set(@@ -3183,7 +3179,7 @@ export async function themeBuildFamily(),),);- const collision = [outPath, jsPath, dtsPath].find(output => {+ const collision = [outPath, cssDtsPath, jsPath, dtsPath].find(output => {const candidates = [path.resolve(output)];if (fs.existsSync(output)) candidates.push(fs.realpathSync(output));return candidates.some(value => sources.has(value.toLowerCase()));@@ -3267,6 +3263,13 @@ export async function themeBuildFamily(generatedHeader(sourceRelative, 'css', buildCommand, root.versions) +css,},+ {+ dest: cssDtsPath,+ allowMissingInCheck: true,+ content:+ generatedHeader(sourceRelative, 'ts', buildCommand, root.versions) ++ 'export {};\n',+ },{dest: jsPath,content:@@ -3282,6 +3285,7 @@ export async function themeBuildFamily(];const outputs = {css: path.relative(cwd, outPath),+ cssDts: path.relative(cwd, cssDtsPath),js: path.relative(cwd, jsPath),dts: path.relative(cwd, dtsPath),};@@ -3309,7 +3313,7 @@ export async function themeBuildFamily(name: root.theme.name,upToDate,stale,- checked: writes.map(write => path.relative(cwd, write.dest)),+ checked: checkedBuildOutputs(writes, cwd),},};}diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjsindex 2e5a5c3187..35e2a2239a 100644--- a/packages/cli/api/theme/build/build.test.mjs+++ b/packages/cli/api/theme/build/build.test.mjs@@ -74,11 +74,13 @@ describe('themeBuild() — receipt', () => {// Output paths are cwd-relative and derive from the theme name…expect(result?.data.outputs.css).toBe('apitheme.css');+ expect(result?.data.outputs.cssDts).toBe('apitheme.css.d.ts');expect(result?.data.outputs.js).toBe('apitheme.js');expect(result?.data.outputs.dts).toBe('apitheme.d.ts');// …and every declared output actually exists on disk.for (const rel of [result?.data.outputs.css,+ result?.data.outputs.cssDts,result?.data.outputs.js,result?.data.outputs.dts,]) {@@ -86,6 +88,9 @@ describe('themeBuild() — receipt', () => {fs.existsSync(path.join(tmpDir, /** @type {string} */ (rel))),).toBe(true);}+ expect(+ fs.readFileSync(path.join(tmpDir, 'apitheme.css.d.ts'), 'utf8'),+ ).toContain('export {};');});it('emits local tokens and preserves enrollment metadata in the built module', async () => {@@ -377,6 +382,31 @@ describe('themeBuild() — check mode', () => {expect(fs.readFileSync(path.join(tmpDir, 'chk.css'), 'utf8')).toBe(before);});+ it('accepts released outputs that do not have a CSS type stub', async () => {+ const themeFile = path.join(tmpDir, 'released.mjs');+ fs.writeFileSync(+ themeFile,+ `export default { name: 'released', tokens: { '--color-bg': '#0a0a0a' } };\n`,+ );+ await themeBuild('released.mjs', {}, {cwd: tmpDir});+ fs.rmSync(path.join(tmpDir, 'released.css.d.ts'));++ const result = await themeBuild(+ 'released.mjs',+ {check: true},+ {cwd: tmpDir},+ );++ expect(result?.data.upToDate).toBe(true);+ expect(result?.data.stale).toEqual([]);+ expect(result?.data.checked).toEqual([+ 'released.css',+ 'released.js',+ 'released.d.ts',+ ]);+ expect(fs.existsSync(path.join(tmpDir, 'released.css.d.ts'))).toBe(false);+ });+it('flags a stale output when the committed CSS content drifts from the source', async () => {const themeFile = path.join(tmpDir, 'drift.mjs');fs.writeFileSync(diff --git a/packages/cli/api/theme/eject/eject.binary.test.mjs b/packages/cli/api/theme/eject/eject.binary.test.mjsnew file mode 100644index 0000000000..ac57f80356--- /dev/null+++ b/packages/cli/api/theme/eject/eject.binary.test.mjs@@ -0,0 +1,90 @@+// 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 {themeEject} from './eject.mjs';++const HEADER = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n';++let tmpDir;++/** Every byte value, so any lossy text decoding shows up as a changed file. */+const FONT_BYTES = Buffer.concat([+ Buffer.from('wOF2'),+ Buffer.from(Array.from({length: 256}, (_, byte) => byte)),+]);++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-binary-'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ dependencies: {'@acme/themes': '^1.0.0'},+ }),+ );+ const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'themes');+ const themeDir = path.join(packageDir, 'themes', 'ocean');+ fs.mkdirSync(path.join(themeDir, 'fonts'), {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: '@acme/themes', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.doc.mjs'),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Integration theme that ships a font.', maintained: true};+`,+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.ts'),+ `${HEADER}export const oceanTheme = {};\n`,+ );+ fs.writeFileSync(path.join(themeDir, 'fonts', 'ocean.woff2'), FONT_BYTES);+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('themeEject copies every file of the theme', () => {+ it('copies a binary file byte for byte', async () => {+ const result = await themeEject('ocean', {+ cwd: tmpDir,+ package: '@acme/themes',+ });++ expect(result.data.files).toEqual([+ 'oceanTheme.ts',+ 'oceanTheme.doc.mjs',+ 'fonts/ocean.woff2',+ ]);+ const copied = fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'fonts', 'ocean.woff2'),+ );+ expect(copied.equals(FONT_BYTES)).toBe(true);+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.doc.mjs'),+ 'utf-8',+ ),+ ).toContain('maintained: false');+ });++ it('still strips the repo header from a text source', async () => {+ await themeEject('ocean', {cwd: tmpDir, package: '@acme/themes'});++ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.ts'),+ 'utf-8',+ ),+ ).toBe('export const oceanTheme = {};\n');+ });+});diff --git a/packages/cli/api/theme/eject/eject.mjs b/packages/cli/api/theme/eject/eject.mjsnew file mode 100644index 0000000000..6af641d7b2--- /dev/null+++ b/packages/cli/api/theme/eject/eject.mjs@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx theme eject` leaf — selects an available theme and delegates+ * its atomic source-copy transaction to the app-theme adapter.+ */++import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {ejectThemeFiles, findTheme, listAvailableThemes} from '../_adapter.mjs';++/**+ * Copy a bundled or installed theme's complete source inventory into the+ * consumer project as an independent local fork.+ *+ * @param {string} slug+ * @param {{targetPath?: string, overwrite?: boolean, cwd?: string, package?: string}} [options]+ * @returns {Promise<import('../theme.type.mjs').ThemeEjectResponse>}+ */+export async function themeEject(slug, options = {}) {+ const {+ targetPath,+ overwrite = false,+ cwd = process.cwd(),+ package: packageName,+ } = options;++ const match = await findTheme(slug, {+ cwd,+ package: packageName,+ includeLocal: false,+ });+ if (!match) {+ const available = await listAvailableThemes(cwd, {includeLocal: false});+ throw new AstryxError(+ `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 outputDir = ejectThemeFiles(match, {+ cwd,+ targetPath,+ overwrite,+ });+ return {+ type: 'theme.eject',+ data: {+ slug: match.slug,+ displayName: match.displayName,+ maintained: match.maintained,+ package: match.package,+ outputDir,+ entry: match.entry,+ exportName: match.exportName,+ files: match.files,+ },+ };+}diff --git a/packages/cli/api/theme/eject/eject.rollback.test.mjs b/packages/cli/api/theme/eject/eject.rollback.test.mjsnew file mode 100644index 0000000000..0a7d213051--- /dev/null+++ b/packages/cli/api/theme/eject/eject.rollback.test.mjs@@ -0,0 +1,158 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * `theme eject` writes a theme as one transaction: when a later file fails to+ * publish, every file it already replaced gets its previous bytes back and+ * every file it created is removed. Publishing is forced to fail by wrapping+ * the two calls that publish a staged file: `linkSync` for a new file and+ * `renameSync` for a replacement.+ *+ * Separate file because vi.mock is hoisted and affects the whole module.+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import * as os from 'node:os';+import * as path from 'node:path';++const failures = vi.hoisted(() => ({+ /** Fail the Nth staged-file publish (1-based); 0 disables. */+ publish: 0,+ /** Also fail every rollback restore. */+ restore: false,+ count: 0,+}));++vi.mock('node:fs', async importOriginal => {+ const actual = /** @type {typeof import('node:fs')} */ (+ await importOriginal()+ );+ /** @param {string} source */+ const isStaged = source => path.basename(String(source)).includes('.tmp');+ /** @param {string} source */+ const isRestore = source =>+ path.basename(String(source)).includes('.restore-');+ /** @param {string} source @param {string} op */+ const maybeFail = (source, op) => {+ if (isStaged(source) && failures.publish > 0) {+ failures.count++;+ if (failures.count === failures.publish) {+ throw Object.assign(new Error(`EIO: forced ${op} failure`), {+ code: 'EIO',+ });+ }+ }+ if (isRestore(source) && failures.restore) {+ throw Object.assign(new Error(`EIO: forced restore failure`), {+ code: 'EIO',+ });+ }+ };+ return {+ ...actual,+ linkSync: vi.fn((source, destination) => {+ maybeFail(source, 'link');+ return actual.linkSync(source, destination);+ }),+ renameSync: vi.fn((source, destination) => {+ maybeFail(source, 'rename');+ return actual.renameSync(source, destination);+ }),+ };+});++const fs = await import('node:fs');+const {themeEject} = await import('./eject.mjs');+const {listThemes} = await import('../_adapter.mjs');++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-rollback-'));+ failures.publish = 0;+ failures.restore = false;+ failures.count = 0;+});++afterEach(() => {+ failures.publish = 0;+ failures.restore = false;+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++function stoneFiles() {+ const theme = listThemes().find(entry => entry.slug === 'stone');+ if (!theme) throw new Error('missing bundled theme stone');+ expect(theme.files.length).toBeGreaterThanOrEqual(2);+ return theme.files.map(name =>+ path.join(tmpDir, 'src', 'themes', 'stone', name),+ );+}++/** Entries staging or rollback left behind in the theme directory. */+function strays() {+ const dir = path.join(tmpDir, 'src', 'themes', 'stone');+ if (!fs.existsSync(dir)) return [];+ return fs+ .readdirSync(dir, {recursive: true})+ .map(String)+ .filter(name => name.includes('.tmp') || name.includes('.restore-'));+}++describe('themeEject rolls back a partial write', () => {+ it('removes every created file when the second publish fails', async () => {+ const files = stoneFiles();+ failures.publish = 2;++ await expect(themeEject('stone', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_WRITE_FAILED',+ });++ for (const file of files) expect(fs.existsSync(file)).toBe(false);+ expect(strays()).toEqual([]);+ });++ it('restores every replaced byte when the second publish fails', async () => {+ const files = stoneFiles();+ fs.mkdirSync(path.dirname(files[0]), {recursive: true});+ const before = Buffer.from([0x00, 0xff, 0x0a, 0x62, 0x65, 0x66]);+ fs.writeFileSync(files[0], before);+ failures.publish = 2;++ await expect(+ themeEject('stone', {cwd: tmpDir, overwrite: true}),+ ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});++ expect(fs.readFileSync(files[0]).equals(before)).toBe(true);+ for (const file of files.slice(1)) expect(fs.existsSync(file)).toBe(false);+ expect(strays()).toEqual([]);+ });++ it('names a file it could not restore', async () => {+ const files = stoneFiles();+ fs.mkdirSync(path.dirname(files[0]), {recursive: true});+ fs.writeFileSync(files[0], 'before\n');+ failures.publish = 2;+ failures.restore = true;++ let error;+ try {+ await themeEject('stone', {cwd: tmpDir, overwrite: true});+ } catch (caught) {+ error = caught;+ }++ expect(error?.code).toBe('ERR_WRITE_FAILED');+ expect(error?.message).toContain('Could not restore');+ expect(error?.message).toContain(files[0]);+ });++ it('writes every file when nothing fails', async () => {+ const files = stoneFiles();++ const result = await themeEject('stone', {cwd: tmpDir});++ expect(result.type).toBe('theme.eject');+ for (const file of files) expect(fs.existsSync(file)).toBe(true);+ expect(strays()).toEqual([]);+ });+});diff --git a/packages/cli/api/theme/eject/eject.staging.test.mjs b/packages/cli/api/theme/eject/eject.staging.test.mjsnew file mode 100644index 0000000000..472c070b7a--- /dev/null+++ b/packages/cli/api/theme/eject/eject.staging.test.mjs@@ -0,0 +1,83 @@+// 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 {themeEject} from './eject.mjs';+import {listThemes} from '../_adapter.mjs';++let tmpDir;+let outsideDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-staging-'));+ outsideDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-themeeject-outside-'),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+ fs.rmSync(outsideDir, {recursive: true, force: true});+});++/**+ * Where `theme eject` writes the first file of `slug`.+ * @param {string} slug+ */+function firstDestination(slug) {+ const theme = listThemes().find(entry => entry.slug === slug);+ if (!theme) throw new Error(`missing bundled theme ${slug}`);+ const dest = path.join(tmpDir, 'src', 'themes', slug, theme.files[0]);+ fs.mkdirSync(path.dirname(dest), {recursive: true});+ return dest;+}++// Staging names are unpredictable and created exclusively, so an entry planted+// at a predictable name beside the destination is never written through.+describe('themeEject staging writes stay inside the project', () => {+ it('never writes through a link planted at a predictable staging name', async () => {+ const victim = path.join(outsideDir, 'victim.txt');+ fs.writeFileSync(victim, 'outside\n');+ const dest = firstDestination('stone');+ fs.symlinkSync(victim, `${dest}.${process.pid}.tmp`);++ await themeEject('stone', {cwd: tmpDir});++ expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');+ expect(fs.lstatSync(dest).isFile()).toBe(true);+ });++ it('never creates a file through a dangling link at a predictable staging name', async () => {+ const victim = path.join(outsideDir, 'created.txt');+ fs.symlinkSync(victim, `${firstDestination('stone')}.${process.pid}.tmp`);++ await themeEject('stone', {cwd: tmpDir});++ expect(fs.existsSync(victim)).toBe(false);+ });++ it('refuses to replace a destination that links outside the project', async () => {+ const victim = path.join(outsideDir, 'victim.txt');+ fs.writeFileSync(victim, 'outside\n');+ const dest = firstDestination('stone');+ fs.symlinkSync(victim, dest);++ await expect(+ themeEject('stone', {cwd: tmpDir, overwrite: true}),+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});+ expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');+ expect(fs.lstatSync(dest).isSymbolicLink()).toBe(true);+ });++ it('never creates a file through a dangling destination link', async () => {+ const victim = path.join(outsideDir, 'created.txt');+ fs.symlinkSync(victim, firstDestination('stone'));++ await expect(themeEject('stone', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_PATH_TRAVERSAL',+ });+ expect(fs.existsSync(victim)).toBe(false);+ });+});diff --git a/packages/cli/api/theme/eject/eject.test.mjs b/packages/cli/api/theme/eject/eject.test.mjsnew file mode 100644index 0000000000..c0ee885857--- /dev/null+++ b/packages/cli/api/theme/eject/eject.test.mjs@@ -0,0 +1,160 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Direct-API tests for the `theme eject` leaf. Copies real bundled themes+ * into a tmp cwd and asserts the receipt + on-disk effects, plus the guard rails+ * (unknown slug, no-overwrite, path traversal). Uses the maintained `neutral`+ * theme so the fixture stays stable.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {themeEject} from './eject.mjs';++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('themeEject (api/theme/eject)', () => {+ it('keeps the released CLI package selector while ejecting bundled source', async () => {+ const result = await themeEject('neutral', {+ cwd: tmpDir,+ package: '@astryxdesign/cli',+ });+ expect(result.type).toBe('theme.eject');+ expect(result.data.slug).toBe('neutral');+ expect(result.data.package).toBe('@astryxdesign/cli');+ expect(result.data.outputDir).toBe(path.join('src', 'themes', 'neutral'));+ // The complete local theme shape includes its same-stem descriptor.+ expect(result.data.files).toEqual([+ 'neutralTheme.ts',+ 'neutralTheme.doc.mjs',+ 'icons.tsx',+ 'neutralPalettes.ts',+ 'neutralPalettes.generated.ts',+ 'neutralPaletteRefs.generated.ts',+ 'neutralPalettes.generated.receipt.json',+ 'palette.config.json',+ ]);+ expect(+ fs.readdirSync(path.join(tmpDir, 'src', 'themes', 'neutral')).sort(),+ ).toEqual([...result.data.files].sort());+ for (const f of result.data.files) {+ expect(+ fs.existsSync(path.join(tmpDir, 'src', 'themes', 'neutral', f)),+ ).toBe(true);+ }+ expect(+ fs.readFileSync(+ path.join(+ tmpDir,+ result.data.outputDir,+ 'neutralTheme.doc.mjs',+ ),+ 'utf-8',+ ),+ ).toContain('maintained: false');+ });++ it('copies every relative import required by the scaffolded theme', async () => {+ const result = await themeEject('neutral', {cwd: tmpDir});+ const outputDir = path.join(tmpDir, result.data.outputDir);+ const relativeImports = /from\s+['"](\.\.?\/[^'"]+)['"]/g;++ for (const file of result.data.files) {+ if (!/\.(?:ts|tsx|mjs)$/.test(file)) continue;+ const source = fs.readFileSync(path.join(outputDir, file), 'utf-8');+ for (const [, specifier] of source.matchAll(relativeImports)) {+ const imported = path.resolve(outputDir, path.dirname(file), specifier);+ expect(+ fs.existsSync(imported) ||+ fs.existsSync(`${imported}.ts`) ||+ fs.existsSync(`${imported}.tsx`) ||+ fs.existsSync(`${imported}.mjs`),+ ).toBe(true);+ }+ }+ });++ it('strips the Meta copyright header from copied files', async () => {+ const result = await themeEject('neutral', {cwd: tmpDir});+ const first = path.join(+ tmpDir,+ result.data.outputDir,+ result.data.files[0],+ );+ expect(fs.readFileSync(first, 'utf-8')).not.toMatch(+ /Copyright \(c\) Meta Platforms/,+ );+ });++ it('resolves the slug case-insensitively', async () => {+ const result = await themeEject('Neutral', {cwd: tmpDir});+ expect(result.data.slug).toBe('neutral');+ });++ it('honors an explicit target path (within cwd)', async () => {+ const result = await themeEject('neutral', {+ cwd: tmpDir,+ targetPath: 'themes/mine',+ });+ expect(result.data.outputDir).toBe(path.join('themes', 'mine'));+ expect(+ fs.existsSync(path.join(tmpDir, 'themes', 'mine', result.data.files[0])),+ ).toBe(true);+ });++ it('throws ERR_UNKNOWN_THEME for an unknown slug (with suggestions)', async () => {+ await expect(+ themeEject('does-not-exist', {cwd: tmpDir}),+ ).rejects.toMatchObject({code: 'ERR_UNKNOWN_THEME'});+ });++ it('refuses to overwrite existing files without overwrite', async () => {+ await themeEject('neutral', {cwd: tmpDir});+ await expect(themeEject('neutral', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_FILE_EXISTS',+ });+ });++ it('replaces files when overwrite is set', async () => {+ await themeEject('neutral', {cwd: tmpDir});+ const result = await themeEject('neutral', {cwd: tmpDir, overwrite: true});+ expect(result.type).toBe('theme.eject');+ });++ it('rejects a target path that escapes cwd', async () => {+ await expect(+ themeEject('neutral', {cwd: tmpDir, targetPath: '../escape'}),+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});+ });++ it('surfaces ERR_WRITE_FAILED (not a raw errno) when the target path is an existing file', async () => {+ fs.writeFileSync(path.join(tmpDir, 'blocker'), 'x');+ await expect(+ themeEject('neutral', {cwd: tmpDir, targetPath: 'blocker'}),+ ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});+ });++ it('surfaces ERR_WRITE_FAILED when an ancestor of the default dir is a file', async () => {+ // A file named `src` blocks mkdir of src/themes/neutral (ENOTDIR).+ fs.writeFileSync(path.join(tmpDir, 'src'), 'x');+ await expect(themeEject('neutral', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_WRITE_FAILED',+ });+ });++ it('ejects into an existing empty target directory', async () => {+ fs.mkdirSync(path.join(tmpDir, 'mydir'));+ const r = await themeEject('neutral', {cwd: tmpDir, targetPath: 'mydir'});+ expect(r.data.outputDir).toBe('mydir');+ });+});diff --git a/packages/cli/api/theme/integration-themes.test.mjs b/packages/cli/api/theme/integration-themes.test.mjsindex c9fbd88733..42ce0870cb 100644--- a/packages/cli/api/theme/integration-themes.test.mjs+++ b/packages/cli/api/theme/integration-themes.test.mjs@@ -4,6 +4,7 @@ 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';+import {themeEject} from './eject/eject.mjs';let tmpDir;@@ -16,9 +17,17 @@ function installThemeIntegration(packageName, slug, source, extraFiles = {}) {const themeDir = path.join(packageDir, 'themes', slug);const stem = `${slug.replace(/-([a-z0-9])/gu, (_, character) => character.toUpperCase())}Theme`;fs.mkdirSync(themeDir, {recursive: true});+ fs.mkdirSync(path.join(packageDir, 'dist'), {recursive: true});fs.writeFileSync(path.join(packageDir, 'package.json'),- JSON.stringify({name: packageName, version: '1.0.0'}),+ JSON.stringify({+ name: packageName,+ version: '1.0.0',+ exports: {+ [`./themes/${slug}`]: `./dist/${slug}.js`,+ [`./themes/${slug}.css`]: `./dist/${slug}.css`,+ },+ }),);fs.writeFileSync(path.join(packageDir, 'astryx.integration.mjs'),@@ -37,6 +46,14 @@ export default {type: 'theme', name: '${slug}', displayName: '${slug === 'neutra`export const ${stem} = {};`,);+ fs.writeFileSync(+ path.join(packageDir, 'dist', `${slug}.js`),+ `export const ${stem} = {name: '${slug}', __built: true};\n`,+ );+ fs.writeFileSync(+ path.join(packageDir, 'dist', `${slug}.css`),+ `[data-astryx-theme="${slug}"] {}\n`,+ );for (const [relativePath, contents] of Object.entries(extraFiles)) {const file = path.join(themeDir, relativePath);fs.mkdirSync(path.dirname(file), {recursive: true});@@ -61,10 +78,10 @@ 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 () => {+describe('package and integration themes', () => {+ it('ejects source from an installed integration and records its owner', async () => {installThemeIntegration('@acme/themes', 'ocean');- const result = await themeAdd('ocean', {cwd: tmpDir});+ const result = await themeEject('ocean', {cwd: tmpDir});expect(result.data.package).toBe('@acme/themes');expect(result.data.outputDir).toBe(path.join('src', 'themes', 'ocean'));@@ -101,6 +118,12 @@ describe('themeAdd with integration themes', () => {'utf-8',),).toContain("type: 'theme'");+ expect(+ fs.readFileSync(+ path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.doc.mjs'),+ 'utf-8',+ ),+ ).toContain('maintained: true');expect(fs.readFileSync(path.join(tmpDir, 'src', 'themes', 'ocean', 'tokens', 'colors.ts'),@@ -134,7 +157,7 @@ describe('themeAdd with integration themes', () => {process.platform === 'win32' ? 'junction' : 'dir',);- await expect(themeAdd('ocean', {cwd: tmpDir})).rejects.toMatchObject({+ await expect(themeEject('ocean', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL',});expect(fs.existsSync(path.join(outsideDir, 'colors.ts'))).toBe(false);@@ -152,9 +175,10 @@ describe('themeAdd with integration themes', () => {});const result = await themeAdd('neutral', {cwd: tmpDir,+ import: true,package: '@acme/themes',});- expect(result.data.package).toBe('@acme/themes');+ expect(result.data.themes[0]?.owner).toBe('@acme/themes');});it('reports a selected installed package with a corrupted theme directory', async () => {diff --git a/packages/cli/api/theme/list/list.mjs b/packages/cli/api/theme/list/list.mjsindex ca59bd028a..85ab285c5e 100644--- a/packages/cli/api/theme/list/list.mjs+++ b/packages/cli/api/theme/list/list.mjs@@ -1,12 +1,27 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import * as path from 'node:path';+/*** @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.+ * bundled-only API contract. `themeListCopySources()` preserves the released+ * `theme add --list` fields. `themeListAvailable()` is the project-aware command+ * seam that adds installed integration themes, local themes, and app state.*/-import {listAvailableThemes, listThemes} from '../_adapter.mjs';+import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';+import {+ listAvailableThemes,+ listThemes,+ listUnmigratedThemeCopies,+ readThemeListState,+ themeRecordOwner,+} from '../_adapter.mjs';++/** @param {string} root @param {string} file */+function pathForProject(root, file) {+ return path.relative(root, file).split(path.sep).join('/');+}/*** List themes bundled with this CLI build.@@ -25,16 +40,20 @@ export function themeList() {}/**- * List bundled and installed integration themes available to this project.+ * Preserve the released `theme add --list` projection. It lists bundled and+ * package source themes only, without local themes or generated app state.* @param {{cwd?: string, package?: string}} [options]* @returns {Promise<import('../theme.type.mjs').ThemeListResponse>}*/-export async function themeListAvailable(options = {}) {- const themes = await listAvailableThemes(options.cwd);+export async function themeListCopySources(options = {}) {+ const cwd = options.cwd ?? process.cwd();+ const themes = await listAvailableThemes(cwd, {includeLocal: false});return {type: 'theme.list',data: themes- .filter(theme => options.package == null || theme.package === options.package)+ .filter(+ theme => options.package == null || theme.package === options.package,+ ).map(theme => ({slug: theme.slug,displayName: theme.displayName,@@ -44,3 +63,52 @@ export async function themeListAvailable(options = {}) {})),};}++/**+ * 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 cwd = options.cwd ?? process.cwd();+ const state = readThemeListState(cwd);+ const themes = await listAvailableThemes(cwd);+ const data = themes+ .filter(+ theme => options.package == null || theme.package === options.package,+ )+ .map(theme => {+ const added = state.themes[theme.slug] === themeRecordOwner(theme);+ return {+ slug: theme.slug,+ displayName: theme.displayName,+ description: theme.description,+ maintained: theme.maintained,+ package: theme.package,+ added,+ default: added && state.defaultSlug === theme.slug,+ source: theme.source,+ };+ });+ const upgradeCommand = `${getCliInvocation(state.projectDir)} upgrade --from 0.6.4 --path . --apply`;+ const unmigratedCopies = (+ options.package == null ? listUnmigratedThemeCopies(state.projectDir) : []+ ).map(copy => ({+ slug: copy.slug,+ path: pathForProject(state.projectDir, copy.sourceDir),+ source: pathForProject(+ state.projectDir,+ path.join(copy.sourceDir, copy.entry),+ ),+ descriptor: pathForProject(+ state.projectDir,+ path.join(copy.sourceDir, copy.descriptor),+ ),+ upgradeCommand,+ }));+ return {+ type: 'theme.list',+ data,+ ...(unmigratedCopies.length > 0 ? {meta: {unmigratedCopies}} : {}),+ };+}diff --git a/packages/cli/api/theme/list/list.test.mjs b/packages/cli/api/theme/list/list.test.mjsindex 25dd497816..b83606c2bf 100644--- a/packages/cli/api/theme/list/list.test.mjs+++ b/packages/cli/api/theme/list/list.test.mjs@@ -3,8 +3,12 @@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 {+ themeList,+ themeListAvailable,+ themeListCopySources,+} from './list.mjs';+import {renderThemeModule} from '../../../foundation/config/theme-state.mjs';let tmpDir;@@ -68,13 +72,51 @@ describe('themeList (bundled compatibility API)', () => {});});+describe('themeListCopySources (theme add --list compatibility API)', () => {+ it('keeps the released fields and excludes local app themes', async () => {+ installThemeIntegration();+ const localDir = path.join(tmpDir, 'src', 'themes', 'local-only');+ fs.mkdirSync(localDir, {recursive: true});+ fs.writeFileSync(+ path.join(localDir, 'localOnlyTheme.doc.mjs'),+ "export default {type:'theme',name:'local-only',displayName:'Local only',description:'App theme.',maintained:false};\n",+ );+ fs.writeFileSync(+ path.join(localDir, 'localOnlyTheme.ts'),+ 'export const localOnlyTheme = {};\n',+ );++ const result = await themeListCopySources({cwd: tmpDir});++ expect(result.type).toBe('theme.list');+ expect(result.data).toContainEqual({+ slug: 'ocean',+ displayName: 'Ocean',+ description: 'Blue and calm.',+ maintained: true,+ package: '@acme/themes',+ });+ expect(result.data.some(theme => theme.slug === 'local-only')).toBe(false);+ expect(Object.keys(result.data[0] ?? {}).sort()).toEqual([+ 'description',+ 'displayName',+ 'maintained',+ 'package',+ 'slug',+ ]);+ });+});+describe('themeListAvailable (project-aware API)', () => {- it('returns bundled themes with owner package', async () => {+ it('returns bundled themes with the released selector 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),+ result.data.some(+ theme =>+ theme.source === 'bundled' && theme.package === '@astryxdesign/cli',+ ),).toBe(true);});@@ -87,6 +129,9 @@ describe('themeListAvailable (project-aware API)', () => {description: 'Blue and calm.',maintained: true,package: '@acme/themes',+ added: false,+ default: false,+ source: 'package',});});@@ -103,18 +148,124 @@ describe('themeListAvailable (project-aware API)', () => {description: 'Blue and calm.',maintained: true,package: '@acme/themes',+ added: false,+ default: false,+ source: 'package',},]);});+ it('shows same-slug local and package themes with independent app fields', async () => {+ installThemeIntegration('@acme/themes', 'sea-glass');+ const localDir = path.join(tmpDir, 'src', 'themes', 'sea-glass');+ fs.mkdirSync(localDir, {recursive: true});+ fs.writeFileSync(+ path.join(localDir, 'seaGlassTheme.doc.mjs'),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type:'theme',name:'sea-glass',displayName:'Local Sea Glass',description:'Local fork.',maintained:false};\n`,+ );+ fs.writeFileSync(+ path.join(localDir, 'seaGlassTheme.ts'),+ 'export const seaGlassTheme = {};\n',+ );+ fs.writeFileSync(+ path.join(tmpDir, 'src', 'astryx-themes.js'),+ renderThemeModule(+ [+ {+ slug: 'sea-glass',+ owner: '@acme/themes',+ exportName: 'seaGlassTheme',+ module: '@acme/themes/themes/sea-glass',+ stylesheet: '@acme/themes/themes/sea-glass.css',+ moduleFile: '',+ stylesheetFile: '',+ source: 'package',+ },+ ],+ 'sea-glass',+ false,+ ),+ );++ const result = await themeListAvailable({cwd: tmpDir});+ const matches = result.data.filter(theme => theme.slug === 'sea-glass');++ expect(matches).toEqual([+ expect.objectContaining({+ package: './src/themes',+ source: 'local',+ added: false,+ default: false,+ }),+ expect.objectContaining({+ package: '@acme/themes',+ source: 'package',+ added: true,+ default: true,+ }),+ ]);+ });++ it('reports a released descriptor-less copy without listing it as a theme', async () => {+ const copyDir = path.join(tmpDir, 'src', 'themes', 'ocean');+ fs.mkdirSync(copyDir, {recursive: true});+ fs.writeFileSync(+ path.join(copyDir, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',+ );++ const result = await themeListAvailable({cwd: tmpDir});++ expect(+ result.data.some(+ theme => theme.slug === 'ocean' && theme.source === 'local',+ ),+ ).toBe(false);+ expect(result.meta?.unmigratedCopies).toEqual([+ {+ slug: 'ocean',+ path: 'src/themes/ocean',+ source: 'src/themes/ocean/oceanTheme.ts',+ descriptor: 'src/themes/ocean/oceanTheme.doc.mjs',+ upgradeCommand: expect.stringContaining(+ 'upgrade --from 0.6.4 --path . --apply',+ ),+ },+ ]);+ });++ it('always discovers local themes under src/themes, not a root themes folder', async () => {+ const rootTheme = path.join(tmpDir, 'themes', 'ocean');+ fs.mkdirSync(rootTheme, {recursive: true});+ fs.writeFileSync(+ path.join(rootTheme, 'oceanTheme.doc.mjs'),+ "export default {type:'theme',name:'ocean',displayName:'Wrong root',description:'',maintained:false};\n",+ );+ fs.writeFileSync(+ path.join(rootTheme, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',+ );++ const result = await themeListAvailable({cwd: tmpDir});++ expect(+ result.data.some(+ theme => theme.slug === 'ocean' && theme.source === 'local',+ ),+ ).toBe(false);+ });+it('projects only public list fields', async () => {const [first] = (await themeListAvailable({cwd: tmpDir})).data;expect(Object.keys(first ?? {}).sort()).toEqual([+ 'added',+ 'default','description','displayName','maintained','package','slug',+ 'source',]);});});diff --git a/packages/cli/api/theme/remove/remove.mjs b/packages/cli/api/theme/remove/remove.mjsnew file mode 100644index 0000000000..26dcd7add9--- /dev/null+++ b/packages/cli/api/theme/remove/remove.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file `astryx theme remove` — stop importing one non-default app theme. */++import {removeThemeFromApp} from '../_adapter.mjs';++/**+ * Remove one added non-default theme and regenerate the app module.+ * @param {string} slug+ * @param {{cwd?: string}} [options]+ * @returns {Promise<import('../theme.type.mjs').ThemeAppResponse>}+ */+export function themeRemove(slug, options = {}) {+ return removeThemeFromApp(slug, options);+}diff --git a/packages/cli/api/theme/remove/remove.test.mjs b/packages/cli/api/theme/remove/remove.test.mjsnew file mode 100644index 0000000000..e00cb005d8--- /dev/null+++ b/packages/cli/api/theme/remove/remove.test.mjs@@ -0,0 +1,94 @@+// 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';+import {themeRemove} from './remove.mjs';+import {parseThemeModuleRecord} from '../../../foundation/config/theme-state.mjs';++let tmpDir;++function installThemes() {+ const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'themes');+ fs.mkdirSync(path.join(packageDir, 'themes'), {recursive: true});+ fs.mkdirSync(path.join(packageDir, 'dist'), {recursive: true});+ const exports = {};+ for (const slug of ['ocean', 'reef']) {+ const sourceDir = path.join(packageDir, 'themes', slug);+ fs.mkdirSync(sourceDir);+ exports[`./themes/${slug}`] = `./dist/${slug}.js`;+ exports[`./themes/${slug}.css`] = `./dist/${slug}.css`;+ fs.writeFileSync(+ path.join(sourceDir, `${slug}Theme.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type:'theme',name:'${slug}',displayName:'${slug}',description:'${slug}',maintained:true};\n`,+ );+ fs.writeFileSync(+ path.join(sourceDir, `${slug}Theme.ts`),+ `export const ${slug}Theme = {};\n`,+ );+ fs.writeFileSync(+ path.join(packageDir, `dist/${slug}.js`),+ `export const ${slug}Theme = {name:'${slug}',__built:true};\n`,+ );+ fs.writeFileSync(path.join(packageDir, `dist/${slug}.css`), '/* css */\n');+ }+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: '@acme/themes', version: '1.0.0', exports}),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes:'./themes'};\n",+ );+}++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-theme-remove-'));+ fs.mkdirSync(path.join(tmpDir, 'src'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@acme/themes': '^1.0.0'}}),+ );+ fs.writeFileSync(path.join(tmpDir, 'tsconfig.json'), '{}\n');+ installThemes();+ await themeAdd('ocean', {cwd: tmpDir, import: true, package: '@acme/themes'});+ await themeAdd('reef', {cwd: tmpDir, import: true, package: '@acme/themes'});+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('themeRemove', () => {+ it('removes a non-default theme and regenerates the module', async () => {+ const result = await themeRemove('ReEf', {cwd: tmpDir});+ expect(result).toMatchObject({+ type: 'theme.app',+ data: {+ default: 'ocean',+ change: {action: 'remove', slug: 'reef', changed: true},+ },+ });+ expect(result.data.themes.map(theme => theme.slug)).toEqual(['ocean']);+ expect(+ parseThemeModuleRecord(+ fs.readFileSync(path.join(tmpDir, 'src/astryx-themes.ts'), 'utf-8'),+ ),+ ).toEqual({themes: {ocean: '@acme/themes'}, defaultSlug: 'ocean'});+ });++ it('refuses to remove the default and names theme use', async () => {+ await expect(themeRemove('ocean', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_THEME_INVALID',+ message: expect.stringContaining('astryx theme use'),+ });+ });++ it('names theme add when the slug is not added', async () => {+ await expect(themeRemove('missing', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_UNKNOWN_THEME',+ message: expect.stringContaining('astryx theme add missing --import'),+ });+ });+});diff --git a/packages/cli/api/theme/template/template.mjs b/packages/cli/api/theme/template/template.mjsindex 3c7fb04e3d..d11f17294d 100644--- a/packages/cli/api/theme/template/template.mjs+++ b/packages/cli/api/theme/template/template.mjs@@ -4,10 +4,9 @@* @file `astryx theme template` leaf — writes the annotated theme template into the* consumer's project.*- * Sibling of `theme add`: both answer "put a theme starting point in my- * project", and they split on where you start. `add` copies a theme we ship- * (you like stone, you want to own it); `template` writes the blank annotated- * reference (you want your own, and need to know what the surface contains).+ * `theme add --import` uses an installed built theme without copying source. This command+ * writes the blank annotated reference for a new theme. `theme eject` is the+ * separate path for starting from a complete source fork of an existing theme.** The template is a doc that happens to compile, so it is one file at the* project root by default rather than a package under src/themes/ — you readdiff --git a/packages/cli/api/theme/theme.mjs b/packages/cli/api/theme/theme.mjsindex dd93f15947..da0ffc1d23 100644--- a/packages/cli/api/theme/theme.mjs+++ b/packages/cli/api/theme/theme.mjs@@ -1,16 +1,17 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file `theme` command barrel — re-exports the build/add/list/template/targets/palette- * leaves so the CLI- * (cli/commands/build-theme.mjs) and scripted callers import from one place.- * Each leaf is also importable directly (e.g. api/theme/add/add.mjs). `theme`- * has real subcommands, so there is no flag-dispatch here — the CLI calls the- * leaf it wants.+ * @file `theme` command barrel. Re-exports the build, app-management,+ * authoring, listing, target, and palette leaves so the CLI and scripted callers+ * import from one place. Each leaf is also importable directly. `theme` has real+ * subcommands, so there is no flag dispatch here.*/export {themeBuild, importSpecifier} from './build/build.mjs';export {themeAdd} from './add/add.mjs';+export {themeRemove} from './remove/remove.mjs';+export {themeUse} from './use/use.mjs';+export {themeEject} from './eject/eject.mjs';export {themeTemplate} from './template/template.mjs';export {themeTargets} from './targets/targets.mjs';export {themePaletteGenerate} from './palette/generate/generate.mjs';@@ -23,5 +24,9 @@ export {parseStopList,validateStops,} from './palette/generate/generator.mjs';-export {themeList, themeListAvailable} from './list/list.mjs';-export {listThemes} from './_adapter.mjs';+export {+ themeList,+ themeListAvailable,+ themeListCopySources,+} from './list/list.mjs';+export {listThemes, resolveRecordedTheme} from './_adapter.mjs';diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjsindex 822e974ffe..65acc57d44 100644--- a/packages/cli/api/theme/theme.type.mjs+++ b/packages/cli/api/theme/theme.type.mjs@@ -2,7 +2,7 @@/*** @file Colocated types for the `theme` command — the source of truth for its- * build/list/add JSON response shapes. The leaves' `@returns` reference these+ * app-management JSON response shapes. The leaves' `@returns` reference these* directly (functions own their types); the public `@astryxdesign/cli/api`* surface re-exports them via types/theme.d.ts, so consumers see the same names.*@@ -12,13 +12,17 @@* astryx --json theme build <file> --check -> theme.build.check* astryx --json theme build <a> <b> … -> theme.build.batch* astryx --json theme list -> theme.list+ * astryx --json theme add --list -> theme.list* astryx --json theme add <slug> -> theme.add+ * astryx --json theme add <slug> --import -> theme.app+ * astryx --json theme remove/use <slug> -> theme.app+ * astryx --json theme eject <slug> -> theme.eject* astryx --json theme template -> theme.template* astryx --json theme targets [filter] -> theme.targets* astryx --json theme palette generate <file> -> theme.palette.generate* (file not found / parse error) -> CLIError*- * @position api — colocated typedefs for api/theme/{theme,build,add,list,template,targets,_adapter}+ * @position api — colocated typedefs for api/theme/{theme,build,add,remove,use,eject,list,template,targets,_adapter}*//**@@ -28,7 +32,7 @@* `warnings` are defects the theme author should fix. `notices` are advisories* about a correct theme — most of them cannot be fixed in a theme file at all,* so folding them into `warnings` makes a clean build look dirty.- * @property {{name: string, tokenCount: number, componentCount: number, sizeKB: number, outputs: {css: string, js: string, dts: string, variantsDts?: string}, warnings: string[], notices: string[]}} data+ * @property {{name: string, tokenCount: number, componentCount: number, sizeKB: number, outputs: {css: string, cssDts: string, js: string, dts: string, variantsDts?: string}, warnings: string[], notices: string[]}} data*//**@@ -55,7 +59,20 @@* @property {string} displayName* @property {string} description* @property {boolean} maintained- * @property {string} [package] owner package for project-aware listings+ * @property {string} [package] source-selector package or local theme root; bundled themes retain @astryxdesign/cli+ * @property {boolean} [added] whether the app module records this theme+ * @property {boolean} [default] whether this is the app's default theme+ * @property {'bundled'|'package'|'local'} [source] where the theme source comes from+ */++/**+ * A source copy made by the released `theme add` before local descriptors.+ * @typedef {object} ThemeUnmigratedCopy+ * @property {string} slug+ * @property {string} path project-relative source directory+ * @property {string} source project-relative theme source+ * @property {string} descriptor project-relative descriptor the upgrade writes+ * @property {string} upgradeCommand command that migrates the copy*//**@@ -63,13 +80,43 @@* @typedef {object} ThemeListResponse* @property {'theme.list'} type* @property {ThemeListEntry[]} data+ * @property {{unmigratedCopies: ThemeUnmigratedCopy[]}} [meta] descriptor-less released copies that are not listed as themes*//**- * astryx --json theme add <slug>+ * astryx --json theme add <slug> [path]* @typedef {object} ThemeAddResponse* @property {'theme.add'} type* @property {{slug: string, displayName: string, maintained: boolean, package: string, outputDir: string, entry: string, exportName: string, files: string[]}} data+ * @property {{deprecations: Array<{id: 'DEP-0005', replacements: string[]}>}} meta additive lifecycle guidance; every released data field is unchanged+ */++/**+ * One built theme imported by the generated app module.+ * @typedef {object} ThemeAppEntry+ * @property {string} slug+ * @property {string} owner package name or local themes root+ * @property {string} module built theme module import+ * @property {string} stylesheet production stylesheet import+ * @property {string} [fontStylesheet] package-owned font stylesheet import+ * @property {'bundled'|'package'|'local'} source+ */++/**+ * astryx --json theme add <slug> --import / remove / use+ * @typedef {object} ThemeAppResponse+ * @property {'theme.app'} type+ * @property {{themes: ThemeAppEntry[], default: string, modulePath: string, change: {action: 'add'|'remove'|'use', slug: string, changed: boolean, firstAdd: boolean}}} data+ */++/**+ * astryx --json theme eject <slug> [path]+ * @typedef {object} ThemeEjectResponse+ * @property {'theme.eject'} type+ * `maintained` describes the selected source theme. The ejected descriptor is+ * always written with `maintained: false` because the app owns the fork.+ * `package` is the source selector; bundled themes retain `@astryxdesign/cli`.+ * @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 597d0df8bc..7f7fa11921 100644--- a/packages/cli/api/theme/themeAdd.doc.mjs+++ b/packages/cli/api/theme/themeAdd.doc.mjs@@ -1,8 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file FunctionDoc for `themeAdd()` / `astryx theme add`.- */+/** @file FunctionDoc for `themeAdd()` / `astryx theme add`. *//** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */export const doc = {@@ -11,39 +9,46 @@ export const doc = {name: 'themeAdd',namespace: 'cli/api',displayName: 'themeAdd()',- summary: 'Copy an available theme into a project as editable source.',+ summary: 'Copy theme source, or import its built output into the app.',description:- "Resolves a theme from the CLI bundle or an installed integration and copies it into the consumer project: a bundled theme's source files, or an integration theme's complete directory with its descriptor. Writes are staged and existing files require explicit overwrite. Duplicate slugs fail closed until the caller selects an owner package.",+ 'Copies a bundled or package theme into the project by default, preserving the released theme.add response while that path is deprecated. With options.import, records a package or built local theme and regenerates the app theme module with its built module and stylesheets. Import refuses targetPath and overwrite before writing.',importPath: '@astryxdesign/cli/api',signature:- 'themeAdd(slug: string, options?: {targetPath?: string, overwrite?: boolean, cwd?: string, package?: string}): Promise<ThemeAddResponse>',- keywords: ['theme', 'add', 'integration', 'scaffold', 'copy', 'eject'],+ 'themeAdd(slug: string, options?: {targetPath?: string, overwrite?: boolean, import?: boolean, cwd?: string, package?: string}): Promise<ThemeAddResponse | ThemeAppResponse>',+ keywords: ['theme', 'add', 'import', 'copy', 'app', 'default', 'local'],params: [{name: 'slug',type: 'string',- description:- 'Slug of the available theme to copy (matched case-insensitively).',+ description: 'Slug of the available theme.',required: true,},{name: 'options.targetPath',type: 'string',description:- 'Destination directory for copied files. Must resolve within cwd.',+ 'Destination for the deprecated source-copy path. Cannot be combined with import.',default: "'src/themes/<slug>'",},{name: 'options.overwrite',type: 'boolean',- description: 'Replace existing files instead of refusing.',+ description:+ 'Replace copied files instead of refusing. Cannot be combined with import.',+ default: 'false',+ },+ {+ name: 'options.import',+ type: 'boolean',+ description:+ 'Import the built theme through the generated app module instead of copying source.',default: 'false',},{name: 'options.cwd',type: 'string',description:- 'Project directory used for integration discovery and target paths.',+ 'Project directory used for discovery, state, and target paths.',default: 'process.cwd()',},{@@ -56,7 +61,12 @@ export const doc = {{type: 'theme.add',description:- 'Copy receipt with slug, displayName, maintained flag, owner package, outputDir, entry, exportName, and files.',+ 'The released copy receipt plus additive meta.deprecations with DEP-0005 and its replacement commands when import is false.',+ },+ {+ type: 'theme.app',+ description:+ 'The complete generated-module state and add change when import is true.',},],throws: [@@ -67,26 +77,29 @@ export const doc = {{code: 'ERR_AMBIGUOUS_THEME', when: 'more than one package owns the slug'},{code: 'ERR_THEME_INVALID',- when: 'the selected installed package has a blocking integration or theme-descriptor error',+ when: 'the selected theme is invalid, or import is combined with a copy option',},- {code: 'ERR_PATH_TRAVERSAL', when: 'the target path escapes cwd'},+ {code: 'ERR_PATH_TRAVERSAL', when: 'a copy target escapes cwd'},{code: 'ERR_NO_SOURCE',- when: 'the bundled theme descriptors cannot be read, or a theme file to copy is missing',+ when: 'a copied source file is missing',},{code: 'ERR_FILE_EXISTS',- when: 'a destination exists and overwrite is not set',+ when: 'a destination or generated module path conflicts',},- {code: 'ERR_WRITE_FAILED', when: 'writing files fails'},+ {code: 'ERR_WRITE_FAILED', when: 'copying or module generation fails'},],examples: [- {label: 'Copy a bundled theme', code: "await themeAdd('butter');"},{- label: 'Name the owner package and the destination',- code: "await themeAdd('butter', {package: '@astryxdesign/cli', targetPath: 'src/brand-theme'});",+ label: 'Import a built theme',+ code: "await themeAdd('butter', {import: true});",+ },+ {+ label: 'Select a package theme over a local theme',+ code: "await themeAdd('ocean', {import: true, package: '@acme/themes'});",},],command: 'theme add',- related: ['themeListAvailable', 'themeTemplate', 'listThemes'],+ related: ['themeRemove', 'themeUse', 'themeEject', 'themeListAvailable'],};diff --git a/packages/cli/api/theme/themeBuild.doc.mjs b/packages/cli/api/theme/themeBuild.doc.mjsindex d1b42e1d42..100f4e88db 100644--- a/packages/cli/api/theme/themeBuild.doc.mjs+++ b/packages/cli/api/theme/themeBuild.doc.mjs@@ -85,7 +85,7 @@ export const doc = {{type: 'theme.build',description:- 'Build receipt {name, tokenCount, componentCount, sizeKB, outputs, warnings, notices}: the theme name; how many tokens (portable plus theme-local) and component targets it overrides; the CSS size in KB; the written outputs {css, js, dts, and variantsDts when custom prop values were augmented}; warnings, the defects the author should fix, including exact canonical replacements for deprecated component target keys and declarations the generator dropped; and notices, advisories about a correct theme, such as a font it names but does not load. Resolves to null instead when the theme produced no CSS (nothing to build).',+ 'Build receipt {name, tokenCount, componentCount, sizeKB, outputs, warnings, notices}: the theme name; how many tokens (portable plus theme-local) and component targets it overrides; the CSS size in KB; the written outputs {css, cssDts for strict side-effect imports, js, dts, and variantsDts when custom prop values were augmented}; warnings, the defects the author should fix, including exact canonical replacements for deprecated component target keys and declarations the generator dropped; and notices, advisories about a correct theme, such as a font it names but does not load. Resolves to null instead when the theme produced no CSS (nothing to build).',},{type: 'theme.build.check',diff --git a/packages/cli/api/theme/themeEject.doc.mjs b/packages/cli/api/theme/themeEject.doc.mjsnew file mode 100644index 0000000000..a3cb5b7ab3--- /dev/null+++ b/packages/cli/api/theme/themeEject.doc.mjs@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file FunctionDoc for `themeEject()` / `astryx theme eject`.+ */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'themeEject',+ namespace: 'cli/api',+ displayName: 'themeEject()',+ summary: 'Eject an available theme into a project as editable source.',+ description:+ "Resolves a theme from the CLI bundle or an installed integration and ejects it into the consumer project: a bundled theme's source files, or an integration theme's complete directory with its descriptor. Writes are staged and existing files require explicit overwrite. Duplicate slugs fail closed until the caller selects an owner package.",+ importPath: '@astryxdesign/cli/api',+ signature:+ 'themeEject(slug: string, options?: {targetPath?: string, overwrite?: boolean, cwd?: string, package?: string}): Promise<ThemeEjectResponse>',+ keywords: ['theme', 'eject', 'integration', 'scaffold', 'copy', 'extract'],+ params: [+ {+ name: 'slug',+ type: 'string',+ description:+ 'Slug of the available theme to eject (matched case-insensitively).',+ required: true,+ },+ {+ name: 'options.targetPath',+ type: 'string',+ description:+ 'Destination directory for ejected files. Must resolve within cwd.',+ default: "'src/themes/<slug>'",+ },+ {+ name: 'options.overwrite',+ type: 'boolean',+ description: 'Replace existing files instead of refusing.',+ default: 'false',+ },+ {+ name: 'options.cwd',+ type: 'string',+ description:+ 'Project directory used for integration discovery and target paths.',+ },+ {+ name: 'options.package',+ type: 'string',+ description:+ 'Exact source-selector package used to disambiguate a shared slug. Bundled themes retain @astryxdesign/cli.',+ },+ ],+ returns: [+ {+ type: 'theme.eject',+ description:+ 'Eject receipt with slug, displayName, the source theme maintained flag, source-selector package, outputDir, entry, exportName, and files. The written local descriptor always uses maintained: false.',+ },+ ],+ throws: [+ {+ 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_THEME_INVALID',+ when: 'the selected installed package has a blocking integration or theme-descriptor error',+ },+ {code: 'ERR_PATH_TRAVERSAL', when: 'the target path escapes cwd'},+ {code: 'ERR_NO_SOURCE', when: 'a theme file to eject is missing'},+ {+ code: 'ERR_FILE_EXISTS',+ when: 'a destination exists and overwrite is not set',+ },+ {code: 'ERR_WRITE_FAILED', when: 'writing files fails'},+ ],+ examples: [+ {label: 'Eject a bundled theme', code: "await themeEject('ocean');"},+ {+ label: 'Eject an integration theme',+ code: "await themeEject('ocean', {package: '@acme/themes'});",+ },+ ],+ command: 'theme eject',+ related: ['themeAdd', 'themeRemove', 'themeUse', 'themeList', 'listThemes'],+};diff --git a/packages/cli/api/theme/themeListAvailable.doc.mjs b/packages/cli/api/theme/themeListAvailable.doc.mjsindex 3607900a08..d861bca97c 100644--- a/packages/cli/api/theme/themeListAvailable.doc.mjs+++ b/packages/cli/api/theme/themeListAvailable.doc.mjs@@ -11,9 +11,9 @@ export const doc = {name: 'themeListAvailable',namespace: 'cli/api',displayName: 'themeListAvailable()',- summary: 'List bundled and installed integration themes.',+ summary: 'List bundled, package, and local themes.',description:- 'Lists the bundled themes plus source themes from integrations installed in cwd, each with its owner package. If the project configuration cannot be read, it falls back to the bundled themes.',+ 'Lists every available theme with its owner, source, added state, and default state. Descriptor-less copies left by the released theme add are not themes yet; response meta names them and the upgrade command that adds their descriptors.',importPath: '@astryxdesign/cli/api',signature:'themeListAvailable(options?: {cwd?: string, package?: string}): Promise<ThemeListResponse>',@@ -29,14 +29,14 @@ export const doc = {{name: 'options.package',type: 'string',- description: 'Optional exact owner-package filter.',+ description: 'Optional exact source-selector package filter.',},],returns: [{type: 'theme.list',description:- 'Every available theme as ThemeListEntry[]: slug, displayName, description, maintained flag, and owner package.',+ 'Every available theme as ThemeListEntry[], plus optional meta.unmigratedCopies entries with the source path, missing descriptor, and upgrade command. Unmigrated copies are not included in data.',},],throws: [diff --git a/packages/cli/api/theme/themeListCopySources.doc.mjs b/packages/cli/api/theme/themeListCopySources.doc.mjsnew file mode 100644index 0000000000..ac77fdd27d--- /dev/null+++ b/packages/cli/api/theme/themeListCopySources.doc.mjs@@ -0,0 +1,60 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file FunctionDoc for the released `astryx theme add --list` projection.+ */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'themeListCopySources',+ namespace: 'cli/api',+ displayName: 'themeListCopySources()',+ summary: 'List themes the source-copy form of theme add can copy.',+ description:+ 'Preserves the released theme add --list result. It lists bundled and package themes with the released fields, excludes local app themes, and does not read generated app-theme state.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'themeListCopySources(options?: {cwd?: string, package?: string}): Promise<ThemeListResponse>',+ keywords: ['theme', 'add', 'list', 'copy', 'source', 'package'],+ params: [+ {+ name: 'options.cwd',+ type: 'string',+ description:+ 'Project directory whose installed integration packages contribute copyable themes.',+ default: 'process.cwd()',+ },+ {+ name: 'options.package',+ type: 'string',+ description: 'Optional exact source-selector package filter.',+ },+ ],+ returns: [+ {+ type: 'theme.list',+ description:+ 'Bundled and package themes using the released slug, displayName, description, maintained, and package fields.',+ },+ ],+ throws: [+ {+ code: 'ERR_NO_SOURCE',+ when: 'the CLI bundled-theme descriptors cannot be read or parsed',+ },+ ],+ examples: [+ {+ label: 'List themes that source-copy add can copy',+ code: 'const {data} = await themeListCopySources();',+ },+ {+ label: 'List one package',+ code: "await themeListCopySources({package: '@acme/themes'});",+ },+ ],+ command: 'theme add',+ related: ['themeAdd', 'themeListAvailable', 'themeEject'],+};diff --git a/packages/cli/api/theme/themeRemove.doc.mjs b/packages/cli/api/theme/themeRemove.doc.mjsnew file mode 100644index 0000000000..3a83dc6873--- /dev/null+++ b/packages/cli/api/theme/themeRemove.doc.mjs@@ -0,0 +1,50 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file FunctionDoc for `themeRemove()` / `astryx theme remove`. */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'themeRemove',+ namespace: 'cli/api',+ displayName: 'themeRemove()',+ summary: "Remove a non-default theme from an app's generated theme module.",+ description:+ 'Reads the generated module record, removes one added theme, and regenerates the whole module. The default cannot be removed until themeUse selects another added theme.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'themeRemove(slug: string, options?: {cwd?: string}): Promise<ThemeAppResponse>',+ keywords: ['theme', 'remove', 'app', 'import', 'generated'],+ params: [+ {+ name: 'slug',+ type: 'string',+ description: 'Slug of the added theme to remove.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Project directory containing the generated theme module.',+ },+ ],+ returns: [+ {+ type: 'theme.app',+ description:+ 'Every remaining theme and its imports, the default slug, the generated module path, and the remove change.',+ },+ ],+ throws: [+ {code: 'ERR_UNKNOWN_THEME', when: 'the theme is not added'},+ {+ code: 'ERR_THEME_INVALID',+ when: 'the theme is the default or generated state is invalid',+ },+ {code: 'ERR_WRITE_FAILED', when: 'the generated module cannot be written'},+ ],+ examples: [{label: 'Remove a theme', code: "await themeRemove('ocean');"}],+ command: 'theme remove',+ related: ['themeAdd', 'themeUse', 'themeListAvailable'],+};diff --git a/packages/cli/api/theme/themeTemplate.doc.mjs b/packages/cli/api/theme/themeTemplate.doc.mjsindex 2f89901025..eeccd28313 100644--- a/packages/cli/api/theme/themeTemplate.doc.mjs+++ b/packages/cli/api/theme/themeTemplate.doc.mjs@@ -19,8 +19,9 @@ export const doc = {'Writes theme.template.ts: the annotated reference for the whole theme surface, covering every ' +'defineTheme field, the token families, the component override syntax, and how a theme is ' +'consumed, with the CLI command that prints the authoritative reference for each section. ' +- 'Read it, copy what you need into your own theme file, delete it. Where `theme add` starts ' +- 'you from a theme we ship, this starts you from a blank one. Refuses to overwrite without ' ++ 'Read it, copy what you need into your own theme file, delete it. Use `theme add --import` to ' ++ 'use an installed built theme, extend that theme for ordinary customization, or use ' ++ '`theme eject` for a complete source fork. This command starts a new blank theme. Refuses to overwrite without ' +'`overwrite`, so it is safe to re-run.',importPath: '@astryxdesign/cli/api',signature:@@ -65,5 +66,5 @@ export const doc = {},],command: 'theme template',- related: ['themeAdd', 'themeBuild', 'themeListAvailable', 'themeTargets'],+ related: ['themeAdd', 'themeEject', 'themeBuild', 'themeListAvailable', 'themeTargets'],};diff --git a/packages/cli/api/theme/themeUse.doc.mjs b/packages/cli/api/theme/themeUse.doc.mjsnew file mode 100644index 0000000000..1fa1489939--- /dev/null+++ b/packages/cli/api/theme/themeUse.doc.mjs@@ -0,0 +1,47 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file FunctionDoc for `themeUse()` / `astryx theme use`. */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'themeUse',+ namespace: 'cli/api',+ displayName: 'themeUse()',+ summary: "Choose an app's default added theme.",+ description:+ 'Reads the generated module record, selects one added slug as the default, and regenerates the whole module. The command does not add a missing theme.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'themeUse(slug: string, options?: {cwd?: string}): Promise<ThemeAppResponse>',+ keywords: ['theme', 'use', 'default', 'app', 'generated'],+ params: [+ {+ name: 'slug',+ type: 'string',+ description: 'Slug of the added theme to make default.',+ required: true,+ },+ {+ name: 'options.cwd',+ type: 'string',+ description: 'Project directory containing the generated theme module.',+ },+ ],+ returns: [+ {+ type: 'theme.app',+ description:+ 'Every added theme and its imports, the selected default, the generated module path, and the use change.',+ },+ ],+ throws: [+ {code: 'ERR_UNKNOWN_THEME', when: 'the theme is not added'},+ {code: 'ERR_THEME_INVALID', when: 'generated state is invalid'},+ {code: 'ERR_WRITE_FAILED', when: 'the generated module cannot be written'},+ ],+ examples: [{label: 'Choose the default', code: "await themeUse('ocean');"}],+ command: 'theme use',+ related: ['themeAdd', 'themeRemove', 'themeListAvailable'],+};diff --git a/packages/cli/api/theme/use/use.mjs b/packages/cli/api/theme/use/use.mjsnew file mode 100644index 0000000000..8cd2fb73d3--- /dev/null+++ b/packages/cli/api/theme/use/use.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file `astryx theme use` — choose the app's default added theme. */++import {useThemeInApp} from '../_adapter.mjs';++/**+ * Set one added theme as the default and regenerate the app module.+ * @param {string} slug+ * @param {{cwd?: string}} [options]+ * @returns {Promise<import('../theme.type.mjs').ThemeAppResponse>}+ */+export function themeUse(slug, options = {}) {+ return useThemeInApp(slug, options);+}diff --git a/packages/cli/api/theme/use/use.test.mjs b/packages/cli/api/theme/use/use.test.mjsnew file mode 100644index 0000000000..ce97e73404--- /dev/null+++ b/packages/cli/api/theme/use/use.test.mjs@@ -0,0 +1,98 @@+// 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';+import {themeUse} from './use.mjs';+import {parseThemeModuleRecord} from '../../../foundation/config/theme-state.mjs';++let tmpDir;++function installThemes() {+ const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'themes');+ fs.mkdirSync(path.join(packageDir, 'themes'), {recursive: true});+ fs.mkdirSync(path.join(packageDir, 'dist'), {recursive: true});+ const exports = {};+ for (const slug of ['ocean', 'reef']) {+ const sourceDir = path.join(packageDir, 'themes', slug);+ fs.mkdirSync(sourceDir);+ exports[`./themes/${slug}`] = `./dist/${slug}.js`;+ exports[`./themes/${slug}.css`] = `./dist/${slug}.css`;+ fs.writeFileSync(+ path.join(sourceDir, `${slug}Theme.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type:'theme',name:'${slug}',displayName:'${slug}',description:'${slug}',maintained:true};\n`,+ );+ fs.writeFileSync(+ path.join(sourceDir, `${slug}Theme.ts`),+ `export const ${slug}Theme = {};\n`,+ );+ fs.writeFileSync(+ path.join(packageDir, `dist/${slug}.js`),+ `export const ${slug}Theme = {name:'${slug}',__built:true};\n`,+ );+ fs.writeFileSync(path.join(packageDir, `dist/${slug}.css`), '/* css */\n');+ }+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: '@acme/themes', version: '1.0.0', exports}),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes:'./themes'};\n",+ );+}++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-theme-use-'));+ fs.mkdirSync(path.join(tmpDir, 'src'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@acme/themes': '^1.0.0'}}),+ );+ fs.writeFileSync(path.join(tmpDir, 'tsconfig.json'), '{}\n');+ installThemes();+ await themeAdd('ocean', {cwd: tmpDir, import: true, package: '@acme/themes'});+ await themeAdd('reef', {cwd: tmpDir, import: true, package: '@acme/themes'});+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('themeUse', () => {+ it('changes the default and regenerates the module', async () => {+ const result = await themeUse('ReEf', {cwd: tmpDir});+ expect(result).toMatchObject({+ type: 'theme.app',+ data: {+ default: 'reef',+ change: {action: 'use', slug: 'reef', changed: true},+ },+ });+ expect(+ parseThemeModuleRecord(+ fs.readFileSync(path.join(tmpDir, 'src/astryx-themes.ts'), 'utf-8'),+ ),+ ).toEqual({+ themes: {ocean: '@acme/themes', reef: '@acme/themes'},+ defaultSlug: 'reef',+ });+ });++ it('regenerates and reports no change when already default', async () => {+ await themeUse('reef', {cwd: tmpDir});+ const moduleFile = path.join(tmpDir, 'src/astryx-themes.ts');+ fs.appendFileSync(moduleFile, '// edited\n');+ const result = await themeUse('reef', {cwd: tmpDir});+ expect(result.data.change.changed).toBe(false);+ expect(fs.readFileSync(moduleFile, 'utf-8')).not.toContain('// edited');+ });++ it('names theme add when the slug is not added', async () => {+ await expect(themeUse('missing', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_UNKNOWN_THEME',+ message: expect.stringContaining('astryx theme add missing --import'),+ });+ });+});diff --git a/packages/cli/assets/codemods/transforms/next/__tests__/migrate-copied-themes-to-descriptors.test.mjs b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-copied-themes-to-descriptors.test.mjsnew file mode 100644index 0000000000..13b2469973--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-copied-themes-to-descriptors.test.mjs@@ -0,0 +1,129 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import manifest from '../index.mjs';+import migrate from '../migrate-copied-themes-to-descriptors.mjs';+import {runCodemods} from '../../../runner.mjs';+import {discoverLocalThemes} from '../../../../../foundation/discovery/theme-discovery.mjs';++let root;++beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-copied-theme-'));+ fs.writeFileSync(+ path.join(root, 'package.json'),+ '{"name":"app","version":"1.0.0"}\n',+ );+});++afterEach(() => {+ fs.rmSync(root, {recursive: true, force: true});+});++/** @param {string} slug */+function writeCopy(slug) {+ const stem = `${slug.replace(/-([a-z0-9])/gu, (_, character) => character.toUpperCase())}Theme`;+ const directory = path.join(root, 'src', 'themes', slug);+ fs.mkdirSync(directory, {recursive: true});+ const source = `export const ${stem} = {name: '${slug}'};\n`;+ fs.writeFileSync(path.join(directory, `${stem}.ts`), source);+ fs.writeFileSync(path.join(directory, 'icons.tsx'), 'export const icons = {};\n');+ return {directory, stem, source};+}++/** @param {boolean} apply */+const run = apply =>+ runCodemods([{version: 'next', transforms: manifest}], {+ apply,+ path: root,+ codemod: undefined,+ silent: true,+ root,+ });++describe('migrate-copied-themes-to-descriptors', () => {+ it('is staged for the next release as a project codemod', () => {+ expect(manifest.map(entry => [entry.name, entry.meta.codemodType])).toEqual([+ ['migrate-copied-themes-to-descriptors', 'project'],+ ]);+ });++ it('writes only the missing descriptor and makes the copy a local theme', async () => {+ const {directory, stem, source} = writeCopy('deep-sea');+ const icons = fs.readFileSync(path.join(directory, 'icons.tsx'), 'utf-8');++ const result = await run(true);++ expect(result).toMatchObject({errors: [], totalFilesChanged: 1});+ expect(fs.readFileSync(path.join(directory, `${stem}.ts`), 'utf-8')).toBe(+ source,+ );+ expect(fs.readFileSync(path.join(directory, 'icons.tsx'), 'utf-8')).toBe(+ icons,+ );+ expect(+ fs.readFileSync(path.join(directory, `${stem}.doc.mjs`), 'utf-8'),+ ).toBe(+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {\n type: 'theme',\n name: 'deep-sea',\n displayName: 'Deep Sea',\n description: 'Deep Sea theme copied into this app.',\n maintained: false,\n};\n",+ );+ expect(discoverLocalThemes(root).map(theme => theme.slug)).toEqual([+ 'deep-sea',+ ]);+ });++ it('leaves non-copies and an already described theme alone', async () => {+ const described = writeCopy('ocean');+ fs.writeFileSync(+ path.join(described.directory, `${described.stem}.doc.mjs`),+ "export default {type: 'theme', name: 'ocean', displayName: 'Mine', description: '', maintained: false};\n",+ );+ fs.mkdirSync(path.join(root, 'src/themes/not-a-theme'), {recursive: true});+ fs.writeFileSync(+ path.join(root, 'src/themes/not-a-theme/helper.ts'),+ 'export const helper = true;\n',+ );+ fs.mkdirSync(path.join(root, 'src/themes/nested/source'), {recursive: true});+ fs.writeFileSync(+ path.join(root, 'src/themes/nested/source/nestedTheme.ts'),+ 'export const nestedTheme = {};\n',+ );+ fs.mkdirSync(path.join(root, 'src/themes/ambiguous'), {recursive: true});+ fs.writeFileSync(+ path.join(root, 'src/themes/ambiguous/firstTheme.ts'),+ 'export const firstTheme = {};\n',+ );+ fs.writeFileSync(+ path.join(root, 'src/themes/ambiguous/secondTheme.ts'),+ 'export const secondTheme = {};\n',+ );++ await expect(migrate(root)).resolves.toEqual({+ writes: [],+ deletes: [],+ problems: [],+ });+ });++ it('is a fixed point on the second run', async () => {+ const {directory, stem, source} = writeCopy('ocean');++ const first = await run(true);+ const descriptor = fs.readFileSync(+ path.join(directory, `${stem}.doc.mjs`),+ 'utf-8',+ );+ const second = await run(true);++ expect(first).toMatchObject({errors: [], totalFilesChanged: 1});+ expect(second).toMatchObject({errors: [], totalFilesChanged: 0});+ expect(+ fs.readFileSync(path.join(directory, `${stem}.doc.mjs`), 'utf-8'),+ ).toBe(descriptor);+ expect(fs.readFileSync(path.join(directory, `${stem}.ts`), 'utf-8')).toBe(+ source,+ );+ });+});diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjsindex 2af3bdfcf0..8886c50ba6 100644--- a/packages/cli/assets/codemods/transforms/next/index.mjs+++ b/packages/cli/assets/codemods/transforms/next/index.mjs@@ -7,4 +7,17 @@* this file into the resolved version folder.*/-export default [];+import migrateCopiedThemesToDescriptors, {+ meta as migrateCopiedThemesToDescriptorsMeta,+} from './migrate-copied-themes-to-descriptors.mjs';++export default [+ {+ name: 'migrate-copied-themes-to-descriptors',+ transform:+ /** @type {import('../../../../authoring/codemod/type').CodemodTransform} */ (+ /** @type {unknown} */ (migrateCopiedThemesToDescriptors)+ ),+ meta: migrateCopiedThemesToDescriptorsMeta,+ },+];diff --git a/packages/cli/assets/codemods/transforms/next/migrate-copied-themes-to-descriptors.mjs b/packages/cli/assets/codemods/transforms/next/migrate-copied-themes-to-descriptors.mjsnew file mode 100644index 0000000000..0123bb2887--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/migrate-copied-themes-to-descriptors.mjs@@ -0,0 +1,54 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Give source themes copied by the released `theme add` the descriptors+ * that make them discoverable local themes.+ *+ * The released copy wrote each theme under `src/themes/<slug>` but left its+ * package descriptor behind. This project codemod writes only the missing+ * same-stem descriptor, marks the app-owned copy as unmaintained, and leaves+ * every existing source byte and import in place.+ */++import * as path from 'node:path';+import {discoverUnmigratedThemeCopies} from '../../../../foundation/discovery/theme-discovery.mjs';+import {themeDescriptorSource} from '../../../../foundation/integrations/theme-descriptor.mjs';++export const meta = {+ title: 'Give copied app themes their local descriptors',+ description:+ 'Writes one unmaintained same-stem descriptor beside each earlier theme copy in src/themes.',+ codemodType: 'project',+};++/** @param {string} slug */+function displayName(slug) {+ return slug+ .split('-')+ .map(part => `${part[0].toUpperCase()}${part.slice(1)}`)+ .join(' ');+}++/**+ * @param {string} root project directory+ * @returns {Promise<import('../../runner.mjs').ProjectCodemodPlan>}+ */+export default async function migrateCopiedThemesToDescriptors(root) {+ return {+ writes: discoverUnmigratedThemeCopies(root).map(copy => {+ const name = displayName(copy.slug);+ return {+ path: path.join(copy.sourceDir, copy.descriptor),+ contents: themeDescriptorSource({+ type: 'theme',+ name: copy.slug,+ displayName: name,+ description: `${name} theme copied into this app.`,+ maintained: false,+ }),+ };+ }),+ deletes: [],+ problems: [],+ };+}diff --git a/packages/cli/assets/docs/getting-started.doc.mjs b/packages/cli/assets/docs/getting-started.doc.mjsindex e24dc6218d..414f6a1e23 100644--- a/packages/cli/assets/docs/getting-started.doc.mjs+++ b/packages/cli/assets/docs/getting-started.doc.mjs@@ -6,8 +6,7 @@ export const docs = {name: 'getting-started',title: 'Getting Started',category: 'guide',- description:- 'Add the design system to your project and start building.',+ description: 'Add the design system to your project and start building.',keywords: ['quick start', 'setup', 'install'],sections: [@@ -32,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 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.",+ code: 'Ask me what look and feel this app should have. Run `npx @astryxdesign/cli theme list`, install the closest theme package, and run `theme add <slug> --import`; use `--package` when owners share a slug. Import `themes` and `defaultThemeSlug` from the generated module once and pass `themes[defaultThemeSlug]` to `<Theme>`. Customize with `defineTheme({extends: importedTheme, ...})`. Use `theme eject` only when I ask for an independent source fork. Default to neutral if I have no preference, and show me the result before moving on.',},],},@@ -66,24 +65,45 @@ export const docs = {],},{- title: 'Add the theme CSS',+ title: 'Add base CSS and a theme',content: [{type: 'prose',- text: 'Import the reset stylesheet and a theme in your global CSS file. Themes provide all design tokens (colors, spacing, radius, typography) as CSS custom properties.',+ text: 'Import the reset and base styles in your global CSS. Then run `astryx theme add neutral --import`; the generated app module imports the theme’s production CSS and font CSS.',},{type: 'code',lang: 'css',label: 'globals.css',code: `@import '@astryxdesign/core/reset.css';-@import '@astryxdesign/core/astryx.css';-@import '@astryxdesign/theme-neutral/theme.css';`,+@import '@astryxdesign/core/astryx.css';`,},{type: 'prose',text: 'Run `astryx theme list` to see every theme.',},+ {+ type: 'code',+ lang: 'tsx',+ label: 'App root',+ code: `import {Theme} from '@astryxdesign/core';+import {themes, defaultThemeSlug} from './astryx-themes';++<Theme theme={themes[defaultThemeSlug]}><App /></Theme>`,+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ '`@astryxdesign/theme-neutral`: muted and minimal; a good starting point',+ '`@astryxdesign/theme-butter`: warm, golden tones with blue accents',+ '`@astryxdesign/theme-chocolate`: rich chocolate and caramel tones',+ '`@astryxdesign/theme-gothic`: dark-only theme with ink and noir influences',+ '`@astryxdesign/theme-matcha`: earthy greens and botanical tones',+ '`@astryxdesign/theme-stone`: warm neutrals inspired by sandstone',+ '`@astryxdesign/theme-y2k`: playful early-2000s pop aesthetic',+ ],+ },{type: 'prose',text: 'These stylesheets are cascade-layered: the reset loads in @layer reset and component styles in @layer astryx-base. If your project has existing global CSS, a legacy reset, or Tailwind, declare the layer order explicitly and assign every stylesheet to a layer deliberately: unlayered styles and later layers both override astryx-base regardless of specificity. Before building screens, read the two cascade layer sections of {@link generic:migration}.',@@ -150,12 +170,36 @@ const overrides = stylex.create({type: 'table',headers: ['Example', 'Stack', 'Path'],rows: [- ['Next.js', 'Next.js + theme CSS', '[apps/example-nextjs](https://github.com/facebook/astryx/tree/main/apps/example-nextjs)'],- ['Next.js + StyleX', 'Next.js + StyleX for custom styles', '[apps/example-nextjs-stylex](https://github.com/facebook/astryx/tree/main/apps/example-nextjs-stylex)'],- ['Next.js + Tailwind', 'Next.js + Tailwind bridge', '[apps/example-nextjs-tailwind](https://github.com/facebook/astryx/tree/main/apps/example-nextjs-tailwind)'],- ['Next.js Source', 'Next.js importing from source', '[apps/example-nextjs-source](https://github.com/facebook/astryx/tree/main/apps/example-nextjs-source)'],- ['Vite', 'Vite', '[apps/example-vite](https://github.com/facebook/astryx/tree/main/apps/example-vite)'],- ['Vite + Tailwind', 'Vite + Tailwind bridge', '[apps/example-vite-tailwind](https://github.com/facebook/astryx/tree/main/apps/example-vite-tailwind)'],+ [+ 'Next.js',+ 'Next.js + theme CSS',+ '[apps/example-nextjs](https://github.com/facebook/astryx/tree/main/apps/example-nextjs)',+ ],+ [+ 'Next.js + StyleX',+ 'Next.js + StyleX for custom styles',+ '[apps/example-nextjs-stylex](https://github.com/facebook/astryx/tree/main/apps/example-nextjs-stylex)',+ ],+ [+ 'Next.js + Tailwind',+ 'Next.js + Tailwind bridge',+ '[apps/example-nextjs-tailwind](https://github.com/facebook/astryx/tree/main/apps/example-nextjs-tailwind)',+ ],+ [+ 'Next.js Source',+ 'Next.js importing from source',+ '[apps/example-nextjs-source](https://github.com/facebook/astryx/tree/main/apps/example-nextjs-source)',+ ],+ [+ 'Vite',+ 'Vite',+ '[apps/example-vite](https://github.com/facebook/astryx/tree/main/apps/example-vite)',+ ],+ [+ 'Vite + Tailwind',+ 'Vite + Tailwind bridge',+ '[apps/example-vite-tailwind](https://github.com/facebook/astryx/tree/main/apps/example-vite-tailwind)',+ ],],},{@@ -186,7 +230,7 @@ pnpm dev`,},{type: 'prose',- text: 'Then discover what\'s available:',+ text: "Then discover what's available:",},{type: 'code',diff --git a/packages/cli/assets/docs/styling-libraries.doc.mjs b/packages/cli/assets/docs/styling-libraries.doc.mjsindex 7900346d89..111322f19d 100644--- a/packages/cli/assets/docs/styling-libraries.doc.mjs+++ b/packages/cli/assets/docs/styling-libraries.doc.mjs@@ -377,7 +377,7 @@ tokens: {lang: 'ts',label: 'Resolve tokens without React context',code: `import {resolveThemeTokens} from '@astryxdesign/core/theme/tokens';-import {neutralTheme} from '@astryxdesign/theme-neutral';+import {neutralTheme} from '@astryxdesign/theme-neutral/built';const tokens = resolveThemeTokens(neutralTheme, {mode: 'light'});diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjsindex 99222f309d..8f5136eeda 100644--- a/packages/cli/assets/docs/theme.doc.dense.mjs+++ b/packages/cli/assets/docs/theme.doc.dense.mjs@@ -16,7 +16,26 @@ export const docsDense = {null,{type: 'prose',- text: 'default import = runtime injection. /built import = pre-compiled CSS (pair with theme.css).',+ text: '`theme add --import` generates the app module with built theme + CSS + optional font CSS. import themes/defaultThemeSlug once. use/remove regenerate it. extend built themes to customize; eject only to fork source.',+ },+ ],+ },+ {+ section: 'Migrating Earlier Theme Copies',+ title: 'Migrate Earlier Copies',+ content: [+ {+ type: 'prose',+ text: 'earlier `theme add` copies stay app source. upgrade writes only their missing unmaintained descriptor.',+ },+ null,+ {+ type: 'prose',+ text: 'before upgrade, theme commands skip them; list and doctor name them. old copy scripts move to `theme eject`; app-use scripts run `theme add --import`.',+ },+ {+ type: 'prose',+ text: '`ASTRYX_THEME` is not read. use `theme use <slug>` for the generated app module. component metadata reads that record’s default when the module exists; without it, the released package.json#astryx.theme lookup keeps its meaning.',},],},@@ -28,7 +47,7 @@ export const docsDense = {null,{type: 'prose',- text: 'published: neutral (start here), butter, chocolate, gothic (dark-only), matcha, stone, y2k. @astryxdesign/theme-{name} = source (runtime). @astryxdesign/theme-{name}/built = optimized (+ theme.css).',+ text: 'published: neutral (start here), butter, chocolate, gothic (dark-only), matcha, stone, y2k. install @astryxdesign/theme-{name}, then `theme add <name> --import`. package exports: /built + theme.css + fonts.css.',},],},@@ -48,7 +67,7 @@ export const docsDense = {content: [{type: 'prose',- 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.',+ text: 'extend an imported built theme for ordinary customization. build + add local results. `theme eject` is only for an independent source fork. only override values that differ.',},null,{@@ -182,7 +201,7 @@ export const docsDense = {content: [{type: 'prose',- text: 'runtime: useInsertionEffect injects styles client-side. built: static CSS on first paint. USE /built + theme.css FOR SSR.',+ text: 'apps use built themes. generated module pairs each built object with production CSS and optional font CSS. package themes keep owner updates; local themes are app-owned. never hand-edit the module.',},null,null,diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjsindex 9d32718d40..ff5d0e3b37 100644--- a/packages/cli/assets/docs/theme.doc.mjs+++ b/packages/cli/assets/docs/theme.doc.mjs@@ -19,19 +19,19 @@ export const docs = {{type: 'code',lang: 'bash',- label: 'Install a theme package',- code: 'npm install @astryxdesign/theme-neutral',+ label: 'Install and add a theme',+ code: 'npm install @astryxdesign/theme-neutral\nastryx theme add neutral --import',},{type: 'code',lang: 'tsx',- label: 'Basic theme setup (runtime injection)',+ label: 'Wire the generated module once',code: `import {Theme} from '@astryxdesign/core';-import {neutralTheme} from '@astryxdesign/theme-neutral';+import {themes, defaultThemeSlug} from './astryx-themes';function App() {return (- <Theme theme={neutralTheme}>+ <Theme theme={themes[defaultThemeSlug]}><YourApp /></Theme>);@@ -40,26 +40,44 @@ function App() {{type: 'code',lang: 'tsx',- label: 'Optimized setup (pre-built CSS)',- code: `import {Theme} from '@astryxdesign/core';-import {neutralTheme} from '@astryxdesign/theme-neutral/built';-import '@astryxdesign/theme-neutral/theme.css';+ label: 'Switch among added themes',+ code: `import {useState} from 'react';+import {themes, type ThemeSlug} from './astryx-themes';-function App() {- return (- <Theme theme={neutralTheme}>- <YourApp />- </Theme>- );-}`,+const [slug, setSlug] = useState<ThemeSlug>('neutral');+const app = <Theme theme={themes[slug]}><YourApp /></Theme>;`,+ },+ {+ type: 'prose',+ text: '`theme add --import` records an installed package theme and regenerates `src/astryx-themes.ts` or `.js` with its built module, production CSS, and optional font CSS. In a project without `src`, the module is at the project root. The first imported theme becomes the default. `theme use <slug>` changes that default, and `theme remove <slug>` removes a non-default theme.',+ },+ {+ type: 'prose',+ text: 'Customize a package theme with `defineTheme({extends: importedTheme, ...})`, then build and add that local theme. Use `theme eject` only when you want an independent source fork that no longer receives the package owner’s updates.',+ },+ ],+ },+ {+ title: 'Migrating Earlier Theme Copies',+ category: 'guide',+ content: [+ {+ type: 'prose',+ text: 'A theme copied by the released `theme add` stays app source. The upgrade does not move, delete, or rewrite it. It only writes the missing same-stem descriptor with `maintained: false`, so the copy becomes a local theme.',+ },+ {+ type: 'code',+ lang: 'bash',+ label: 'Add descriptors to earlier copies',+ code: 'astryx upgrade --from 0.6.4 --path . --apply',},{type: 'prose',- text: 'Each theme ships as its own npm package. Install the one you want, then wrap your app in `<Theme>`. The same pattern works for every theme; just swap the package and import name.',+ text: 'Before the upgrade runs, theme commands skip a descriptor-less copy in `src/themes`. `theme list` and doctor name it as unmigrated and show the upgrade command. A script that meant to copy source now runs `theme eject` with the same arguments. A script that meant to make the app use a theme runs `theme add --import`.',},{type: 'prose',- text: 'The default import uses runtime style injection, which works everywhere with no build step. The `/built` import skips injection and relies on the pre-compiled CSS file for better performance and SSR support.',+ text: '`ASTRYX_THEME` is no longer read. Run `theme add <slug> --import` and `theme use <slug>` to choose the default in a generated app theme module. When that module exists, component metadata reads its recorded default theme. Without the module, the released `package.json#astryx.theme` lookup keeps its meaning.',},],},@@ -69,52 +87,52 @@ function App() {content: [{type: 'prose',- text: 'Install the theme package you want with `npm install @astryxdesign/theme-{name}`, then import its theme object as shown below.',+ text: 'Install the theme package you want with `npm install @astryxdesign/theme-{name}`, then import its slug with `theme add <slug> --import`. The CLI imports the package’s built outputs for you.',},{type: 'table',- headers: ['Theme', 'Import', 'Description'],+ headers: ['Theme', 'Add command', 'Description'],rows: [['Neutral',- "import {neutralTheme} from '@astryxdesign/theme-neutral'",+ 'astryx theme add neutral --import','Muted, minimal aesthetic with Figtree typography. A good starting point.',],['Butter',- "import {butterTheme} from '@astryxdesign/theme-butter'",+ 'astryx theme add butter --import','Golden, buttery surfaces with blue accents; Sarina + Outfit type.',],['Chocolate',- "import {chocolateTheme} from '@astryxdesign/theme-chocolate'",+ 'astryx theme add chocolate --import','Warm brown tones and cozy beige; Fraunces + Albert Sans type.',],['Gothic',- "import {gothicTheme} from '@astryxdesign/theme-gothic'",+ 'astryx theme add gothic --import','Dark-only atmospheric theme; deep blue-gray surfaces, distressed display type.',],['Matcha',- "import {matchaTheme} from '@astryxdesign/theme-matcha'",+ 'astryx theme add matcha --import','Earthy greens; DM Sans + Playwrite US Trad type.',],['Stone',- "import {stoneTheme} from '@astryxdesign/theme-stone'",+ 'astryx theme add stone --import','Warm stone and slate tones; Montserrat + Figtree type.',],['Y2K',- "import {y2kTheme} from '@astryxdesign/theme-y2k'",+ 'astryx theme add y2k --import','Playful Y2K pop; periwinkle body, holographic accents, Poppins + `Crimson Text`.',],],},{type: 'prose',- text: 'All theme packages export from two subpaths:\n- `@astryxdesign/theme-{name}`: source theme (runtime injection)\n- `@astryxdesign/theme-{name}/built`: pre-built theme (pair with `theme.css`)',+ text: 'Every first-party package exports its built theme at `@astryxdesign/theme-{name}/built`, production CSS at `/theme.css`, and font loading CSS at `/fonts.css`. `theme add --import` writes those imports into the generated app module.',},],},@@ -135,17 +153,17 @@ function App() {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`.',+ text: 'Install the integration as a direct dependency. Astryx discovers its themes and guides without an `astryx.config` entry. A theme can be added only when the installed package exports its built module and production stylesheet.',},{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',+ label: 'Install, inspect, and add',+ code: 'npm install @astryxdesign/core @acme/brand-integration\nastryx theme list --package @acme/brand-integration\nastryx docs brand-theme\nastryx theme add ocean --import --package @acme/brand-integration',},{type: 'prose',- text: 'The copy is editable project source, not a reference back into node_modules. The complete theme directory comes with it, including its typed `.doc.mjs`, nested token and palette modules, and receipts. A second add refuses to overwrite those files unless you pass `--overwrite`.',+ text: '`theme add --import` keeps the owner package in the app record and imports its built module, stylesheet, and optional font stylesheet. Package updates continue to reach the app. Run `theme eject ocean --package @acme/brand-integration` only to copy the source and descriptor into `src/themes/ocean` as an independent local fork.',},],},@@ -156,13 +174,13 @@ function App() {content: [{type: 'prose',- 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.',+ text: 'Use an installed built theme as the base for ordinary customization. Import it into your source and pass it as `extends` to `defineTheme({extends: importedTheme, ...})`. Build the result, then add the local slug. Only eject when you need to own and maintain a full source fork.',},{type: 'code',lang: 'bash',- label: 'Browse, then copy a theme in as editable source',- code: 'astryx theme list\nastryx theme add stone\nastryx theme add ocean --package @acme/themes',+ label: 'Add to use, eject to fork',+ code: 'astryx theme list\nastryx theme add stone --import\nastryx theme eject stone\nastryx theme build src/themes/stone/stoneTheme.ts\nastryx theme add stone --import',},{type: 'prose',@@ -246,7 +264,7 @@ const myTheme = defineTheme({lang: 'tsx',label: 'Extending the neutral theme',code: `import {defineTheme} from '@astryxdesign/core/theme';-import {neutralTheme} from '@astryxdesign/theme-neutral';+import {neutralTheme} from '@astryxdesign/theme-neutral/built';import {myIcons} from './icons';const brandTheme = defineTheme({@@ -628,41 +646,31 @@ esbuild src/themes/icons.tsx --bundle --format=esm --outfile=dist/icons.mjs \\content: [{type: 'prose',- text: 'Themes work in two modes:',+ text: 'Apps use built themes. The generated app module imports each theme object with its production CSS and optional font CSS, so every added theme is ready on first paint. Source-theme imports remain an authoring input for `theme build`, not the app wiring model.',},{type: 'table',- headers: ['', 'Runtime (source)', 'Built'],+ headers: ['App concern', 'Package theme', 'Local theme'],rows: [[- 'Import (published theme)',- '@astryxdesign/theme-{name}',- '@astryxdesign/theme-{name}/built + theme.css',- ],- [- 'Import (custom theme)',- 'defineTheme() directly',- 'Built .js + .css from `astryx theme build`',- ],- [- 'How it works',- 'useInsertionEffect injects <style> at hydration',- 'Pre-compiled .css file loaded with the page',+ 'Add',+ '`astryx theme add <slug> --import [--package <package>]`',+ '`astryx theme build <source>` then `astryx theme add <slug> --import`',],[- 'Component overrides',- 'Injected client-only',- 'In static CSS: present during SSR',+ 'Module import',+ 'Package `./built` or `./themes/<slug>` export',+ 'Built `<slug>.js` beside the source',],[- 'SSR safe',- 'Tokens yes, component overrides flash on hydration',- 'Fully SSR safe: no flash',+ 'Styles',+ '`./theme.css` or `./themes/<slug>.css`, plus optional font CSS',+ 'Built `<slug>.css`, plus optional `<slug>.fonts.css`',],[- 'Best for',- 'Dev, prototyping, client-only SPAs',- 'Production, SSR apps (Next.js, Remix)',+ 'Updates',+ 'Stay owned by the installed package',+ 'Stay owned and rebuilt by the app',],],},@@ -670,17 +678,18 @@ esbuild src/themes/icons.tsx --bundle --format=esm --outfile=dist/icons.mjs \\type: 'list',style: 'do',items: [- 'Use the /built subpath + theme.css for production SSR apps.',- 'Use runtime themes during development for fast iteration.',- 'Run `astryx theme build` for custom themes to get the built artifacts.',+ 'Import `themes` and `defaultThemeSlug` from the generated module once.',+ 'Extend an imported built theme for ordinary customization.',+ 'Use `theme eject` only when you want an independent source fork.',],},{type: 'list',style: 'dont',items: [- 'Use runtime themes in production SSR apps; component overrides will flash on hydration.',- "Import /built without the CSS file; component overrides won't apply.",+ 'Import package theme source into app runtime code.',+ "Import a built theme without its stylesheet; component overrides won't apply.",+ 'Hand-edit the generated theme module; add, remove, and use regenerate it.',],},],@@ -771,7 +780,7 @@ const pandaOrEmotionTheme = {lang: 'ts',label: 'Resolve token values without a hook',code: `import {resolveThemeTokens} from '@astryxdesign/core/theme/tokens';-import {neutralTheme} from '@astryxdesign/theme-neutral';+import {neutralTheme} from '@astryxdesign/theme-neutral/built';const lightTokens = resolveThemeTokens(neutralTheme, {mode: 'light'});const chartTheme = {diff --git a/packages/cli/assets/docs/theme.doc.zh.mjs b/packages/cli/assets/docs/theme.doc.zh.mjsindex 050d9ac3dc..9107741a04 100644--- a/packages/cli/assets/docs/theme.doc.zh.mjs+++ b/packages/cli/assets/docs/theme.doc.zh.mjs@@ -3,18 +3,164 @@/** @type {import('@astryxdesign/cli/authoring').ReferenceTranslationDoc} */export const docsZh = {- description: 'Theme 提供者、自定义主题、生产/SSR 主题构建、亮/暗模式和组件样式覆盖。',+ description:+ 'Theme 提供者、自定义主题、生产/SSR 主题构建、亮/暗模式和组件样式覆盖。',sections: [- { section: 'Wrap your app in a theme', 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: [{ type: 'prose', text: "`<Theme>` 接受 `theme`(必填)、`mode`(默认 `'system'`,也可以是 `'light'` 或 `'dark'`)和 `children`。运行 `astryx component Theme` 查看全部属性。" }] },- { section: 'Custom themes', 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: 'Build a theme', title: '构建主题', content: [{ type: 'prose', text: 'astryx theme build 将 defineTheme 编译为静态 CSS。输出 .css + .js(__built:true)+ .d.ts。' }] },- { section: 'Built themes with an icon registry', title: '带图标注册表的构建主题', content: [{ 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 移动输出位置也会改变相对导入的解析位置;使用打包器并不意味着它能自动找到原来的源码。' }] },- { section: 'Runtime vs Built Themes', title: '运行时 vs 构建', content: [{ type: 'prose', text: '运行时:useInsertionEffect 在客户端注入样式。构建:静态 CSS 在首次渲染时就存在。SSR 应用请使用 /built + theme.css。' }, null, null, null] },- { section: 'Dark mode', title: '亮/暗模式', content: [{ type: 'prose', text: "令牌值使用 [light, dark] 元组实现自动模式切换。Theme 上 mode='system'(默认)跟随系统偏好。" }, null, null] },- { section: 'Nested themes', title: '嵌套主题', content: [{ type: 'prose', text: '将不同部分包裹在独立的 <Theme> 提供者中。' }, null] },- { section: 'useTheme Hook', title: 'useTheme 钩子', content: [null, null, { type: 'prose', text: '普通样式优先使用 CSS 变量、StyleX 令牌导入、xstyle 或 className。useTheme() 是只读的:要更改主题或模式,在应用层管理状态并传递给 <Theme>。' }] },+ {+ section: 'Wrap your app in a theme',+ title: '用主题包裹应用',+ content: [+ null,+ null,+ null,+ null,+ {+ type: 'prose',+ text: '`theme add --import` 会生成应用主题模块,并导入构建后的主题、生产 CSS 和可选字体 CSS。应用只需导入一次 themes/defaultThemeSlug;use/remove 会重新生成模块。普通定制应扩展构建主题,只有需要独立源码分支时才使用 eject。',+ },+ ],+ },+ {+ section: 'Migrating Earlier Theme Copies',+ title: '迁移早期复制的主题',+ content: [+ {+ type: 'prose',+ text: '早期 `theme add` 复制的主题仍是应用源码。upgrade 只写入缺失的、maintained: false 的描述文件。',+ },+ null,+ {+ type: 'prose',+ text: '运行 upgrade 前,主题命令会跳过这些复制;list 和 doctor 会指出它们。旧的复制脚本改用 `theme eject`,应用使用主题的脚本改用 `theme add --import`。',+ },+ {+ type: 'prose',+ text: '`ASTRYX_THEME` 不再读取。用 `theme use <slug>` 选择生成的应用主题模块中的默认主题。该模块存在时,组件元数据读取记录中的默认主题;没有该模块时,package.json#astryx.theme 保持原有含义。',+ },+ ],+ },+ {+ section: 'Available Themes',+ title: '可用主题',+ content: [+ null,+ null,+ {+ type: 'prose',+ text: '已发布主题:neutral(推荐起点)、butter、chocolate、gothic(仅暗色)、matcha、stone、y2k。先安装 @astryxdesign/theme-{name},再运行 `theme add <name> --import`。包导出 /built、theme.css 和 fonts.css。',+ },+ ],+ },+ {+ section: 'Theme Props',+ title: 'Theme 属性',+ content: [+ {+ type: 'prose',+ text: "`<Theme>` 接受 `theme`(必填)、`mode`(默认 `'system'`,也可以是 `'light'` 或 `'dark'`)和 `children`。运行 `astryx component Theme` 查看全部属性。",+ },+ ],+ },+ {+ section: 'Custom themes',+ title: '自定义主题',+ content: [+ {+ type: 'prose',+ text: '普通定制应扩展已导入的构建主题,构建后再添加本地结果。`theme eject` 只用于创建独立维护的源码分支。只覆盖与基础主题不同的值。',+ },+ 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: 'Build a theme',+ title: '构建主题',+ content: [+ {+ type: 'prose',+ text: 'astryx theme build 将 defineTheme 编译为静态 CSS。输出 .css + .js(__built:true)+ .d.ts。',+ },+ ],+ },+ {+ section: 'Built themes with an icon registry',+ title: '带图标注册表的构建主题',+ content: [+ {+ 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 移动输出位置也会改变相对导入的解析位置;使用打包器并不意味着它能自动找到原来的源码。',+ },+ ],+ },+ {+ section: 'Runtime vs Built Themes',+ title: '运行时 vs 构建',+ content: [+ {+ type: 'prose',+ text: '应用使用构建主题。生成的模块会为每个主题同时导入主题对象、生产 CSS 和可选字体 CSS。包主题继续接收包更新,本地主题由应用维护。不要手动编辑生成模块。',+ },+ null,+ null,+ null,+ ],+ },+ {+ section: 'Dark mode',+ title: '亮/暗模式',+ content: [+ {+ type: 'prose',+ text: "令牌值使用 [light, dark] 元组实现自动模式切换。Theme 上 mode='system'(默认)跟随系统偏好。",+ },+ null,+ null,+ ],+ },+ {+ section: 'Nested themes',+ title: '嵌套主题',+ content: [+ {type: 'prose', text: '将不同部分包裹在独立的 <Theme> 提供者中。'},+ null,+ ],+ },+ {+ section: 'useTheme Hook',+ title: 'useTheme 钩子',+ content: [+ null,+ null,+ {+ type: 'prose',+ text: '普通样式优先使用 CSS 变量、StyleX 令牌导入、xstyle 或 className。useTheme() 是只读的:要更改主题或模式,在应用层管理状态并传递给 <Theme>。',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/add-a-theme.doc.mjs b/packages/cli/assets/docs/tree/add-a-theme.doc.mjsindex 4ce5fdc618..8e967d02f2 100644--- a/packages/cli/assets/docs/tree/add-a-theme.doc.mjs+++ b/packages/cli/assets/docs/tree/add-a-theme.doc.mjs@@ -44,11 +44,11 @@ Declare theme root ./themes in astryx.integration.mjs.},{type: 'prose',- text: "`oceanTheme.ts` exports `oceanTheme`, a `defineTheme` source. `oceanTheme.doc.mjs` describes it with `type: 'theme'`, `name`, `displayName`, `description`, and `maintained`; `theme list` shows its `name`, `description`, and `maintained`. Every field is in {@link generic:authoring}.",+ text: "`oceanTheme.ts` exports `oceanTheme`, a `defineTheme` source. `oceanTheme.doc.mjs` describes it with `type: 'theme'`, `name`, `displayName`, `description`, and `maintained`; `theme list` shows its `name`, `description`, and `maintained`. The command also declares `./themes/ocean` and `./themes/ocean.css` package exports. Every descriptor field is in {@link generic:authoring}.",},{type: 'prose',- text: 'The source ships in your package. An app installs the package and applies the theme — it is not copied; see {@link generic:use-a-theme-in-an-app}.',+ text: 'The source and built outputs ship in your package. Build the source with `theme build`, then run `integration verify` before publishing. An app runs `theme add --import` to record and import the built module and stylesheets; plain `theme add` still copies source while that default is deprecated. See {@link generic:use-a-theme-in-an-app}.',},],},diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjsindex 97949c4937..f89d88718f 100644--- a/packages/cli/assets/docs/tree/checks.doc.mjs+++ b/packages/cli/assets/docs/tree/checks.doc.mjs@@ -106,6 +106,7 @@ export const docs = {'It checks that every contribution file is in the `.tgz` file. A root missing from `files` fails with `Add "templates" to "files" in package.json.`','It lists the components, templates, themes, docs, and codemods the temporary app sees, and compares them with your source.',"It resolves each component's `import`, and each template's public import, the way Node does, and checks that the module exports the component, or a default export for a template.",+ 'For each theme, it rebuilds the source, compares the built module and production CSS with the authored outputs, and proves the module, CSS, and optional font CSS exports resolve from the packed package.','It fails a package that needs an `@astryxdesign/cli` peer and lacks it: `>=0.7.0` for a template that sets `replaces` or `keywords`, and `>=0.6.4` for a docs section, a placed guide, a doc section with an `id`, or a theme.',],},diff --git a/packages/cli/assets/docs/tree/document-the-theme.doc.mjs b/packages/cli/assets/docs/tree/document-the-theme.doc.mjsindex ee488f701f..bbdeac8308 100644--- a/packages/cli/assets/docs/tree/document-the-theme.doc.mjs+++ b/packages/cli/assets/docs/tree/document-the-theme.doc.mjs@@ -21,7 +21,7 @@ export const docs = {content: [{type: 'prose',- text: 'Give your theme a doc topic that extends the core `theme` topic, so an app that lists your package sees your theme at the end of `astryx docs theme`. Add it with `extends: \'theme\'` ({@link generic:extend-or-replace}).',+ text: "Give your theme a doc topic that extends the core `theme` topic, so an app that lists your package sees your theme at the end of `astryx docs theme`. Add it with `extends: 'theme'` ({@link generic:extend-or-replace}).",},{type: 'code',@@ -41,7 +41,7 @@ export default {content: [{type: 'prose',- text: "Add \`@acme/astryx-widgets\` to the app's dependencies and apply the Ocean theme with \`<Theme theme={oceanTheme}>\`.",+ text: 'Install @acme/astryx-widgets, then run astryx theme add ocean --import --package @acme/astryx-widgets and apply it from the generated app theme module.',},],},@@ -50,7 +50,7 @@ export default {},{type: 'prose',- text: 'Keep the section short: how to add the package, apply the theme ({@link generic:use-a-theme-in-an-app}), and — if the theme uses a custom font — which fonts the app must load ({@link generic:fonts-and-assets}). Extend `theme` rather than a topic another package replaces, or an app that lists that package first drops your section.',+ text: 'Keep the section short: how to install the package, run `theme add --import`, apply the generated module ({@link generic:use-a-theme-in-an-app}), and customize with `extends`. When the theme uses a custom font, name the families and the optional exported font stylesheet that `theme add --import` imports ({@link generic:fonts-and-assets}). Extend `theme` rather than a topic another package replaces, or an app that lists that package first drops your section.',},],},@@ -60,7 +60,7 @@ export default {content: [{type: 'prose',- text: 'Do not put theme usage in `agentDocs`. Agent lines land in every app\'s agent file and are for guidance needed every session; a theme\'s install-and-use steps belong in a doc topic that people and agents read on demand. See {@link generic:agent-guidance}.',+ text: "Do not put theme usage in `agentDocs`. Agent lines land in every app's agent file and are for guidance needed every session; a theme's install-and-use steps belong in a doc topic that people and agents read on demand. See {@link generic:agent-guidance}.",},],},diff --git a/packages/cli/assets/docs/tree/fonts-and-assets.doc.mjs b/packages/cli/assets/docs/tree/fonts-and-assets.doc.mjsindex 7446b4ebf5..ae4ac8e324 100644--- a/packages/cli/assets/docs/tree/fonts-and-assets.doc.mjs+++ b/packages/cli/assets/docs/tree/fonts-and-assets.doc.mjs@@ -2,7 +2,7 @@/*** @file `astryx docs cli/integrations/building-blocks/themes/fonts-and-assets`:- * name a theme's fonts, and have the app load them (Astryx never loads a font).+ * ship a theme's optional font loader beside its built module and CSS.*//** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */@@ -10,10 +10,10 @@ export const docs = {type: 'generic',name: 'fonts-and-assets',placement: {parent: 'namespace:themes', slot: 'guides', order: 35},- title: 'Fonts',+ title: 'Fonts and assets',category: 'guide',description:- 'Name your theme\'s fonts in its tokens, then have the app load them — Astryx never loads a font file.',+ 'Name the fonts in the theme, then export an optional font stylesheet that `theme add --import` imports with the built theme.',sections: [{id: 'name-the-font',@@ -43,28 +43,33 @@ export const oceanTheme = defineTheme({],},{- id: 'load-the-font-in-the-app',- title: 'Load the font in the app',+ id: 'ship-the-font-loader',+ title: 'Ship the font loader',content: [{type: 'prose',- text: 'Naming a family does not load it — Astryx never downloads a font file. The app that uses your theme loads the font itself, so your job is to tell your users which families and weights to load, in your theme\'s docs ({@link generic:document-the-theme}). An app loads a font one of two ways:',+ text: 'Naming a family does not load it. When the theme uses non-system fonts, add `<slug>.fonts.css` beside the built module and production CSS, then export it as `./themes/<slug>.fonts.css`. `theme add --import` imports that stylesheet with the built theme.',},{- type: 'list',- style: 'unordered',- items: [- 'Link a hosted stylesheet in the app\'s `<head>` — for example a Google Fonts `<link>` covering every weight the UI uses.',- 'Self-host: serve the font files and add an `@font-face` for each weight and style to the app\'s global CSS.',- ],+ type: 'code',+ lang: 'json',+ code: `"exports": {+ "./themes/ocean": "./themes/ocean/ocean.js",+ "./themes/ocean.css": "./themes/ocean/ocean.css",+ "./themes/ocean.fonts.css": "./themes/ocean/ocean.fonts.css"+}`,+ },+ {+ type: 'prose',+ text: 'The stylesheet can contain self-hosted `@font-face` rules or import a hosted stylesheet. A hosted `@import` is simple, but it delays loading compared with a preconnected `<link>`; choose that trade-off deliberately. If the app loads the same family outside the generated module, Doctor warns because it cannot prove the loader, but the warning does not fail the app.',},{type: 'code',lang: 'css',- code: `/* In the app's global CSS, when self-hosting */+ code: `/* themes/ocean/ocean.fonts.css */@font-face {font-family: 'Acme Sans';- src: url('/fonts/acme-sans.woff2') format('woff2');+ src: url('./fonts/acme-sans.woff2') format('woff2');font-weight: 100 900;font-style: normal;font-display: swap;@@ -75,10 +80,10 @@ export const oceanTheme = defineTheme({type: 'list',style: 'unordered',items: [- 'Load every weight and style the theme uses. Do not let the browser synthesize bold or italic — include the italic face, with the same `unicode-range`s as the roman.',- 'Set a `unicode-range` per face so the browser downloads only the subsets it needs.',- 'Use `font-display: swap` unless a measured need justifies another value.',- 'Serve WOFF2; add another format only when a target browser needs it.',+ 'Load every weight and style the theme uses. Do not let the browser synthesize bold or italic.',+ 'Include self-hosted font files and their licenses in the packed package.',+ 'Keep CSS and font assets side-effectful so a bundler does not remove the loader.',+ 'Run `integration verify`; it fails when an exported font stylesheet or one of its packed files cannot resolve.',],},],@@ -89,7 +94,7 @@ export const oceanTheme = defineTheme({content: [{type: 'prose',- text: 'Before publishing, install the package in a clean app, apply the theme, load the fonts, and open it in a browser. The source and the applied result are not the same thing until you look.',+ text: 'Before publishing, run `integration verify`. Then install the package in a clean app, run `theme add --import`, apply the generated theme, and open it in a browser. The source, packed exports, and applied result form one chain; check the last step too.',},{type: 'list',diff --git a/packages/cli/assets/docs/tree/themes.doc.mjs b/packages/cli/assets/docs/tree/themes.doc.mjsindex 76f7ed9072..9a384a5601 100644--- a/packages/cli/assets/docs/tree/themes.doc.mjs+++ b/packages/cli/assets/docs/tree/themes.doc.mjs@@ -23,11 +23,11 @@ export const docs = {blocks: [{type: 'prose',- text: 'A theme is an editable `defineTheme` source with a generated color palette. An integration ships a theme the same way a standalone theme package does: an app installs the package, applies the theme with `<Theme>`, and customizes it with `extends`. An integration theme and a standalone theme package are the same shape.',+ text: 'A theme contribution has editable `defineTheme` source plus a built module and production CSS. `integration add theme` scaffolds the source and declares the package exports; `theme build` writes the built outputs. An app installs the package, runs `theme add --import`, applies the theme from its generated app module, and customizes it with `extends` instead of copying source.',},{type: 'prose',- text: 'These guides cover authoring a theme inside an integration — scaffold it, generate its palette, define its tokens, ship its fonts, and document it. Using a theme, applying and extending it, is the same for every theme; see {@link generic:theme}.',+ text: 'These guides cover the whole path: scaffold the source, generate its palette, define and build the theme, ship fonts and assets, run `integration verify`, and document how apps add and extend it. Applying a theme, including mode and SSR, works the same for every theme; see {@link generic:theme}.',},],slots: {diff --git a/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs b/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjsindex 2e5b75874c..624e6a4531 100644--- a/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs+++ b/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs@@ -21,19 +21,24 @@ export const docs = {content: [{type: 'prose',- text: 'An app installs the integration as a dependency and applies your theme like any Astryx theme: wrap the app in `<Theme>`. The theme comes from the installed package — there is no copy step. Your theme only names its fonts; the app loads them ({@link generic:fonts-and-assets}).',+ text: 'Install the integration, then run `theme add --import` with its slug and package. The command records the package owner and regenerates one app theme module that imports the built theme, production CSS, and optional font CSS. Plain `theme add` still copies source while that default is deprecated.',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'npm install @acme/astryx-widgets\nnpx astryx theme add ocean --import --package @acme/astryx-widgets',},{type: 'code',lang: 'tsx',code: `import {Theme} from '@astryxdesign/core/theme';-import {oceanTheme} from '@acme/astryx-widgets/themes/ocean';+import {themes, defaultThemeSlug} from './astryx-themes';-<Theme theme={oceanTheme}>{/* app */}</Theme>`,+<Theme theme={themes[defaultThemeSlug]}>{/* app */}</Theme>`,},{type: 'prose',- text: 'The import specifier is whatever your integration exports for the theme. Applying a theme — `mode`, SSR, and the production build — works the same for every theme; see {@link generic:theme}.',+ text: '`theme list` shows the available, added, and default themes. Use `theme use <slug>` to change the default, `theme remove <slug>` to stop importing one, and `theme eject <slug>` only when the app needs an independent source fork. Applying a theme — `mode`, SSR, and the production build — works the same for every theme; see {@link generic:theme}.',},],},@@ -43,7 +48,19 @@ import {oceanTheme} from '@acme/astryx-widgets/themes/ocean';content: [{type: 'prose',- text: 'To change a theme, an app does not copy it — it derives a new one with `extends`: import your theme and override only the tokens it changes. See {@link generic:define-the-theme}.',+ text: 'For ordinary customization, do not copy the package source. Import the built theme and derive a new one with `defineTheme({extends: importedTheme, ...})`, overriding only the tokens the app changes. Use `theme eject` only when the app must own an independent source fork. See {@link generic:define-the-theme}.',+ },+ {+ type: 'code',+ lang: 'ts',+ code: `import {defineTheme} from '@astryxdesign/core/theme';+import {oceanTheme} from '@acme/astryx-widgets/themes/ocean';++export const productTheme = defineTheme({+ name: 'product',+ extends: oceanTheme,+ tokens: {'--color-accent': ['#0051a3', '#4aa3ff']},+});`,},],},diff --git a/packages/cli/assets/docs/tree/versioning.doc.mjs b/packages/cli/assets/docs/tree/versioning.doc.mjsindex c22785f3e6..cf167f9863 100644--- a/packages/cli/assets/docs/tree/versioning.doc.mjs+++ b/packages/cli/assets/docs/tree/versioning.doc.mjs@@ -60,7 +60,10 @@ export const docs = {'A template id, such as `acme-dashboard`','`npx astryx template acme-dashboard`',],- ['A theme slug, such as `ocean`', '`npx astryx theme add ocean`'],+ [+ 'A theme slug, such as `ocean`',+ '`npx astryx theme add ocean --import`',+ ],['A topic name or route, such as `acme/deploying`','Reads of the old name, and links to it from other docs',diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjsindex 6ee5d9ad32..232b257a84 100644--- a/packages/cli/authoring/integration/integration.doc.mjs+++ b/packages/cli/authoring/integration/integration.doc.mjs@@ -58,7 +58,7 @@ export const doc = {name: 'themes',type: 'string',description:- 'The folder that holds your themes, relative to package.json, with one folder per theme. Each theme folder has the theme source and a matching .doc.mjs file with the same name. Installed themes show up in `astryx theme list` and can be copied with `astryx theme add`.',+ 'The folder that holds your themes, relative to package.json, with one folder per theme. Each theme folder has the theme source and a matching .doc.mjs file with the same name. Installed themes show up in `astryx theme list`; `theme add --import` imports their built package exports, and `theme eject` creates an editable local fork.',example: "'./themes'",},{diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjsindex 55f49d1e94..c433ac99b2 100644--- a/packages/cli/clients/cli/commands/build-theme.mjs+++ b/packages/cli/clients/cli/commands/build-theme.mjs@@ -33,24 +33,37 @@ import {fileURLToPath} from 'node:url';import {spawn} from 'node:child_process';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';import {jsonOut} from '../../../foundation/response/json.mjs';-import {emit, section, text, list, records, code} from '../formatters/index.mjs';+import {+ emit,+ section,+ text,+ records,+ code,+ list,+} 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 {themeRemove} from '../../../api/theme/remove/remove.mjs';+import {themeUse} from '../../../api/theme/use/use.mjs';+import {themeEject} from '../../../api/theme/eject/eject.mjs';import {themeTemplate} from '../../../api/theme/template/template.mjs';-import {themeListAvailable} from '../../../api/theme/list/list.mjs';+import {+ themeListAvailable,+ themeListCopySources,+} from '../../../api/theme/list/list.mjs';import {themeTargets} from '../../../api/theme/targets/targets.mjs';import {serializePaletteCandidate,themePaletteGenerate,} from '../../../api/theme/palette/generate/generate.mjs';import {+ importSpecifier,themeBuild,themeBuildFamily,- importSpecifier,} from '../../../api/theme/build/build.mjs';import {defineCommand} from '../lib/define-command.mjs';import {NO_RESULT_SET, resultSet} from '../../../foundation/debug/index.mjs';@@ -58,6 +71,9 @@ import {doc as themeGroup} from './theme.doc.mjs';import {doc as themeBuildCommand} from './theme-build.doc.mjs';import {doc as themeListCommand} from './theme-list.doc.mjs';import {doc as themeAddCommand} from './theme-add.doc.mjs';+import {doc as themeRemoveCommand} from './theme-remove.doc.mjs';+import {doc as themeUseCommand} from './theme-use.doc.mjs';+import {doc as themeEjectCommand} from './theme-eject.doc.mjs';import {doc as themeTemplateCommand} from './theme-template.doc.mjs';import {doc as themeTargetsCommand} from './theme-targets.doc.mjs';import {doc as themePaletteGroup} from './theme-palette.doc.mjs';@@ -65,6 +81,9 @@ import {doc as themePaletteGenerateCommand} from './theme-palette-generate.doc.mimport {doc as themeBuildFn} from '../../../api/theme/themeBuild.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 themeRemoveFn} from '../../../api/theme/themeRemove.doc.mjs';+import {doc as themeUseFn} from '../../../api/theme/themeUse.doc.mjs';+import {doc as themeEjectFn} from '../../../api/theme/themeEject.doc.mjs';import {doc as themeTemplateFn} from '../../../api/theme/themeTemplate.doc.mjs';import {doc as themeTargetsFn} from '../../../api/theme/themeTargets.doc.mjs';import {doc as themePaletteGenerateFn} from '../../../api/theme/themePaletteGenerate.doc.mjs';@@ -203,12 +222,10 @@ async function warnOnThemeIntegrationIssues(json) {}/**- * 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.+ * Preserve the released human projection of `theme add --list`.* @param {import('../../../api/theme/theme.type.mjs').ThemeListEntry[]} themes*/-function printThemeList(themes) {+function printThemeAddList(themes) {const run = getCliInvocation();// `theme list` shows what this project can add now. Themes in packages it// has not installed are `discover`'s.@@ -222,10 +239,10 @@ function printThemeList(themes) {emit(section('Themes'),list(- themes.map(t => {- const status = t.maintained ? 'maintained' : 'example';- const head = `${t.slug} (${status}, ${t.package})`;- return t.description ? [head, t.description] : head;+ themes.map(theme => {+ const status = theme.maintained ? 'maintained' : 'example';+ const head = `${theme.slug} (${status}, ${theme.package})`;+ return theme.description ? [head, theme.description] : head;}),),text(@@ -235,6 +252,144 @@ function printThemeList(themes) {);}+/**+ * Print every field in the `theme.list` entries. Duplicate slugs stay separate+ * because each record names its owner.+ * @param {import('../../../api/theme/theme.type.mjs').ThemeListEntry[]} themes+ * @param {import('../../../api/theme/theme.type.mjs').ThemeUnmigratedCopy[]} [unmigratedCopies]+ */+function printThemeList(themes, unmigratedCopies = []) {+ const run = getCliInvocation();+ const more = text(+ `More themes in packages you could add: ${run} discover theme`,+ );+ if (themes.length === 0) {+ emit(text('No themes are available in this project.'), more);+ } else {+ emit(+ section('Themes', `${themes.length} available`),+ records(themes, {+ fields: [+ 'slug',+ 'displayName',+ 'description',+ 'maintained',+ 'package',+ 'source',+ 'added',+ 'default',+ ],+ layout: 'stacked',+ format: {+ maintained: (/** @type {boolean} */ value) => (value ? 'yes' : 'no'),+ added: (/** @type {boolean} */ value) => (value ? 'yes' : 'no'),+ default: (/** @type {boolean} */ value) => (value ? 'yes' : 'no'),+ },+ }),+ text(+ `Import one: ${run} theme add <slug> --import [--package <package>]\n` ++ `Fork source: ${run} theme eject <slug> [target-path]`,+ ),+ more,+ );+ }+ if (unmigratedCopies.length > 0) {+ emit(+ section(+ 'Unmigrated theme copies',+ `${unmigratedCopies.length} not listed as themes`,+ ),+ records(unmigratedCopies, {+ fields: ['slug', 'path', 'source', 'descriptor'],+ layout: 'stacked',+ }),+ text(`Migrate them: ${unmigratedCopies[0].upgradeCommand}`),+ );+ }+}++/**+ * Print every `theme.app` receipt field and the one-time app wiring on the first+ * add.+ * @param {import('../../../api/theme/theme.type.mjs').ThemeAppResponse} result+ */+function printThemeApp(result) {+ const {themes, default: defaultSlug, modulePath, change} = result.data;+ emit(+ section('App themes', `${themes.length} added`),+ records(themes, {+ fields: [+ 'slug',+ 'owner',+ 'module',+ 'stylesheet',+ 'fontStylesheet',+ 'source',+ ],+ layout: 'stacked',+ }),+ records(+ [+ {+ default: defaultSlug,+ modulePath,+ action: change.action,+ slug: change.slug,+ changed: change.changed,+ firstAdd: change.firstAdd,+ },+ ],+ {+ fields: [+ 'default',+ 'modulePath',+ 'action',+ 'slug',+ 'changed',+ 'firstAdd',+ ],+ layout: 'stacked',+ },+ ),+ );+ if (!change.firstAdd) return;+ const stem = path.basename(modulePath, path.extname(modulePath));+ emit(+ text('Wire the generated module once in the app root:'),+ code(+ `import {themes, defaultThemeSlug} from './${stem}';\n\n` ++ '<Theme theme={themes[defaultThemeSlug]}>\n <App />\n</Theme>',+ ),+ );+}++/**+ * Print every field in a source-fork receipt.+ * @param {import('../../../api/theme/theme.type.mjs').ThemeEjectResponse} result+ */+function printThemeEject(result) {+ const {data} = result;+ emit(+ section('Ejected theme'),+ records([data], {+ fields: [+ 'slug',+ 'displayName',+ 'maintained',+ 'package',+ 'outputDir',+ 'entry',+ 'exportName',+ 'files',+ ],+ layout: 'stacked',+ }),+ text(+ `This is a local fork. Build it with ${getCliInvocation()} theme build ${path.join(data.outputDir, data.entry)}.`,+ ),+ );+}+/*** @param {import('commander').Command} program*/@@ -588,7 +743,7 @@ export function registerTheme(program) {return answered;}- printThemeList(result.data);+ printThemeList(result.data, result.meta?.unmigratedCopies);return answered;},});@@ -598,26 +753,22 @@ export function registerTheme(program) {action: async (/** @type {string | undefined} */ slug,/** @type {string | undefined} */ targetPath,- /** @type {{list?: boolean, overwrite?: boolean, package?: string}} */ options,+ /** @type {{list?: boolean, overwrite?: boolean, import?: boolean, package?: string}} */ options,) => {const json = program.opts().json || false;-- // The CLI is non-interactive: never prompt to confirm an overwrite.- // Existing files require an explicit --overwrite; otherwise themeAdd's- // ERR_FILE_EXISTS guard rejects the write. `--list` (or a bare `theme add`- // with no slug) is the list affordance — route it to the list leaf.- /** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse | import('../../../api/theme/theme.type.mjs').ThemeAddResponse} */+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse | import('../../../api/theme/theme.type.mjs').ThemeAddResponse | import('../../../api/theme/theme.type.mjs').ThemeAppResponse} */let result;try {result =options.list || !slug- ? await themeListAvailable({+ ? await themeListCopySources({cwd: process.cwd(),package: options.package,}): await themeAdd(slug, {targetPath,overwrite: options.overwrite,+ import: options.import,cwd: process.cwd(),package: options.package,});@@ -631,8 +782,6 @@ export function registerTheme(program) {}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'? resultSet({count: result.data.length, resultKind: 'theme'})@@ -642,13 +791,15 @@ export function registerTheme(program) {jsonOut(result);return answered;}-if (result.type === 'theme.list') {- printThemeList(result.data);+ printThemeAddList(result.data);+ return answered;+ }+ if (result.type === 'theme.app') {+ printThemeApp(result);return answered;}- // theme.add — print where files landed + how to use the theme.const {displayName,outputDir,@@ -663,7 +814,7 @@ export function registerTheme(program) {);emit(text(`[ok] Added ${displayName} theme from ${owner} to ${outputDir}/`),- list(files.map(f => `${outputDir}/${f}`)),+ list(files.map(file => `${outputDir}/${file}`)),text('Use it in your app (import path is relative to a file in src/ — adjust if yours lives elsewhere):',),@@ -675,10 +826,91 @@ export function registerTheme(program) {`This is your copy of the ${displayName} theme — edit ${entry} to make it your own.`,),);+ console.error(+ `Warning: \`theme add\` source copying is deprecated (DEP-0005). Run \`${getCliInvocation()} theme eject ${result.data.slug}\` to fork source or \`${getCliInvocation()} theme add ${result.data.slug} --import\` to use the built theme.`,+ );return answered;},});+ defineCommand(theme, themeRemoveCommand, {+ fn: themeRemoveFn,+ action: async (/** @type {string} */ slug) => {+ const json = program.opts().json || false;+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeAppResponse} */+ let result;+ try {+ result = await themeRemove(slug, {cwd: process.cwd()});+ } catch (e) {+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);+ return cliError(err.message, {+ suggestions: err.suggestions || [],+ code: err.code,+ });+ }+ await warnOnThemeIntegrationIssues(json);+ if (json) jsonOut(result);+ else printThemeApp(result);+ return NO_RESULT_SET;+ },+ });++ defineCommand(theme, themeUseCommand, {+ fn: themeUseFn,+ action: async (/** @type {string} */ slug) => {+ const json = program.opts().json || false;+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeAppResponse} */+ let result;+ try {+ result = await themeUse(slug, {cwd: process.cwd()});+ } catch (e) {+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);+ return cliError(err.message, {+ suggestions: err.suggestions || [],+ code: err.code,+ });+ }+ await warnOnThemeIntegrationIssues(json);+ if (json) jsonOut(result);+ else printThemeApp(result);+ return NO_RESULT_SET;+ },+ });++ defineCommand(theme, themeEjectCommand, {+ fn: themeEjectFn,+ action: async (+ /** @type {string} */ slug,+ /** @type {string | undefined} */ targetPath,+ /** @type {{overwrite?: boolean, package?: string}} */ options,+ ) => {+ const json = program.opts().json || false;+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeEjectResponse} */+ let result;+ try {+ result = await themeEject(slug, {+ targetPath,+ overwrite: options.overwrite,+ cwd: process.cwd(),+ package: options.package,+ });+ } catch (e) {+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);+ return cliError(err.message, {+ suggestions: err.suggestions || [],+ code: err.code,+ });+ }+ await warnOnThemeIntegrationIssues(json);+ if (json) jsonOut(result);+ else printThemeEject(result);+ return NO_RESULT_SET;+ },+ });+defineCommand(theme, themeTemplateCommand, {fn: themeTemplateFn,action: (@@ -779,7 +1011,14 @@ export function registerTheme(program) {`${targets.length} across ${componentCount} component${componentCount === 1 ? '' : 's'}\n(key - component - props - states - className - deprecatedFor)`,),records(targets, {- fields: ['key', 'component', 'props', 'states', 'className', 'deprecatedFor'],+ fields: [+ 'key',+ 'component',+ 'props',+ 'states',+ 'className',+ 'deprecatedFor',+ ],layout: 'inline',format: {deprecatedFor: (/** @type {string|null} */ v) =>diff --git a/packages/cli/clients/cli/commands/component/index.mjs b/packages/cli/clients/cli/commands/component/index.mjsindex 193c7c0e60..81f9814878 100644--- a/packages/cli/clients/cli/commands/component/index.mjs+++ b/packages/cli/clients/cli/commands/component/index.mjs@@ -93,7 +93,7 @@ function summarize(result) {* @param {import('../../../../api/component/component.type.mjs').ComponentSingleResponse} result* @param {string} requestedName* @param {'full'|'compact'|'brief'} detail- * @param {ReturnType<typeof resolveTheme>} themeData+ * @param {Awaited<ReturnType<typeof resolveTheme>>} themeData* @returns {import('../../formatters/index.mjs').Block[]}*/function componentDetailBlocks(result, requestedName, detail, themeData) {@@ -255,7 +255,18 @@ export function registerComponent(program) {// The api layer already resolved against core (result exists), so core is// present on this path; narrow away the null branch findCoreDir allows.const coreDir = /** @type {string} */ (findCoreDir(process.cwd()));- const themeData = resolveTheme(process.cwd());+ let themeData;+ try {+ themeData = await resolveTheme(process.cwd());+ } catch (error) {+ const message =+ error instanceof Error+ ? error.message.split('\n', 1)[0]?.trim() || error.name+ : String(error);+ return cliError(`Could not load the recorded theme: ${message}`, {+ code: ERROR_CODES.ERR_THEME_LOAD,+ });+ }// Footer shared by the compact + names list views (prose → text()).const listFooter = text(diff --git a/packages/cli/clients/cli/commands/docs.test.mjs b/packages/cli/clients/cli/commands/docs.test.mjsindex 50faea28d0..82c9471f93 100644--- a/packages/cli/clients/cli/commands/docs.test.mjs+++ b/packages/cli/clients/cli/commands/docs.test.mjs@@ -198,8 +198,8 @@ describe('blocks as text', () => {it('prints the labels of a real section above their fences', async () => {const {status, stdout} = await runCli(['docs', 'theme', 'quick-start']);expect(status).toBe(0);- expect(stdout).toContain('Install a theme package:\n```bash\nnpm install');- expect(stdout).not.toContain('// Install a theme package');+ expect(stdout).toContain('Install and add a theme:\n```bash\nnpm install');+ expect(stdout).not.toContain('// Install and add a theme');}, SLOW);});diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjsindex 71416b24e9..00611df301 100644--- a/packages/cli/clients/cli/commands/doctor.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs@@ -16,7 +16,7 @@ export const doc = {summary: 'Diagnose Astryx projects and integration packages',description:'Runs read-only project health diagnostics by default: Node version, @astryxdesign/core ' +- 'install and version alignment, themes, config, integrations (linked without a config entry, ' ++ 'install and version alignment, generated app themes when present, earlier copied-theme migration, config, integrations (linked without a config entry, ' +'provider identity, contribution issues), agent docs, core peer dependencies, package manager, ' +"and the docs the CLI reads. It writes nothing, but loading astryx.config runs that file's code. " +'The `integration` subcommands provide authoring checks for one integration package.',diff --git a/packages/cli/clients/cli/commands/doctor.test.mjs b/packages/cli/clients/cli/commands/doctor.test.mjsindex ed54add32f..7265e4d199 100644--- a/packages/cli/clients/cli/commands/doctor.test.mjs+++ b/packages/cli/clients/cli/commands/doctor.test.mjs@@ -14,7 +14,6 @@ import {checkNodeVersion,checkCoreInstalled,checkVersionAlignment,- checkThemes,checkConfig,checkAgentDocs,checkPeerDeps,@@ -63,33 +62,6 @@ function installPkg(name, version = '1.0.0') {return dir;}-/**- * Mirror pnpm's layout: the real package lives under node_modules/.pnpm and- * the entry in the scope directory is a symlink to it.- */-function installPkgPnpmStyle(name, version = '1.0.0') {- const realDir = path.join(- tmpDir,- 'node_modules',- '.pnpm',- `${name.replace('/', '+')}@${version}`,- 'node_modules',- ...name.split('/'),- );- fs.mkdirSync(realDir, {recursive: true});- fs.writeFileSync(- path.join(realDir, 'package.json'),- JSON.stringify({name, version, main: 'index.js'}),- );- fs.writeFileSync(path.join(realDir, 'index.js'), 'module.exports = {};');- const linkPath = path.join(tmpDir, 'node_modules', ...name.split('/'));- fs.mkdirSync(path.dirname(linkPath), {recursive: true});- // 'junction' keeps this working on Windows without elevated permissions;- // it is ignored on posix.- fs.symlinkSync(realDir, linkPath, 'junction');- return linkPath;-}-function find(checks, id) {return checks.find(c => c.id === id);}@@ -128,29 +100,15 @@ describe('doctor — individual checks', () => {expect(res.status).toBe('info');});- it('themes: WARN when no theme packages installed', () => {- const res = checkThemes({cwd: tmpDir, configTheme: null});- expect(res.status).toBe('warn');- });-- it('themes: WARN when theme installed but not wired', () => {- installPkg('@astryxdesign/theme-neutral', '0.0.14');- const res = checkThemes({cwd: tmpDir, configTheme: null});- expect(res.status).toBe('warn');- expect(res.message).toContain('@astryxdesign/theme-neutral');- });-- it('themes: PASS when theme installed and wired via config', () => {- installPkg('@astryxdesign/theme-neutral', '0.0.14');- const res = checkThemes({cwd: tmpDir, configTheme: 'default'});- expect(res.status).toBe('pass');- });-- it('themes: detects pnpm-style symlinked theme packages (#3530)', () => {- installPkgPnpmStyle('@astryxdesign/theme-neutral', '0.1.2');- const res = checkThemes({cwd: tmpDir, configTheme: 'default'});- expect(res.status).toBe('pass');- expect(res.message).toContain('@astryxdesign/theme-neutral');+ it('app themes: reports unmanaged state as one INFO check', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"app"}\n');+ const result = await runChecks({cwd: tmpDir});+ const themeChecks = result.checks.filter(check =>+ check.id.startsWith('theme-'),+ );+ expect(themeChecks).toEqual([+ expect.objectContaining({id: 'theme-management', status: 'info'}),+ ]);});it('config: INFO when no astryx.config.mjs', async () => {diff --git a/packages/cli/clients/cli/commands/init.next-steps.test.mjs b/packages/cli/clients/cli/commands/init.next-steps.test.mjsindex 28bbf90dd6..4f91541d1c 100644--- a/packages/cli/clients/cli/commands/init.next-steps.test.mjs+++ b/packages/cli/clients/cli/commands/init.next-steps.test.mjs@@ -1,22 +1,11 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Regression test for `astryx init` "Next steps" theme guidance.+ * @file Regression tests for `astryx init` app-theme next steps.*- * The init command previously steered users toward the slower runtime- * style-injection path:- *- * import { neutralTheme } from '@astryxdesign/theme-neutral'- * <Theme theme={neutralTheme}>...</Theme>- *- * ...which contradicted the runtime console warning emitted by core's- * <Theme> component (packages/core/src/theme/Theme.tsx) recommending the- * pre-built path, and left users with an unstyled app because the base CSS- * imports were never mentioned (facebook/astryx#3080).- *- * These assertions lock in the corrected guidance: base CSS imports, the- * pre-built (`/built` + `theme.css`) theme path, and the custom-theme build- * command.+ * The guidance follows the generated-module workflow: base CSS once, add an+ * installed theme, import the generated record once, extend to customize, and+ * eject only to make an independent source fork.*/import {describe, it, expect} from 'vitest';@@ -30,17 +19,23 @@ describe('init Next steps theme guidance', () => {expect(text).toContain("'@astryxdesign/core/astryx.css'");});- it('uses the pre-built theme path matching the runtime recommendation', () => {- expect(text).toContain("'@astryxdesign/theme-neutral/built'");- expect(text).toContain("'@astryxdesign/theme-neutral/theme.css'");+ it('adds an installed theme through the CLI', () => {+ expect(text).toContain('npm install @astryxdesign/theme-neutral');+ expect(text).toContain('npx astryx theme add neutral --import');+ });++ it('wires the generated theme record once', () => {+ expect(text).toContain("{ themes, defaultThemeSlug } from './astryx-themes'");+ expect(text).toContain('themes[defaultThemeSlug]');});- it('mentions building custom themes via `astryx theme build`', () => {- expect(text).toContain('astryx theme build <file>');+ it('names extension for customization and eject only for a source fork', () => {+ expect(text).toContain('Extend an imported theme');+ expect(text).toContain('npx astryx theme eject <slug>');+ expect(text).toContain('only to fork source');});- it('does not steer users to the runtime style-injection import', () => {- // The bare source import (no `/built`) is the slow runtime-injection path.- expect(text).not.toContain("from '@astryxdesign/theme-neutral'");+ it('does not teach a direct package theme import', () => {+ expect(text).not.toContain("from '@astryxdesign/theme-neutral");});});diff --git a/packages/cli/clients/cli/commands/integration-real-world.test.mjs b/packages/cli/clients/cli/commands/integration-real-world.test.mjsindex 021e067b43..de48b6b77d 100644--- a/packages/cli/clients/cli/commands/integration-real-world.test.mjs+++ b/packages/cli/clients/cli/commands/integration-real-world.test.mjs@@ -3,7 +3,8 @@/*** @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 packed docs, codemods, and source themes.+ * no-config consumer, then exercises packed docs, codemods, built themes, and+ * explicit source ejection.*/import {afterEach, describe, expect, it} from 'vitest';@@ -201,6 +202,15 @@ export const oceanTheme = defineTheme({});`,);+ const providerBuild = await runCli(+ ['theme', 'build', 'themes/ocean/oceanTheme.ts', '--json'],+ providerDir,+ );+ expect(providerBuild.status, providerBuild.stderr).toBe(0);+ expect(parseEnvelope(providerBuild.stdout)).toMatchObject({+ type: 'theme.build',+ data: {name: 'ocean'},+ });const providerPackage = JSON.parse(fs.readFileSync(path.join(providerDir, 'package.json'), 'utf-8'),@@ -313,8 +323,8 @@ export const oceanTheme = defineTheme({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`.+ // Core package as the consumer's normal app dependency so an ejected source+ // can build against 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});@@ -427,7 +437,7 @@ export const oceanTheme = defineTheme({}const ambiguous = await runCli(- ['theme', 'add', 'ocean', 'src/themes/ambiguous', '--json'],+ ['theme', 'add', 'ocean', '--json'],consumerDir,);expect(ambiguous.status).not.toBe(0);@@ -435,11 +445,50 @@ export const oceanTheme = defineTheme({code: 'ERR_AMBIGUOUS_THEME',});+ const addedTheme = await runCli(+ [+ 'theme',+ 'add',+ 'ocean',+ '--import',+ '--package',+ '@acme/brand-integration',+ '--json',+ ],+ consumerDir,+ );+ expect(addedTheme.status, addedTheme.stderr).toBe(0);+ expect(parseEnvelope(addedTheme.stdout)).toMatchObject({+ type: 'theme.app',+ data: {+ default: 'ocean',+ change: {action: 'add', slug: 'ocean', changed: true},+ themes: [+ {+ slug: 'ocean',+ owner: '@acme/brand-integration',+ module: '@acme/brand-integration/themes/ocean',+ stylesheet: '@acme/brand-integration/themes/ocean.css',+ },+ ],+ },+ });+ const generatedModule = fs.readFileSync(+ path.join(consumerDir, 'src', 'astryx-themes.js'),+ 'utf-8',+ );+ expect(generatedModule).toContain(+ 'from "@acme/brand-integration/themes/ocean"',+ );+ expect(generatedModule).toContain(+ 'import "@acme/brand-integration/themes/ocean.css"',+ );+const target = path.join('src', 'themes', 'acme-ocean');const copied = await runCli(['theme',- 'add',+ 'eject','ocean',target,'--package',@@ -450,17 +499,17 @@ export const oceanTheme = defineTheme({);expect(copied.status, copied.stderr).toBe(0);expect(parseEnvelope(copied.stdout)).toMatchObject({- type: 'theme.add',+ type: 'theme.eject',data: {slug: 'ocean',package: '@acme/brand-integration',outputDir: target,- files: [+ files: expect.arrayContaining(['oceanTheme.ts','oceanTheme.doc.mjs','tokens/ocean.palette.receipt.json','tokens/ocean.palette.ts',- ],+ ]),},});expect(@@ -501,7 +550,7 @@ export const oceanTheme = defineTheme({const duplicate = await runCli(['theme',- 'add',+ 'eject','ocean',target,'--package',@@ -517,7 +566,7 @@ export const oceanTheme = defineTheme({const overwritten = await runCli(['theme',- 'add',+ 'eject','ocean',target,'--package',@@ -528,7 +577,7 @@ export const oceanTheme = defineTheme({consumerDir,);expect(overwritten.status, overwritten.stderr).toBe(0);- expect(parseEnvelope(overwritten.stdout).type).toBe('theme.add');+ expect(parseEnvelope(overwritten.stdout).type).toBe('theme.eject');const installedCodemod = path.join(installedDir,@@ -594,7 +643,7 @@ export const oceanTheme = defineTheme({const corruptedInstall = await runCli(['theme',- 'add',+ 'eject','ocean','src/themes/corrupted','--package',diff --git a/packages/cli/clients/cli/commands/no-prompt-wording.test.mjs b/packages/cli/clients/cli/commands/no-prompt-wording.test.mjsindex e09afc2d0e..16ce432699 100644--- a/packages/cli/clients/cli/commands/no-prompt-wording.test.mjs+++ b/packages/cli/clients/cli/commands/no-prompt-wording.test.mjs@@ -50,13 +50,13 @@ async function optionText(command, flag) {}describe('no help text describes a prompt', () => {- it('theme add --overwrite states the refusal, and a refused run writes nothing', async () => {- const help = await optionText('theme add', '--overwrite');+ it('theme eject --overwrite states the refusal, and a refused run writes nothing', async () => {+ const help = await optionText('theme eject', '--overwrite');expect(help).not.toMatch(/prompt/i);expect(help).toContain('ERR_FILE_EXISTS');expect(help).toMatch(/nothing is written/);- const first = await runCli(['--json', 'theme', 'add', 'matcha'], tmpDir);+ const first = await runCli(['--json', 'theme', 'eject', 'matcha'], tmpDir);expect(first.status).toBe(0);const {outputDir, files} = JSON.parse(first.stdout).data;expect(files.length).toBeGreaterThan(1);@@ -64,7 +64,7 @@ describe('no help text describes a prompt', () => {fs.writeFileSync(path.join(dir, files[0]), '// edited\n');fs.rmSync(path.join(dir, files[1]));- const refused = await runCli(['--json', 'theme', 'add', 'matcha'], tmpDir);+ const refused = await runCli(['--json', 'theme', 'eject', 'matcha'], tmpDir);expect(refused.status).toBe(1);expect(JSON.parse(refused.stdout).code).toBe('ERR_FILE_EXISTS');expect(fs.readFileSync(path.join(dir, files[0]), 'utf8')).toBe('// edited\n');diff --git a/packages/cli/clients/cli/commands/search.test.mjs b/packages/cli/clients/cli/commands/search.test.mjsindex f288dd4955..4f75e7f791 100644--- a/packages/cli/clients/cli/commands/search.test.mjs+++ b/packages/cli/clients/cli/commands/search.test.mjs@@ -123,7 +123,7 @@ describe('search() API — filters', () => {expect(data.results.map(r => r.name)).toContain('neutral');for (const r of data.results) {expect(r.domain).toBe('theme');- expect(r.command).toBe(`astryx theme add ${r.name}`);+ expect(r.command).toBe(`astryx theme add --import ${r.name}`);}});diff --git a/packages/cli/clients/cli/commands/text-json-parity.test.mjs b/packages/cli/clients/cli/commands/text-json-parity.test.mjsindex 6bd9358e66..560994bd69 100644--- a/packages/cli/clients/cli/commands/text-json-parity.test.mjs+++ b/packages/cli/clients/cli/commands/text-json-parity.test.mjs@@ -449,6 +449,24 @@ const CASES = [// Themes are rendered as list items, not records.skipFieldChecks: true,},+ {+ name: 'theme remove',+ args: ['theme', 'remove', 'does-not-exist'],+ errorExpected: true,+ skipFieldChecks: true,+ },+ {+ name: 'theme use',+ args: ['theme', 'use', 'does-not-exist'],+ errorExpected: true,+ skipFieldChecks: true,+ },+ {+ name: 'theme eject',+ args: ['theme', 'eject', 'does-not-exist'],+ errorExpected: true,+ skipFieldChecks: true,+ },{name: 'theme build',args: ['theme', 'build', 'nonexistent.ts'],diff --git a/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs b/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjsnew file mode 100644index 0000000000..5886680a2b--- /dev/null+++ b/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs@@ -0,0 +1,129 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Compatibility and deprecation coverage for the two-step theme-add lifecycle. */++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 {runCli} from '../../../test-utils/run-cli.mjs';++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-add-cli-'));+ fs.mkdirSync(path.join(tmpDir, 'src'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'app', private: true}),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('theme add compatibility lifecycle', () => {+ it('keeps copy stdout and emits one text-only deprecation warning', async () => {+ const result = await runCli(['theme', 'add', 'neutral'], tmpDir);++ expect(result.status, result.stderr).toBe(0);+ expect(result.stdout).toContain(+ '[ok] Added Neutral theme from @astryxdesign/cli to src/themes/neutral/',+ );+ expect(result.stdout).toContain('This is your copy of the Neutral theme');+ expect(result.stderr.match(/source copying is deprecated/g)).toHaveLength(+ 1,+ );+ expect(result.stderr).toContain('pnpm exec astryx theme eject neutral');+ expect(result.stderr).toContain(+ 'pnpm exec astryx theme add neutral --import',+ );+ expect(fs.existsSync(path.join(tmpDir, 'src/themes/neutral'))).toBe(true);+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(+ false,+ );+ });++ it('keeps theme.add data and adds machine-readable deprecation metadata', async () => {+ const result = await runCli(['theme', 'add', 'neutral', '--json'], tmpDir);++ expect(result.status, result.stderr).toBe(0);+ expect(result.stderr).not.toContain('source copying is deprecated');+ expect(JSON.parse(result.stdout)).toMatchObject({+ type: 'theme.add',+ data: {+ slug: 'neutral',+ package: '@astryxdesign/cli',+ outputDir: 'src/themes/neutral',+ },+ meta: {+ deprecations: [+ {+ id: 'DEP-0005',+ replacements: ['theme eject', 'theme add --import'],+ },+ ],+ },+ });+ });++ it('keeps the list path unchanged and warning-free', async () => {+ fs.mkdirSync(path.join(tmpDir, 'src/themes/broken'), {recursive: true});+ fs.writeFileSync(+ path.join(tmpDir, 'src/themes/broken/brokenTheme.ts'),+ 'export const brokenTheme = {};\n',+ );++ const textResult = await runCli(['theme', 'add', '--list'], tmpDir);+ expect(textResult.status, textResult.stderr).toBe(0);+ expect(textResult.stdout).toContain(+ 'theme add <slug> [target-path] Scaffold a theme file you own',+ );+ expect(textResult.stdout).not.toContain('theme add <slug> --import');+ expect(textResult.stderr).not.toContain('deprecated');++ const result = await runCli(['theme', 'add', '--list', '--json'], tmpDir);++ expect(result.status, result.stderr).toBe(0);+ const payload = JSON.parse(result.stdout);+ expect(payload).toMatchObject({type: 'theme.list'});+ expect(payload.meta).toBeUndefined();+ expect(payload.data.some(theme => theme.slug === 'broken')).toBe(false);+ expect(Object.keys(payload.data[0]).sort()).toEqual([+ 'description',+ 'displayName',+ 'maintained',+ 'package',+ 'slug',+ ]);+ expect(result.stderr).not.toContain('deprecated');+ });++ it.each([+ ['target path', ['src/brand']],+ ['overwrite', ['--overwrite']],+ ])('rejects --import with a %s before writing', async (_label, extra) => {+ const result = await runCli(+ ['theme', 'add', 'neutral', '--import', ...extra, '--json'],+ tmpDir,+ );++ expect(result.status).not.toBe(0);+ expect(JSON.parse(result.stdout)).toMatchObject({+ code: 'ERR_THEME_INVALID',+ error: expect.stringContaining('cannot be combined'),+ });+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(+ false,+ );+ expect(fs.existsSync(path.join(tmpDir, 'src/brand'))).toBe(false);+ });++ it('lists --import in help', async () => {+ const result = await runCli(['theme', 'add', '--help'], tmpDir);++ expect(result.status, result.stderr).toBe(0);+ expect(result.stdout).toContain('--import');+ });+});diff --git a/packages/cli/clients/cli/commands/theme-add.doc.mjs b/packages/cli/clients/cli/commands/theme-add.doc.mjsindex a90eb96970..97ddeb30cc 100644--- a/packages/cli/clients/cli/commands/theme-add.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-add.doc.mjs@@ -1,12 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file CommandDoc for `astryx theme add`. The terminal binding of the- * `themeAdd()` function (referenced via `fn`); its args/flags map to that- * function's params so a converter can build Commander config + --help from one- * source of truth.- * @position packages/cli/clients/cli/commands — command documentation- */+/** @file CommandDoc for `astryx theme add`. *//** @type {import('@astryxdesign/cli/authoring').CommandDoc} */export const doc = {@@ -14,11 +8,9 @@ export const doc = {name: 'theme add',displayName: 'astryx theme add',namespace: 'cli/commands',- summary: 'Scaffold a theme into your project as editable source',+ summary: 'Copy a theme, or import its built output into the app',description:- "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.',+ 'With --import, records the theme in the generated app module and imports its built module and stylesheets. Without --import, keeps the released source-copy behavior, emits one text warning, and adds meta.deprecations with DEP-0005 and the theme eject/theme add --import replacements to JSON. A bare command or --list delegates to themeListCopySources() so the released list fields stay unchanged; use --package when owners share a slug.',fn: 'themeAdd',args: [{name: 'slug', param: 'slug', required: false},@@ -28,10 +20,15 @@ export const doc = {{flag: '-f, --overwrite',param: 'options.overwrite',- description:- 'Replace existing files. Without it, existing files fail the command with ERR_FILE_EXISTS and nothing is written',+ description: 'Replace copied files. Cannot be combined with --import',},{flag: '--list', description: 'List available themes'},+ {+ flag: '--import',+ param: 'options.import',+ description:+ 'Use the built theme through the generated app module instead of copying source',+ },{flag: '--package <package>',param: 'options.package',@@ -39,18 +36,21 @@ export const doc = {},],examples: [- {label: 'Scaffold a theme', cli: 'astryx theme add matcha'},{- label: 'Pick the owner when two packages ship the same slug',- cli: 'astryx theme add ocean --package @acme/themes',+ label: 'Import a built theme into the app',+ cli: 'astryx theme add ocean --import',+ },+ {+ label: 'Select a package theme over a local theme',+ cli: 'astryx theme add ocean --import --package @acme/themes',},],exitCodes: [- {code: 0, when: 'success'},+ {code: 0, when: 'the theme is listed, copied, or imported'},{code: 1,- when: 'unknown or ambiguous theme, a path escape, a missing descriptor or source, or an existing file without --overwrite',+ when: 'the theme, its source or built imports, its record, the target path, or the option combination is invalid',},],- related: ['theme list', 'theme build'],+ related: ['theme list', 'theme remove', 'theme use', 'theme eject'],};diff --git a/packages/cli/clients/cli/commands/theme-eject.doc.mjs b/packages/cli/clients/cli/commands/theme-eject.doc.mjsnew file mode 100644index 0000000000..c10459f6f8--- /dev/null+++ b/packages/cli/clients/cli/commands/theme-eject.doc.mjs@@ -0,0 +1,47 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx theme eject`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'theme eject',+ displayName: 'astryx theme eject',+ namespace: 'cli/commands',+ summary: 'Fork a theme as editable local source',+ description:+ "Copies a bundled or installed package theme's complete source into the local themes root, including a local descriptor. Writes are atomic. Existing files require --overwrite. Use --package when package themes share a slug.",+ fn: 'themeEject',+ args: [+ {name: 'slug', param: 'slug', required: true},+ {name: 'path', param: 'options.targetPath', required: false},+ ],+ options: [+ {+ flag: '-f, --overwrite',+ param: 'options.overwrite',+ description:+ 'Replace existing files. Without it, an existing file fails with ERR_FILE_EXISTS and nothing is written',+ },+ {+ flag: '--package <package>',+ param: 'options.package',+ description: 'Select the package that owns the theme',+ },+ ],+ examples: [+ {label: 'Fork a theme into the local root', cli: 'astryx theme eject ocean'},+ {+ label: 'Fork one package theme elsewhere',+ cli: 'astryx theme eject ocean src/themes/my-ocean --package @acme/themes',+ },+ ],+ exitCodes: [+ {code: 0, when: 'all source and descriptor files are written'},+ {+ code: 1,+ when: 'the theme is unknown or ambiguous, a path escapes, a source file is missing, or a destination exists',+ },+ ],+ related: ['theme add', 'theme build', 'theme list'],+};diff --git a/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs b/packages/cli/clients/cli/commands/theme-list.behavior.test.mjsindex b0bd1aa628..1815b72cfd 100644--- a/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs+++ b/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs@@ -23,11 +23,14 @@ afterEach(() => {});describe('astryx theme list', () => {- it('lists the bundled themes and points at discover for more', async () => {+ it('lists bundled themes and points at import, eject, and discover', async () => {const {status, stdout} = await runCli(['theme', 'list'], {cwd: tmpDir});expect(status).toBe(0);- expect(stdout).toMatch(/^- neutral \(maintained, @astryxdesign\/cli\)/m);+ expect(stdout).toMatch(/^slug:\s+neutral$/m);+ expect(stdout).toMatch(/^package:\s+@astryxdesign\/cli$/m);+ expect(stdout).toMatch(/Import one: .*theme add <slug> --import/m);+ expect(stdout).toMatch(/Fork source: .*theme eject <slug>/m);expect(stdout).toMatch(/More themes in packages you could add: .*discover theme$/m);});diff --git a/packages/cli/clients/cli/commands/theme-list.doc.mjs b/packages/cli/clients/cli/commands/theme-list.doc.mjsindex 949ddb49e6..c533f5e82b 100644--- a/packages/cli/clients/cli/commands/theme-list.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-list.doc.mjs@@ -16,8 +16,8 @@ export const doc = {namespace: 'cli/commands',summary: 'List themes available to add',description:- '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.',+ 'Lists bundled, package, and local themes with their owner, source, added state, and default state. ' ++ 'Earlier descriptor-less copies are not listed as themes; the receipt names them with the upgrade command.',fn: 'themeListAvailable',options: [{diff --git a/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs b/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjsindex c9bb168377..c7336b5f6e 100644--- a/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs@@ -21,8 +21,7 @@ export const doc = {'JSON is also supported. Existing author-owned files are left untouched unless --overwrite is explicit. ' +'When used in a theme integration, keep the palette request under the theme slug, ' +'write the candidate and receipt under that same slug, import the candidate from the theme source, ' +- 'and keep all three inside the theme directory: `astryx theme add` copies that whole ' +- 'directory into the consumer project, so nothing else has to list them.',+ 'and keep all three inside the theme directory. The package ships that directory as one source unit for discovery and explicit eject, while apps use its built exports.',fn: 'themePaletteGenerate',args: [{name: 'config', param: 'configPath', required: true}],options: [diff --git a/packages/cli/clients/cli/commands/theme-remove.doc.mjs b/packages/cli/clients/cli/commands/theme-remove.doc.mjsnew file mode 100644index 0000000000..4f894c4e50--- /dev/null+++ b/packages/cli/clients/cli/commands/theme-remove.doc.mjs@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx theme remove`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'theme remove',+ displayName: 'astryx theme remove',+ namespace: 'cli/commands',+ summary: 'Remove a non-default theme from the app',+ description:+ 'Removes one added theme from the generated module and regenerates the whole module. Choose another default with theme use before removing the current default.',+ fn: 'themeRemove',+ args: [{name: 'slug', param: 'slug', required: true}],+ examples: [{label: 'Remove an added theme', cli: 'astryx theme remove ocean'}],+ exitCodes: [+ {code: 0, when: 'the module is regenerated without the theme'},+ {code: 1, when: 'the theme is not added, is the default, or state is invalid'},+ ],+ related: ['theme add', 'theme use', 'theme list'],+};diff --git a/packages/cli/clients/cli/commands/theme-template.doc.mjs b/packages/cli/clients/cli/commands/theme-template.doc.mjsindex 67889d8ec6..8e9a39877c 100644--- a/packages/cli/clients/cli/commands/theme-template.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-template.doc.mjs@@ -19,8 +19,9 @@ export const doc = {'Writes theme.template.ts: the annotated reference for the whole theme surface, covering every ' +'defineTheme field, the token families, the component override syntax, and how a theme is ' +'consumed, naming the CLI command that prints the authoritative reference for each. Read ' +- 'it, copy what you need into your own theme file, delete it. Use `theme add <slug>` instead ' +- 'to start from a theme we ship. Leaves an existing file untouched unless --overwrite.',+ 'it, copy what you need into your own theme file, delete it. Use `theme add <slug> --import` to ' ++ 'use an installed built theme, extend that theme for ordinary customization, or use ' ++ '`theme eject <slug>` for a complete source fork. Leaves an existing file untouched unless --overwrite.',fn: 'themeTemplate',args: [{name: 'path', param: 'options.targetPath', required: false}],options: [@@ -38,5 +39,5 @@ export const doc = {{code: 0, when: 'success, including when an existing file was left untouched'},{code: 1, when: 'the target path escapes the project, or the file cannot be written'},],- related: ['theme add', 'theme list', 'theme build'],+ related: ['theme add', 'theme eject', 'theme list', 'theme build'],};diff --git a/packages/cli/clients/cli/commands/theme-use.doc.mjs b/packages/cli/clients/cli/commands/theme-use.doc.mjsnew file mode 100644index 0000000000..1b1ede769c--- /dev/null+++ b/packages/cli/clients/cli/commands/theme-use.doc.mjs@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx theme use`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'theme use',+ displayName: 'astryx theme use',+ namespace: 'cli/commands',+ summary: 'Choose the app default from its added themes',+ description:+ 'Sets one added slug as the default and regenerates the generated theme module. Add the theme first if it is not already in the app.',+ fn: 'themeUse',+ args: [{name: 'slug', param: 'slug', required: true}],+ examples: [{label: 'Choose the default theme', cli: 'astryx theme use ocean'}],+ exitCodes: [+ {code: 0, when: 'the module is regenerated with the selected default'},+ {code: 1, when: 'the theme is not added or state is invalid'},+ ],+ related: ['theme add', 'theme remove', 'theme list'],+};diff --git a/packages/cli/clients/cli/commands/theme.doc.mjs b/packages/cli/clients/cli/commands/theme.doc.mjsindex df0dfb8baf..833c1f035c 100644--- a/packages/cli/clients/cli/commands/theme.doc.mjs+++ b/packages/cli/clients/cli/commands/theme.doc.mjs@@ -1,10 +1,8 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file CommandDoc for the `astryx theme` command group. A parent group with no- * behavior of its own; it dispatches to the build/add/list subcommands, which- * carry the actual args, flags, and wrapped functions.- * @position packages/cli/clients/cli/commands — command documentation+ * @file CommandDoc for the `astryx theme` command group. It is a real group,+ * not a compatibility alias. Its subcommands own the work.*//** @type {import('@astryxdesign/cli/authoring').CommandDoc} */@@ -13,18 +11,25 @@ export const doc = {name: 'theme',displayName: 'astryx theme',namespace: 'cli/commands',- summary:- 'Create and build themes: add a shipped one, compile to CSS, or list what a theme can override',+ summary: 'Add, switch, build, and author themes',description:- '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 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'],+ 'The theme command group. Import built themes into an app, choose its default, remove them, list available and added themes, or eject source to make a local fork. Plain theme add still copies source while that default is deprecated. The authoring commands build themes, generate palettes, write the annotated template, and list component theme targets.',+ subcommands: [+ 'build',+ 'list',+ 'add',+ 'remove',+ 'use',+ 'eject',+ 'template',+ 'palette',+ 'targets',+ ],examples: [- {label: 'List available themes', cli: 'astryx theme list'},- {label: 'Scaffold a theme', cli: 'astryx theme add matcha'},+ {label: 'List available and added themes', cli: 'astryx theme list'},+ {label: 'Import a theme into the app', cli: 'astryx theme add ocean --import'},+ {label: 'Choose the default', cli: 'astryx theme use ocean'},+ {label: 'Fork source to customize', cli: 'astryx theme eject ocean'},{label: 'Generate a palette candidate',cli: 'astryx theme palette generate palette.config.json',@@ -32,8 +37,8 @@ export const doc = {{label: 'See what a theme can override', cli: 'astryx theme targets'},],exitCodes: [- {code: 0, when: 'success (help shown, or a subcommand succeeded)'},- {code: 1, when: 'an unknown subcommand'},+ {code: 0, when: 'help is shown or a subcommand succeeds'},+ {code: 1, when: 'an unknown subcommand or a subcommand failure'},],related: ['init'],};diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex 4e3fbcf597..cde360e5a7 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -91,6 +91,9 @@ export const JSON_SUPPORTED = new Set(['theme build','theme list','theme add',+ 'theme remove',+ 'theme use',+ 'theme eject','theme template','theme targets','theme palette generate',diff --git a/packages/cli/clients/cli/lib/resolve-theme.mjs b/packages/cli/clients/cli/lib/resolve-theme.mjsindex 91c6035052..f7dd5cb726 100644--- a/packages/cli/clients/cli/lib/resolve-theme.mjs+++ b/packages/cli/clients/cli/lib/resolve-theme.mjs@@ -1,13 +1,14 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Theme resolution — resolve a theme from config or environment+ * @file Resolve the theme used by component metadata.*- * Resolution sources (in priority order):- * 1. ASTRYX_THEME environment variable- * 2. xds.theme field in package.json+ * A generated app-theme module is authoritative when present: its static record+ * selects the default theme's built module. Without that module, the released+ * `package.json#astryx.theme` field keeps its meaning. Environment variables+ * never select a theme.*- * Resolution strategy for the value:+ * Resolution strategy for the configured value:* - Starts with `.` or `/` → file path relative to cwd* - Starts with `@` → npm package (require/import)* - Otherwise → try `@astryxdesign/theme-{name}`, then try as bare package name@@ -19,30 +20,24 @@import * as fs from 'node:fs';import * as path from 'node:path';import {createRequire} from 'node:module';+import {resolveRecordedTheme} from '../../../api/theme/theme.mjs';-const _require = createRequire(import.meta.url);+const legacyRequire = createRequire(import.meta.url);/**- * Try to load a module, returning the default export or the module itself.- * Returns null if the module cannot be found.+ * Released package-field loader. Bare package names resolve from the CLI's own+ * installation; relative paths resolve from the exact cwd given to the command.* @param {string} specifier* @param {string} cwd* @returns {unknown}*/-function tryLoadModule(specifier, cwd) {- // For relative/absolute paths, resolve against cwd- if (specifier.startsWith('.') || specifier.startsWith('/')) {- const resolved = path.resolve(cwd, specifier);- try {- return _require(resolved);- } catch {- return null;- }- }-- // For package specifiers, try require+function tryLoadLegacyModule(specifier, cwd) {+ const target =+ specifier.startsWith('.') || specifier.startsWith('/')+ ? path.resolve(cwd, specifier)+ : specifier;try {- return _require(specifier);+ return legacyRequire(target);} catch {return null;}@@ -58,22 +53,19 @@ function tryLoadModule(specifier, cwd) {function extractTheme(mod) {if (!mod || typeof mod !== 'object') return null;- // Check default exportconst obj = mod.default || mod;+ if (obj.name && (obj.tokens || obj.variants)) return obj;- // If it looks like a theme (has name + tokens or variants), use it directly- if (obj.name && (obj.tokens || obj.variants)) {- return obj;- }-- // Check for a `theme` named exportif (mod.theme && typeof mod.theme === 'object' && mod.theme.name) {return mod.theme;}- // Check for any export ending in 'Theme'for (const key of Object.keys(mod)) {- if (key.endsWith('Theme') && typeof mod[key] === 'object' && mod[key]?.name) {+ if (+ key.endsWith('Theme') &&+ typeof mod[key] === 'object' &&+ mod[key]?.name+ ) {return mod[key];}}@@ -81,76 +73,86 @@ function extractTheme(mod) {return null;}+/** @param {unknown} mod @param {string} specifier */+function resolvedThemeData(mod, specifier) {+ const theme = extractTheme(mod);+ if (!theme) {+ console.warn(+ `⚠ theme: loaded "${specifier}" but could not find a theme object`,+ );+ return null;+ }+ return {+ name: theme.name || null,+ variants: theme.variants || null,+ fonts: theme.fonts || null,+ };+}+/**- * Resolve the active Astryx theme from config and environment.+ * Resolve the active Astryx theme from the generated record, or from+ * `package.json#astryx.theme` when there is no generated module.*- * @param {string} [cwd] - Working directory (defaults to process.cwd())- * @returns {{ variants?: Record<string, string[]>, fonts?: Record<string, string>, name?: string } | null}+ * @param {string} [cwd] Working directory (defaults to process.cwd())+ * @returns {Promise<{variants?: Record<string, string[]>|null, fonts?: Record<string, string>|null, name?: string|null}|null>}*/-export function resolveTheme(cwd = process.cwd()) {- // 1. Determine theme specifier- let specifier = process.env.ASTRYX_THEME || null;-- if (!specifier) {- // Read from package.json- const pkgPath = path.join(cwd, 'package.json');- if (fs.existsSync(pkgPath)) {- try {- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));- specifier = pkg.astryx?.theme || null;- } catch {- // Ignore parse errors- }+export async function resolveTheme(cwd = process.cwd()) {+ const loaded = await resolveRecordedTheme(cwd);+ if (loaded.configured) {+ if (!loaded.module) {+ console.warn(+ `⚠ theme: ${loaded.problem ?? `could not resolve the generated default theme (${loaded.specifier})`}`,+ );+ return null;}+ return resolvedThemeData(loaded.module, loaded.specifier);}- // `astryx.theme` (package.json) and ASTRYX_THEME are user/third-party- // controlled and may be any value. Anything that isn't a usable non-empty- // string means "no theme" — degrade to null rather than crashing on- // specifier.startsWith(...) below. (Subsumes the empty-string case.)- if (typeof specifier !== 'string' || specifier.length === 0) {- return null;+ // No generated module: keep the released package-field lookup byte-for-byte in+ // behavior. It reads only cwd/package.json, resolves relative paths from cwd,+ // and resolves bare packages from the CLI installation.+ let specifier = null;+ const pkgPath = path.join(cwd, 'package.json');+ if (fs.existsSync(pkgPath)) {+ try {+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));+ specifier = pkg.astryx?.theme || null;+ } catch {+ // Ignore parse errors.+ }}- // 2. Resolve the specifier to a module- let mod;+ // `astryx.theme` is user/third-party controlled and may be any value.+ // Anything that is not a usable non-empty string means "no theme".+ if (typeof specifier !== 'string' || specifier.length === 0) return null;+ let mod;if (specifier.startsWith('.') || specifier.startsWith('/')) {- // File path- mod = tryLoadModule(specifier, cwd);+ mod = tryLoadLegacyModule(specifier, cwd);if (!mod) {- console.warn(`⚠ theme: could not resolve file "${specifier}" from ${cwd}`);+ console.warn(+ `⚠ theme: could not resolve file "${specifier}" from ${cwd}`,+ );return null;}} else if (specifier.startsWith('@')) {- // Scoped package- mod = tryLoadModule(specifier, cwd);+ mod = tryLoadLegacyModule(specifier, cwd);if (!mod) {console.warn(`⚠ theme: could not resolve package "${specifier}"`);return null;}} else {- // Convention: try @astryxdesign/theme-{name} first, then bare package- mod = tryLoadModule(`@astryxdesign/theme-${specifier}`, cwd);- if (!mod) {- mod = tryLoadModule(specifier, cwd);- }+ const conventional = `@astryxdesign/theme-${specifier}`;+ mod =+ tryLoadLegacyModule(conventional, cwd) ??+ tryLoadLegacyModule(specifier, cwd);if (!mod) {- console.warn(`⚠ theme: could not resolve "${specifier}" (tried @astryxdesign/theme-${specifier} and ${specifier})`);+ console.warn(+ `⚠ theme: could not resolve "${specifier}" (tried ${conventional} and ${specifier})`,+ );return null;}}- // 3. Extract theme data- const theme = extractTheme(mod);- if (!theme) {- console.warn(`⚠ theme: loaded "${specifier}" but could not find a theme object`);- return null;- }-- return {- name: theme.name || null,- variants: theme.variants || null,- fonts: theme.fonts || null,- };+ return resolvedThemeData(mod, specifier);}diff --git a/packages/cli/clients/cli/lib/resolve-theme.test.mjs b/packages/cli/clients/cli/lib/resolve-theme.test.mjsindex ef31235fca..a67025aad0 100644--- a/packages/cli/clients/cli/lib/resolve-theme.test.mjs+++ b/packages/cli/clients/cli/lib/resolve-theme.test.mjs@@ -1,47 +1,543 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file Tests for resolveTheme's handling of a malformed `astryx.theme`.- * The field is user/third-party-controlled config, so a non-string value must- * degrade to null (like an unknown slug) rather than crash `astryx component`- * with a raw TypeError from specifier.startsWith(...).- */--import {describe, it, expect, afterEach} from 'vitest';+/** @file Tests generated-record default resolution and released package-field fallback. */++import {afterEach, 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 {resolveTheme} from './resolve-theme.mjs';+import {themeAdd} from '../../../api/theme/add/add.mjs';+import {themeBuild} from '../../../api/theme/build/build.mjs';+import {themeEject} from '../../../api/theme/eject/eject.mjs';+import {themeUse} from '../../../api/theme/use/use.mjs';+import {renderThemeModule} from '../../../foundation/config/theme-state.mjs';+import {checkAppThemes} from '../../../api/doctor/theme-checks.mjs';++const REPO_ROOT = path.resolve(import.meta.dirname, '../../../../..');+/** @type {string[]} */const dirs = [];-function fixture(pkg) {- const d = fs.mkdtempSync(path.join(os.tmpdir(), 'resolve-theme-'));- dirs.push(d);- fs.writeFileSync(path.join(d, 'package.json'), JSON.stringify(pkg));- return d;++function fixture(pkg = {name: 'app'}) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'resolve-theme-'));+ dirs.push(dir);+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg));+ return dir;+}++function writeTheme(dir, filename, name) {+ fs.writeFileSync(+ path.join(dir, filename),+ `module.exports = {name: '${name}', variants: {Button: ['${name}']}, fonts: {body: '${name}'}};\n`,+ );+}++function writeGeneratedRecord(dir) {+ const sourceDir = path.join(dir, 'src', 'themes', 'ocean');+ fs.mkdirSync(sourceDir, {recursive: true});+ const moduleFile = path.join(sourceDir, 'ocean.js');+ fs.writeFileSync(+ moduleFile,+ "export const oceanTheme = {name: 'ocean', variants: {Button: ['ocean']}};\n",+ );+ fs.writeFileSync(+ path.join(dir, 'src', 'astryx-themes.js'),+ renderThemeModule(+ [+ {+ slug: 'ocean',+ owner: './src/themes',+ exportName: 'oceanTheme',+ module: '',+ stylesheet: '',+ moduleFile,+ stylesheetFile: path.join(sourceDir, 'ocean.css'),+ source: 'local',+ },+ ],+ 'ocean',+ false,+ ),+ );+}++function writePackageRecord(dir, slugs, exportsMap, artifacts) {+ fs.writeFileSync(+ path.join(dir, 'astryx.config.mjs'),+ "export default {integrations: ['@acme/themes']};\n",+ );+ const packageDir = path.join(dir, 'node_modules', '@acme', 'themes');+ fs.mkdirSync(path.join(packageDir, 'themes'), {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({+ name: '@acme/themes',+ version: '1.0.0',+ type: 'module',+ exports: exportsMap,+ }),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+ for (const slug of slugs) {+ const themeDir = path.join(packageDir, 'themes', slug);+ fs.mkdirSync(themeDir, {recursive: true});+ fs.writeFileSync(+ path.join(themeDir, `${slug}Theme.ts`),+ `export const ${slug}Theme = {name: '${slug}', tokens: {}};\n`,+ );+ fs.writeFileSync(+ path.join(themeDir, `${slug}Theme.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: '${slug}', displayName: '${slug}', description: '${slug} theme', maintained: true};\n`,+ );+ }+ for (const [file, content] of Object.entries(artifacts)) {+ const target = path.join(packageDir, file);+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.writeFileSync(target, content);+ }+ fs.mkdirSync(path.join(dir, 'src'), {recursive: true});+ const slug = slugs[0];+ fs.writeFileSync(+ path.join(dir, 'src', 'astryx-themes.ts'),+ renderThemeModule(+ [+ {+ slug,+ owner: '@acme/themes',+ exportName: `${slug}Theme`,+ module: `@acme/themes/themes/${slug}`,+ stylesheet: `@acme/themes/themes/${slug}.css`,+ source: 'package',+ },+ ],+ slug,+ true,+ ),+ );+}++/** @param {string} slug */+function builtTheme(slug) {+ return `export const ${slug}Theme = {name: '${slug}', tokens: {}, variants: {Button: ['${slug}']}};\n`;+}++function installCore(dir) {+ const scope = path.join(dir, 'node_modules', '@astryxdesign');+ fs.mkdirSync(scope, {recursive: true});+ fs.symlinkSync(+ path.join(REPO_ROOT, 'packages', 'core'),+ path.join(scope, 'core'),+ );+}++/** @param {'missing'|'ambiguous'|'malformed'|'runtime'} kind */+function brokenThemeProject(kind) {+ const dir = fixture({+ name: 'app',+ type: 'module',+ dependencies: {+ '@acme/themes': '1.0.0',+ '@astryxdesign/core': '*',+ },+ });+ if (kind === 'missing') {+ writePackageRecord(+ dir,+ ['ocean'],+ {'./theme.css': './dist/theme.css'},+ {'dist/theme.css': '.ocean {}\n'},+ );+ } else if (kind === 'ambiguous') {+ writePackageRecord(+ dir,+ ['ocean', 'reef'],+ {'./built': './dist/built.js', './theme.css': './dist/theme.css'},+ {'dist/built.js': builtTheme('reef'), 'dist/theme.css': '.reef {}\n'},+ );+ } else if (kind === 'malformed') {+ writePackageRecord(+ dir,+ ['ocean'],+ {'./themes/ocean': './dist/ocean.js'},+ {'dist/ocean.js': 'export const oceanTheme = ;\n'},+ );+ } else {+ writePackageRecord(+ dir,+ ['ocean'],+ {'./themes/ocean': './dist/ocean.js'},+ {'dist/ocean.js': "throw new Error('runtime theme boom');\n"},+ );+ }+ installCore(dir);+ return dir;+}++/** @param {'single'|'explicit'} kind */+function workingThemeProject(kind) {+ const dir = fixture({+ name: 'app',+ type: 'module',+ dependencies: {+ '@acme/themes': '1.0.0',+ '@astryxdesign/core': '*',+ },+ });+ if (kind === 'single') {+ writePackageRecord(+ dir,+ ['ocean'],+ {'./built': './dist/built.js', './theme.css': './dist/theme.css'},+ {'dist/built.js': builtTheme('ocean'), 'dist/theme.css': '.ocean {}\n'},+ );+ } else {+ writePackageRecord(+ dir,+ ['ocean', 'reef'],+ {+ './themes/ocean': './dist/ocean.js',+ './themes/ocean.css': './dist/ocean.css',+ './built': './dist/built.js',+ './theme.css': './dist/theme.css',+ },+ {+ 'dist/ocean.js': builtTheme('ocean'),+ 'dist/ocean.css': '.ocean {}\n',+ 'dist/built.js': builtTheme('reef'),+ 'dist/theme.css': '.reef {}\n',+ },+ );+ }+ installCore(dir);+ return dir;+}++/** @param {string} dir @param {string[]} args */+function runComponent(dir, args) {+ return spawnSync(+ process.execPath,+ [path.join(REPO_ROOT, 'packages/cli/clients/cli/bin/astryx.mjs'), ...args],+ {cwd: dir, encoding: 'utf-8', timeout: 30_000},+ );}+afterEach(() => {+ vi.restoreAllMocks();delete process.env.ASTRYX_THEME;- while (dirs.length) fs.rmSync(dirs.pop(), {recursive: true, force: true});+ while (dirs.length > 0) {+ fs.rmSync(dirs.pop(), {recursive: true, force: true});+ }+});++describe('resolveTheme package field', () => {+ it('keeps package.json astryx.theme behavior', async () => {+ const dir = fixture({name: 'app', astryx: {theme: './legacy.cjs'}});+ writeTheme(dir, 'legacy.cjs', 'legacy');++ expect(await resolveTheme(dir)).toEqual({+ name: 'legacy',+ variants: {Button: ['legacy']},+ fonts: {body: 'legacy'},+ });+ });++ it.each([123, ['a'], {x: 1}, true, ''])(+ 'treats malformed value %j as absent',+ async value => {+ expect(await resolveTheme(fixture({astryx: {theme: value}}))).toBeNull();+ },+ );++ it('returns null with no theme field', async () => {+ expect(await resolveTheme(fixture())).toBeNull();+ });++ it('does not inherit astryx.theme from a parent package', async () => {+ const dir = fixture({name: 'app', astryx: {theme: './legacy.cjs'}});+ writeTheme(dir, 'legacy.cjs', 'legacy');+ const nested = path.join(dir, 'src', 'feature');+ fs.mkdirSync(nested, {recursive: true});++ expect(await resolveTheme(nested)).toBeNull();+ });++ it('does not resolve a bare legacy theme from project node_modules', async () => {+ const dir = fixture({name: 'app', astryx: {theme: 'project-theme'}});+ const packageDir = path.join(dir, 'node_modules', 'project-theme');+ fs.mkdirSync(packageDir, {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: 'project-theme', main: 'index.cjs'}),+ );+ writeTheme(packageDir, 'index.cjs', 'project-only');++ expect(await resolveTheme(dir)).toBeNull();+ });});-describe('resolveTheme — malformed astryx.theme degrades to null', () => {- it('numeric theme → null', () => {- expect(resolveTheme(fixture({astryx: {theme: 123}}))).toBeNull();+describe('resolveTheme source precedence', () => {+ it('uses the generated record default and ignores astryx.theme when a module exists', async () => {+ const dir = fixture({+ name: 'app',+ type: 'module',+ astryx: {theme: './legacy.cjs'},+ });+ writeTheme(dir, 'legacy.cjs', 'legacy');+ writeGeneratedRecord(dir);++ expect((await resolveTheme(dir))?.name).toBe('ocean');});- it('array theme → null', () => {- expect(resolveTheme(fixture({astryx: {theme: ['a']}}))).toBeNull();++ it('uses the built shorthand for a proven single-theme package', async () => {+ const dir = fixture({+ name: 'app',+ type: 'module',+ dependencies: {'@acme/themes': '1.0.0'},+ });+ writePackageRecord(+ dir,+ ['ocean'],+ {'./built': './dist/built.js', './theme.css': './dist/theme.css'},+ {'dist/built.js': builtTheme('ocean'), 'dist/theme.css': '.ocean {}\n'},+ );++ expect((await resolveTheme(dir))?.name).toBe('ocean');+ });++ it('warns and returns no theme for an ambiguous multi-theme shorthand', async () => {+ const dir = fixture({+ name: 'app',+ type: 'module',+ dependencies: {'@acme/themes': '1.0.0'},+ });+ writePackageRecord(+ dir,+ ['ocean', 'reef'],+ {'./built': './dist/built.js', './theme.css': './dist/theme.css'},+ {'dist/built.js': builtTheme('reef'), 'dist/theme.css': '.reef {}\n'},+ );+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await expect(resolveTheme(dir)).resolves.toBeNull();+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('multi-theme package @acme/themes'),+ );+ warn.mockRestore();+ });++ it('warns and returns no theme when a single-theme package has no built export', async () => {+ const dir = fixture({+ name: 'app',+ type: 'module',+ dependencies: {'@acme/themes': '1.0.0'},+ });+ writePackageRecord(+ dir,+ ['ocean'],+ {'./theme.css': './dist/theme.css'},+ {'dist/theme.css': '.ocean {}\n'},+ );+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await expect(resolveTheme(dir)).resolves.toBeNull();+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('could not resolve the generated default theme'),+ );+ warn.mockRestore();+ });++ it('warns and returns no theme for a malformed recorded module', async () => {+ const dir = fixture({+ name: 'app',+ type: 'module',+ dependencies: {'@acme/themes': '1.0.0'},+ });+ writePackageRecord(+ dir,+ ['ocean'],+ {'./themes/ocean': './dist/ocean.js'},+ {'dist/ocean.js': 'export const oceanTheme = ;\n'},+ );+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await expect(resolveTheme(dir)).resolves.toBeNull();+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('could not load the recorded theme artifact'),+ );+ warn.mockRestore();});- it('object theme → null', () => {- expect(resolveTheme(fixture({astryx: {theme: {x: 1}}}))).toBeNull();++ it('does not swallow an unrelated recorded-module runtime error', async () => {+ const dir = brokenThemeProject('runtime');++ await expect(resolveTheme(dir)).rejects.toThrow('runtime theme boom');});- it('boolean theme → null', () => {- expect(resolveTheme(fixture({astryx: {theme: true}}))).toBeNull();++ it('uses an explicit per-theme export from a multi-theme package', async () => {+ const dir = fixture({+ name: 'app',+ type: 'module',+ dependencies: {'@acme/themes': '1.0.0'},+ });+ writePackageRecord(+ dir,+ ['ocean', 'reef'],+ {+ './themes/ocean': './dist/ocean.js',+ './themes/ocean.css': './dist/ocean.css',+ './built': './dist/built.js',+ './theme.css': './dist/theme.css',+ },+ {+ 'dist/ocean.js': builtTheme('ocean'),+ 'dist/ocean.css': '.ocean {}\n',+ 'dist/built.js': builtTheme('reef'),+ 'dist/theme.css': '.reef {}\n',+ },+ );++ expect((await resolveTheme(dir))?.name).toBe('ocean');+ });++ it('loads a real built local default with an icon registry', async () => {+ const dir = fixture({+ name: 'app',+ type: 'module',+ dependencies: {'@astryxdesign/core': '*'},+ });+ fs.symlinkSync(+ path.join(process.cwd(), 'node_modules'),+ path.join(dir, 'node_modules'),+ 'dir',+ );+ fs.mkdirSync(path.join(dir, 'src'));+ fs.writeFileSync(path.join(dir, 'tsconfig.json'), '{}\n');++ await themeEject('stone', {cwd: dir});+ await themeBuild('src/themes/stone/stoneTheme.ts', {}, {cwd: dir});+ await themeAdd('stone', {cwd: dir, import: true});+ await themeUse('stone', {cwd: dir});++ expect((await resolveTheme(dir))?.name).toBe('stone');+ }, 30_000);++ it('does not read ASTRYX_THEME', async () => {+ const dir = fixture();+ writeTheme(dir, 'environment.cjs', 'environment');+ process.env.ASTRYX_THEME = './environment.cjs';++ expect(await resolveTheme(dir)).toBeNull();});- it('empty-string theme → null', () => {- expect(resolveTheme(fixture({astryx: {theme: ''}}))).toBeNull();++ it('does not let ASTRYX_THEME replace astryx.theme', async () => {+ const dir = fixture({name: 'app', astryx: {theme: './legacy.cjs'}});+ writeTheme(dir, 'legacy.cjs', 'legacy');+ writeTheme(dir, 'environment.cjs', 'environment');+ process.env.ASTRYX_THEME = './environment.cjs';++ expect((await resolveTheme(dir))?.name).toBe('legacy');});- it('no theme field → null', () => {- expect(resolveTheme(fixture({name: 'p'}))).toBeNull();+});++describe('component output with a broken recorded theme', () => {+ it.each([+ ['missing', 'could not resolve the generated default theme'],+ [+ 'ambiguous',+ 'theme "ocean" is recorded from multi-theme package @acme/themes',+ ],+ ['malformed', 'could not load the recorded theme artifact'],+ ])(+ 'keeps text and JSON output valid for a %s artifact',+ async (kind, warning) => {+ const dir = brokenThemeProject(kind);++ const text = runComponent(dir, ['component', 'Button']);+ expect(text.status, text.stderr).toBe(0);+ expect(text.stdout).toContain('# Button');+ expect(text.stderr).toContain(`⚠ theme: ${warning}`);+ expect(text.stderr.match(/⚠ theme:/gu) ?? []).toHaveLength(1);+ expect(text.stderr).not.toMatch(/\n\s+at /u);++ const json = runComponent(dir, ['--json', 'component', 'Button']);+ expect(json.status, json.stderr).toBe(0);+ expect(() => JSON.parse(json.stdout)).not.toThrow();+ expect(JSON.parse(json.stdout).type).toBe('component.detail');+ expect(json.stderr).toBe('');++ const checks = await checkAppThemes(dir);+ expect(+ checks.find(check => check.id === 'theme-owners')?.status,+ ).not.toBe('pass');+ },+ 30_000,+ );++ it.each([+ ['list', ['component', '--list'], 'component.list'],+ ['props', ['component', 'Button', '--props'], 'component.detail.props'],+ ['source', ['component', 'Button', '--source'], 'component.detail.source'],+ [+ 'showcase',+ ['component', 'Button', '--showcase'],+ 'component.detail.showcase',+ ],+ ['blocks', ['component', 'Button', '--blocks'], 'component.detail.blocks'],+ ])(+ 'keeps the ambiguous-theme %s projection alive in text and JSON',+ (projection, args, type) => {+ const dir = brokenThemeProject('ambiguous');++ const text = runComponent(dir, args);+ expect(text.status, text.stderr).toBe(0);+ expect(text.stdout).not.toBe('');+ expect(text.stderr).toContain('multi-theme package @acme/themes');+ expect(text.stderr.match(/⚠ theme:/gu) ?? []).toHaveLength(1);+ expect(text.stderr).not.toMatch(/\n\s+at /u);++ const json = runComponent(dir, ['--json', ...args]);+ expect(json.status, json.stderr).toBe(0);+ expect(JSON.parse(json.stdout).type).toBe(type);+ expect(json.stderr).toBe('');+ },+ 30_000,+ );++ it.each(['single', 'explicit'])(+ 'keeps the %s package control silent',+ kind => {+ const dir = workingThemeProject(kind);+ const text = runComponent(dir, ['component', 'Button']);+ expect(text.status, text.stderr).toBe(0);+ expect(text.stdout).toContain('# Button');+ expect(text.stderr).not.toContain('⚠ theme:');++ const json = runComponent(dir, ['--json', 'component', 'Button']);+ expect(json.status, json.stderr).toBe(0);+ expect(JSON.parse(json.stdout).type).toBe('component.detail');+ expect(json.stderr).toBe('');+ },+ 30_000,+ );++ it('formats an unrelated loader error instead of swallowing it', () => {+ const dir = brokenThemeProject('runtime');++ const text = runComponent(dir, ['component', 'Button']);+ expect(text.status).toBe(1);+ expect(text.stderr).toContain(+ 'Could not load the recorded theme: runtime theme boom',+ );+ expect(text.stderr).not.toMatch(/\n\s+at /u);++ const json = runComponent(dir, ['--json', 'component', 'Button']);+ expect(json.status, json.stderr).toBe(0);+ expect(JSON.parse(json.stdout).type).toBe('component.detail');+ expect(json.stderr).toBe('');});});diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex eaa6b59d41..3c88dd749d 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -453,7 +453,7 @@ export function generateCompressedIndex(} else {lines.push("- Custom styling: component props first; else style/className with tokens — var(--color-*|--spacing-*|--radius-*). No raw hex/px. (No StyleX/Tailwind compiler here — don't use xstyle/utility classes.)");}- lines.push('- Tokens for every value (`astryx docs tokens`). Brand/accent belongs in the theme (`astryx theme list` / `theme add <slug>`, or `astryx theme template` for a custom one) — never override --color-* in :root.');+ lines.push('- Tokens for every value (`astryx docs tokens`). Brand/accent belongs in the theme. Run `astryx theme list`, install a package, and `theme add <slug> --import` to import its built theme through the generated app module. Extend that theme to customize it. Use `theme eject <slug>` only to fork source and `astryx theme template` for a new theme — never override --color-* in :root.');// Self-check — post-generation pass. Validated via vibe tests (internal/vibe-tests/// prompt-purity-test): on complex multi-step UIs the rules above alone still leave raw// CSS in ~11-13% of runs; a re-read-and-fix pass cuts that ~4x at negligible token cost.diff --git a/packages/cli/foundation/agent-docs/app-theme-workflow.test.mjs b/packages/cli/foundation/agent-docs/app-theme-workflow.test.mjsnew file mode 100644index 0000000000..51e8978069--- /dev/null+++ b/packages/cli/foundation/agent-docs/app-theme-workflow.test.mjs@@ -0,0 +1,16 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {generateCompressedIndex} from './agent-docs.mjs';++describe('generated agent docs app-theme workflow', () => {+ it('keeps the add, extend, and eject guidance together', () => {+ const result = generateCompressedIndex('1.0.0');++ expect(result).toContain('theme add <slug> --import');+ expect(result).toContain('generated app module');+ expect(result).toContain('Extend that theme');+ expect(result).toContain('theme eject <slug>` only to fork source');+ expect(result).toContain('never override --color-');+ });+});diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 5669ff2fd0..2ce91daa4f 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -68,6 +68,7 @@ import {import {discoverBundledThemes,discoverIntegrationThemes,+ discoverLocalThemes,} from '../discovery/theme-discovery.mjs';import {getTransformsBetween} from '../../assets/codemods/registry.mjs';import {@@ -757,16 +758,20 @@ 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 theme- * contribution is reported without hiding the package's other valid kinds.+ * Bundled source themes, themes contributed by installed integrations, and+ * source themes under this app's conventional local authoring root. Each+ * record keeps its owner and source directory so app imports and explicit+ * ejects share one discovery seam. A broken integration theme contribution is+ * reported without hiding the package's other valid kinds.*+ * @param {{includeLocal?: boolean}} [options]* @returns {Promise<import('../discovery/theme-discovery.mjs').DiscoveredTheme[]>}*/- async themes() {- return this.#memo('themes', async () => {+ async themes({includeLocal = true} = {}) {+ return this.#memo(includeLocal ? 'themes' : 'themes:external', async () => {const themes = discoverBundledThemes();+ const projectDir = findPackageRoot(this.#cwd) ?? this.#cwd;+ if (includeLocal) themes.push(...discoverLocalThemes(projectDir));for (const integration of this.#loadedIntegrations) {await this.#collectIssues(integration);diff --git a/packages/cli/foundation/config/theme-private-vars.mjs b/packages/cli/foundation/config/theme-private-vars.mjsnew file mode 100644index 0000000000..c4aff1824a--- /dev/null+++ b/packages/cli/foundation/config/theme-private-vars.mjs@@ -0,0 +1,107 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Pure validation for private custom properties written directly in theme+ * input. Compiler-generated `--_*` declarations are not input and never enter+ * this check.+ */++/** @param {Record<string, any>} themeDef */+function adaptationRuleValues(themeDef) {+ if (Array.isArray(themeDef.__adaptationRules)) {+ return themeDef.__adaptationRules;+ }+ const rules = themeDef.adaptations?.rules ?? themeDef.__adaptations?.rules;+ if (!Array.isArray(rules)) return [];+ return rules+ .map(/** @param {any} rule */ rule => rule?.value)+ .filter(Boolean);+}++/**+ * Every named theme-input surface that can contain token or component writes.+ * @param {Record<string, any>} themeDef+ */+function inputSurfaces(themeDef) {+ const surfaces = [+ {name: 'theme', value: themeDef},+ {name: 'onDark', value: themeDef.onDark ?? themeDef.__onDark},+ {name: 'onLight', value: themeDef.onLight ?? themeDef.__onLight},+ ...adaptationRuleValues(themeDef).map((value, index) => ({+ name: `adaptation rule ${index + 1}`,+ value,+ })),+ ];+ return surfaces.filter(+ surface =>+ surface.value !== null &&+ typeof surface.value === 'object' &&+ !Array.isArray(surface.value),+ );+}++/**+ * Validate that authored theme input does not directly set private (`--_*`)+ * custom properties. Derived private variables emitted by the compiler are not+ * part of the input object and are valid.+ *+ * @param {Record<string, any>} themeDef+ * @returns {string[]}+ */+export function validatePrivateVars(themeDef) {+ /** @type {string[]} */+ const errors = [];++ for (const surface of inputSurfaces(themeDef)) {+ for (const field of ['tokens', 'localTokens']) {+ const values = surface.value[field];+ if (!values || typeof values !== 'object' || Array.isArray(values)) {+ continue;+ }+ for (const name of Object.keys(values)) {+ if (!name.startsWith('--_')) continue;+ errors.push(+ `${surface.name} ${field} sets private var "${name}". ` ++ 'Private vars (--_*) are internal; use a public token or standard CSS property instead.',+ );+ }+ }++ const components = surface.value.components;+ if (+ !components ||+ typeof components !== 'object' ||+ Array.isArray(components)+ ) {+ continue;+ }+ for (const [component, rules] of Object.entries(components)) {+ if (!rules || typeof rules !== 'object' || Array.isArray(rules)) continue;+ for (const [key, styles] of Object.entries(rules)) {+ /**+ * @param {unknown} value+ * @param {string[]} [path]+ */+ const visit = (value, path = []) => {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ return;+ for (const [prop, nested] of Object.entries(value)) {+ if (prop.startsWith('--_')) {+ errors.push(+ `Component "${component}" (${[surface.name, key, ...path].join(+ ' ',+ )}) sets private var "${prop}". ` ++ 'Private vars (--_*) are internal; use standard CSS properties ' ++ '(e.g. borderRadius, padding) instead. The pipeline expands them automatically.',+ );+ }+ visit(nested, [...path, prop]);+ }+ };+ visit(styles);+ }+ }+ }++ return [...new Set(errors)];+}diff --git a/packages/cli/foundation/config/theme-private-vars.test.mjs b/packages/cli/foundation/config/theme-private-vars.test.mjsnew file mode 100644index 0000000000..76246fcb99--- /dev/null+++ b/packages/cli/foundation/config/theme-private-vars.test.mjs@@ -0,0 +1,55 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {validatePrivateVars} from './theme-private-vars.mjs';++describe('validatePrivateVars', () => {+ it('accepts guaranteed properties that the compiler expands to private variables', () => {+ expect(+ validatePrivateVars({+ name: 'correct',+ tokens: {},+ components: {+ button: {base: {borderRadius: 'var(--radius-full)'}},+ card: {base: {padding: 'var(--spacing-4)'}},+ },+ }),+ ).toEqual([]);+ });++ it('reports direct private keys on every authored input surface', () => {+ const errors = validatePrivateVars({+ name: 'private-inputs',+ tokens: {'--_root-token': 'red'},+ localTokens: {'--_root-local': 'blue'},+ components: {button: {base: {'--_root-component': '1px'}}},+ onDark: {+ tokens: {'--_dark-token': 'black'},+ components: {card: {base: {'--_dark-component': '2px'}}},+ },+ adaptations: {+ rules: [+ {+ when: {pointer: 'coarse'},+ value: {+ localTokens: {'--_rule-local': '3px'},+ components: {button: {base: {'--_rule-component': '4px'}}},+ },+ },+ ],+ },+ });++ for (const name of [+ '--_root-token',+ '--_root-local',+ '--_root-component',+ '--_dark-token',+ '--_dark-component',+ '--_rule-local',+ '--_rule-component',+ ]) {+ expect(errors.join('\n')).toContain(name);+ }+ });+});diff --git a/packages/cli/foundation/config/theme-state.mjs b/packages/cli/foundation/config/theme-state.mjsnew file mode 100644index 0000000000..75d19eea5c--- /dev/null+++ b/packages/cli/foundation/config/theme-state.mjs@@ -0,0 +1,417 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file App-theme state stored in the generated theme module.+ *+ * The module is both the app import surface and the only record of added themes.+ * Its generated header records owners and the default without adding another public+ * export. Commands parse that header without running project code, regenerate the+ * whole marked file instead of editing it, and never replace an authored file.+ *+ * @input A project directory and resolved built-theme imports+ * @output Parsed state plus deterministic generated-module write plans+ * @position packages/cli/foundation/config — shared app-theme state+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';++export const LOCAL_THEME_ROOT = './src/themes';+export const THEME_MODULE_BASENAME = 'astryx-themes';+export const THEME_MODULE_MARKER =+ '@generated by `astryx theme` — do not edit manually.';+export const THEME_RECORD_MARKER = '@astryx-theme-record';++const THEME_SLUG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;++export class ThemeStateError extends Error {}++/** @param {unknown} value @returns {value is Record<string, unknown>} */+function isRecord(value) {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++/** @param {string} value */+export function projectPath(value) {+ return value.split(path.sep).join('/');+}++/**+ * Find the nearest package.json from a working directory.+ * @param {string} cwd+ */+export function findThemeProject(cwd) {+ let projectDir = path.resolve(cwd);+ for (let depth = 0; depth < 50; depth++) {+ const packageFile = path.join(projectDir, 'package.json');+ if (fs.existsSync(packageFile)) return {projectDir, packageFile};+ const parent = path.dirname(projectDir);+ if (parent === projectDir) break;+ projectDir = parent;+ }+ throw new ThemeStateError(+ 'No package.json found. Run this command inside an app project.',+ );+}++/**+ * Whether an owner value names a project-relative local theme root instead of+ * an installed package.+ * @param {string} owner+ */+export function isLocalThemeOwner(owner) {+ return owner.startsWith('./') || owner.startsWith('../') || path.isAbsolute(owner);+}++/** @param {string} projectDir */+export function projectUsesTypeScript(projectDir) {+ try {+ return fs+ .readdirSync(projectDir, {withFileTypes: true})+ .some(+ entry =>+ entry.isFile() &&+ /^tsconfig(?:\.[^.]+)*\.json$/u.test(entry.name),+ );+ } catch {+ return false;+ }+}++/**+ * All conventional module locations. The preferred new location is first.+ * @param {string} projectDir+ */+export function themeModuleCandidates(projectDir) {+ const src = path.join(projectDir, 'src');+ const hasSrc = fs.existsSync(src) && fs.statSync(src).isDirectory();+ const typescript = projectUsesTypeScript(projectDir);+ const preferredDir = hasSrc ? src : projectDir;+ const otherDir = hasSrc ? projectDir : src;+ const preferredExtension = typescript ? '.ts' : '.js';+ const otherExtension = typescript ? '.js' : '.ts';+ return [+ path.join(preferredDir, `${THEME_MODULE_BASENAME}${preferredExtension}`),+ path.join(preferredDir, `${THEME_MODULE_BASENAME}${otherExtension}`),+ path.join(otherDir, `${THEME_MODULE_BASENAME}${preferredExtension}`),+ path.join(otherDir, `${THEME_MODULE_BASENAME}${otherExtension}`),+ ];+}++/**+ * @param {unknown} value+ * @param {string} label+ */+function validThemeRecord(value, label) {+ if (!isRecord(value) || !isRecord(value.themes)) {+ throw new ThemeStateError(+ `${label} must carry a static ${THEME_RECORD_MARKER} header. Regenerate it with \`astryx theme add <slug> --import\`.`,+ );+ }+ const keys = Object.keys(value);+ if (+ keys.length !== 2 ||+ !keys.includes('themes') ||+ !keys.includes('defaultThemeSlug')+ ) {+ throw new ThemeStateError(+ `${label} ${THEME_RECORD_MARKER} header must contain only themes and defaultThemeSlug.`,+ );+ }++ /** @type {Record<string, string>} */+ const themes = {};+ for (const [slug, owner] of Object.entries(value.themes)) {+ if (+ !THEME_SLUG_RE.test(slug) ||+ typeof owner !== 'string' ||+ owner.trim() === ''+ ) {+ throw new ThemeStateError(+ `${label} theme record must map lowercase kebab-case slugs to package names or local theme roots.`,+ );+ }+ themes[slug] = owner;+ }+ if (+ typeof value.defaultThemeSlug !== 'string' ||+ !THEME_SLUG_RE.test(value.defaultThemeSlug)+ ) {+ throw new ThemeStateError(+ `${label} defaultThemeSlug must be a lowercase kebab-case slug. Regenerate it with \`astryx theme use <slug>\`.`,+ );+ }+ return {themes, defaultSlug: value.defaultThemeSlug};+}++/**+ * Parse the generated module's record without executing the module.+ * @param {string} source+ * @param {string} label+ */+export function parseThemeModuleRecord(source, label = 'theme module') {+ if (!source.includes(THEME_MODULE_MARKER)) {+ throw new ThemeStateError(`${label} does not carry the Astryx generated marker.`);+ }+ const recordLines = source+ .split(/\r?\n/u)+ .filter(line => /^\s*\*\s*@astryx-theme-record\s+/u.test(line));+ if (recordLines.length !== 1) {+ throw new ThemeStateError(+ `${label} must carry exactly one static ${THEME_RECORD_MARKER} header. Regenerate it with \`astryx theme add <slug> --import\`.`,+ );+ }+ const payload = recordLines[0].replace(+ /^\s*\*\s*@astryx-theme-record\s+/u,+ '',+ );+ let record;+ try {+ record = JSON.parse(payload);+ } catch (error) {+ throw new ThemeStateError(+ `${label} has an invalid ${THEME_RECORD_MARKER} header: ${error instanceof Error ? error.message : String(error)}`,+ {cause: error},+ );+ }+ return validThemeRecord(record, label);+}++/**+ * Preserve the one existing generated module. With none, choose the first+ * conventional location. Two generated copies are ambiguous and fail closed.+ * @param {string} projectDir+ * @param {{forWrite?: boolean}} [options]+ */+export function resolveThemeModule(projectDir, {forWrite = false} = {}) {+ const candidates = themeModuleCandidates(projectDir);+ const generated = candidates.filter(file => {+ try {+ return fs.readFileSync(file, 'utf-8').includes(THEME_MODULE_MARKER);+ } catch {+ return false;+ }+ });+ if (generated.length > 1) {+ throw new ThemeStateError(+ `More than one generated theme module exists: ${generated+ .map(file => projectPath(path.relative(projectDir, file)))+ .join(', ')}. Keep one and remove the others before running the command again.`,+ );+ }+ const file = generated[0] ?? candidates[0];+ if (forWrite) {+ try {+ assertWithin(path.relative(projectDir, file), projectDir, {+ label: 'generated theme module',+ });+ } catch (error) {+ if (error instanceof PathSafetyError) {+ throw new ThemeStateError(error.message, {cause: error});+ }+ throw error;+ }+ }+ let expectedOriginal;+ if (fs.existsSync(file)) {+ expectedOriginal = fs.readFileSync(file);+ if (!expectedOriginal.toString('utf-8').includes(THEME_MODULE_MARKER)) {+ if (forWrite) {+ throw new ThemeStateError(+ `Refusing to replace ${projectPath(path.relative(projectDir, file))}: it is not an Astryx-generated theme module. Move that file before adding themes.`,+ );+ }+ expectedOriginal = undefined;+ }+ }+ return {+ file,+ path: projectPath(path.relative(projectDir, file)),+ typescript: file.endsWith('.ts'),+ expectedOriginal,+ exists: generated.length === 1,+ };+}++/**+ * @typedef {object} ThemeState+ * @property {string} projectDir+ * @property {string} packageFile+ * @property {Record<string, string>} themes+ * @property {string|null} defaultSlug+ * @property {string|null} legacyTheme+ * @property {boolean} configured+ * @property {ReturnType<typeof resolveThemeModule>} module+ */++/**+ * Read app-theme state from the generated module. Only when no module exists is+ * the released `package.json#astryx.theme` meaning returned as legacy input.+ * @param {string} [cwd]+ * @returns {ThemeState}+ */+export function readThemeState(cwd = process.cwd()) {+ const {projectDir, packageFile} = findThemeProject(cwd);+ const module = resolveThemeModule(projectDir);+ if (module.exists && module.expectedOriginal) {+ const record = parseThemeModuleRecord(+ module.expectedOriginal.toString('utf-8'),+ module.path,+ );+ return {+ projectDir,+ packageFile,+ themes: record.themes,+ defaultSlug: record.defaultSlug,+ legacyTheme: null,+ configured: true,+ module,+ };+ }++ let legacyTheme = null;+ try {+ const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ if (+ isRecord(pkg) &&+ isRecord(pkg.astryx) &&+ typeof pkg.astryx.theme === 'string'+ ) {+ legacyTheme = pkg.astryx.theme;+ }+ } catch {+ // Theme commands surface package problems at their own write boundary. A+ // legacy lookup with no readable package field simply has no configured theme.+ }+ return {+ projectDir,+ packageFile,+ themes: {},+ defaultSlug: null,+ legacyTheme,+ configured: false,+ module,+ };+}++/**+ * @typedef {object} ResolvedAppTheme+ * @property {string} slug+ * @property {string} owner+ * @property {string} exportName+ * @property {string} module+ * @property {string} stylesheet+ * @property {string} [fontStylesheet]+ * @property {string} moduleFile+ * @property {string} stylesheetFile+ * @property {string} [fontStylesheetFile]+ * @property {'bundled'|'package'|'local'} source+ */++/**+ * Render one generated module from final resolved state.+ * @param {ResolvedAppTheme[]} themes+ * @param {string} defaultSlug+ * @param {boolean} typescript+ */+export function renderThemeModule(themes, defaultSlug, typescript) {+ if (!themes.some(theme => theme.slug === defaultSlug)) {+ throw new ThemeStateError(+ `Default theme "${defaultSlug}" is not added. Run \`astryx theme add ${defaultSlug} --import\` first.`,+ );+ }+ /** @type {string[]} */+ const imports = [];+ /** @type {string[]} */+ const entries = [];+ /** @type {Record<string, string>} */+ const owners = {};+ themes.forEach((theme, index) => {+ const local = `_astryxTheme${index}`;+ imports.push(+ `import {${theme.exportName} as ${local}} from ${JSON.stringify(theme.module)};`,+ `import ${JSON.stringify(theme.stylesheet)};`,+ );+ if (theme.fontStylesheet) {+ imports.push(`import ${JSON.stringify(theme.fontStylesheet)};`);+ }+ entries.push(` ${JSON.stringify(theme.slug)}: ${local},`);+ owners[theme.slug] = theme.owner;+ });+ const record = JSON.stringify({themes: owners, defaultThemeSlug: defaultSlug});+ return `/**\n * ${THEME_MODULE_MARKER}\n * ${THEME_RECORD_MARKER} ${record}\n */\n\n${imports.join(+ '\n',+ )}\n\nexport const themes = {\n${entries.join('\n')}\n}${+ typescript ? ' as const' : ''+ };\n${+ typescript ? 'export type ThemeSlug = keyof typeof themes;\n' : ''+ }\nexport const defaultThemeSlug${+ typescript ? ': keyof typeof themes' : ''+ } = ${JSON.stringify(defaultSlug)};\n`;+}++/**+ * Resolve a project-relative import from the generated module to a local file.+ * @param {string} moduleFile+ * @param {string} target+ */+export function localImportSpecifier(moduleFile, target) {+ let relative = projectPath(path.relative(path.dirname(moduleFile), target));+ if (!relative.startsWith('.')) relative = `./${relative}`;+ return relative;+}++/**+ * Plan the generated-module write. The caller applies it through the shared+ * atomic transaction.+ * @param {ThemeState} state+ * @param {Record<string, string>} themes+ * @param {string} defaultSlug+ * @param {ResolvedAppTheme[]} resolvedThemes+ */+export function planThemeAppWrite(state, themes, defaultSlug, resolvedThemes) {+ const module = resolveThemeModule(state.projectDir, {forWrite: true});+ const entries = resolvedThemes.map(theme =>+ theme.source === 'local'+ ? {+ ...theme,+ module: localImportSpecifier(module.file, theme.moduleFile),+ stylesheet: localImportSpecifier(module.file, theme.stylesheetFile),+ ...(theme.fontStylesheetFile+ ? {+ fontStylesheet: localImportSpecifier(+ module.file,+ theme.fontStylesheetFile,+ ),+ }+ : {}),+ }+ : theme,+ );+ for (const theme of entries) {+ if (themes[theme.slug] !== theme.owner) {+ throw new ThemeStateError(+ `Theme record for "${theme.slug}" does not match its resolved owner.`,+ );+ }+ }+ const moduleContents = renderThemeModule(+ entries,+ defaultSlug,+ module.typescript,+ );+ return {+ module,+ entries,+ plan: {+ path: module.file,+ contents: moduleContents,+ createOnly: module.expectedOriginal == null,+ ...(module.expectedOriginal != null+ ? {expectedOriginal: module.expectedOriginal}+ : {}),+ },+ moduleContents,+ };+}diff --git a/packages/cli/foundation/config/theme-state.test.mjs b/packages/cli/foundation/config/theme-state.test.mjsnew file mode 100644index 0000000000..053b1789c2--- /dev/null+++ b/packages/cli/foundation/config/theme-state.test.mjs@@ -0,0 +1,182 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ LOCAL_THEME_ROOT,+ THEME_MODULE_MARKER,+ parseThemeModuleRecord,+ planThemeAppWrite,+ readThemeState,+ renderThemeModule,+ resolveThemeModule,+} from './theme-state.mjs';++/** @type {string[]} */+const dirs = [];++function project(pkg = {name: 'app'}) {+ const dir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-theme-state-'));+ dirs.push(dir);+ fs.writeFileSync(path.join(dir, 'package.json'), `${JSON.stringify(pkg)}\n`);+ return dir;+}++afterEach(() => {+ while (dirs.length > 0) {+ fs.rmSync(dirs.pop(), {recursive: true, force: true});+ }+});++function packageEntry(slug = 'ocean') {+ return {+ slug,+ owner: '@acme/themes',+ exportName: `${slug}Theme`,+ module: `@acme/themes/themes/${slug}`,+ stylesheet: `@acme/themes/themes/${slug}.css`,+ moduleFile: `/node_modules/@acme/themes/themes/${slug}.js`,+ stylesheetFile: `/node_modules/@acme/themes/themes/${slug}.css`,+ source: /** @type {const} */ ('package'),+ };+}++describe('generated theme-module state', () => {+ it('keeps released package.json astryx.theme meaning only without a module', () => {+ const dir = project({name: 'app', astryx: {theme: '@acme/legacy'}});+ expect(readThemeState(dir)).toMatchObject({+ themes: {},+ defaultSlug: null,+ legacyTheme: '@acme/legacy',+ configured: false,+ });+ });++ it('renders and statically reads the complete record without executing it', () => {+ const source = renderThemeModule([packageEntry()], 'ocean', true);+ expect(source).toContain(THEME_MODULE_MARKER);+ expect(source).toContain('export type ThemeSlug = keyof typeof themes');+ expect(+ [...source.matchAll(/^export (?:const|type) (\w+)/gmu)].map(+ match => match[1],+ ),+ ).toEqual(['themes', 'ThemeSlug', 'defaultThemeSlug']);+ expect(source).not.toContain('export const themeOwners');+ expect(parseThemeModuleRecord(source)).toEqual({+ themes: {ocean: '@acme/themes'},+ defaultSlug: 'ocean',+ });+ });++ it('emits JavaScript without TypeScript syntax', () => {+ const source = renderThemeModule([packageEntry()], 'ocean', false);+ expect(source).not.toContain('export type');+ expect(source).not.toContain(' as const');+ expect(+ [...source.matchAll(/^export const (\w+)/gmu)].map(match => match[1]),+ ).toEqual(['themes', 'defaultThemeSlug']);+ expect(parseThemeModuleRecord(source)).toEqual({+ themes: {ocean: '@acme/themes'},+ defaultSlug: 'ocean',+ });+ });++ it('uses src for a TypeScript project and the project root without src', () => {+ const typed = project();+ fs.mkdirSync(path.join(typed, 'src'));+ fs.writeFileSync(path.join(typed, 'tsconfig.json'), '{}\n');+ expect(resolveThemeModule(typed).path).toBe('src/astryx-themes.ts');++ const plain = project();+ expect(resolveThemeModule(plain).path).toBe('astryx-themes.js');+ });++ it('preserves an existing marked module when project shape changes', () => {+ const dir = project();+ const existing = path.join(dir, 'astryx-themes.js');+ fs.writeFileSync(+ existing,+ renderThemeModule([packageEntry()], 'ocean', false),+ );+ fs.mkdirSync(path.join(dir, 'src'));+ fs.writeFileSync(path.join(dir, 'tsconfig.json'), '{}\n');+ expect(resolveThemeModule(dir).file).toBe(existing);+ });++ it('fails closed when two generated modules exist', () => {+ const dir = project();+ fs.mkdirSync(path.join(dir, 'src'));+ const source = renderThemeModule([packageEntry()], 'ocean', false);+ fs.writeFileSync(path.join(dir, 'astryx-themes.js'), source);+ fs.writeFileSync(path.join(dir, 'src', 'astryx-themes.js'), source);+ expect(() => readThemeState(dir)).toThrow(+ /more than one generated theme module/i,+ );+ });++ it('refuses to replace an authored file at the selected path', () => {+ const dir = project();+ fs.writeFileSync(+ path.join(dir, 'astryx-themes.js'),+ 'export const mine = true;\n',+ );+ const state = readThemeState(dir);+ expect(() =>+ planThemeAppWrite(state, {ocean: '@acme/themes'}, 'ocean', [+ packageEntry(),+ ]),+ ).toThrow(/refusing to replace/i);+ });++ it('rejects a generated-module write through a symlink outside the project', () => {+ const dir = project();+ const outside = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-theme-state-outside-'),+ );+ dirs.push(outside);+ fs.symlinkSync(outside, path.join(dir, 'src'));+ fs.writeFileSync(path.join(dir, 'tsconfig.json'), '{}\n');+ const state = readThemeState(dir);++ expect(() =>+ planThemeAppWrite(state, {ocean: '@acme/themes'}, 'ocean', [+ packageEntry(),+ ]),+ ).toThrow(/outside the project root.*symlink/i);+ expect(fs.existsSync(path.join(outside, 'astryx-themes.ts'))).toBe(false);+ });++ it('records a local owner and renders local paths relative to the module', () => {+ const dir = project();+ fs.mkdirSync(path.join(dir, 'src'));+ fs.writeFileSync(path.join(dir, 'tsconfig.json'), '{}\n');+ const state = readThemeState(dir);+ const sourceDir = path.join(dir, 'src', 'themes', 'ocean');+ const prepared = planThemeAppWrite(+ state,+ {ocean: LOCAL_THEME_ROOT},+ 'ocean',+ [+ {+ slug: 'ocean',+ owner: LOCAL_THEME_ROOT,+ exportName: 'oceanTheme',+ module: '',+ stylesheet: '',+ moduleFile: path.join(sourceDir, 'ocean.js'),+ stylesheetFile: path.join(sourceDir, 'ocean.css'),+ source: 'local',+ },+ ],+ );+ expect(prepared.moduleContents).toContain('from "./themes/ocean/ocean.js"');+ expect(prepared.moduleContents).toContain(+ 'import "./themes/ocean/ocean.css"',+ );+ expect(parseThemeModuleRecord(prepared.moduleContents)).toEqual({+ themes: {ocean: LOCAL_THEME_ROOT},+ defaultSlug: 'ocean',+ });+ });+});diff --git a/packages/cli/foundation/discovery/module-exports.mjs b/packages/cli/foundation/discovery/module-exports.mjsnew file mode 100644index 0000000000..40cae65fdf--- /dev/null+++ b/packages/cli/foundation/discovery/module-exports.mjs@@ -0,0 +1,146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Static JavaScript module export inspection.+ *+ * Proves a runtime export without executing package code. Local ESM re-exports+ * are followed recursively; unresolved or unparsable modules fail closed.+ *+ * @input A module path and runtime export name+ * @output Whether that export can be proved statically+ * @position packages/cli/foundation/discovery — shared package inspection+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import jscodeshift from 'jscodeshift';++const MODULE_EXTENSIONS = [+ '.mjs',+ '.js',+ '.cjs',+ '.mts',+ '.ts',+ '.cts',+ '.tsx',+ '.jsx',+];+const parser = 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 => {+ try {+ return fs.statSync(candidate).isFile();+ } catch {+ return false;+ }+ }) ?? null;+}++/** @param {any} declaration @param {string} exportName */+function declarationExports(declaration, exportName) {+ if (!declaration || declaration.declare === true) 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,+ );+}++/** @param {any} declaration */+function runtimeDefault(declaration) {+ return (+ declaration != null &&+ declaration.declare !== true &&+ ![+ 'TSDeclareFunction',+ 'TSInterfaceDeclaration',+ 'TSTypeAliasDeclaration',+ ].includes(declaration.type)+ );+}++/**+ * Check one module's static export surface without executing it.+ * @param {string} file+ * @param {string} exportName+ * @param {Set<string>} [seen]+ */+export function moduleExportsName(file, exportName, seen = new Set()) {+ const identity = `${file}\0${exportName}`;+ if (seen.has(identity)) return false;+ seen.add(identity);+ try {+ if (!fs.statSync(file).isFile()) return false;+ } catch {+ return false;+ }++ let root;+ try {+ root = parser(fs.readFileSync(file, 'utf-8'));+ } catch {+ return false;+ }++ let found = false;+ root+ .find(parser.ExportNamedDeclaration)+ .forEach((/** @type {any} */ exportPath) => {+ if (found || exportPath.node.exportKind === 'type') return;+ const node = exportPath.node;+ if (declarationExports(node.declaration, exportName)) {+ found = true;+ return;+ }+ for (const specifier of node.specifiers ?? []) {+ if (+ specifier.type !== 'ExportSpecifier' ||+ specifier.exportKind === 'type'+ ) {+ continue;+ }+ 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') {+ const defaults = root.find(parser.ExportDefaultDeclaration).nodes();+ if (defaults.some((/** @type {any} */ node) => runtimeDefault(node.declaration))) {+ return true;+ }+ }++ root+ .find(parser.ExportAllDeclaration)+ .forEach((/** @type {any} */ exportPath) => {+ if (found || exportPath.node.exportKind === 'type') return;+ const target = resolveLocalModule(exportPath.node.source?.value, file);+ if (target && moduleExportsName(target, exportName, seen)) found = true;+ });+ return found;+}diff --git a/packages/cli/foundation/discovery/package-exports.mjs b/packages/cli/foundation/discovery/package-exports.mjsnew file mode 100644index 0000000000..181ca8b275--- /dev/null+++ b/packages/cli/foundation/discovery/package-exports.mjs@@ -0,0 +1,200 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Package export-map inspection for built theme assets.+ *+ * Resolves exact and wildcard subpaths through ordinary conditional export+ * objects without executing package code. Packages with no exports map retain+ * their legacy public deep paths and are resolved from files on disk.+ *+ * @input Parsed package.json, package directory, and a public subpath+ * @output The public specifier and confined target file, when exported+ * @position packages/cli/foundation/discovery — shared package import metadata+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++const MODULE_EXTENSIONS = [+ '.mjs',+ '.js',+ '.cjs',+ '.mts',+ '.ts',+ '.cts',+ '.tsx',+ '.jsx',+];+const CONDITION_ORDER = ['import', 'default', 'browser', 'node', 'require'];++/** @param {unknown} value @returns {value is Record<string, unknown>} */+function isRecord(value) {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++/**+ * Select one string target from a conditional or fallback export value.+ * @param {unknown} value+ * @returns {string|null}+ */+function targetString(value) {+ if (typeof value === 'string') return value;+ if (Array.isArray(value)) {+ for (const item of value) {+ const selected = targetString(item);+ if (selected) return selected;+ }+ return null;+ }+ if (!isRecord(value)) return null;+ const keys = [+ ...CONDITION_ORDER.filter(key => Object.hasOwn(value, key)),+ ...Object.keys(value).filter(+ key => key !== 'types' && !CONDITION_ORDER.includes(key),+ ),+ ];+ for (const key of keys) {+ const selected = targetString(value[key]);+ if (selected) return selected;+ }+ return null;+}++/**+ * Find an exact or one-star subpath mapping and the wildcard value it matched.+ * @param {Record<string, unknown>} map+ * @param {string} subpath+ */+function subpathValue(map, subpath) {+ if (Object.hasOwn(map, subpath)) {+ return {found: map[subpath] != null, value: map[subpath], wildcard: ''};+ }+ const patterns = Object.keys(map)+ .filter(key => key.startsWith('./') && key.split('*').length === 2)+ .sort((a, b) => b.length - a.length);+ for (const pattern of patterns) {+ const star = pattern.indexOf('*');+ const prefix = pattern.slice(0, star);+ const suffix = pattern.slice(star + 1);+ if (+ subpath.length >= prefix.length + suffix.length &&+ subpath.startsWith(prefix) &&+ subpath.endsWith(suffix)+ ) {+ return {+ found: map[pattern] != null,+ value: map[pattern],+ wildcard: subpath.slice(prefix.length, subpath.length - suffix.length),+ };+ }+ }+ return {found: false, value: null, wildcard: ''};+}++/**+ * Select the export value for one subpath.+ * @param {unknown} exportsField+ * @param {string} subpath+ */+function exportValue(exportsField, subpath) {+ if (exportsField === undefined) {+ return {hasMap: false, exported: true, target: null};+ }+ if (!isRecord(exportsField)) {+ return {+ hasMap: true,+ exported: subpath === '.' && exportsField != null,+ target: subpath === '.' ? targetString(exportsField) : null,+ };+ }+ const keys = Object.keys(exportsField);+ const subpathMap = keys.some(key => key.startsWith('.'));+ if (!subpathMap) {+ return {+ hasMap: true,+ exported: subpath === '.',+ target: subpath === '.' ? targetString(exportsField) : null,+ };+ }+ const selected = subpathValue(exportsField, subpath);+ const target = selected.found ? targetString(selected.value) : null;+ return {+ hasMap: true,+ exported: selected.found && target != null,+ target: target?.replaceAll('*', selected.wildcard) ?? null,+ };+}++/** @param {string} file */+function regularFile(file) {+ try {+ return fs.statSync(file).isFile();+ } catch {+ return false;+ }+}++/**+ * Resolve an export target while confining it to its package.+ * @param {string} packageDir+ * @param {string} target+ */+function resolveTarget(packageDir, target) {+ if (!target.startsWith('./')) return null;+ const resolved = path.resolve(packageDir, target);+ const root = path.resolve(packageDir);+ if (resolved !== root && !resolved.startsWith(root + path.sep)) return null;+ return regularFile(resolved) ? resolved : null;+}++/**+ * Resolve a public legacy deep path for a package with no exports map.+ * @param {string} packageDir+ * @param {string} subpath+ */+function resolveLegacy(packageDir, subpath) {+ if (!subpath.startsWith('./')) return null;+ const base = path.resolve(packageDir, subpath.slice(2));+ const root = path.resolve(packageDir);+ if (base !== root && !base.startsWith(root + path.sep)) return null;+ const candidates = [+ base,+ ...MODULE_EXTENSIONS.map(extension => `${base}${extension}`),+ ...MODULE_EXTENSIONS.map(extension => path.join(base, `index${extension}`)),+ ];+ return candidates.find(regularFile) ?? null;+}++/**+ * @typedef {object} PackageExportResult+ * @property {string} subpath+ * @property {string} specifier+ * @property {boolean} exported+ * @property {string|null} target+ * @property {string|null} authoredTarget+ */++/**+ * Inspect one public package subpath.+ * @param {{name?: unknown, exports?: unknown}} pkg+ * @param {string} packageDir+ * @param {string} subpath `.` or a `./`-prefixed subpath+ * @returns {PackageExportResult}+ */+export function inspectPackageExport(pkg, packageDir, subpath) {+ const name = typeof pkg.name === 'string' ? pkg.name : '';+ const selected = exportValue(pkg.exports, subpath);+ const target = selected.hasMap+ ? selected.target+ ? resolveTarget(packageDir, selected.target)+ : null+ : resolveLegacy(packageDir, subpath);+ const suffix = subpath === '.' ? '' : `/${subpath.slice(2)}`;+ return {+ subpath,+ specifier: `${name}${suffix}`,+ exported: selected.exported,+ target,+ authoredTarget: selected.target,+ };+}diff --git a/packages/cli/foundation/discovery/theme-discovery.mjs b/packages/cli/foundation/discovery/theme-discovery.mjsindex bd47313f1e..6f517d4bdb 100644--- a/packages/cli/foundation/discovery/theme-discovery.mjs+++ b/packages/cli/foundation/discovery/theme-discovery.mjs@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Theme descriptor discovery shared by Project, theme list/add, and+ * @file Theme descriptor discovery shared by Project, theme list/add/eject, and* integration validation.** A theme root contains one directory per lower-kebab slug. Each directory has@@ -22,6 +22,7 @@ import * as path from 'node:path';import {lowerDoc} from '../doc-compiler/compile.mjs';import {packageSource} from '../doc-compiler/source.mjs';import {CLI_ROOT} from '../fs/paths.mjs';+import {LOCAL_THEME_ROOT} from '../config/theme-state.mjs';import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';export const BUNDLED_THEME_PACKAGE = '@astryxdesign/cli';@@ -62,14 +63,28 @@ function sourceParser() {* @property {boolean} maintained* @property {string} entry* @property {string} exportName- * @property {string[]} files what `theme add` copies, relative to sourceDir,+ * @property {string[]} files what `theme eject` copies, relative to sourceDir,* entry first- * @property {string} package+ * @property {string} package package exposed for discovery and --package selection+ * @property {string} [importPackage] package that owns built imports when it differs from the selector package+ * @property {string} [packageDir] absolute package/project directory+ * @property {Record<string, unknown>|null} [packageExports] parsed package exports+ * @property {'bundled'|'package'|'local'} source* @property {string} sourceDir absolute directory holding this theme's files* @property {boolean} bundled* @property {string} docPath absolute descriptor path*/+/**+ * The package written to the app record and used for built imports. Bundled+ * themes keep the released CLI package as their selector while importing from+ * their standalone theme package.+ * @param {DiscoveredTheme} theme+ */+export function themeImportPackage(theme) {+ return theme.importPackage ?? theme.package;+}+/*** Resolve one authored relative path without allowing POSIX or Windows escape* syntax, even when discovery runs on the other platform.@@ -1016,7 +1031,7 @@ export function isThemeFolder(folder) {/*** The files one theme folder ships: every regular file below it except* {@link isIgnoredThemeEntry} entries. What pack-check requires and what- * `theme add` copies.+ * `theme eject` copies.* @param {string} folder absolute path* @returns {string[]} sorted POSIX paths relative to the folder*/@@ -1024,14 +1039,76 @@ export function listThemeFiles(folder) {return listThemeFolder(folder).files;}+/**+ * @typedef {object} UnmigratedThemeCopy+ * @property {string} slug+ * @property {string} sourceDir+ * @property {string} entry+ * @property {string} exportName+ * @property {string} descriptor+ */++/**+ * Recognize the shape released `theme add` copied before local descriptors+ * existed. Keep this narrow so an unrelated broken folder still follows the+ * ordinary discovery error path.+ * @param {string} folder+ * @returns {UnmigratedThemeCopy|null}+ */+function unmigratedThemeCopy(folder) {+ const slug = path.basename(folder);+ if (!THEME_SLUG_RE.test(slug)) return null;+ const listing = listThemeFolder(folder);+ if (+ listing.symlinks.length > 0 ||+ listing.files.some(file => file.endsWith(THEME_DOC_SUFFIX))+ ) {+ return null;+ }+ const sources = listing.files.filter(+ file => !file.includes('/') && THEME_SOURCE_RE.test(file),+ );+ if (sources.length !== 1) return null;+ const entry = sources[0];+ const exportName = entry.replace(/\.(?:mjs|js|mts|ts|tsx|jsx)$/u, '');+ return {+ slug,+ sourceDir: folder,+ entry,+ exportName,+ descriptor: `${exportName}${THEME_DOC_SUFFIX}`,+ };+}++/**+ * Source copies left by the released `theme add`, before it copied a+ * descriptor. Commands skip these until the next-release project codemod adds+ * the same-stem descriptor.+ * @param {string} projectDir+ * @param {string} [owner]+ * @returns {UnmigratedThemeCopy[]}+ */+export function discoverUnmigratedThemeCopies(+ projectDir,+ owner = LOCAL_THEME_ROOT,+) {+ const root = path.resolve(projectDir, owner);+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];+ return fs+ .readdirSync(root, {withFileTypes: true})+ .filter(entry => entry.isDirectory() && !isIgnoredThemeEntry(entry.name))+ .map(entry => unmigratedThemeCopy(path.join(root, entry.name)))+ .filter(copy => copy !== null)+ .sort((a, b) => a.slug.localeCompare(b.slug));+}+/** @param {string[]} files */function quoted(files) {return files.map(file => `"${file}"`).join(', ');}/**- * The files `theme add` has always copied after a bundled theme's entry, in- * copy order. SYNC: scripts/generate-cli-themes.mjs bundles these.+ * The files `theme eject` copies after a bundled theme's entry, in copy order. SYNC: scripts/generate-cli-themes.mjs bundles these.* @param {string} id the theme's export name without `Theme`*/function bundledThemeArtifacts(id) {@@ -1046,9 +1123,9 @@ function bundledThemeArtifacts(id) {}/**- * The files `theme add` copies, entry first. A bundled theme's descriptor is- * the CLI's own metadata and stays behind; an integration theme copies its- * whole directory.+ * The files `theme eject` copies, entry first. Every ejected theme keeps its+ * same-stem descriptor so the local themes root remains discoverable without a+ * catalog. An integration theme copies its complete directory.* @param {string[]} files every regular file in the theme directory, sorted* @param {string} entry* @param {string} descriptor@@ -1056,13 +1133,12 @@ function bundledThemeArtifacts(id) {* @param {boolean} bundled*/function copiedThemeFiles(files, entry, descriptor, exportName, bundled) {- const rest = files.filter(- file => file !== entry && !(bundled && file === descriptor),- );- if (!bundled) return [entry, ...rest];+ const rest = files.filter(file => file !== entry && file !== descriptor);+ if (!bundled) return [entry, descriptor, ...rest];const order = bundledThemeArtifacts(exportName.replace(/Theme$/u, ''));return [entry,+ descriptor,...order.filter(file => rest.includes(file)),...rest.filter(file => !order.includes(file)),];@@ -1072,14 +1148,15 @@ function copiedThemeFiles(files, entry, descriptor, exportName, bundled) {* Discover and validate one theme root.* @param {string} themeRoot absolute root containing one directory per slug* @param {string} owner package that owns the root- * @param {{bundled?: boolean}} [options] a bundled root is the CLI's own; its- * sources are checked by the CLI's tests rather than on every read+ * @param {{bundled?: boolean, allowUnmigrated?: boolean}} [options] a bundled root is the CLI's own; its+ * sources are checked by the CLI's tests rather than on every read. A local+ * root may skip released source copies until `astryx upgrade` adds descriptors.* @returns {DiscoveredTheme[]}*/export function discoverThemeDirectory(themeRoot,owner,- {bundled = false} = {},+ {bundled = false, allowUnmigrated = false} = {},) {if (!fs.existsSync(themeRoot) || !fs.statSync(themeRoot).isDirectory()) {throw new Error(@@ -1149,6 +1226,13 @@ export function discoverThemeDirectory(file.endsWith(THEME_DOC_SUFFIX),);const docs = descriptors.filter(file => !file.includes('/'));+ if (+ allowUnmigrated &&+ descriptors.length === 0 &&+ unmigratedThemeCopy(sourceDir)+ ) {+ continue;+ }if (docs.length !== 1) {const detail =docs.length > 1@@ -1263,6 +1347,7 @@ export function discoverThemeDirectory(bundled,),package: owner,+ source: bundled ? 'bundled' : 'package',sourceDir,bundled,docPath,@@ -1375,15 +1460,46 @@ export function discoverBundledThemes() {THEMES_DIR,BUNDLED_THEME_PACKAGE,{bundled: true},- );+ ).map(theme => ({+ ...theme,+ importPackage: `@astryxdesign/theme-${theme.slug}`,+ source: /** @type {const} */ ('bundled'),+ }));return bundledThemeCache.map(theme => ({...theme, files: [...theme.files]}));}+/**+ * Discover authored themes in the app's conventional local themes root.+ * @param {string} projectDir+ * @param {string} [owner]+ * @returns {DiscoveredTheme[]}+ */+export function discoverLocalThemes(projectDir, owner = LOCAL_THEME_ROOT) {+ const root = path.resolve(projectDir, owner);+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];+ return discoverThemeDirectory(root, owner, {allowUnmigrated: true}).map(+ theme => ({+ ...theme,+ package: owner,+ packageDir: projectDir,+ packageExports: null,+ source: /** @type {const} */ ('local'),+ }),+ );+}+/*** @param {import('../integrations/integrations.mjs').LoadedIntegration} integration* @returns {Promise<DiscoveredTheme[]>}*/export async function discoverIntegrationThemes(integration) {if (!integration.themes) return [];- return discoverThemeDirectory(integration.themes, integration.name);+ return discoverThemeDirectory(integration.themes, integration.name).map(+ theme => ({+ ...theme,+ packageDir: integration.__packageDir,+ packageExports: integration.__packageExports,+ source: /** @type {const} */ ('package'),+ }),+ );}diff --git a/packages/cli/foundation/discovery/theme-discovery.test.mjs b/packages/cli/foundation/discovery/theme-discovery.test.mjsindex 975bcfb3ac..fd831b896a 100644--- a/packages/cli/foundation/discovery/theme-discovery.test.mjs+++ b/packages/cli/foundation/discovery/theme-discovery.test.mjs@@ -62,12 +62,17 @@ afterEach(() => {});describe('theme descriptor discovery', () => {- it('reads bundled descriptors with package ownership', () => {+ it('keeps the released selector package and records the import package', () => {const themes = discoverBundledThemes();expect(themes.length).toBeGreaterThan(0);expect(themes.every(theme => theme.package === BUNDLED_THEME_PACKAGE)).toBe(true,);+ expect(+ themes.every(+ theme => theme.importPackage === `@astryxdesign/theme-${theme.slug}`,+ ),+ ).toBe(true);expect(themes.every(theme => theme.bundled)).toBe(true);expect(themes.filter(theme => theme.maintained).map(theme => theme.slug),@@ -717,10 +722,11 @@ describe('folders under a theme root that are not themes', () => {});describe('bundled theme files', () => {- it('copies what the bundle has always copied, entry first, without its descriptor', () => {+ it('keeps entry first and includes the descriptor needed by theme eject', () => {const themes = discoverBundledThemes();expect(themes.find(theme => theme.slug === 'neutral')?.files).toEqual(['neutralTheme.ts',+ 'neutralTheme.doc.mjs','icons.tsx','neutralPalettes.ts','neutralPalettes.generated.ts',@@ -730,7 +736,7 @@ describe('bundled theme files', () => {]);for (const theme of themes) {expect(theme.files[0]).toBe(theme.entry);- expect(theme.files.some(file => file.endsWith('.doc.mjs'))).toBe(false);+ expect(theme.files).toContain(path.basename(theme.docPath));}});diff --git a/packages/cli/foundation/discovery/theme-imports.mjs b/packages/cli/foundation/discovery/theme-imports.mjsnew file mode 100644index 0000000000..6bdada88ea--- /dev/null+++ b/packages/cli/foundation/discovery/theme-imports.mjs@@ -0,0 +1,217 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Resolve one discovered source theme to the built imports an app uses.+ *+ * Package themes use their fixed public export paths. Local themes use the+ * `.js` and `.css` outputs `astryx theme build` writes beside their source.+ * Resolution fails closed and never falls back to runtime source or copying.+ *+ * @input A discovered theme, project directory, and owner theme count+ * @output Built module/CSS import metadata with absolute files for verification+ * @position packages/cli/foundation/discovery — source-to-built theme boundary+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {findInstalledPackage} from '../fs/paths.mjs';+import {moduleExportsName} from './module-exports.mjs';+import {inspectPackageExport} from './package-exports.mjs';+import {themeImportPackage} from './theme-discovery.mjs';+import {isLocalThemeOwner, projectPath} from '../config/theme-state.mjs';++export class ThemeImportError extends Error {}++/** @param {string} file */+function readPackage(file) {+ try {+ return JSON.parse(fs.readFileSync(file, 'utf-8'));+ } catch (error) {+ throw new ThemeImportError(+ `Cannot read theme package metadata at ${file}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ {cause: error},+ );+ }+}++/**+ * @param {import('./theme-discovery.mjs').DiscoveredTheme} theme+ * @param {string} cwd+ */+function resolveLocalTheme(theme, cwd) {+ const moduleFile = path.join(theme.sourceDir, `${theme.slug}.js`);+ const stylesheetFile = path.join(theme.sourceDir, `${theme.slug}.css`);+ const fontStylesheetFile = path.join(+ theme.sourceDir,+ `${theme.slug}.fonts.css`,+ );+ const missing = [moduleFile, stylesheetFile].filter(file => {+ try {+ return !fs.statSync(file).isFile();+ } catch {+ return true;+ }+ });+ if (missing.length > 0) {+ const source = projectPath(+ path.relative(cwd, path.join(theme.sourceDir, theme.entry)),+ );+ throw new ThemeImportError(+ `Local theme "${theme.slug}" is not built. Run \`astryx theme build ${source}\` and try again. Missing: ${missing+ .map(file => projectPath(path.relative(cwd, file)))+ .join(', ')}.`,+ );+ }+ if (!moduleExportsName(moduleFile, theme.exportName)) {+ throw new ThemeImportError(+ `Local theme "${theme.slug}" built module ${projectPath(+ path.relative(cwd, moduleFile),+ )} does not export "${theme.exportName}". Rebuild it with \`astryx theme build ${projectPath(+ path.relative(cwd, path.join(theme.sourceDir, theme.entry)),+ )}\`.`,+ );+ }+ return {+ slug: theme.slug,+ owner: theme.package,+ exportName: theme.exportName,+ module: '',+ stylesheet: '',+ moduleFile,+ stylesheetFile,+ ...(fs.existsSync(fontStylesheetFile) ? {fontStylesheetFile} : {}),+ source: /** @type {const} */ ('local'),+ };+}++/**+ * Inspect one package export triplet.+ * @param {Record<string, any>} pkg+ * @param {string} packageDir+ * @param {string} moduleSubpath+ * @param {string} stylesheetSubpath+ * @param {string} fontSubpath+ */+function packageTriplet(+ pkg,+ packageDir,+ moduleSubpath,+ stylesheetSubpath,+ fontSubpath,+) {+ return {+ module: inspectPackageExport(pkg, packageDir, moduleSubpath),+ stylesheet: inspectPackageExport(pkg, packageDir, stylesheetSubpath),+ font: inspectPackageExport(pkg, packageDir, fontSubpath),+ };+}++/** @param {ReturnType<typeof packageTriplet>} triplet */+function complete(triplet) {+ return (+ triplet.module.exported &&+ triplet.module.target != null &&+ triplet.stylesheet.exported &&+ triplet.stylesheet.target != null+ );+}++/**+ * @param {import('./theme-discovery.mjs').DiscoveredTheme} theme+ * @param {string} cwd+ * @param {number} ownerThemeCount+ */+function resolvePackageTheme(theme, cwd, ownerThemeCount) {+ const importPackage = themeImportPackage(theme);+ const packageDir =+ /** @type {any} */ (theme).packageDir ??+ findInstalledPackage(cwd, importPackage);+ if (!packageDir) {+ throw new ThemeImportError(+ `Theme package "${importPackage}" is not installed. Run \`npm install ${importPackage}\` (or yarn/pnpm/bun), then run \`astryx theme add ${theme.slug} --import\`.`,+ );+ }+ const pkg = readPackage(path.join(packageDir, 'package.json'));+ const perTheme = packageTriplet(+ pkg,+ packageDir,+ `./themes/${theme.slug}`,+ `./themes/${theme.slug}.css`,+ `./themes/${theme.slug}.fonts.css`,+ );+ const single =+ ownerThemeCount === 1+ ? packageTriplet(pkg, packageDir, './built', './theme.css', './fonts.css')+ : null;+ const selected = complete(perTheme)+ ? perTheme+ : single && complete(single)+ ? single+ : null;+ if (!selected) {+ const missing = [];+ if (!perTheme.module.exported || !perTheme.module.target) {+ missing.push(`module export ${pkg.name}/themes/${theme.slug}`);+ }+ if (!perTheme.stylesheet.exported || !perTheme.stylesheet.target) {+ missing.push(`stylesheet export ${pkg.name}/themes/${theme.slug}.css`);+ }+ if (ownerThemeCount === 1) {+ missing.push(+ `or the single-theme exports ${pkg.name}/built and ${pkg.name}/theme.css`,+ );+ }+ throw new ThemeImportError(+ `Theme "${theme.slug}" from ${importPackage} has no resolvable built module and stylesheet. Missing ${missing.join(', ')}. The package must build and export them before it can be added.`,+ );+ }+ if (selected.font.exported && selected.font.target == null) {+ throw new ThemeImportError(+ `Theme "${theme.slug}" from ${importPackage} exports ${selected.font.specifier}, but that font stylesheet does not resolve from the installed package.`,+ );+ }+ if (+ !selected.module.target ||+ !moduleExportsName(selected.module.target, theme.exportName)+ ) {+ throw new ThemeImportError(+ `Theme "${theme.slug}" built module ${selected.module.specifier} does not export "${theme.exportName}". Rebuild the package theme before adding it.`,+ );+ }+ return {+ slug: theme.slug,+ owner: importPackage,+ exportName: theme.exportName,+ module: selected.module.specifier,+ stylesheet: selected.stylesheet.specifier,+ ...(selected.font.exported && selected.font.target+ ? {fontStylesheet: selected.font.specifier}+ : {}),+ moduleFile: selected.module.target,+ stylesheetFile: /** @type {string} */ (selected.stylesheet.target),+ ...(selected.font.target ? {fontStylesheetFile: selected.font.target} : {}),+ source:+ /** @type {any} */ (theme).source === 'bundled' || theme.bundled+ ? /** @type {const} */ ('bundled')+ : /** @type {const} */ ('package'),+ };+}++/**+ * Resolve a discovered theme to app imports.+ * @param {import('./theme-discovery.mjs').DiscoveredTheme} theme+ * @param {{cwd?: string, ownerThemeCount?: number}} [options]+ * @returns {import('../config/theme-state.mjs').ResolvedAppTheme}+ */+export function resolveThemeImports(theme, options = {}) {+ const cwd = options.cwd ?? process.cwd();+ if (+ /** @type {any} */ (theme).source === 'local' ||+ isLocalThemeOwner(theme.package)+ ) {+ return resolveLocalTheme(theme, cwd);+ }+ return resolvePackageTheme(theme, cwd, options.ownerThemeCount ?? 1);+}diff --git a/packages/cli/foundation/discovery/theme-imports.test.mjs b/packages/cli/foundation/discovery/theme-imports.test.mjsnew file mode 100644index 0000000000..f50ce4d729--- /dev/null+++ b/packages/cli/foundation/discovery/theme-imports.test.mjs@@ -0,0 +1,173 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {resolveThemeImports} from './theme-imports.mjs';++/** @type {string[]} */+const dirs = [];++function project() {+ const dir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-theme-imports-'),+ );+ dirs.push(dir);+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"app"}\n');+ return dir;+}++function packageTheme(dir, exportsMap) {+ const packageDir = path.join(dir, 'node_modules', '@acme', 'themes');+ fs.mkdirSync(path.join(packageDir, 'dist'), {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: '@acme/themes', exports: exportsMap}),+ );+ return packageDir;+}++function discovered(fields = {}) {+ return {+ slug: 'ocean',+ displayName: 'Ocean',+ description: 'Ocean theme.',+ maintained: true,+ entry: 'oceanTheme.ts',+ exportName: 'oceanTheme',+ files: ['oceanTheme.ts'],+ package: '@acme/themes',+ sourceDir: '/source/ocean',+ bundled: false,+ docPath: '/source/ocean/oceanTheme.doc.mjs',+ source: /** @type {const} */ ('package'),+ ...fields,+ };+}++afterEach(() => {+ while (dirs.length > 0) {+ fs.rmSync(dirs.pop(), {recursive: true, force: true});+ }+});++describe('resolveThemeImports', () => {+ it('resolves the per-theme built module, CSS, and optional font CSS', () => {+ const dir = project();+ const packageDir = packageTheme(dir, {+ './themes/ocean': './dist/ocean.js',+ './themes/ocean.css': './dist/ocean.css',+ './themes/ocean.fonts.css': './dist/ocean.fonts.css',+ });+ fs.writeFileSync(+ path.join(packageDir, 'dist/ocean.js'),+ 'export const oceanTheme = {};\n',+ );+ fs.writeFileSync(path.join(packageDir, 'dist/ocean.css'), '.ocean {}\n');+ fs.writeFileSync(+ path.join(packageDir, 'dist/ocean.fonts.css'),+ '@font-face {}\n',+ );++ expect(resolveThemeImports(discovered(), {cwd: dir})).toMatchObject({+ owner: '@acme/themes',+ module: '@acme/themes/themes/ocean',+ stylesheet: '@acme/themes/themes/ocean.css',+ fontStylesheet: '@acme/themes/themes/ocean.fonts.css',+ source: 'package',+ });+ });++ it('uses the single-theme shorthand only when the owner has one theme', () => {+ const dir = project();+ const packageDir = packageTheme(dir, {+ './built': {import: './dist/built.mjs'},+ './theme.css': {default: './dist/theme.css'},+ });+ fs.writeFileSync(+ path.join(packageDir, 'dist/built.mjs'),+ 'export const oceanTheme = {};\n',+ );+ fs.writeFileSync(path.join(packageDir, 'dist/theme.css'), '.ocean {}\n');++ expect(+ resolveThemeImports(discovered(), {cwd: dir, ownerThemeCount: 1}),+ ).toMatchObject({+ module: '@acme/themes/built',+ stylesheet: '@acme/themes/theme.css',+ });+ expect(() =>+ resolveThemeImports(discovered(), {cwd: dir, ownerThemeCount: 2}),+ ).toThrow(/no resolvable built module and stylesheet/i);+ });++ it('fails when the built module does not export the descriptor stem', () => {+ const dir = project();+ const packageDir = packageTheme(dir, {+ './themes/ocean': './dist/ocean.js',+ './themes/ocean.css': './dist/ocean.css',+ });+ fs.writeFileSync(+ path.join(packageDir, 'dist/ocean.js'),+ 'export const wrongTheme = {};\n',+ );+ fs.writeFileSync(path.join(packageDir, 'dist/ocean.css'), '.ocean {}\n');++ expect(() => resolveThemeImports(discovered(), {cwd: dir})).toThrow(+ /does not export "oceanTheme"/i,+ );+ });++ it('fails rather than ignoring a declared font export with no file', () => {+ const dir = project();+ const packageDir = packageTheme(dir, {+ './themes/ocean': './dist/ocean.js',+ './themes/ocean.css': './dist/ocean.css',+ './themes/ocean.fonts.css': './dist/missing.css',+ });+ fs.writeFileSync(+ path.join(packageDir, 'dist/ocean.js'),+ 'export const oceanTheme = {};\n',+ );+ fs.writeFileSync(path.join(packageDir, 'dist/ocean.css'), '.ocean {}\n');++ expect(() => resolveThemeImports(discovered(), {cwd: dir})).toThrow(+ /font stylesheet does not resolve/i,+ );+ });++ it('requires local build outputs and names the build command', () => {+ const dir = project();+ const sourceDir = path.join(dir, 'src', 'themes', 'ocean');+ fs.mkdirSync(sourceDir, {recursive: true});+ const theme = discovered({+ package: './src/themes',+ sourceDir,+ docPath: path.join(sourceDir, 'oceanTheme.doc.mjs'),+ source: /** @type {const} */ ('local'),+ });++ expect(() => resolveThemeImports(theme, {cwd: dir})).toThrow(+ /astryx theme build src\/themes\/ocean\/oceanTheme\.ts/i,+ );+ fs.writeFileSync(+ path.join(sourceDir, 'ocean.js'),+ 'export const oceanTheme = {};\n',+ );+ fs.writeFileSync(path.join(sourceDir, 'ocean.css'), '.ocean {}\n');+ expect(resolveThemeImports(theme, {cwd: dir})).toMatchObject({+ source: 'local',+ owner: './src/themes',+ });+ });++ it('uses ThemeImportError and gives the install command for an uninstalled package', () => {+ const dir = project();+ expect(() => resolveThemeImports(discovered(), {cwd: dir})).toThrow(+ expect.objectContaining({+ name: 'Error',+ message: expect.stringContaining('npm install @acme/themes'),+ }),+ );+ });+});diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex aec8084766..2f6354e78d 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -53,13 +53,17 @@ const RUNNERS = {sites: ['import(node:child_process)', 'worker_threads.Worker'],},'api/integration/pack-check.mjs': {- runs: '`npm pack`, `tar`, and a Node script that resolves the packed specifiers, to check a package as published, and the package\'s doc modules, to see which need a newer CLI',+ runs: "`npm pack`, `tar`, and a Node script that resolves the packed specifiers, to check a package as published, and the package's doc modules, to see which need a newer CLI",sites: ['child_process.spawnSync ×3', 'loadTopicModule'],},'api/swizzle/_github.mjs': {runs: '`gh auth status`, to check the GitHub CLI is signed in',sites: ['child_process.execFileSync'],},+ 'api/theme/_adapter.mjs': {+ runs: 'recorded built theme modules through the shared app-theme loader',+ sites: ['importThemeArtifact'],+ },'api/theme/build/build.mjs': {runs: "theme source modules, through jiti; eval for legacy theme object literals; the project's installed Core",sites: [@@ -104,17 +108,23 @@ const RUNNERS = {'child_process.spawn','import ../../../api/theme/themeAdd.doc.mjs','import ../../../api/theme/themeBuild.doc.mjs',+ 'import ../../../api/theme/themeEject.doc.mjs','import ../../../api/theme/themeListAvailable.doc.mjs','import ../../../api/theme/themePaletteGenerate.doc.mjs',+ 'import ../../../api/theme/themeRemove.doc.mjs','import ../../../api/theme/themeTargets.doc.mjs','import ../../../api/theme/themeTemplate.doc.mjs',+ 'import ../../../api/theme/themeUse.doc.mjs','import ./theme-add.doc.mjs','import ./theme-build.doc.mjs',+ 'import ./theme-eject.doc.mjs','import ./theme-list.doc.mjs','import ./theme-palette-generate.doc.mjs','import ./theme-palette.doc.mjs',+ 'import ./theme-remove.doc.mjs','import ./theme-targets.doc.mjs','import ./theme-template.doc.mjs',+ 'import ./theme-use.doc.mjs','import ./theme.doc.mjs',],},@@ -241,8 +251,8 @@ const RUNNERS = {sites: ['import ../commands/manifest.doc.mjs'],},'clients/cli/lib/resolve-theme.mjs': {- runs: 'the configured theme (ASTRYX_THEME or package.json), by path or package name',- sites: ['require(<computed>) ×2'],+ runs: 'the generated record default theme, or the released package.json astryx.theme value when no record exists',+ sites: ['require(<computed>)'],},'foundation/config/project.mjs': {runs: 'astryx.config, through the config parser',@@ -276,8 +286,8 @@ const RUNNERS = {'foundation/fs/module-loader.mjs': {runs: 'user modules (config, manifests, handlers, codemods): natively, through jiti, or by require for a fresh CommonJS read',sites: [- '.import() ×2',- 'createJiti ×2',+ '.import() ×3',+ 'createJiti ×3','import(<computed>)','require(<computed>)','require.cache',diff --git a/packages/cli/foundation/doc-compiler/inputs.mjs b/packages/cli/foundation/doc-compiler/inputs.mjsindex f41d7beb2e..48f3ac2125 100644--- a/packages/cli/foundation/doc-compiler/inputs.mjs+++ b/packages/cli/foundation/doc-compiler/inputs.mjs@@ -22,6 +22,7 @@ import {findComponentReadme,} from '../discovery/component-discovery.mjs';import {discoverHooks, findHookDoc} from '../discovery/hook-discovery.mjs';+import {themeImportPackage} from '../discovery/theme-discovery.mjs';import {CLI_ROOT, findCoreDir} from '../fs/paths.mjs';import {packageSource} from './source.mjs';import {treeDocFiles} from './tree.mjs';@@ -110,7 +111,7 @@ export async function collectDocInputs(project) {}for (const theme of await project.themes()) {- list.add('themes', theme.slug, theme.package, theme.docPath);+ list.add('themes', theme.slug, themeImportPackage(theme), theme.docPath);}for (const topic of (await project.docs()).entries()) {diff --git a/packages/cli/foundation/fs/module-loader.mjs b/packages/cli/foundation/fs/module-loader.mjsindex e0e045a1cc..afe069d8c4 100644--- a/packages/cli/foundation/fs/module-loader.mjs+++ b/packages/cli/foundation/fs/module-loader.mjs@@ -6,8 +6,9 @@* Both config loading and integration loading need to (a) import a* user-authored module (`.ts` via jiti, `.mjs`/`.js` via native dynamic* import) and (b) find conventional files by basename in a fixed- * load-precedence order. These helpers centralize that so the two callers stay- * in lockstep. A module's stdout writes go to stderr while it loads, so+ * load-precedence order. Generated theme artifacts also use a dedicated jiti+ * path that resolves extensionless JSX/TSX registry imports. These helpers+ * centralize that behavior so callers stay in lockstep. A module's stdout writes go to stderr while it loads, so* project code that prints cannot corrupt a `--json` envelope.** `loadModuleWithParser` builds on these primitives to provide the single@@ -113,6 +114,74 @@ export async function importUserModule(file, {fresh = false} = {}) {return await withStdoutOnStderr(() => importModule(file, fresh));}+const THEME_ARTIFACT_EXTENSIONS = [+ '.js',+ '.jsx',+ '.ts',+ '.tsx',+ '.mjs',+ '.cjs',+ '.mts',+ '.cts',+];++class ThemeArtifactNotFoundError extends Error {+ code = 'ERR_THEME_ARTIFACT_NOT_FOUND';++ /** @param {string} specifier @param {unknown} [cause] */+ constructor(specifier, cause) {+ super(`Theme artifact "${specifier}" does not resolve.`, {cause});+ this.name = 'ThemeArtifactNotFoundError';+ }+}++/** @param {unknown} error */+function isMissingPackageExport(error) {+ if (error == null || typeof error !== 'object' || !('code' in error)) {+ return false;+ }+ return (+ typeof error.code === 'string' &&+ [+ 'ERR_MODULE_NOT_FOUND',+ 'ERR_PACKAGE_PATH_NOT_EXPORTED',+ 'MODULE_NOT_FOUND',+ ].includes(error.code)+ );+}++/**+ * Load a generated theme artifact and its extensionless JS/JSX/TS/TSX graph.+ * Package specifiers resolve from the consumer project, while relative paths+ * resolve from that same project root.+ * @param {string} specifier+ * @param {string} cwd+ * @returns {Promise<Record<string, unknown>>}+ */+export async function importThemeArtifact(specifier, cwd) {+ const loader = createJiti(path.join(cwd, 'package.json'), {+ moduleCache: false,+ jsx: true,+ interopDefault: true,+ extensions: THEME_ARTIFACT_EXTENSIONS,+ });+ let target;+ if (specifier.startsWith('.') || path.isAbsolute(specifier)) {+ target = path.resolve(cwd, specifier);+ } else {+ try {+ target = loader.resolve(specifier);+ } catch (error) {+ if (!isMissingPackageExport(error)) throw error;+ throw new ThemeArtifactNotFoundError(specifier, error);+ }+ }+ if (!fs.existsSync(target)) {+ throw new ThemeArtifactNotFoundError(specifier);+ }+ return await withStdoutOnStderr(() => loader.import(target));+}+/*** @param {string} file absolute path* @param {boolean} freshdiff --git a/packages/cli/foundation/integrations/contribution-inventory.mjs b/packages/cli/foundation/integrations/contribution-inventory.mjsindex 79d08ec4f3..118fad4725 100644--- a/packages/cli/foundation/integrations/contribution-inventory.mjs+++ b/packages/cli/foundation/integrations/contribution-inventory.mjs@@ -71,9 +71,9 @@ function enumerateThemeFiles(root, pkgDir) {if (!root || !fs.existsSync(root) || !fs.statSync(root).isDirectory()) {return [];}- // Exactly what `theme add` copies: each theme folder's files, including- // tests and fixtures, but no dot entry or file npm never publishes. Files- // beside the theme folders belong to no theme.+ // Exactly what `theme eject` copies and what the package ships as source:+ // each theme folder's files, including tests and fixtures, but no dot entry+ // or file npm never publishes. Files beside the theme folders belong to no theme./** @type {string[]} */const files = [];for (const entry of fs.readdirSync(root, {withFileTypes: true})) {diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex a5813ba9e6..bd1e797d4d 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -224,7 +224,7 @@ export const doc = {{value: 'theme.build',description:- 'A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load).',+ 'A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load).',},{value: 'theme.build.check',@@ -239,12 +239,22 @@ export const doc = {{value: 'theme.list',description:- 'Every bundled or installed integration theme as a ThemeListEntry[]: each with slug, displayName, description, maintained flag, and owner package.',+ 'Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries.',},{value: 'theme.add',description:- 'A scaffold receipt: resolved slug, displayName, maintained flag, owner package, outputDir (relative to cwd), the theme entry file, its exportName, and the files written.',+ 'The released source-copy receipt: slug, displayName, maintained flag, owner package, outputDir, source entry, exportName, and files. Its additive meta.deprecations entry names DEP-0005 and the source-fork/import replacements.',+ },+ {+ value: 'theme.app',+ description:+ 'The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change.',+ },+ {+ value: 'theme.eject',+ description:+ 'A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false.',},{value: 'theme.template',diff --git a/packages/cli/foundation/response/response.doc.mjs b/packages/cli/foundation/response/response.doc.mjsindex b5321ada66..6a6e9c0c8e 100644--- a/packages/cli/foundation/response/response.doc.mjs+++ b/packages/cli/foundation/response/response.doc.mjs@@ -65,7 +65,7 @@ export const doc = {name: 'meta',type: 'Record<string, unknown>',description:- 'Optional sidecar, emitted as a sibling of data (never merged in).',+ 'Optional sidecar, emitted as a sibling of data (never merged in). A `deprecations` field is an array of `{id, replacements}` entries; each stable lifecycle id names the replacement commands without changing the command data.',},],},diff --git a/packages/cli/foundation/text/copyright-header.mjs b/packages/cli/foundation/text/copyright-header.mjsindex a22aa872a8..0c4127002e 100644--- a/packages/cli/foundation/text/copyright-header.mjs+++ b/packages/cli/foundation/text/copyright-header.mjs@@ -5,7 +5,7 @@* else's project.** Every file in this repo carries the Meta copyright header, and several- * commands copy repo files out verbatim — `theme add` (bundled theme sources),+ * commands copy repo files out verbatim — `theme eject` (bundled theme sources),* `init --features theme` (the annotated theme template), `template --cdn` (the* CDN starter page). A consumer's own source tree should not inherit our* boilerplate, and their lint may well reject it.diff --git a/packages/cli/foundation/text/copyright-header.test.mjs b/packages/cli/foundation/text/copyright-header.test.mjsindex 434afbcb2f..a39dd9c929 100644--- a/packages/cli/foundation/text/copyright-header.test.mjs+++ b/packages/cli/foundation/text/copyright-header.test.mjs@@ -3,7 +3,7 @@/*** @file Unit tests for the shared copyright-header stripper.*- * Two commands copy repo files into a consumer's project (`theme add`,+ * Two commands copy repo files into a consumer's project (`theme eject`,* `init --features theme`); this is what keeps our boilerplate out of their* tree. The BOM/shebang cases are the ones worth pinning — a naive strip* corrupts the file rather than merely leaving a stray comment.diff --git a/packages/cli/test/__golden__/search.json b/packages/cli/test/__golden__/search.jsonindex 4dda24f4ce..674f246bdd 100644--- a/packages/cli/test/__golden__/search.json+++ b/packages/cli/test/__golden__/search.json@@ -45,7 +45,7 @@"reason": "description mentions \"zorblax\"","description": "A zorblax blue.","displayName": "Ocean",- "command": "astryx theme add ocean"+ "command": "astryx theme add --import ocean"}]}diff --git a/packages/cli/test/__golden__/theme-list.json b/packages/cli/test/__golden__/theme-list.jsonindex 3f151e11a5..81dd19e186 100644--- a/packages/cli/test/__golden__/theme-list.json+++ b/packages/cli/test/__golden__/theme-list.json@@ -7,7 +7,10 @@"displayName": "Ocean","description": "A zorblax blue.","maintained": true,- "package": "@acme/kit"+ "package": "@acme/kit",+ "added": false,+ "default": false,+ "source": "package"}]}diff --git a/packages/cli/test/doc-routes.ids.json b/packages/cli/test/doc-routes.ids.jsonindex 9d2b0fed48..20b7879769 100644--- a/packages/cli/test/doc-routes.ids.json+++ b/packages/cli/test/doc-routes.ids.json@@ -969,15 +969,13 @@"VStackBasic","VStackShowcase"],- "@astryxdesign/cli/theme": [- "butter",- "chocolate",- "gothic",- "matcha",- "neutral",- "stone",- "y2k"- ],+ "@astryxdesign/theme-butter/theme": ["butter"],+ "@astryxdesign/theme-chocolate/theme": ["chocolate"],+ "@astryxdesign/theme-gothic/theme": ["gothic"],+ "@astryxdesign/theme-matcha/theme": ["matcha"],+ "@astryxdesign/theme-neutral/theme": ["neutral"],+ "@astryxdesign/theme-stone/theme": ["stone"],+ "@astryxdesign/theme-y2k/theme": ["y2k"],"@astryxdesign/cli/command": ["blog","build",@@ -1008,11 +1006,14 @@"theme","theme add","theme build",+ "theme eject","theme list","theme palette","theme palette generate",+ "theme remove","theme targets","theme template",+ "theme use","upgrade"],"@astryxdesign/cli/function": [@@ -1050,11 +1051,14 @@"template","themeAdd","themeBuild",+ "themeEject","themeList","themeListAvailable","themePaletteGenerate",+ "themeRemove","themeTargets","themeTemplate",+ "themeUse","upgrade","validateIntegration"],diff --git a/packages/cli/test/doc-routes.json b/packages/cli/test/doc-routes.jsonindex 74ba25d8ec..2f6278f5ba 100644--- a/packages/cli/test/doc-routes.json+++ b/packages/cli/test/doc-routes.json@@ -2736,9 +2736,9 @@},{"kind": "section",- "id": "getting-started#add-the-theme-css",- "oldCliRoute": "astryx docs getting-started add-the-theme-css",- "oldDocsiteUrl": "/docs/getting-started#add-the-theme-css",+ "id": "getting-started#add-base-css-and-a-theme",+ "oldCliRoute": "astryx docs getting-started add-base-css-and-a-theme",+ "oldDocsiteUrl": "/docs/getting-started#add-base-css-and-a-theme","placement": "keep-flat","aliasNeeded": false,"rationale": "Stays a section of getting-started under the same key.",@@ -3794,6 +3794,16 @@"rationale": "Stays a section of theme under the same key.","status": "proposed"},+ {+ "kind": "section",+ "id": "theme#migrating-earlier-theme-copies",+ "oldCliRoute": "astryx docs theme migrating-earlier-theme-copies",+ "oldDocsiteUrl": "/docs/theme#migrating-earlier-theme-copies",+ "placement": "keep-flat",+ "aliasNeeded": false,+ "rationale": "Stays a section of theme under the same key.",+ "status": "proposed"+ },{"kind": "section","id": "theme#theme-props",@@ -4426,25 +4436,103 @@},{"kind": "theme",- "id": "@astryxdesign/cli/theme",- "provider": "@astryxdesign/cli",- "count": 7,+ "id": "@astryxdesign/theme-butter/theme",+ "provider": "@astryxdesign/theme-butter",+ "count": 1,+ "oldCliRoute": "astryx theme add <id>",+ "oldDocsiteUrl": "/themes?theme=<id>",+ "placement": "generated:@astryxdesign/theme-butter/theme",+ "aliasNeeded": false,+ "evidence": "The theme descriptor authors no docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. Discovery reports the installable theme package as the provider; `astryx theme list` reads every descriptor, and `theme add <id>` takes the slug.",+ "status": "proposed"+ },+ {+ "kind": "theme",+ "id": "@astryxdesign/theme-chocolate/theme",+ "provider": "@astryxdesign/theme-chocolate",+ "count": 1,"oldCliRoute": "astryx theme add <id>","oldDocsiteUrl": "/themes?theme=<id>","docsiteExceptions": {"chocolate": "Not a docsite dependency: /themes?theme=chocolate shows Neutral without a message."},- "placement": "generated:@astryxdesign/cli/theme",+ "placement": "generated:@astryxdesign/theme-chocolate/theme",+ "aliasNeeded": false,+ "evidence": "The theme descriptor authors no docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. Discovery reports the installable theme package as the provider; `astryx theme list` reads every descriptor, and `theme add <id>` takes the slug.",+ "status": "proposed"+ },+ {+ "kind": "theme",+ "id": "@astryxdesign/theme-gothic/theme",+ "provider": "@astryxdesign/theme-gothic",+ "count": 1,+ "oldCliRoute": "astryx theme add <id>",+ "oldDocsiteUrl": "/themes?theme=<id>",+ "placement": "generated:@astryxdesign/theme-gothic/theme",+ "aliasNeeded": false,+ "evidence": "The theme descriptor authors no docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. Discovery reports the installable theme package as the provider; `astryx theme list` reads every descriptor, and `theme add <id>` takes the slug.",+ "status": "proposed"+ },+ {+ "kind": "theme",+ "id": "@astryxdesign/theme-matcha/theme",+ "provider": "@astryxdesign/theme-matcha",+ "count": 1,+ "oldCliRoute": "astryx theme add <id>",+ "oldDocsiteUrl": "/themes?theme=<id>",+ "placement": "generated:@astryxdesign/theme-matcha/theme",+ "aliasNeeded": false,+ "evidence": "The theme descriptor authors no docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. Discovery reports the installable theme package as the provider; `astryx theme list` reads every descriptor, and `theme add <id>` takes the slug.",+ "status": "proposed"+ },+ {+ "kind": "theme",+ "id": "@astryxdesign/theme-neutral/theme",+ "provider": "@astryxdesign/theme-neutral",+ "count": 1,+ "oldCliRoute": "astryx theme add <id>",+ "oldDocsiteUrl": "/themes?theme=<id>",+ "placement": "generated:@astryxdesign/theme-neutral/theme",+ "aliasNeeded": false,+ "evidence": "The theme descriptor authors no docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. Discovery reports the installable theme package as the provider; `astryx theme list` reads every descriptor, and `theme add <id>` takes the slug.",+ "status": "proposed"+ },+ {+ "kind": "theme",+ "id": "@astryxdesign/theme-stone/theme",+ "provider": "@astryxdesign/theme-stone",+ "count": 1,+ "oldCliRoute": "astryx theme add <id>",+ "oldDocsiteUrl": "/themes?theme=<id>",+ "placement": "generated:@astryxdesign/theme-stone/theme",+ "aliasNeeded": false,+ "evidence": "The theme descriptor authors no docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. Discovery reports the installable theme package as the provider; `astryx theme list` reads every descriptor, and `theme add <id>` takes the slug.",+ "status": "proposed"+ },+ {+ "kind": "theme",+ "id": "@astryxdesign/theme-y2k/theme",+ "provider": "@astryxdesign/theme-y2k",+ "count": 1,+ "oldCliRoute": "astryx theme add <id>",+ "oldDocsiteUrl": "/themes?theme=<id>",+ "placement": "generated:@astryxdesign/theme-y2k/theme","aliasNeeded": false,- "evidence": "No theme descriptor authors a docs-graph placement.",- "rationale": "Unplaced typed descriptors go to their provider's generated bucket. No read-only single-theme route exists: `astryx theme list` prints every descriptor, and `theme add <id>`, which writes files, is the only command that takes the slug.",+ "evidence": "The theme descriptor authors no docs-graph placement.",+ "rationale": "Unplaced typed descriptors go to their provider's generated bucket. Discovery reports the installable theme package as the provider; `astryx theme list` reads every descriptor, and `theme add <id>` takes the slug.","status": "proposed"},{"kind": "command","id": "@astryxdesign/cli/command","provider": "@astryxdesign/cli",- "count": 35,+ "count": 38,"oldCliRoute": "astryx <id> --help","oldDocsiteUrl": null,"placement": "namespace:cli/commands",@@ -4457,7 +4545,7 @@"kind": "function","id": "@astryxdesign/cli/function","provider": "@astryxdesign/cli",- "count": 41,+ "count": 44,"oldCliRoute": null,"oldDocsiteUrl": null,"placement": "namespace:cli/api/functions",diff --git a/packages/cli/test/inv28-package-provenance.test.mjs b/packages/cli/test/inv28-package-provenance.test.mjsindex 655baf9b00..4ea96bfc6a 100644--- a/packages/cli/test/inv28-package-provenance.test.mjs+++ b/packages/cli/test/inv28-package-provenance.test.mjs@@ -28,12 +28,21 @@ const ACME = '@acme/widgets';// The API reads integrations through Project.load(). Vitest cannot import an// astryx.config.mjs from a temporary root, so the project is mocked the way// component-ownership.test.mjs mocks it, with the integration's files on disk.-// The CLI cases run in a child process and are not affected.+// The CLI cases fall through to the real Project.load; the integration cases+// install the temporary project mock in their scoped beforeEach.const projectLoadMock = vi.fn();-vi.mock('../foundation/config/project.mjs', async importOriginal => ({- ...(await importOriginal()),- Project: {load: (/** @type {unknown[]} */ ...args) => projectLoadMock(...args)},-}));+vi.mock('../foundation/config/project.mjs', async importOriginal => {+ const original = await importOriginal();+ return {+ ...original,+ Project: {+ load: (/** @type {unknown[]} */ ...args) =>+ projectLoadMock.getMockImplementation()+ ? projectLoadMock(...args)+ : original.Project.load(...args),+ },+ };+});const {component} = await import('../api/component/component.mjs');const {search} = await import('../api/search/search.mjs');diff --git a/packages/themes/butter/fonts.css b/packages/themes/butter/fonts.cssnew file mode 100644index 0000000000..5b2bb4450c--- /dev/null+++ b/packages/themes/butter/fonts.css@@ -0,0 +1,3 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&family=Outfit:wght@400;500;600;700&family=Sarina&display=swap');diff --git a/packages/themes/butter/fonts.css.d.ts b/packages/themes/butter/fonts.css.d.tsnew file mode 100644index 0000000000..e976d8c27c--- /dev/null+++ b/packages/themes/butter/fonts.css.d.ts@@ -0,0 +1,3 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {};diff --git a/packages/themes/butter/package.json b/packages/themes/butter/package.jsonindex f083ff1db9..ccb6bcdeca 100644--- a/packages/themes/butter/package.json+++ b/packages/themes/butter/package.json@@ -22,7 +22,9 @@"lucide","design-tokens"],- "sideEffects": false,+ "sideEffects": [+ "**/*.css"+ ],"main": "./dist/source.js","types": "./dist/source.d.ts","exports": {@@ -39,11 +41,17 @@"./theme.css": {"types": "./theme.css.d.ts","default": "./dist/theme.css"+ },+ "./fonts.css": {+ "types": "./fonts.css.d.ts",+ "default": "./fonts.css"}},"files": ["dist",- "src"+ "src",+ "fonts.css",+ "fonts.css.d.ts"],"scripts": {"build": "node ../../../scripts/clean-dist.mjs && astryx theme build src/butterTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json && node ../../../scripts/check-fully-specified.mjs"diff --git a/packages/themes/chocolate/fonts.css b/packages/themes/chocolate/fonts.cssnew file mode 100644index 0000000000..114034de7c--- /dev/null+++ b/packages/themes/chocolate/fonts.css@@ -0,0 +1,3 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++@import url('https://fonts.googleapis.com/css2?family=Albert+Sans:wght@400;500;600;700&family=Fraunces:opsz,[email protected],400;9..144,500;9..144,600;9..144,700&family=JetBrains+Mono:wght@400;500;600;700&display=swap');diff --git a/packages/themes/chocolate/fonts.css.d.ts b/packages/themes/chocolate/fonts.css.d.tsnew file mode 100644index 0000000000..e976d8c27c--- /dev/null+++ b/packages/themes/chocolate/fonts.css.d.ts@@ -0,0 +1,3 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {};diff --git a/packages/themes/chocolate/package.json b/packages/themes/chocolate/package.jsonindex cbfcfb142b..e5f7934ba2 100644--- a/packages/themes/chocolate/package.json+++ b/packages/themes/chocolate/package.json@@ -22,7 +22,9 @@"lucide","design-tokens"],- "sideEffects": false,+ "sideEffects": [+ "**/*.css"+ ],"main": "./dist/source.js","types": "./dist/source.d.ts","exports": {@@ -39,11 +41,17 @@"./theme.css": {"types": "./theme.css.d.ts","default": "./dist/theme.css"+ },+ "./fonts.css": {+ "types": "./fonts.css.d.ts",+ "default": "./fonts.css"}},"files": ["dist",- "src"+ "src",+ "fonts.css",+ "fonts.css.d.ts"],"scripts": {"build": "node ../../../scripts/clean-dist.mjs && astryx theme build src/chocolateTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json && node ../../../scripts/check-fully-specified.mjs"diff --git a/packages/themes/gothic/fonts.css b/packages/themes/gothic/fonts.cssnew file mode 100644index 0000000000..bce2df758d--- /dev/null+++ b/packages/themes/gothic/fonts.css@@ -0,0 +1,3 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++@import url('https://fonts.googleapis.com/css2?family=Fustat:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&family=Manufacturing+Consent&family=UnifrakturMaguntia&display=swap');diff --git a/packages/themes/gothic/fonts.css.d.ts b/packages/themes/gothic/fonts.css.d.tsnew file mode 100644index 0000000000..e976d8c27c--- /dev/null+++ b/packages/themes/gothic/fonts.css.d.ts@@ -0,0 +1,3 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {};diff --git a/packages/themes/gothic/package.json b/packages/themes/gothic/package.jsonindex 27fe76fdf3..0db0709153 100644--- a/packages/themes/gothic/package.json+++ b/packages/themes/gothic/package.json@@ -22,7 +22,9 @@"lucide","design-tokens"],- "sideEffects": false,+ "sideEffects": [+ "**/*.css"+ ],"main": "./dist/source.js","types": "./dist/source.d.ts","exports": {@@ -39,11 +41,17 @@"./theme.css": {"types": "./theme.css.d.ts","default": "./dist/theme.css"+ },+ "./fonts.css": {+ "types": "./fonts.css.d.ts",+ "default": "./fonts.css"}},"files": ["dist",- "src"+ "src",+ "fonts.css",+ "fonts.css.d.ts"],"scripts": {"build": "node ../../../scripts/clean-dist.mjs && astryx theme build src/gothicTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json && node ../../../scripts/check-fully-specified.mjs"diff --git a/packages/themes/matcha/fonts.css b/packages/themes/matcha/fonts.cssnew file mode 100644index 0000000000..71eb35abaa--- /dev/null+++ b/packages/themes/matcha/fonts.css@@ -0,0 +1,3 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&family=Playwrite+US+Trad&display=swap');diff --git a/packages/themes/matcha/fonts.css.d.ts b/packages/themes/matcha/fonts.css.d.tsnew file mode 100644index 0000000000..e976d8c27c--- /dev/null+++ b/packages/themes/matcha/fonts.css.d.ts@@ -0,0 +1,3 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {};diff --git a/packages/themes/matcha/package.json b/packages/themes/matcha/package.jsonindex 53f3973a62..1e672a0843 100644--- a/packages/themes/matcha/package.json+++ b/packages/themes/matcha/package.json@@ -21,7 +21,9 @@"lucide","design-tokens"],- "sideEffects": false,+ "sideEffects": [+ "**/*.css"+ ],"main": "./dist/source.js","types": "./dist/source.d.ts","exports": {@@ -38,11 +40,17 @@"./theme.css": {"types": "./theme.css.d.ts","default": "./dist/theme.css"+ },+ "./fonts.css": {+ "types": "./fonts.css.d.ts",+ "default": "./fonts.css"}},"files": ["dist",- "src"+ "src",+ "fonts.css",+ "fonts.css.d.ts"],"scripts": {"build": "node ../../../scripts/clean-dist.mjs && astryx theme build src/matchaTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json && node ../../../scripts/check-fully-specified.mjs"diff --git a/packages/themes/neutral/fonts.css b/packages/themes/neutral/fonts.cssnew file mode 100644index 0000000000..e6e9dadeab--- /dev/null+++ b/packages/themes/neutral/fonts.css@@ -0,0 +1,3 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++@import url('https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&display=swap');diff --git a/packages/themes/neutral/fonts.css.d.ts b/packages/themes/neutral/fonts.css.d.tsnew file mode 100644index 0000000000..e976d8c27c--- /dev/null+++ b/packages/themes/neutral/fonts.css.d.ts@@ -0,0 +1,3 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {};diff --git a/packages/themes/neutral/package.json b/packages/themes/neutral/package.jsonindex 2cf64089dd..9270846f44 100644--- a/packages/themes/neutral/package.json+++ b/packages/themes/neutral/package.json@@ -22,7 +22,9 @@"lucide","design-tokens"],- "sideEffects": false,+ "sideEffects": [+ "**/*.css"+ ],"main": "./dist/source.js","types": "./dist/source.d.ts","exports": {@@ -39,11 +41,17 @@"./theme.css": {"types": "./theme.css.d.ts","default": "./dist/theme.css"+ },+ "./fonts.css": {+ "types": "./fonts.css.d.ts",+ "default": "./fonts.css"}},"files": ["dist","src",+ "fonts.css",+ "fonts.css.d.ts","palette.config.json"],"scripts": {diff --git a/packages/themes/stone/fonts.css b/packages/themes/stone/fonts.cssnew file mode 100644index 0000000000..2a6f66ccf4--- /dev/null+++ b/packages/themes/stone/fonts.css@@ -0,0 +1,3 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++@import url('https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&family=Montserrat:wght@400;500;600;700&display=swap');diff --git a/packages/themes/stone/fonts.css.d.ts b/packages/themes/stone/fonts.css.d.tsnew file mode 100644index 0000000000..e976d8c27c--- /dev/null+++ b/packages/themes/stone/fonts.css.d.ts@@ -0,0 +1,3 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {};diff --git a/packages/themes/stone/package.json b/packages/themes/stone/package.jsonindex 9968225e2d..15334d3cfc 100644--- a/packages/themes/stone/package.json+++ b/packages/themes/stone/package.json@@ -22,7 +22,9 @@"lucide","design-tokens"],- "sideEffects": false,+ "sideEffects": [+ "**/*.css"+ ],"main": "./dist/source.js","types": "./dist/source.d.ts","exports": {@@ -39,11 +41,17 @@"./theme.css": {"types": "./theme.css.d.ts","default": "./dist/theme.css"+ },+ "./fonts.css": {+ "types": "./fonts.css.d.ts",+ "default": "./fonts.css"}},"files": ["dist",- "src"+ "src",+ "fonts.css",+ "fonts.css.d.ts"],"scripts": {"build": "node ../../../scripts/clean-dist.mjs && astryx theme build src/stoneTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json && node ../../../scripts/check-fully-specified.mjs"diff --git a/packages/themes/y2k/fonts.css b/packages/themes/y2k/fonts.cssnew file mode 100644index 0000000000..4d86c7eaef--- /dev/null+++ b/packages/themes/y2k/fonts.css@@ -0,0 +1,3 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++@import url('https://fonts.googleapis.com/css2?family=Crimson+Text:wght@400;600;700&family=JetBrains+Mono:wght@400;500;600;700&family=Poppins:wght@400;500;600;700&display=swap');diff --git a/packages/themes/y2k/fonts.css.d.ts b/packages/themes/y2k/fonts.css.d.tsnew file mode 100644index 0000000000..e976d8c27c--- /dev/null+++ b/packages/themes/y2k/fonts.css.d.ts@@ -0,0 +1,3 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {};diff --git a/packages/themes/y2k/package.json b/packages/themes/y2k/package.jsonindex cf4cd23777..dab2acf8ce 100644--- a/packages/themes/y2k/package.json+++ b/packages/themes/y2k/package.json@@ -22,7 +22,9 @@"lucide","design-tokens"],- "sideEffects": false,+ "sideEffects": [+ "**/*.css"+ ],"main": "./dist/source.js","types": "./dist/source.d.ts","exports": {@@ -39,11 +41,17 @@"./theme.css": {"types": "./theme.css.d.ts","default": "./dist/theme.css"+ },+ "./fonts.css": {+ "types": "./fonts.css.d.ts",+ "default": "./fonts.css"}},"files": ["dist",- "src"+ "src",+ "fonts.css",+ "fonts.css.d.ts"],"scripts": {"build": "node ../../../scripts/clean-dist.mjs && astryx theme build src/y2kTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json && node ../../../scripts/check-fully-specified.mjs"diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjsindex 13ee856976..57f1895b6a 100644--- a/scripts/check-cli-structure.mjs+++ b/scripts/check-cli-structure.mjs@@ -472,6 +472,44 @@ const inv21Count = checkEnvironmentImports('INV21', apiScopedFiles, API, INV21_KNOWN_GAPS,);+// --- INV22 recorded-theme client seam ---+//+// Component metadata keeps the released package-field reader in its client+// helper, but all generated-record discovery and loading belongs to the theme+// subject. Pin that narrow seam so another adapter or foundation import cannot+// bypass the API boundary unnoticed.+const RESOLVE_THEME_HELPER = path.join(+ CLI,+ 'clients/cli/lib/resolve-theme.mjs',+);+const RESOLVE_THEME_ALLOWED_IMPORTS = new Set([+ 'node:fs',+ 'node:module',+ 'node:path',+ '../../../api/theme/theme.mjs',+]);+let clientHelperBoundaryCount = 0;+if (!fs.existsSync(RESOLVE_THEME_HELPER)) {+ errors.push(+ 'INV22 client helper: clients/cli/lib/resolve-theme.mjs is missing — update this boundary check if it moved',+ );+} else {+ clientHelperBoundaryCount++;+ const imports = importSources(RESOLVE_THEME_HELPER);+ for (const spec of imports) {+ if (!RESOLVE_THEME_ALLOWED_IMPORTS.has(spec)) {+ errors.push(+ `INV22 client helper: resolve-theme.mjs imports ${spec} — generated-record access must go through api/theme/theme.mjs`,+ );+ }+ }+ if (!imports.includes('../../../api/theme/theme.mjs')) {+ errors.push(+ 'INV22 client helper: resolve-theme.mjs no longer imports api/theme/theme.mjs — keep generated-record access behind the theme subject entry',+ );+ }+}+// ── 3b. INV23: text-layout patterns ─────────────────────────────────//// Handlers must use the formatter kit (section, text, list, record,@@ -534,6 +572,11 @@ for (const filePath of handlerFiles) {// programmatic surface.const apiIndexSrc = fs.readFileSync(path.join(API, 'index.mjs'), 'utf8');+if (/\bresolveRecordedTheme\b/u.test(apiIndexSrc)) {+ errors.push(+ 'theme boundary: resolveRecordedTheme is internal and must not be exported from api/index.mjs',+ );+}/** Extract named function exports from api/index.mjs (skip type re-exports). */const apiExports = new Set();@@ -636,7 +679,7 @@ console.log([`✅ CLI structure is intact:`,` ${doctypeCount} doc-type(s), ${apiCount} api folder(s),`,- ` ${inv22Count} handler(s) checked for INV22, ${inv21Count} api module(s) for INV21,`,+ ` ${inv22Count} handler(s) checked for INV22, ${clientHelperBoundaryCount} client helper boundary, ${inv21Count} api module(s) for INV21,`,` ${inv23Count} handler(s) checked for INV23,`,` ${fr1Count} CommandDoc fn(s) checked for FR1, ${fr2Count} api export(s) for FR2.`,].join('\n'),diff --git a/scripts/check-cli-theme-bundle.test.mjs b/scripts/check-cli-theme-bundle.test.mjsindex 91f32353c1..d526556e34 100644--- a/scripts/check-cli-theme-bundle.test.mjs+++ b/scripts/check-cli-theme-bundle.test.mjs@@ -248,15 +248,13 @@ describe('CLI theme bundle is in sync with source', () => {});}- it('theme add copies each bundled theme in bundle order, without its descriptor', () => {+ it('theme eject copies each bundled theme in bundle order, with its descriptor', () => {const discovered = new Map(discoverBundledThemes().map(theme => [theme.slug, theme.files]),);for (const slug of slugs) {expect(discovered.get(slug), slug).toEqual(- expectedFiles(slug)- .map(file => file.output)- .filter(file => !file.endsWith('.doc.mjs')),+ expectedFiles(slug).map(file => file.output),);}});diff --git a/scripts/generate-cli-themes.mjs b/scripts/generate-cli-themes.mjsindex dbd40d257d..c47c8df55c 100644--- a/scripts/generate-cli-themes.mjs+++ b/scripts/generate-cli-themes.mjs@@ -4,7 +4,7 @@/*** @file Bundles each public theme's source, strongly typed same-stem descriptor,* optional icons, and palette-authoring artifacts into- * `packages/cli/assets/templates/themes/` so `astryx theme add` can scaffold a+ * `packages/cli/assets/templates/themes/` so `astryx theme eject` can scaffold a* complete theme without the package installed. There is no central catalog.* Run from the repo root and commit the generated bundle.*/@@ -118,7 +118,7 @@ function main() {}// Keep optional theme-owned authoring artifacts with the template. A- // palette-backed theme must remain reproducible after `theme add`.+ // palette-backed theme must remain reproducible after `theme eject`.const optionalFiles = [{source: path.join(sourceDir, 'icons.tsx'), output: 'icons.tsx'},{