@astryxdesign/cli 0.6.5-canary.bfb918a → 0.6.5-canary.c2a49ec

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +2 -2
  2. package/api/build/_adapter.d.mts +14 -0
  3. package/api/build/_adapter.mjs +58 -1
  4. package/api/build/build.test.mjs +74 -1
  5. package/api/build/kit/kit.mjs +39 -7
  6. package/api/build/kit/rank.d.mts +8 -0
  7. package/api/build/kit/rank.mjs +14 -0
  8. package/api/build/kit/weights.d.mts +82 -0
  9. package/api/build/kit/weights.json +1 -0
  10. package/api/build/kit/weights.mjs +305 -0
  11. package/api/build/kit/weights.test.mjs +190 -0
  12. package/api/docs/docs.d.mts +6 -0
  13. package/api/docs/docs.depth.test.mjs +132 -0
  14. package/api/docs/docs.doc.mjs +31 -2
  15. package/api/docs/docs.mjs +44 -1
  16. package/api/docs/docs.type.d.mts +38 -1
  17. package/api/docs/docs.type.mjs +18 -1
  18. package/api/docs/node/node.d.mts +28 -3
  19. package/api/docs/node/node.mjs +146 -23
  20. package/api/gap-report/gap-report.d.mts +3 -1
  21. package/api/gap-report/gap-report.mjs +12 -2
  22. package/api/gap-report/gap-report.test.mjs +106 -0
  23. package/api/hook/list/list.d.mts +1 -1
  24. package/api/integration/add-theme.mjs +93 -3
  25. package/api/integration/add-theme.test.mjs +100 -0
  26. package/api/integration/integrationAddTheme.doc.mjs +1 -1
  27. package/api/search/search.d.mts +12 -5
  28. package/api/search/search.doc.mjs +4 -4
  29. package/api/search/search.mjs +123 -53
  30. package/api/search/search.test.mjs +123 -8
  31. package/api/search/search.type.d.mts +5 -5
  32. package/api/search/search.type.mjs +5 -5
  33. package/api/theme/build/build.icon-lineage.test.mjs +117 -0
  34. package/api/theme/build/build.icon-preservation.test.mjs +639 -0
  35. package/api/theme/build/build.mjs +146 -69
  36. package/api/theme/build/build.test.mjs +190 -1
  37. package/api/theme/build/icon-imports.d.mts +47 -0
  38. package/api/theme/build/icon-imports.mjs +691 -0
  39. package/api/theme/themeBuild.doc.d.mts +4 -1
  40. package/api/theme/themeBuild.doc.mjs +14 -3
  41. package/assets/docs/theme.doc.mjs +2 -1
  42. package/assets/docs/tokens.doc.mjs +3 -3
  43. package/assets/docs/tree/add-a-theme.doc.mjs +4 -0
  44. package/assets/docs/tree/debug-and-gap-reports.doc.mjs +1 -1
  45. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupShowcase.doc.mjs +15 -0
  46. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupShowcase.tsx +38 -0
  47. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupWithSelectable.doc.mjs +20 -0
  48. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupWithSelectable.tsx +48 -0
  49. package/clients/cli/commands/build-theme.mjs +8 -2
  50. package/clients/cli/commands/discover.mjs +29 -1
  51. package/clients/cli/commands/discover.no-source.test.mjs +75 -0
  52. package/clients/cli/commands/docs.depth.test.mjs +219 -0
  53. package/clients/cli/commands/docs.doc.mjs +15 -2
  54. package/clients/cli/commands/docs.mjs +222 -5
  55. package/clients/cli/commands/gap-report.mjs +12 -0
  56. package/clients/cli/commands/gap-report.test.mjs +63 -0
  57. package/clients/cli/commands/integration-add.doc.mjs +1 -1
  58. package/clients/cli/commands/search.doc.mjs +5 -4
  59. package/clients/cli/commands/search.mjs +30 -6
  60. package/clients/cli/commands/search.test.mjs +60 -16
  61. package/clients/cli/commands/theme-list.behavior.test.mjs +41 -0
  62. package/foundation/agent-docs/agent-docs.mjs +2 -1
  63. package/foundation/agent-docs/agent-docs.test.mjs +8 -0
  64. package/foundation/discovery/theme-discovery.d.mts +6 -0
  65. package/foundation/discovery/theme-discovery.mjs +9 -0
  66. package/foundation/doc-compiler/doc-loads.test.mjs +1 -1
  67. package/package.json +9 -9
@@ -2,6 +2,9 @@
2
2
 
3
3
  /**
4
4
  * @file theme build API — compile standalone themes or one selected family.
5
+ * @input JS/TS theme modules, build/check options, and the installed Core.
6
+ * @output Generated artifacts preserving imported and inherited icon registries.
7
+ * @position CLI theme compiler; standalone icon provenance is icon-imports.mjs.
5
8
  *
6
9
  * `themeBuild` and `themeBuildFamily` share the same loader, compiler,
7
10
  * serializers, check, and writer. They read defineTheme() sources and, via
@@ -12,11 +15,14 @@
12
15
  * - A .d.ts (plus an optional .variants.d.ts for custom prop values)
13
16
  *
14
17
  * It performs the writes and returns a `theme.build` receipt — its `warnings`
15
- * carry override problems, every declaration core's generator dropped because
16
- * its value could not stay one CSS declaration, and any fonts the theme names
17
- * but does not load (font-warning.mjs) — or `null` when the theme produced no
18
- * CSS (nothing to build). Errors throw AstryxError (with
19
- * a stable code). Human progress is emitted through the shared `logger`
18
+ * carry override problems and every declaration core's generator dropped
19
+ * because its value could not stay one CSS declaration; `notices` carry fonts
20
+ * the theme names but does not load (font-warning.mjs) — or `null` when the
21
+ * theme produced no CSS (nothing to build). Standalone icon imports come from
22
+ * the selected theme's parsed bindings and inheritance, never from comment or
23
+ * string contents. A registry that cannot be preserved fails before output
24
+ * generation, including in check mode. Errors throw AstryxError (with a stable
25
+ * code). Human progress is emitted through the shared `logger`
20
26
  * (silent by default), so the CLI keeps its exact output while a programmatic
21
27
  * caller stays quiet.
22
28
  *
@@ -67,6 +73,7 @@ import {
67
73
  import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';
68
74
  import {interceptCore} from './core-interception.mjs';
69
75
  import {generateFamilyCSS, resolveThemeFamily} from './family.mjs';
76
+ import {resolveIconImports} from './icon-imports.mjs';
70
77
 
71
78
  // Import shared theme processing from core. `astryx theme build` MUST produce the
72
79
  // exact same CSS as the `<Theme>` runtime, so it has exactly one generation
@@ -1506,6 +1513,19 @@ async function validateRegistryGraphs(/** @type {Array<{specifier: string, expor
1506
1513
  if (!(root.exportName in exports)) throw registryGraphError(`Family registry ${root.file} does not export "${root.exportName}".`);
1507
1514
  }
1508
1515
  }
1516
+ /**
1517
+ * Resolve inherited source with exactly the loader's extension precedence.
1518
+ * This reads module locations only; icon discovery never executes a second load.
1519
+ * @param {string} specifier
1520
+ * @param {string} fromFile
1521
+ * @returns {string}
1522
+ */
1523
+ function resolveThemeModule(specifier, fromFile) {
1524
+ return createJiti(fromFile, {extensions: THEME_MODULE_EXTENSIONS}).resolve(
1525
+ specifier,
1526
+ );
1527
+ }
1528
+
1509
1529
  /**
1510
1530
  * Errors that mean "the synchronous loader cannot evaluate this module", as
1511
1531
  * opposed to "this module is broken". Only the former may fall back to the
@@ -1553,7 +1573,7 @@ function isSyncLoaderLimitation(error) {
1553
1573
  *
1554
1574
  * @param {string} filePath
1555
1575
  * @param {import('./core-interception.mjs').CoreInterception} [interception]
1556
- * @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
1576
+ * @returns {Promise<{theme: any, exportName: string, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
1557
1577
  */
1558
1578
  // prettier-ignore
1559
1579
  async function importThemeModule(filePath, interception, /** @type {any} */ loader = undefined) {
@@ -1603,12 +1623,14 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
1603
1623
  mod = await jiti.import(filePath, {default: true});
1604
1624
  }
1605
1625
 
1606
- if (isThemeObject(mod)) return {theme: mod, degraded};
1626
+ if (isThemeObject(mod)) return {theme: mod, exportName: 'default', degraded};
1607
1627
 
1608
1628
  if (mod && typeof mod === 'object') {
1609
- if (isThemeObject(mod.default)) return {theme: mod.default, degraded};
1610
- for (const value of Object.values(mod)) {
1611
- if (isThemeObject(value)) return {theme: value, degraded};
1629
+ if (isThemeObject(mod.default)) {
1630
+ return {theme: mod.default, exportName: 'default', degraded};
1631
+ }
1632
+ for (const [exportName, value] of Object.entries(mod)) {
1633
+ if (isThemeObject(value)) return {theme: value, exportName, degraded};
1612
1634
  }
1613
1635
  }
1614
1636
 
@@ -1642,7 +1664,7 @@ function isThemeObject(value) {
1642
1664
  *
1643
1665
  * @param {string} filePath
1644
1666
  * @param {import('./core-interception.mjs').CoreInterception} [interception]
1645
- * @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
1667
+ * @returns {Promise<{theme: any, exportName?: string, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
1646
1668
  */
1647
1669
  // prettier-ignore
1648
1670
  async function extractThemeDefinition(filePath, interception, /** @type {any} */ loader = undefined) {
@@ -1667,6 +1689,8 @@ async function extractThemeDefinition(filePath, interception, /** @type {any} */
1667
1689
  /**
1668
1690
  * Fallback extraction via regex + eval.
1669
1691
  * Only works for plain object literals — can't follow imports or variables.
1692
+ * Never erase icon references: an unresolved registry must preserve the loader
1693
+ * error instead of turning an incomplete theme into a successful build.
1670
1694
  * @param {string} filePath
1671
1695
  * @returns {any}
1672
1696
  */
@@ -1688,10 +1712,6 @@ function extractThemeDefinitionLegacy(filePath) {
1688
1712
 
1689
1713
  let objStr = defineMatch[1];
1690
1714
  objStr = objStr.replace(/\s+as\s+const/g, '');
1691
- objStr = objStr.replace(
1692
- /icons:\s*[a-zA-Z_][a-zA-Z0-9_]*/g,
1693
- 'icons: undefined',
1694
- );
1695
1715
 
1696
1716
  try {
1697
1717
  return eval(`(${objStr})`);
@@ -1706,30 +1726,19 @@ function extractThemeDefinitionLegacy(filePath) {
1706
1726
  }
1707
1727
 
1708
1728
  /**
1709
- * Extract icon import info from a theme source file.
1710
- * Returns { importPath, exportName } or null if no icons.
1729
+ * Extract a family member's named registry import from its source file.
1730
+ * Returns { importPath, exportName } or null when the theme names none.
1731
+ * Standalone builds resolve icons through `resolveIconImports` instead.
1711
1732
  *
1712
1733
  * Looks for patterns like:
1713
1734
  * import { defaultIconRegistry } from './icons';
1714
1735
  * icons: defaultIconRegistry,
1715
1736
  * @param {string} filePath
1737
+ * @param {'icons' | 'indicators'} field
1716
1738
  * @returns {{exportName: string, importPath: string} | null}
1717
1739
  */
1718
- function extractRegistryInfo(filePath, field = 'icons', familyMode = false) {
1740
+ function extractRegistryInfo(filePath, field) {
1719
1741
  const content = fs.readFileSync(filePath, 'utf8');
1720
- if (!familyMode) {
1721
- const fieldMatch = content.match(
1722
- new RegExp(`${field}:\\s*([a-zA-Z_][a-zA-Z0-9_]*)`),
1723
- );
1724
- if (!fieldMatch) return null;
1725
- const varName = fieldMatch[1];
1726
- const match = content.match(
1727
- new RegExp(
1728
- `import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,
1729
- ),
1730
- );
1731
- return match ? {exportName: varName, importPath: match[1]} : null;
1732
- }
1733
1742
  const defineIndex = content.indexOf('defineTheme(');
1734
1743
  if (defineIndex < 0) return null;
1735
1744
  const themeSource = content.slice(defineIndex);
@@ -1769,17 +1778,18 @@ function extractRegistryInfo(filePath, field = 'icons', familyMode = false) {
1769
1778
  * override it had.
1770
1779
  *
1771
1780
  * The icon registry is imported rather than inlined because it holds React
1772
- * elements, which cannot be serialized. `extractIconInfo` lifts the specifier
1773
- * out of the TypeScript source, where an extensionless `./icons` is resolved by
1781
+ * elements, which cannot be serialized. `resolveIconImports` reads actual
1782
+ * imports from the selected theme's source, where extensionless `./icons` uses
1774
1783
  * the TypeScript resolver — but the artifact here is ESM JavaScript, which
1775
1784
  * requires a fully specified path. Only the caller knows what its own build
1776
1785
  * will emit and under what name, so `iconsSpecifier` lets it say. When it is
1777
- * not given, the scraped specifier is emitted unchanged.
1786
+ * not given, direct registry specifiers are preserved, and inherited relative
1787
+ * imports are rebased from the base module to the theme entry's directory.
1778
1788
  *
1779
1789
  * @param {any} themeDef
1780
- * @param {{exportName: string, importPath: string} | null} iconInfo
1781
- * @param {string} [iconsSpecifier] - Overrides the scraped icon import specifier.
1782
- * @param {{themeBinding?: string, iconBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]
1790
+ * @param {import('./icon-imports.mjs').IconImports | null} iconInfo
1791
+ * @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
1792
+ * @param {{themeBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]
1783
1793
  * @returns {string}
1784
1794
  */
1785
1795
  function generateBuiltModule(
@@ -1790,29 +1800,46 @@ function generateBuiltModule(
1790
1800
  ) {
1791
1801
  const themeBinding =
1792
1802
  moduleOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
1793
- const iconBinding = moduleOptions.iconBinding ?? iconInfo?.exportName;
1794
1803
  const artifactBaseName = moduleOptions.artifactBaseName ?? themeDef.name;
1795
1804
  const exportIcons = moduleOptions.exportIcons ?? true;
1796
- // Preserve the historical generated bytes when no override is supplied.
1797
- // User-provided specifiers need string-literal encoding so quotes and
1798
- // backslashes cannot produce invalid JavaScript.
1799
- const renderedSpecifier =
1800
- iconsSpecifier === undefined
1801
- ? `'${iconInfo?.importPath}'`
1802
- : JSON.stringify(iconsSpecifier);
1803
- const iconImport = iconInfo
1804
- ? `import { ${iconInfo.exportName}${iconBinding === iconInfo.exportName ? '' : ` as ${iconBinding}`} } from ${renderedSpecifier};\n`
1805
- : '';
1806
- const iconsExpression =
1807
- moduleOptions.iconsExpression ?? (iconInfo ? iconBinding : undefined);
1805
+ // Keep ordinary direct named imports byte-compatible, while encoding paths
1806
+ // with quotes/escapes and retaining default, namespace, and aliased bindings.
1807
+ const iconImport = (iconInfo?.imports ?? [])
1808
+ .map(({importPath, importedName, localName}) => {
1809
+ const overridden =
1810
+ iconsSpecifier !== undefined &&
1811
+ importPath === iconInfo?.iconsSpecifierImportPath &&
1812
+ localName === iconInfo?.iconsSpecifierLocalName;
1813
+ const specifier = overridden
1814
+ ? JSON.stringify(iconsSpecifier)
1815
+ : /['\\\r\n]/u.test(importPath)
1816
+ ? JSON.stringify(importPath)
1817
+ : `'${importPath}'`;
1818
+ const imported = /^[$\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(
1819
+ importedName,
1820
+ )
1821
+ ? importedName
1822
+ : JSON.stringify(importedName);
1823
+ const binding =
1824
+ importedName === 'default'
1825
+ ? localName
1826
+ : importedName === '*'
1827
+ ? `* as ${localName}`
1828
+ : `{ ${imported}${importedName === localName ? '' : ` as ${localName}`} }`;
1829
+ return `import ${binding} from ${specifier};\n`;
1830
+ })
1831
+ .join('');
1832
+ const iconDeclaration =
1833
+ iconInfo && iconInfo.expression !== iconInfo.exportName
1834
+ ? `const ${iconInfo.exportName} = ${iconInfo.expression};\n`
1835
+ : '';
1836
+ const iconsExpression = moduleOptions.iconsExpression ?? iconInfo?.exportName;
1808
1837
  const iconsField = iconsExpression ? ` icons: ${iconsExpression},` : '';
1809
1838
  const indicatorsField = moduleOptions.indicatorsExpression
1810
1839
  ? `\n indicators: ${moduleOptions.indicatorsExpression},`
1811
1840
  : '';
1812
1841
  const iconReExport =
1813
- iconInfo && exportIcons
1814
- ? `\nexport { ${iconBinding}${iconBinding === iconInfo.exportName ? '' : ` as ${iconInfo.exportName}`} };\n`
1815
- : '';
1842
+ iconInfo && exportIcons ? `\nexport { ${iconInfo.exportName} };\n` : '';
1816
1843
 
1817
1844
  // Resolve token values — tuples become light-dark() strings
1818
1845
  /** @type {Record<string, unknown>} */
@@ -1871,7 +1898,7 @@ function generateBuiltModule(
1871
1898
  serializeField('__adaptations', themeDef.__adaptations) +
1872
1899
  serializeField('__axes', themeDef.__axes ?? {}, true);
1873
1900
 
1874
- return `${iconImport}/**
1901
+ return `${iconImport}${iconDeclaration}/**
1875
1902
  * ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
1876
1903
  * Import the CSS file alongside this module:
1877
1904
  *
@@ -1890,7 +1917,7 @@ ${iconReExport}`;
1890
1917
  /**
1891
1918
  * Generate TypeScript declarations for a built theme module.
1892
1919
  * @param {any} themeDef
1893
- * @param {{exportName: string, importPath: string} | null} iconInfo
1920
+ * @param {{exportName: string} | null} iconInfo - The re-exported registry, if any.
1894
1921
  * @param {string | null} variantsFileName
1895
1922
  * @param {{themeBinding?: string, includeIconExport?: boolean, includeThemeImport?: boolean}} [typeOptions]
1896
1923
  * @returns {string}
@@ -2316,7 +2343,7 @@ function validateHeadingTypeAugmentationSupport(themeDef) {
2316
2343
  * `out` overrides the output CSS path; `check` compares against on-disk outputs
2317
2344
  * instead of writing. `iconsSpecifier` overrides the icon registry import
2318
2345
  * specifier in the generated module (e.g. `./icons.mjs`); when omitted, the
2319
- * specifier scraped from the theme source is emitted unchanged.
2346
+ * direct registry specifiers from the theme source are emitted unchanged.
2320
2347
  * @param {{cwd?: string}} [ctx]
2321
2348
  * @returns {Promise<any>}
2322
2349
  */
@@ -2351,6 +2378,8 @@ async function themeBuildInternal(
2351
2378
 
2352
2379
  // Extract theme definition
2353
2380
  let themeDef;
2381
+ /** The export actually selected by the loader, not the first AST match. */
2382
+ let themeExportName;
2354
2383
  /** Paths through the load that interception could not fully observe. */
2355
2384
  let loadDegradation;
2356
2385
  try {
@@ -2360,6 +2389,7 @@ async function themeBuildInternal(
2360
2389
  options.__familyLoader,
2361
2390
  );
2362
2391
  themeDef = loaded.theme;
2392
+ themeExportName = loaded.exportName;
2363
2393
  loadDegradation = loaded.degraded;
2364
2394
  } catch (e) {
2365
2395
  const err = /** @type {Error} */ (e);
@@ -2425,6 +2455,25 @@ async function themeBuildInternal(
2425
2455
  throw err;
2426
2456
  }
2427
2457
 
2458
+ // A generated module must preserve the registry through an import: it may
2459
+ // contain React elements, which cannot be serialized. Validate before CSS
2460
+ // generation so neither the no-CSS return nor --check can bypass the error.
2461
+ // Family preparation keeps its own named-import registry contract, which
2462
+ // themeBuildFamily checks against the selected members' graph.
2463
+ const standaloneIcons = !options.__prepareFamily;
2464
+ const iconResolution = {
2465
+ readSource: (/** @type {string} */ file) => fs.readFileSync(file, 'utf8'),
2466
+ resolveModule: resolveThemeModule,
2467
+ reservedNames: [`${toIdentifier(themeDef.name)}Theme`],
2468
+ rawInput: 'extends' in themeDef,
2469
+ hasIcons:
2470
+ Object.keys(themeDef.icons ?? {}).length > 0 ||
2471
+ Object.keys(themeDef.extends?.icons ?? {}).length > 0,
2472
+ };
2473
+ let iconInfo = standaloneIcons
2474
+ ? await resolveIconImports(filePath, themeExportName, iconResolution)
2475
+ : null;
2476
+
2428
2477
  // Validate component overrides
2429
2478
  const warnings = await validateComponentOverrides(themeDef);
2430
2479
  const warningMessages = [];
@@ -2531,6 +2580,40 @@ async function themeBuildInternal(
2531
2580
  resolvedTheme = themeDef;
2532
2581
  }
2533
2582
 
2583
+ // Raw object exports can acquire icons only when Core resolves `extends`.
2584
+ // Recheck an unresolved provenance result before any generator runs.
2585
+ if (
2586
+ standaloneIcons &&
2587
+ !iconInfo &&
2588
+ Object.keys(resolvedTheme.icons ?? {}).length > 0
2589
+ ) {
2590
+ iconInfo = await resolveIconImports(filePath, themeExportName, {
2591
+ ...iconResolution,
2592
+ hasIcons: true,
2593
+ });
2594
+ }
2595
+ // An opaque package base can legitimately have no icons. Its .icons
2596
+ // reference is unnecessary; direct empty registry imports remain intact.
2597
+ if (
2598
+ iconInfo &&
2599
+ iconInfo.iconsSpecifierLocalName === undefined &&
2600
+ Object.keys(resolvedTheme.icons ?? {}).length === 0
2601
+ ) {
2602
+ iconInfo = null;
2603
+ }
2604
+ if (
2605
+ iconInfo &&
2606
+ options.iconsSpecifier !== undefined &&
2607
+ iconInfo.iconsSpecifierImportPath === undefined
2608
+ ) {
2609
+ throw new AstryxError(
2610
+ 'The icon registry is inherited through a theme import. ' +
2611
+ 'To use --icons-specifier, import the registry directly and set icons to that binding.',
2612
+ undefined,
2613
+ ERROR_CODES.ERR_THEME_INVALID,
2614
+ );
2615
+ }
2616
+
2534
2617
  // Cores that predate adaptations can still resolve typography, color,
2535
2618
  // radius, and motion into root tokens, but they do not retain the raw axis
2536
2619
  // inputs. Keep the effective metadata captured from the same defineTheme
@@ -2756,15 +2839,6 @@ async function themeBuildInternal(
2756
2839
  const jsPath = path.join(outDir, `${baseName}.js`);
2757
2840
  const dtsPath = path.join(outDir, `${baseName}.d.ts`);
2758
2841
 
2759
- const iconInfo = extractRegistryInfo(
2760
- filePath,
2761
- 'icons',
2762
- options.__prepareFamily,
2763
- );
2764
- const indicatorInfo = options.__prepareFamily
2765
- ? extractRegistryInfo(filePath, 'indicators', true)
2766
- : null;
2767
-
2768
2842
  // Type augmentation .d.ts if theme has custom prop values. Computed
2769
2843
  // before the main .d.ts so the latter can reference it (see below).
2770
2844
  const augmentationSource = resolvedTheme || themeDef;
@@ -2812,8 +2886,8 @@ async function themeBuildInternal(
2812
2886
  theme: displayTheme,
2813
2887
  sourceTheme: themeDef,
2814
2888
  sourceParent,
2815
- iconInfo,
2816
- indicatorInfo,
2889
+ iconInfo: extractRegistryInfo(filePath, 'icons'),
2890
+ indicatorInfo: extractRegistryInfo(filePath, 'indicators'),
2817
2891
  variantDecl,
2818
2892
  css: cssPlan,
2819
2893
  versions,
@@ -3157,11 +3231,14 @@ export async function themeBuildFamily(
3157
3231
  const indicatorImport = indicator.info
3158
3232
  ? `import { ${indicator.info.exportName} as ${ownIndicators} } from ${JSON.stringify(indicator.specifier ?? indicator.info.importPath)};\n`
3159
3233
  : '';
3234
+ // The member's own registry import, bound to its family-unique name; a
3235
+ // rebased or overridden specifier replaces the scraped one.
3236
+ // prettier-ignore
3237
+ const iconImports = icon.info && ownIcons ? {imports: [{importPath: icon.info.importPath, importedName: icon.info.exportName, localName: ownIcons}], expression: ownIcons, exportName: ownIcons, iconsSpecifierImportPath: icon.info.importPath, iconsSpecifierLocalName: ownIcons} : null;
3160
3238
  return (
3161
3239
  indicatorImport +
3162
- generateBuiltModule(member.theme, icon.info, icon.specifier, {
3240
+ generateBuiltModule(member.theme, iconImports, icon.specifier, {
3163
3241
  themeBinding,
3164
- iconBinding: ownIcons ?? undefined,
3165
3242
  iconsExpression: expression(ownIcons, inheritedIcons),
3166
3243
  indicatorsExpression: expression(ownIndicators, inheritedIndicators),
3167
3244
  artifactBaseName: baseName,
@@ -8,7 +8,8 @@
8
8
  * end-to-end; these assert the API contract you get calling `themeBuild()` in
9
9
  * code: the typed `theme.build` receipt (with files actually written to disk),
10
10
  * that it honors the `cwd` option, stays SILENT under the default noopLogger,
11
- * and returns `null` when there is nothing to build.
11
+ * returns `null` when there is nothing to build, and rejects unsupported icon
12
+ * registries without creating or changing outputs in build and check modes.
12
13
  *
13
14
  * `themeBuild` compiles via @astryxdesign/core's generator, so it needs a built
14
15
  * core — the `node` project's globalSetup (vitest.global-setup.node.mjs) builds
@@ -611,6 +612,194 @@ describe('themeBuild() — the shipped theme template', () => {
611
612
  });
612
613
  });
613
614
 
615
+ describe('themeBuild() — icon registry detection', () => {
616
+ /**
617
+ * The emitted icon import statement, or null. Reads the statement rather
618
+ * than the whole file: the `@generated` header quotes a usage example, so a
619
+ * substring search over the file would match comment text too.
620
+ */
621
+ function iconImportLine(generated) {
622
+ const match = generated.match(/^import .*$/m);
623
+ return match ? match[0] : null;
624
+ }
625
+
626
+ it('emits the import, icons key and re-export for a registry that arrives via an import', async () => {
627
+ fs.writeFileSync(
628
+ path.join(tmpDir, 'icons.mjs'),
629
+ 'export const liveIcons = {};\n',
630
+ );
631
+ fs.writeFileSync(
632
+ path.join(tmpDir, 'live.mjs'),
633
+ `import {liveIcons} from './icons';\n` +
634
+ `export default {name: 'live', icons: liveIcons, tokens: {'--color-bg': '#fff'}};\n`,
635
+ );
636
+
637
+ const result = await themeBuild('live.mjs', {}, {cwd: tmpDir});
638
+
639
+ const generated = fs.readFileSync(path.join(tmpDir, 'live.js'), 'utf8');
640
+ expect(iconImportLine(generated)).toBe(
641
+ "import { liveIcons } from './icons';",
642
+ );
643
+ expect(generated).toContain('icons: liveIcons,');
644
+ expect(generated).toContain('export { liveIcons };');
645
+ expect(result?.data.warnings).toEqual([]);
646
+ });
647
+
648
+ it('does not re-emit an import that only appears inside a comment (#5058)', async () => {
649
+ // The reported repro: the registry was inlined into the theme source, and
650
+ // a doc comment kept the old import line for context. The comment's
651
+ // specifier was scraped and emitted as live code in the built module,
652
+ // pointing at a file that no longer exists.
653
+ fs.writeFileSync(
654
+ path.join(tmpDir, 'commented.mjs'),
655
+ `/**\n` +
656
+ ` * The scaffold put this in a sibling icons file, so the built module\n` +
657
+ ` * carried \`import { ghostIcons } from './icons'\` — which Node\n` +
658
+ ` * cannot resolve.\n` +
659
+ ` */\n` +
660
+ `const ghostIcons = {close: 'inline'};\n` +
661
+ `export default {name: 'commented', icons: ghostIcons, tokens: {'--color-bg': '#fff'}};\n`,
662
+ );
663
+
664
+ await expect(
665
+ themeBuild('commented.mjs', {}, {cwd: tmpDir}),
666
+ ).rejects.toMatchObject({
667
+ code: 'ERR_THEME_INVALID',
668
+ message: expect.stringContaining('icons: ghostIcons'),
669
+ });
670
+ expect(fs.readdirSync(tmpDir)).toEqual(['commented.mjs']);
671
+ });
672
+
673
+ it('scrapes the live import even when a comment quotes a stale one', async () => {
674
+ fs.writeFileSync(
675
+ path.join(tmpDir, 'icons.mjs'),
676
+ 'export const realIcons = {};\n',
677
+ );
678
+ fs.writeFileSync(
679
+ path.join(tmpDir, 'both.mjs'),
680
+ `// was: import { realIcons } from './old-icons';\n` +
681
+ `import {realIcons} from './icons';\n` +
682
+ `export default {name: 'both', icons: realIcons, tokens: {'--color-bg': '#fff'}};\n`,
683
+ );
684
+
685
+ const result = await themeBuild('both.mjs', {}, {cwd: tmpDir});
686
+
687
+ // The comment comes first in the source, so the old scan matched it first
688
+ // and emitted `./old-icons` — the live import must win.
689
+ const generated = fs.readFileSync(path.join(tmpDir, 'both.js'), 'utf8');
690
+ expect(iconImportLine(generated)).toBe(
691
+ "import { realIcons } from './icons';",
692
+ );
693
+ expect(generated).not.toContain('old-icons');
694
+ expect(result?.data.warnings).toEqual([]);
695
+ });
696
+
697
+ it('ignores a commented-out icons: field entirely', async () => {
698
+ fs.writeFileSync(
699
+ path.join(tmpDir, 'nofield.mjs'),
700
+ `// icons: retiredIcons,\n` +
701
+ `export default {name: 'nofield', tokens: {'--color-bg': '#fff'}};\n`,
702
+ );
703
+
704
+ const result = await themeBuild('nofield.mjs', {}, {cwd: tmpDir});
705
+
706
+ const generated = fs.readFileSync(path.join(tmpDir, 'nofield.js'), 'utf8');
707
+ expect(iconImportLine(generated)).toBeNull();
708
+ expect(generated).not.toContain('icons:');
709
+ // No icons field means nothing was dropped — no warning either.
710
+ expect(result?.data.warnings).toEqual([]);
711
+ });
712
+
713
+ describe.each([false, true])('unsupported registries (check: %s)', check => {
714
+ it('rejects before the generator can return no CSS', async () => {
715
+ fs.writeFileSync(
716
+ path.join(tmpDir, 'inline.mjs'),
717
+ `const inlineIcons = {chevron: 'stub'};\n` +
718
+ `export default {name: 'inline', icons: inlineIcons, tokens: {}};\n`,
719
+ );
720
+
721
+ await mockGenerateThemeRulesSplit.withImplementation(
722
+ () => ({component: [], prose: []}),
723
+ async () => {
724
+ await mockGenerateOnMediaCSS.withImplementation(
725
+ () => '',
726
+ async () => {
727
+ await expect(
728
+ themeBuild('inline.mjs', {check}, {cwd: tmpDir}),
729
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
730
+ },
731
+ );
732
+ },
733
+ );
734
+ expect(mockGenerateThemeRulesSplit).not.toHaveBeenCalled();
735
+ expect(fs.readdirSync(tmpDir)).toEqual(['inline.mjs']);
736
+ });
737
+
738
+ it.each([
739
+ ['local binding', 'icons: inlineIcons'],
740
+ ['object literal', "icons: {chevron: 'stub'}"],
741
+ ['shorthand', 'icons'],
742
+ ])('rejects a %s without creating output files', async (_label, field) => {
743
+ fs.writeFileSync(
744
+ path.join(tmpDir, 'inline.mjs'),
745
+ `const inlineIcons = {chevron: 'stub'};\n` +
746
+ `const icons = inlineIcons;\n` +
747
+ `export default {name: 'inline', ${field}, tokens: {'--color-bg': '#fff'}};\n`,
748
+ );
749
+
750
+ await expect(
751
+ themeBuild(
752
+ 'inline.mjs',
753
+ {check, out: 'dist/inline.css'},
754
+ {cwd: tmpDir},
755
+ ),
756
+ ).rejects.toMatchObject({
757
+ code: 'ERR_THEME_INVALID',
758
+ message: expect.stringContaining(
759
+ 'Move the registry to its own module and import it',
760
+ ),
761
+ });
762
+ expect(fs.readdirSync(tmpDir)).toEqual(['inline.mjs']);
763
+ });
764
+
765
+ it('rejects even when committed output already matches the missing-icons result', async () => {
766
+ const themeFile = path.join(tmpDir, 'inline.mjs');
767
+ const withoutIcons =
768
+ `export default {name: 'inline', tokens: {'--color-bg': '#fff'}, ` +
769
+ `components: {button: {'variant:custom': {color: 'red'}}}};\n`;
770
+ fs.writeFileSync(themeFile, withoutIcons);
771
+ const built = await themeBuild('inline.mjs', {}, {cwd: tmpDir});
772
+ expect(built?.data.outputs.variantsDts).toBe('inline.variants.d.ts');
773
+ const outputs = Object.values(built.data.outputs);
774
+ const before = outputs.map(file =>
775
+ fs.readFileSync(path.join(tmpDir, file), 'utf8'),
776
+ );
777
+ // This source used to emit exactly the same output as the icon-free
778
+ // theme, so --check passed after the incomplete artifacts were committed.
779
+ fs.writeFileSync(
780
+ themeFile,
781
+ `const inlineIcons = {chevron: 'stub'};\n` +
782
+ withoutIcons.replace(
783
+ "name: 'inline',",
784
+ "name: 'inline', icons: inlineIcons,",
785
+ ),
786
+ );
787
+ const filesBefore = fs.readdirSync(tmpDir).sort();
788
+
789
+ await expect(
790
+ themeBuild('inline.mjs', {check}, {cwd: tmpDir}),
791
+ ).rejects.toMatchObject({
792
+ code: 'ERR_THEME_INVALID',
793
+ message: expect.stringContaining('icons: inlineIcons'),
794
+ });
795
+ expect(
796
+ outputs.map(file => fs.readFileSync(path.join(tmpDir, file), 'utf8')),
797
+ ).toEqual(before);
798
+ expect(fs.readdirSync(tmpDir).sort()).toEqual(filesBefore);
799
+ });
800
+ });
801
+ });
802
+
614
803
  describe('themeBuild() — extends', () => {
615
804
  // These fixtures `import {defineTheme} from '@astryxdesign/core/theme'` the
616
805
  // way a real theme file does, so they have to sit somewhere that specifier
@@ -0,0 +1,47 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * Parse only real module declarations and follow the export chosen by the loader.
6
+ * Local base themes are traced to their registry imports. Package bases remain
7
+ * public theme imports, so their implementation and private files stay private.
8
+ *
9
+ * @param {string} filePath
10
+ * @param {string | undefined} exportName
11
+ * @param {{hasIcons: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
12
+ * @returns {Promise<IconImports | null>}
13
+ */
14
+ export function resolveIconImports(filePath: string, exportName: string | undefined, { hasIcons, readSource, resolveModule, reservedNames, rawInput }: {
15
+ hasIcons: boolean;
16
+ readSource: (filename: string) => string;
17
+ resolveModule: (specifier: string, fromFile: string) => string | Promise<string>;
18
+ reservedNames?: string[];
19
+ rawInput?: boolean;
20
+ }): Promise<IconImports | null>;
21
+ export type IconImports = {
22
+ imports: {
23
+ importPath: string;
24
+ importedName: string;
25
+ localName: string;
26
+ }[];
27
+ expression: string;
28
+ exportName: string;
29
+ iconsSpecifierImportPath?: string | undefined;
30
+ iconsSpecifierLocalName?: string | undefined;
31
+ };
32
+ export type RegistryReference = {
33
+ kind: "reference";
34
+ module: any;
35
+ binding: any;
36
+ members: string[];
37
+ };
38
+ export type RegistryPlan = {
39
+ kind: "registry";
40
+ ref: RegistryReference;
41
+ preferredName: string;
42
+ override?: boolean;
43
+ } | {
44
+ kind: "merge";
45
+ base: RegistryPlan;
46
+ own: RegistryPlan;
47
+ };