@astryxdesign/cli 0.6.1-canary.f48d468 → 0.6.2-canary.a4bcbeb

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.
@@ -1,10 +1,10 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
3
  /**
4
- * @file theme build API — compile a defineTheme file to CSS + JS + .d.ts.
4
+ * @file theme build API — compile standalone themes or one selected family.
5
5
  *
6
- * `themeBuild(file, options, ctx)` is the programmatic surface behind
7
- * `astryx theme build`. It reads a theme file that uses defineTheme() and, via
6
+ * `themeBuild` and `themeBuildFamily` share the same loader, compiler,
7
+ * serializers, check, and writer. They read defineTheme() sources and, via
8
8
  * @astryxdesign/core's shared generator (the SINGLE source of truth so the
9
9
  * build emits the exact CSS the `<Theme>` runtime does), writes:
10
10
  * - A CSS file with token overrides and component styles
@@ -39,7 +39,9 @@
39
39
 
40
40
  import * as fs from 'node:fs';
41
41
  import * as path from 'node:path';
42
- import {fileURLToPath} from 'node:url';
42
+ import {isBuiltin} from 'node:module';
43
+ import {fileURLToPath, pathToFileURL} from 'node:url';
44
+ import {parse} from '@babel/parser';
43
45
  import {createJiti} from 'jiti';
44
46
  import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
45
47
  import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';
@@ -58,6 +60,7 @@ import {
58
60
  } from '../../../foundation/discovery/theming-targets.mjs';
59
61
  import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';
60
62
  import {interceptCore} from './core-interception.mjs';
63
+ import {generateFamilyCSS, resolveThemeFamily} from './family.mjs';
61
64
 
62
65
  // Import shared theme processing from core. `astryx theme build` MUST produce the
63
66
  // exact same CSS as the `<Theme>` runtime, so it has exactly one generation
@@ -199,6 +202,52 @@ function normalizeForCompare(content) {
199
202
  .join('\n');
200
203
  }
201
204
 
205
+ /** @param {Array<{dest: string, content: string}>} writes @param {string} cwd @returns {Array<{path: string, reason: 'missing' | 'outdated'}>} */
206
+ function staleBuildOutputs(writes, cwd) {
207
+ /** @type {Array<{path: string, reason: 'missing' | 'outdated'}>} */
208
+ const stale = [];
209
+ for (const write of writes) {
210
+ const rel = path.relative(cwd, write.dest);
211
+ if (!fs.existsSync(write.dest)) {
212
+ stale.push({path: rel, reason: 'missing'});
213
+ continue;
214
+ }
215
+ const onDisk = fs.readFileSync(write.dest, 'utf8');
216
+ if (normalizeForCompare(onDisk) !== normalizeForCompare(write.content)) {
217
+ stale.push({path: rel, reason: 'outdated'});
218
+ }
219
+ }
220
+ return stale;
221
+ }
222
+
223
+ /** @param {Array<{dest: string, content: string}>} writes */
224
+ function writeBuildOutputs(writes) {
225
+ if (writes.length === 0) return;
226
+ fs.mkdirSync(path.dirname(writes[0].dest), {recursive: true});
227
+ /** @type {Array<{tmp: string, dest: string}>} */
228
+ const staged = [];
229
+ try {
230
+ for (const write of writes) {
231
+ const tmp = `${write.dest}.${process.pid}.tmp`;
232
+ fs.writeFileSync(tmp, write.content);
233
+ staged.push({tmp, dest: write.dest});
234
+ }
235
+ for (const stagedWrite of staged) {
236
+ fs.renameSync(stagedWrite.tmp, stagedWrite.dest);
237
+ }
238
+ } catch (error) {
239
+ for (const stagedWrite of staged) {
240
+ try {
241
+ fs.rmSync(stagedWrite.tmp, {force: true});
242
+ } catch {
243
+ // Best effort: the command still fails and never reports success.
244
+ }
245
+ }
246
+ const message = `Failed to write theme outputs: ${/** @type {Error} */ (error).message}`;
247
+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
248
+ }
249
+ }
250
+
202
251
  /**
203
252
  * Convert a theme name to a valid JS identifier.
204
253
  *
@@ -1157,7 +1206,85 @@ const THEME_MODULE_EXTENSIONS = [
1157
1206
  '.js',
1158
1207
  '.json',
1159
1208
  ];
1160
-
1209
+ // prettier-ignore
1210
+ const registryGraphError = (/** @type {string} */ message) => new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
1211
+ // prettier-ignore
1212
+ function parseRegistryModule(/** @type {string} */ source, /** @type {string} */ filePath) {
1213
+ try { return parse(source, {sourceType: 'unambiguous', plugins: ['typescript', 'jsx', 'decorators-legacy', 'importAttributes']}); }
1214
+ catch (error) { throw registryGraphError(`Cannot inspect registry module ${filePath}: ${error instanceof Error ? error.message : String(error)}`); }
1215
+ }
1216
+ // prettier-ignore
1217
+ function moduleDependencies(/** @type {string} */ source, /** @type {string} */ filePath) {
1218
+ const ast = parseRegistryModule(source, filePath);
1219
+ /** @type {Array<{specifier: string, commonJs: boolean, imports: string[]}>} */ const found = [];
1220
+ /** @param {any} node */ const literal = node => typeof node?.value === 'string' ? node.value : node?.type === 'TemplateLiteral' && node.expressions.length === 0 ? node.quasis[0]?.value?.cooked : null;
1221
+ /** @param {any} node */ const visit = node => {
1222
+ if (!node || typeof node !== 'object') return;
1223
+ if (['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration'].includes(node.type) && node.importKind !== 'type' && typeof node.source?.value === 'string') {
1224
+ const specifiers = /** @type {any[]} */ (node.specifiers);
1225
+ const imports = node.type === 'ImportDeclaration' ? specifiers.filter(item => item.importKind !== 'type' && item.type !== 'ImportNamespaceSpecifier').map(item => item.type === 'ImportDefaultSpecifier' ? 'default' : item.imported?.name ?? item.imported?.value) : node.type === 'ExportNamedDeclaration' ? specifiers.filter(item => item.exportKind !== 'type' && item.type === 'ExportSpecifier').map(item => item.local?.name ?? item.local?.value) : [];
1226
+ found.push({specifier: node.source.value, commonJs: false, imports});
1227
+ }
1228
+ const dependency = node.type === 'ImportExpression' ? node.source : node.type === 'CallExpression' && (node.callee?.type === 'Import' || node.callee?.name === 'require') ? node.arguments?.[0] : null;
1229
+ if (dependency) { const specifier = literal(dependency); if (specifier == null) throw registryGraphError(`Registry module ${filePath} has a non-static dependency; family output cannot prove that graph is resolvable and CSS-free.`); found.push({specifier, commonJs: node.callee?.name === 'require', imports: []}); }
1230
+ for (const value of Object.values(node)) if (Array.isArray(value)) value.forEach(child => child?.type && visit(child)); else if (value?.type) visit(value);
1231
+ };
1232
+ visit(ast); return found;
1233
+ }
1234
+ // prettier-ignore
1235
+ function resolveRegistryModule(/** @type {string} */ specifier, /** @type {string} */ parentPath, commonJs = false) {
1236
+ if (isBuiltin(specifier) || specifier.startsWith('node:')) return null;
1237
+ let resolved;
1238
+ try {
1239
+ const resolver = createJiti(parentPath, {extensions: THEME_MODULE_EXTENSIONS});
1240
+ if (commonJs) resolved = resolver.resolve(specifier);
1241
+ else if (specifier.startsWith('.')) resolved = fileURLToPath(new URL(specifier, pathToFileURL(parentPath)));
1242
+ else if (path.isAbsolute(specifier)) resolved = specifier;
1243
+ else { const url = resolver.esmResolve(specifier); resolved = url.startsWith('file:') ? fileURLToPath(url) : url; }
1244
+ } catch (error) { throw registryGraphError(`Cannot resolve registry import "${specifier}" from ${parentPath}: ${error instanceof Error ? error.message : String(error)}`); }
1245
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) throw registryGraphError(`Cannot resolve registry import "${specifier}" from ${parentPath}.`);
1246
+ return fs.realpathSync(resolved);
1247
+ }
1248
+ /** @returns {boolean | null} */
1249
+ // prettier-ignore
1250
+ function hasNamedExport(/** @type {string} */ file, /** @type {string} */ name, seen = new Set()) {
1251
+ const key = `${file}\0${name}`; if (seen.has(key)) return false; seen.add(key);
1252
+ const ast = parseRegistryModule(fs.readFileSync(file, 'utf8'), file); let esm = false; let unknown = false;
1253
+ for (const node of /** @type {any[]} */ (ast.program.body)) {
1254
+ if (node.type === 'ExportDefaultDeclaration') { esm = true; if (name === 'default') return true; }
1255
+ if (node.type === 'ExportNamedDeclaration') {
1256
+ esm = true; const declaration = /** @type {any} */ (node.declaration);
1257
+ if ((declaration?.id?.name === name) || (declaration?.type === 'VariableDeclaration' && declaration.declarations.some((/** @type {any} */ item) => item.id?.name === name))) return true;
1258
+ for (const specifier of /** @type {any[]} */ (node.specifiers)) if ((specifier.exported?.name ?? specifier.exported?.value) === name) {
1259
+ if (!node.source || specifier.type === 'ExportNamespaceSpecifier') return true;
1260
+ const target = resolveRegistryModule(node.source.value, file); return target ? hasNamedExport(target, specifier.local?.name ?? specifier.local?.value, seen) : false;
1261
+ }
1262
+ }
1263
+ if (node.type === 'ExportAllDeclaration') { esm = true; const target = resolveRegistryModule(node.source.value, file); const status = target ? hasNamedExport(target, name, seen) : false; if (status === true) return true; if (status === null) unknown = true; }
1264
+ }
1265
+ return esm ? unknown ? null : false : null;
1266
+ }
1267
+ // prettier-ignore
1268
+ async function validateRegistryGraphs(/** @type {Array<{specifier: string, exportName: string}>} */ registries, /** @type {string} */ aggregatePath) {
1269
+ /** @type {Array<{specifier: string, parent: string, commonJs: boolean, imports: string[], root?: {exportName: string}}>} */ const pending = registries.map(root => ({specifier: root.specifier, parent: aggregatePath, commonJs: false, imports: [root.exportName], root}));
1270
+ /** @type {Array<{file: string, exportName: string}>} */ const runtimeChecks = []; const seen = new Set();
1271
+ while (pending.length > 0) {
1272
+ const current = pending.pop(); if (!current) break; const {specifier, parent, commonJs, imports, root} = current;
1273
+ if (/\.css(?:$|[?#])/i.test(specifier)) throw registryGraphError(`Theme family registry graph imports CSS: ${specifier}`);
1274
+ const file = resolveRegistryModule(specifier, parent, commonJs); if (!file) continue;
1275
+ if (/\.css$/i.test(file)) throw registryGraphError(`Theme family registry graph imports CSS: ${file}`);
1276
+ const external = file.split(path.sep).includes('node_modules');
1277
+ for (const name of imports) if (external) runtimeChecks.push({file, exportName: name}); else { const named = hasNamedExport(file, name); if (named === false) throw registryGraphError(`Family registry ${file} does not export "${name}".`); if (named === null) runtimeChecks.push({file, exportName: name}); }
1278
+ if (root) runtimeChecks.push({file, exportName: root.exportName});
1279
+ if (seen.has(file)) continue; seen.add(file);
1280
+ if (/\.[cm]?[jt]sx?$/i.test(file)) for (const edge of moduleDependencies(fs.readFileSync(file, 'utf8'), file)) pending.push({...edge, parent: file});
1281
+ }
1282
+ for (const [index, root] of runtimeChecks.entries()) {
1283
+ let exports; try { exports = await import(`${pathToFileURL(root.file).href}?astryx-family-check=${Date.now()}-${index}`); }
1284
+ catch (error) { throw registryGraphError(`Cannot import family registry ${root.file}: ${error instanceof Error ? error.message : String(error)}`); }
1285
+ if (!(root.exportName in exports)) throw registryGraphError(`Family registry ${root.file} does not export "${root.exportName}".`);
1286
+ }
1287
+ }
1161
1288
  /**
1162
1289
  * Errors that mean "the synchronous loader cannot evaluate this module", as
1163
1290
  * opposed to "this module is broken". Only the former may fall back to the
@@ -1196,23 +1323,27 @@ function isSyncLoaderLimitation(error) {
1196
1323
  * author's adaptations unobserved. The sync path transpiles it, so the wrapped
1197
1324
  * core reaches inside installed packages too.
1198
1325
  *
1199
- * A module the sync path cannot evaluate at all (top-level await) still has to
1200
- * load, so it falls back to the async import — but that fallback is DEGRADED:
1201
- * package sources on that path resolve their own core again. The caller is
1202
- * told, and treats anything it could not observe as unproven rather than
1203
- * assuming it is clean.
1326
+ * A module the sync path cannot evaluate (top-level await) is force-transpiled
1327
+ * through jiti's asynchronous evaluator. That keeps interception active for
1328
+ * the entry and captures its exact `extends` value; relative dependencies may
1329
+ * use native ESM, so family mode binds those objects back to the exact selected
1330
+ * source export and old-Core adaptation checks keep treating that path as
1331
+ * degraded/fail-closed.
1204
1332
  *
1205
1333
  * @param {string} filePath
1206
1334
  * @param {import('./core-interception.mjs').CoreInterception} [interception]
1207
1335
  * @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
1208
1336
  */
1209
- async function importThemeModule(filePath, interception) {
1210
- const jiti = createJiti(import.meta.url, {
1211
- moduleCache: false,
1212
- jsx: true,
1213
- extensions: THEME_MODULE_EXTENSIONS,
1214
- ...(interception ? {virtualModules: interception.modules} : {}),
1215
- });
1337
+ // prettier-ignore
1338
+ async function importThemeModule(filePath, interception, /** @type {any} */ loader = undefined) {
1339
+ const jiti =
1340
+ loader ??
1341
+ createJiti(import.meta.url, {
1342
+ moduleCache: false,
1343
+ jsx: true,
1344
+ extensions: THEME_MODULE_EXTENSIONS,
1345
+ ...(interception ? {virtualModules: interception.modules} : {}),
1346
+ });
1216
1347
 
1217
1348
  /** @type {any} */
1218
1349
  let mod;
@@ -1232,7 +1363,17 @@ async function importThemeModule(filePath, interception) {
1232
1363
  // theme's own failure and belongs to the caller unchanged.
1233
1364
  if (!isSyncLoaderLimitation(error)) throw error;
1234
1365
  degraded.topLevelAwait = true;
1235
- mod = await jiti.import(filePath, {default: true});
1366
+ // Force asynchronous transformation instead of native import: this
1367
+ // keeps virtual Core interception active even when the module uses
1368
+ // top-level await.
1369
+ mod = await jiti.evalModule(fs.readFileSync(filePath, 'utf8'), {
1370
+ id: filePath,
1371
+ filename: filePath,
1372
+ ext: path.extname(filePath),
1373
+ cache: jiti.cache,
1374
+ async: true,
1375
+ forceTranspile: true,
1376
+ });
1236
1377
  }
1237
1378
  } finally {
1238
1379
  commonJsPatch.undo();
@@ -1282,9 +1423,10 @@ function isThemeObject(value) {
1282
1423
  * @param {import('./core-interception.mjs').CoreInterception} [interception]
1283
1424
  * @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
1284
1425
  */
1285
- async function extractThemeDefinition(filePath, interception) {
1426
+ // prettier-ignore
1427
+ async function extractThemeDefinition(filePath, interception, /** @type {any} */ loader = undefined) {
1286
1428
  try {
1287
- return await importThemeModule(filePath, interception);
1429
+ return await importThemeModule(filePath, interception, loader);
1288
1430
  } catch (jitiError) {
1289
1431
  try {
1290
1432
  return {
@@ -1352,26 +1494,45 @@ function extractThemeDefinitionLegacy(filePath) {
1352
1494
  * @param {string} filePath
1353
1495
  * @returns {{exportName: string, importPath: string} | null}
1354
1496
  */
1355
- function extractIconInfo(filePath) {
1497
+ function extractRegistryInfo(filePath, field = 'icons', familyMode = false) {
1356
1498
  const content = fs.readFileSync(filePath, 'utf8');
1357
-
1358
- // Find the icons field in defineTheme
1359
- const iconsMatch = content.match(/icons:\s*([a-zA-Z_][a-zA-Z0-9_]*)/);
1360
- if (!iconsMatch) return null;
1361
-
1362
- const varName = /** @type {string} */ (iconsMatch[1]);
1363
-
1364
- // Find the import for that variable
1365
- const importRegex = new RegExp(
1366
- `import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,
1499
+ if (!familyMode) {
1500
+ const fieldMatch = content.match(
1501
+ new RegExp(`${field}:\\s*([a-zA-Z_][a-zA-Z0-9_]*)`),
1502
+ );
1503
+ if (!fieldMatch) return null;
1504
+ const varName = fieldMatch[1];
1505
+ const match = content.match(
1506
+ new RegExp(
1507
+ `import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,
1508
+ ),
1509
+ );
1510
+ return match ? {exportName: varName, importPath: match[1]} : null;
1511
+ }
1512
+ const defineIndex = content.indexOf('defineTheme(');
1513
+ if (defineIndex < 0) return null;
1514
+ const themeSource = content.slice(defineIndex);
1515
+ const explicit = themeSource.match(
1516
+ new RegExp(`${field}:\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*(?=[,}])`),
1367
1517
  );
1368
- const importMatch = content.match(importRegex);
1369
- if (!importMatch) return null;
1370
-
1371
- return {
1372
- exportName: varName,
1373
- importPath: /** @type {string} */ (importMatch[1]),
1374
- };
1518
+ const shorthand = themeSource.match(
1519
+ new RegExp(`[,{]\\s*(${field})\\s*(?=[,}])`),
1520
+ );
1521
+ const varName = explicit?.[1] ?? shorthand?.[1];
1522
+ if (!varName) return null;
1523
+ for (const match of content.matchAll(
1524
+ /import\s*{([^}]*)}\s*from\s*['"]([^'"]+)['"]/g,
1525
+ )) {
1526
+ for (const specifier of match[1].split(',')) {
1527
+ const [exportName, localName = exportName] = specifier
1528
+ .trim()
1529
+ .split(/\s+as\s+/);
1530
+ if (localName === varName) {
1531
+ return {exportName, importPath: match[2]};
1532
+ }
1533
+ }
1534
+ }
1535
+ return null;
1375
1536
  }
1376
1537
 
1377
1538
  /**
@@ -1397,9 +1558,20 @@ function extractIconInfo(filePath) {
1397
1558
  * @param {any} themeDef
1398
1559
  * @param {{exportName: string, importPath: string} | null} iconInfo
1399
1560
  * @param {string} [iconsSpecifier] - Overrides the scraped icon import specifier.
1561
+ * @param {{themeBinding?: string, iconBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]
1400
1562
  * @returns {string}
1401
1563
  */
1402
- function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
1564
+ function generateBuiltModule(
1565
+ themeDef,
1566
+ iconInfo,
1567
+ iconsSpecifier,
1568
+ moduleOptions = {},
1569
+ ) {
1570
+ const themeBinding =
1571
+ moduleOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
1572
+ const iconBinding = moduleOptions.iconBinding ?? iconInfo?.exportName;
1573
+ const artifactBaseName = moduleOptions.artifactBaseName ?? themeDef.name;
1574
+ const exportIcons = moduleOptions.exportIcons ?? true;
1403
1575
  // Preserve the historical generated bytes when no override is supplied.
1404
1576
  // User-provided specifiers need string-literal encoding so quotes and
1405
1577
  // backslashes cannot produce invalid JavaScript.
@@ -1408,10 +1580,18 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
1408
1580
  ? `'${iconInfo?.importPath}'`
1409
1581
  : JSON.stringify(iconsSpecifier);
1410
1582
  const iconImport = iconInfo
1411
- ? `import { ${iconInfo.exportName} } from ${renderedSpecifier};\n`
1583
+ ? `import { ${iconInfo.exportName}${iconBinding === iconInfo.exportName ? '' : ` as ${iconBinding}`} } from ${renderedSpecifier};\n`
1584
+ : '';
1585
+ const iconsExpression =
1586
+ moduleOptions.iconsExpression ?? (iconInfo ? iconBinding : undefined);
1587
+ const iconsField = iconsExpression ? ` icons: ${iconsExpression},` : '';
1588
+ const indicatorsField = moduleOptions.indicatorsExpression
1589
+ ? `\n indicators: ${moduleOptions.indicatorsExpression},`
1412
1590
  : '';
1413
- const iconsField = iconInfo ? ` icons: ${iconInfo.exportName},` : '';
1414
- const iconReExport = iconInfo ? `\nexport { ${iconInfo.exportName} };\n` : '';
1591
+ const iconReExport =
1592
+ iconInfo && exportIcons
1593
+ ? `\nexport { ${iconBinding}${iconBinding === iconInfo.exportName ? '' : ` as ${iconInfo.exportName}`} };\n`
1594
+ : '';
1415
1595
 
1416
1596
  // Resolve token values — tuples become light-dark() strings
1417
1597
  /** @type {Record<string, unknown>} */
@@ -1474,14 +1654,14 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
1474
1654
  * ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
1475
1655
  * Import the CSS file alongside this module:
1476
1656
  *
1477
- * import { ${toIdentifier(themeDef.name)}Theme } from './${themeDef.name}';
1478
- * import './${themeDef.name}.css';
1657
+ * import { ${themeBinding} } from './${artifactBaseName}';
1658
+ * import './${artifactBaseName}.css';
1479
1659
  */
1480
- export const ${toIdentifier(themeDef.name)}Theme = {
1660
+ export const ${themeBinding} = {
1481
1661
  name: '${themeDef.name}',
1482
1662
  __built: true,
1483
1663
  tokens: ${tokensStr},
1484
- ${inheritableFields}${iconsField}
1664
+ ${inheritableFields}${iconsField}${indicatorsField}
1485
1665
  };
1486
1666
  ${iconReExport}`;
1487
1667
  }
@@ -1491,14 +1671,23 @@ ${iconReExport}`;
1491
1671
  * @param {any} themeDef
1492
1672
  * @param {{exportName: string, importPath: string} | null} iconInfo
1493
1673
  * @param {string | null} variantsFileName
1674
+ * @param {{themeBinding?: string, includeIconExport?: boolean, includeThemeImport?: boolean}} [typeOptions]
1494
1675
  * @returns {string}
1495
1676
  */
1496
- function generateBuiltTypes(themeDef, iconInfo, variantsFileName) {
1497
- const iconType = iconInfo
1498
- ? `import type { IconRegistry } from '@astryxdesign/core/Icon';
1677
+ function generateBuiltTypes(
1678
+ themeDef,
1679
+ iconInfo,
1680
+ variantsFileName,
1681
+ typeOptions = {},
1682
+ ) {
1683
+ const themeBinding =
1684
+ typeOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
1685
+ const iconType =
1686
+ iconInfo && (typeOptions.includeIconExport ?? true)
1687
+ ? `import type { IconRegistry } from '@astryxdesign/core/Icon';
1499
1688
  export declare const ${iconInfo.exportName}: IconRegistry;
1500
1689
  `
1501
- : '';
1690
+ : '';
1502
1691
  // Pull in the generated custom-variant augmentations so that importing the
1503
1692
  // theme's types also loads the module augmentations (otherwise the
1504
1693
  // `.variants.d.ts` is emitted but never referenced, and the custom variants
@@ -1507,9 +1696,11 @@ export declare const ${iconInfo.exportName}: IconRegistry;
1507
1696
  ? `/// <reference path="./${variantsFileName}" />
1508
1697
  `
1509
1698
  : '';
1510
- return `${variantsRef}import type { DefinedTheme } from '@astryxdesign/core/theme';
1511
- ${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedTheme;
1512
- `;
1699
+ const themeImport =
1700
+ (typeOptions.includeThemeImport ?? true)
1701
+ ? `import type { DefinedTheme } from '@astryxdesign/core/theme';\n`
1702
+ : '';
1703
+ return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: DefinedTheme;\n`;
1513
1704
  }
1514
1705
 
1515
1706
  // =============================================================================
@@ -1853,15 +2044,15 @@ function validateHeadingTypeAugmentationSupport(themeDef) {
1853
2044
  * `logger` (silent by default).
1854
2045
  *
1855
2046
  * @param {string} file - Theme file path, resolved against `cwd`.
1856
- * @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] -
2047
+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any}} [options] -
1857
2048
  * `out` overrides the output CSS path; `check` compares against on-disk outputs
1858
2049
  * instead of writing. `iconsSpecifier` overrides the icon registry import
1859
2050
  * specifier in the generated module (e.g. `./icons.mjs`); when omitted, the
1860
2051
  * specifier scraped from the theme source is emitted unchanged.
1861
2052
  * @param {{cwd?: string}} [ctx]
1862
- * @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>}
2053
+ * @returns {Promise<any>}
1863
2054
  */
1864
- export async function themeBuild(
2055
+ async function themeBuildInternal(
1865
2056
  file,
1866
2057
  options = {},
1867
2058
  {cwd = process.cwd()} = {},
@@ -1878,21 +2069,26 @@ export async function themeBuild(
1878
2069
 
1879
2070
  logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);
1880
2071
 
1881
- // When the installed core cannot compile adaptations, watch its
1882
- // `defineTheme` as the theme loads: that core erases `adaptations` while
1883
- // resolving, so the raw input captured here is the only remaining witness
1884
- // to what the author wrote. Costs no extra execution — the theme is loaded
1885
- // once either way — and a core that CAN compile them needs none of it.
1886
- const interception = _generateAdaptationCSS
1887
- ? undefined
1888
- : interceptCore(_coreThemeModule, _coreRootModule);
2072
+ // Standalone builds only need interception when an older Core could erase
2073
+ // adaptations. Family preparation always supplies the same recorder as its
2074
+ // shared loader so exact authored parent identity stays CLI-private instead
2075
+ // of becoming a public DefinedTheme field.
2076
+ const interception =
2077
+ options.__familyInterception ??
2078
+ (_generateAdaptationCSS
2079
+ ? undefined
2080
+ : interceptCore(_coreThemeModule, _coreRootModule));
1889
2081
 
1890
2082
  // Extract theme definition
1891
2083
  let themeDef;
1892
2084
  /** Paths through the load that interception could not fully observe. */
1893
2085
  let loadDegradation;
1894
2086
  try {
1895
- const loaded = await extractThemeDefinition(filePath, interception);
2087
+ const loaded = await extractThemeDefinition(
2088
+ filePath,
2089
+ interception,
2090
+ options.__familyLoader,
2091
+ );
1896
2092
  themeDef = loaded.theme;
1897
2093
  loadDegradation = loaded.degraded;
1898
2094
  } catch (e) {
@@ -1904,6 +2100,16 @@ export async function themeBuild(
1904
2100
  // reaches anything that reads or writes it. (Symbol keys are invisible to
1905
2101
  // JSON.stringify and Object.keys, so it could not reach output regardless.)
1906
2102
  // Both reads happen BEFORE the strip, which is what removes the evidence.
2103
+ const ancestryObserved =
2104
+ !options.__prepareFamily ||
2105
+ !interception ||
2106
+ interception.observed(themeDef) ||
2107
+ Object.hasOwn(themeDef, 'extends');
2108
+ if (options.__prepareFamily && interception) interception.retain(themeDef);
2109
+ const sourceParent =
2110
+ options.__prepareFamily && interception
2111
+ ? interception.parentOf(themeDef)
2112
+ : undefined;
1907
2113
  const adaptationLineage = interception
1908
2114
  ? interception.lineageOf(themeDef)
1909
2115
  : undefined;
@@ -1916,6 +2122,13 @@ export async function themeBuild(
1916
2122
  const unobservedLineage =
1917
2123
  interception && hasCoverageGap ? interception.unobservedIn(themeDef) : [];
1918
2124
  if (interception) interception.strip(themeDef);
2125
+ if (!ancestryObserved) {
2126
+ throw new AstryxError(
2127
+ `Theme "${themeDef.name ?? path.basename(filePath)}" exact family ancestry could not be observed during CLI loading.`,
2128
+ undefined,
2129
+ ERROR_CODES.ERR_THEME_INVALID,
2130
+ );
2131
+ }
1919
2132
 
1920
2133
  if (!themeDef.name) {
1921
2134
  throw new AstryxError(
@@ -2009,6 +2222,7 @@ export async function themeBuild(
2009
2222
 
2010
2223
  let css;
2011
2224
  let resolvedTheme;
2225
+ let cssPlan;
2012
2226
  {
2013
2227
  // jiti returns an already-resolved theme; a plain object literal (or the
2014
2228
  // legacy eval path) returns raw defineTheme input, which still has to go
@@ -2152,8 +2366,9 @@ export async function themeBuild(
2152
2366
  }
2153
2367
  // Media-surface rules come last so onDark/onLight win over matching
2154
2368
  // adaptations on the same resolved leaf.
2369
+ let onMediaCss = '';
2155
2370
  if (_generateOnMediaCSS) {
2156
- const onMediaCss = _generateOnMediaCSS(resolvedTheme);
2371
+ onMediaCss = _generateOnMediaCSS(resolvedTheme);
2157
2372
  if (onMediaCss) {
2158
2373
  cssParts.push(`@layer astryx-theme {\n${onMediaCss}\n}`);
2159
2374
  }
@@ -2182,6 +2397,15 @@ export async function themeBuild(
2182
2397
  `@layer astryx-base {\n${baseCss}\n}`,
2183
2398
  );
2184
2399
  }
2400
+ cssPlan = {
2401
+ base: baseCss,
2402
+ prose,
2403
+ component,
2404
+ adaptation: adaptationCss.component,
2405
+ adaptationProse: adaptationCss.prose,
2406
+ onMedia: onMediaCss,
2407
+ colorScheme: colorSchemeDecl.trimEnd(),
2408
+ };
2185
2409
  css = cssParts.join('\n\n') + '\n';
2186
2410
  }
2187
2411
 
@@ -2225,7 +2449,14 @@ export async function themeBuild(
2225
2449
  const jsPath = path.join(outDir, `${baseName}.js`);
2226
2450
  const dtsPath = path.join(outDir, `${baseName}.d.ts`);
2227
2451
 
2228
- const iconInfo = extractIconInfo(filePath);
2452
+ const iconInfo = extractRegistryInfo(
2453
+ filePath,
2454
+ 'icons',
2455
+ options.__prepareFamily,
2456
+ );
2457
+ const indicatorInfo = options.__prepareFamily
2458
+ ? extractRegistryInfo(filePath, 'indicators', true)
2459
+ : null;
2229
2460
 
2230
2461
  // Type augmentation .d.ts if theme has custom prop values. Computed
2231
2462
  // before the main .d.ts so the latter can reference it (see below).
@@ -2258,10 +2489,34 @@ export async function themeBuild(
2258
2489
  generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
2259
2490
  generateBuiltTypes(themeDef, iconInfo, variantsFileName);
2260
2491
 
2261
- // Atomic-ish write: stage every file as `<dest>.tmp`, then rename
2262
- // each into place. If any stage step fails we clean up partials and
2263
- // exit; if a rename fails mid-way we still have the originals (or
2264
- // nothing) — never a half-built output set.
2492
+ const unloadedFonts = [
2493
+ ...new Set([
2494
+ ...collectUnloadedFonts(resolvedTheme),
2495
+ ...adaptationRuleValues(resolvedTheme).flatMap(
2496
+ (/** @type {any} */ value) => collectUnloadedFonts(value),
2497
+ ),
2498
+ ]),
2499
+ ];
2500
+
2501
+ if (options.__prepareFamily) {
2502
+ return {
2503
+ filePath,
2504
+ sourceRelative: sourceRelative.split(path.sep).join('/'),
2505
+ theme: displayTheme,
2506
+ sourceTheme: themeDef,
2507
+ sourceParent,
2508
+ iconInfo,
2509
+ indicatorInfo,
2510
+ variantDecl,
2511
+ css: cssPlan,
2512
+ versions,
2513
+ tokenCount,
2514
+ componentCount,
2515
+ warnings: warningMessages,
2516
+ unloadedFonts,
2517
+ };
2518
+ }
2519
+
2265
2520
  const writes = [
2266
2521
  {dest: outPath, content: cssContent},
2267
2522
  {dest: jsPath, content: jsContent},
@@ -2276,19 +2531,7 @@ export async function themeBuild(
2276
2531
  // volatile @generated `Command:` line is ignored. Returns a
2277
2532
  // receipt listing stale/missing outputs so callers (CI) can fail on drift.
2278
2533
  if (options.check) {
2279
- /** @type {Array<{path: string, reason: 'missing' | 'outdated'}>} */
2280
- const stale = [];
2281
- for (const w of writes) {
2282
- const rel = path.relative(cwd, w.dest);
2283
- if (!fs.existsSync(w.dest)) {
2284
- stale.push({path: rel, reason: 'missing'});
2285
- continue;
2286
- }
2287
- const onDisk = fs.readFileSync(w.dest, 'utf8');
2288
- if (normalizeForCompare(onDisk) !== normalizeForCompare(w.content)) {
2289
- stale.push({path: rel, reason: 'outdated'});
2290
- }
2291
- }
2534
+ const stale = staleBuildOutputs(writes, cwd);
2292
2535
  const upToDate = stale.length === 0;
2293
2536
  if (upToDate) {
2294
2537
  logger.log(`\n✓ Theme outputs are up to date with ${sourceRelative}.`);
@@ -2314,30 +2557,7 @@ export async function themeBuild(
2314
2557
  };
2315
2558
  }
2316
2559
 
2317
- fs.mkdirSync(outDir, {recursive: true});
2318
- /** @type {Array<{tmp: string, dest: string}>} */
2319
- const staged = [];
2320
- try {
2321
- for (const w of writes) {
2322
- const tmp = `${w.dest}.${process.pid}.tmp`;
2323
- fs.writeFileSync(tmp, w.content);
2324
- staged.push({tmp, dest: w.dest});
2325
- }
2326
- for (const s of staged) {
2327
- fs.renameSync(s.tmp, s.dest);
2328
- }
2329
- } catch (err) {
2330
- // Roll back any temp files we managed to create.
2331
- for (const s of staged) {
2332
- try {
2333
- fs.rmSync(s.tmp, {force: true});
2334
- } catch {
2335
- /* best-effort */
2336
- }
2337
- }
2338
- const msg = `Failed to write theme outputs: ${/** @type {Error} */ (err).message}`;
2339
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_WRITE_FAILED);
2340
- }
2560
+ writeBuildOutputs(writes);
2341
2561
 
2342
2562
  logger.log(`\n✓ ${path.relative(cwd, outPath)}`);
2343
2563
  logger.log(
@@ -2390,14 +2610,6 @@ Or with a <link> tag:
2390
2610
  // permanently in violation of its own "compiles with no warnings" guard).
2391
2611
  // Adaptation rules are resolved theme writes in their own right, so a family
2392
2612
  // named only inside one needs the same notice as one named at the root.
2393
- const unloadedFonts = [
2394
- ...new Set([
2395
- ...collectUnloadedFonts(resolvedTheme),
2396
- ...adaptationRuleValues(resolvedTheme).flatMap(
2397
- (/** @type {any} */ value) => collectUnloadedFonts(value),
2398
- ),
2399
- ]),
2400
- ];
2401
2613
  for (const family of unloadedFonts) {
2402
2614
  const msg = `Font "${family}" is named by this theme but not loaded — add a <link> or @font-face in your app (recipe: astryx docs typography)`;
2403
2615
  noticeMessages.push(msg);
@@ -2427,3 +2639,330 @@ Or with a <link> tag:
2427
2639
  },
2428
2640
  };
2429
2641
  }
2642
+
2643
+ /** @param {string} file @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] @param {{cwd?: string}} [ctx] @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>} */
2644
+ export async function themeBuild(file, options = {}, ctx = {}) {
2645
+ return /** @type {any} */ (themeBuildInternal(file, options, ctx));
2646
+ }
2647
+ /** @param {string} name */
2648
+ // prettier-ignore
2649
+ function familyThemeBinding(name) {
2650
+ const words = name.split(/[^A-Za-z0-9_$]+/).filter(Boolean);
2651
+ let identifier = words.map((word, index) => index === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1)).join('');
2652
+ if (!/^[A-Za-z_$]/.test(identifier)) identifier = `_${identifier}`;
2653
+ return `${identifier || '_'}Theme`;
2654
+ }
2655
+ /** @param {any[]} members */
2656
+ // prettier-ignore
2657
+ function allocateFamilyBindings(members) {
2658
+ const used = new Map();
2659
+ return new Map(members.map(member => { const base = familyThemeBinding(member.theme.name), count = used.get(base) ?? 0; used.set(base, count + 1); return [member.theme.name, count === 0 ? base : `${base}${count + 1}`]; }));
2660
+ }
2661
+ /** Rebase a scraped relative registry import to the aggregate module. @param {any} info @param {string} filePath @param {string} outDir @param {string | undefined} override */
2662
+ // prettier-ignore
2663
+ function familyRegistryInput(info, filePath, outDir, override) {
2664
+ if (!info || override !== undefined) return {info, specifier: override};
2665
+ const source = info.importPath;
2666
+ if (!source.startsWith('./') && !source.startsWith('../')) return {info, specifier: undefined};
2667
+ const absolute = path.resolve(path.dirname(filePath), source);
2668
+ let specifier = path.relative(outDir, absolute).split(path.sep).join('/');
2669
+ if (!specifier.startsWith('./') && !specifier.startsWith('../')) specifier = `./${specifier}`;
2670
+ return {info, specifier};
2671
+ }
2672
+ /** Dependency-first load plan including local barrels between selected files. @param {string[]} files @param {string} cwd */
2673
+ // prettier-ignore
2674
+ function planFamilySources(files, cwd) {
2675
+ /** @type {Array<{file: string, filePath: string}>} */ const entries = files.map(file => ({file, filePath: path.resolve(cwd, file)}));
2676
+ /** @param {string} value */ const canonical = value => fs.existsSync(value) ? fs.realpathSync(value) : path.resolve(value);
2677
+ /** @type {Map<string, {file: string, filePath: string}>} */ const selected = new Map(entries.map(entry => [canonical(entry.filePath), entry]));
2678
+ if (selected.size !== entries.length) return entries.map(entry => ({...entry, selected: true}));
2679
+ /** @type {Map<string, Set<string>>} */ const reachableMemo = new Map(), dependencies = new Map();
2680
+ /** @param {string} filePath @param {Set<string>} [visiting] @returns {Set<string>} */
2681
+ const reachableSelected = (filePath, visiting = new Set()) => {
2682
+ const key = canonical(filePath), cached = reachableMemo.get(key); if (cached) return cached;
2683
+ if (visiting.has(key) || !fs.existsSync(key)) return new Set();
2684
+ visiting.add(key); /** @type {Set<string>} */ const found = new Set(), direct = new Set(); let ast;
2685
+ try { ast = parse(fs.readFileSync(key, 'utf8'), {sourceType: 'unambiguous', plugins: ['typescript', 'jsx', 'decorators-legacy', 'importAttributes']}); }
2686
+ catch { visiting.delete(key); reachableMemo.set(key, found); return found; }
2687
+ for (const node of /** @type {any[]} */ (ast.program.body)) {
2688
+ const specifier = node.importKind !== 'type' ? node.source?.value : null; if (typeof specifier !== 'string' || (!specifier.startsWith('.') && !path.isAbsolute(specifier))) continue;
2689
+ let dependency; try { dependency = canonical(createJiti(key, {extensions: THEME_MODULE_EXTENSIONS}).resolve(specifier)); } catch { continue; }
2690
+ if (!dependency.split(path.sep).includes('node_modules') && /\.[cm]?[jt]sx?$/.test(dependency)) direct.add(dependency);
2691
+ if (selected.has(dependency)) found.add(dependency); else for (const nested of reachableSelected(dependency, visiting)) found.add(nested);
2692
+ }
2693
+ visiting.delete(key); dependencies.set(key, direct); reachableMemo.set(key, found); return found;
2694
+ };
2695
+ for (const entry of entries) reachableSelected(entry.filePath);
2696
+ /** @type {Array<{file: string, filePath: string, selected: boolean}>} */ const plan = []; /** @type {Set<string>} */ const marks = new Set();
2697
+ /** @param {string} key */ const visit = key => { if (marks.has(key)) return; marks.add(key); for (const dependency of dependencies.get(key) ?? []) if (selected.has(dependency) || reachableSelected(dependency).size > 0) visit(dependency); const entry = selected.get(key); plan.push(entry ? {...entry, selected: true} : {file: key, filePath: key, selected: false}); };
2698
+ for (const entry of entries) visit(canonical(entry.filePath)); return plan;
2699
+ }
2700
+
2701
+ /** Preload an intermediary module into the shared family cache. @param {string} filePath @param {any} loader @param {import('./core-interception.mjs').CoreInterception} interception */
2702
+ // prettier-ignore
2703
+ async function preloadFamilySource(filePath, loader, interception) {
2704
+ const patch = interception.patchCommonJs(filePath);
2705
+ try { try { loader(filePath); } catch (error) { if (!isSyncLoaderLimitation(error)) throw error; await loader.evalModule(fs.readFileSync(filePath, 'utf8'), {id: filePath, filename: filePath, ext: path.extname(filePath), cache: loader.cache, async: true, forceTranspile: true}); } }
2706
+ finally { patch.undo(); }
2707
+ }
2708
+
2709
+ /** @param {string[]} files @param {{familyKey: string, check?: boolean, iconsSpecifier?: string}} options @param {{cwd?: string}} [ctx] */
2710
+ export async function themeBuildFamily(
2711
+ files,
2712
+ options,
2713
+ {cwd = process.cwd()} = {},
2714
+ ) {
2715
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options?.familyKey ?? '')) {
2716
+ throw new AstryxError(
2717
+ 'Family key must be an exact lower-kebab filename stem (for example, ocean-family).',
2718
+ undefined,
2719
+ ERROR_CODES.ERR_THEME_INVALID,
2720
+ );
2721
+ }
2722
+ try {
2723
+ sanitizeName(options.familyKey, {label: 'family key'});
2724
+ } catch (error) {
2725
+ const message =
2726
+ error instanceof Error ? error.message : 'Invalid family key.';
2727
+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
2728
+ }
2729
+ const familyInterception = interceptCore(_coreThemeModule, _coreRootModule);
2730
+ // prettier-ignore
2731
+ const familyLoader = createJiti(import.meta.url, {moduleCache: true, interopDefault: false, jsx: true, extensions: THEME_MODULE_EXTENSIONS, virtualModules: familyInterception.modules});
2732
+ /** @type {any[]} */
2733
+ const prepared = [];
2734
+ for (const source of planFamilySources(files, cwd)) {
2735
+ if (!source.selected) {
2736
+ await preloadFamilySource(
2737
+ source.filePath,
2738
+ familyLoader,
2739
+ familyInterception,
2740
+ );
2741
+ continue;
2742
+ }
2743
+ const file = source.file;
2744
+ // prettier-ignore
2745
+ const member = await themeBuildInternal(file, {iconsSpecifier: options.iconsSpecifier, __prepareFamily: true, __familyLoader: familyLoader, __familyInterception: familyInterception}, {cwd});
2746
+ if (!member || member.type) {
2747
+ throw new AstryxError(
2748
+ `Theme family member "${file}" did not produce a complete build plan.`,
2749
+ undefined,
2750
+ ERROR_CODES.ERR_THEME_INVALID,
2751
+ );
2752
+ }
2753
+ prepared.push(member);
2754
+ }
2755
+ let members;
2756
+ try {
2757
+ members = resolveThemeFamily(prepared);
2758
+ } catch (error) {
2759
+ const message =
2760
+ error instanceof Error ? error.message : 'Invalid selected theme family.';
2761
+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
2762
+ }
2763
+ for (const member of members) {
2764
+ for (const [field, info] of [
2765
+ ['icons', member.iconInfo],
2766
+ ['indicators', member.indicatorInfo],
2767
+ ]) {
2768
+ const value = member.theme[field];
2769
+ const inherited = member.sourceParent?.[field];
2770
+ if (
2771
+ value &&
2772
+ Object.keys(value).length > 0 &&
2773
+ value !== inherited &&
2774
+ !info
2775
+ ) {
2776
+ throw new AstryxError(
2777
+ `Theme "${member.theme.name}" must supply ${field} through a named import for family output.`,
2778
+ undefined,
2779
+ ERROR_CODES.ERR_THEME_INVALID,
2780
+ );
2781
+ }
2782
+ }
2783
+ }
2784
+ const baseName = options.familyKey;
2785
+ if (members.some(member => member.theme.name === baseName)) {
2786
+ throw new AstryxError(
2787
+ `Family key "${baseName}" collides with a selected theme's standalone outputs. Choose a distinct filename stem.`,
2788
+ undefined,
2789
+ ERROR_CODES.ERR_THEME_INVALID,
2790
+ );
2791
+ }
2792
+ const root = members[0];
2793
+ const outDir = path.dirname(root.filePath);
2794
+ const outPath = path.join(outDir, `${baseName}.css`);
2795
+ const jsPath = path.join(outDir, `${baseName}.js`);
2796
+ const dtsPath = path.join(outDir, `${baseName}.d.ts`);
2797
+ const sources = new Set(
2798
+ members.flatMap(member =>
2799
+ [path.resolve(member.filePath), fs.realpathSync(member.filePath)].map(
2800
+ value => value.toLowerCase(),
2801
+ ),
2802
+ ),
2803
+ );
2804
+ const collision = [outPath, jsPath, dtsPath].find(output => {
2805
+ const candidates = [path.resolve(output)];
2806
+ if (fs.existsSync(output)) candidates.push(fs.realpathSync(output));
2807
+ return candidates.some(value => sources.has(value.toLowerCase()));
2808
+ });
2809
+ if (collision) {
2810
+ throw new AstryxError(
2811
+ `Family output ${path.relative(cwd, collision)} collides with a selected source file.`,
2812
+ undefined,
2813
+ ERROR_CODES.ERR_THEME_INVALID,
2814
+ );
2815
+ }
2816
+ const sourceRelative = members
2817
+ .map(member => member.sourceRelative)
2818
+ .join(', ');
2819
+ const buildCommand = `${getCliInvocation()} theme build --family ${members
2820
+ .map(member => member.sourceRelative)
2821
+ .join(' ')} --family-key ${baseName}`;
2822
+ const bindings = allocateFamilyBindings(members);
2823
+ const css = generateFamilyCSS(members);
2824
+ /** @type {Array<{specifier: string, exportName: string}>} */
2825
+ const registryImports = [];
2826
+ const js = members
2827
+ .map(member => {
2828
+ const themeBinding = bindings.get(member.theme.name);
2829
+ const parentBinding = member.parentName
2830
+ ? bindings.get(member.parentName)
2831
+ : null;
2832
+ // prettier-ignore
2833
+ const icon = familyRegistryInput(member.iconInfo, member.filePath, outDir, options.iconsSpecifier);
2834
+ // prettier-ignore
2835
+ const indicator = familyRegistryInput(member.indicatorInfo, member.filePath, outDir, undefined);
2836
+ // prettier-ignore
2837
+ for (const registry of [icon, indicator]) if (registry.info) registryImports.push({specifier: registry.specifier ?? registry.info.importPath, exportName: registry.info.exportName});
2838
+ const ownIcons = icon.info ? `${themeBinding}Icons` : null;
2839
+ const inheritedIcons = parentBinding ? `${parentBinding}.icons` : null;
2840
+ const ownIndicators = indicator.info ? `${themeBinding}Indicators` : null;
2841
+ const inheritedIndicators = parentBinding
2842
+ ? `${parentBinding}.indicators`
2843
+ : null;
2844
+ /** @param {string | null} own @param {string | null} inherited */
2845
+ const expression = (own, inherited) =>
2846
+ own && inherited
2847
+ ? `{...${inherited}, ...${own}}`
2848
+ : (own ?? inherited ?? undefined);
2849
+ const indicatorImport = indicator.info
2850
+ ? `import { ${indicator.info.exportName} as ${ownIndicators} } from ${JSON.stringify(indicator.specifier ?? indicator.info.importPath)};\n`
2851
+ : '';
2852
+ return (
2853
+ indicatorImport +
2854
+ generateBuiltModule(member.theme, icon.info, icon.specifier, {
2855
+ themeBinding,
2856
+ iconBinding: ownIcons ?? undefined,
2857
+ iconsExpression: expression(ownIcons, inheritedIcons),
2858
+ indicatorsExpression: expression(ownIndicators, inheritedIndicators),
2859
+ artifactBaseName: baseName,
2860
+ exportIcons: false,
2861
+ })
2862
+ );
2863
+ })
2864
+ .join('\n');
2865
+ await validateRegistryGraphs(registryImports, jsPath);
2866
+ const declarations = members
2867
+ .map((member, index) =>
2868
+ generateBuiltTypes(member.theme, member.iconInfo, null, {
2869
+ themeBinding: bindings.get(member.theme.name),
2870
+ includeIconExport: false,
2871
+ includeThemeImport: index === 0,
2872
+ }),
2873
+ )
2874
+ .join('');
2875
+ const augmentations = [
2876
+ ...new Set(members.map(member => member.variantDecl).filter(Boolean)),
2877
+ ].join('\n');
2878
+ const writes = [
2879
+ {
2880
+ dest: outPath,
2881
+ content:
2882
+ generatedHeader(sourceRelative, 'css', buildCommand, root.versions) +
2883
+ css,
2884
+ },
2885
+ {
2886
+ dest: jsPath,
2887
+ content:
2888
+ generatedHeader(sourceRelative, 'js', buildCommand, root.versions) + js,
2889
+ },
2890
+ {
2891
+ dest: dtsPath,
2892
+ content:
2893
+ generatedHeader(sourceRelative, 'ts', buildCommand, root.versions) +
2894
+ declarations +
2895
+ (augmentations ? `\n${augmentations}` : ''),
2896
+ },
2897
+ ];
2898
+ const outputs = {
2899
+ css: path.relative(cwd, outPath),
2900
+ js: path.relative(cwd, jsPath),
2901
+ dts: path.relative(cwd, dtsPath),
2902
+ };
2903
+ if (options.check) {
2904
+ const stale = staleBuildOutputs(writes, cwd);
2905
+ const upToDate = stale.length === 0;
2906
+ if (upToDate) {
2907
+ logger.log(
2908
+ `\n✓ Theme family outputs are up to date with ${sourceRelative}.`,
2909
+ );
2910
+ } else {
2911
+ logger.error(
2912
+ `\n✗ ${stale.length} theme family output(s) are out of date:`,
2913
+ );
2914
+ for (const entry of stale) {
2915
+ logger.error(
2916
+ ` ${entry.reason === 'missing' ? 'missing' : 'stale'}: ${entry.path}`,
2917
+ );
2918
+ }
2919
+ logger.error(`\n Rebuild with: ${buildCommand}`);
2920
+ }
2921
+ return {
2922
+ type: 'theme.build.check',
2923
+ data: {
2924
+ name: root.theme.name,
2925
+ upToDate,
2926
+ stale,
2927
+ checked: writes.map(write => path.relative(cwd, write.dest)),
2928
+ },
2929
+ };
2930
+ }
2931
+ writeBuildOutputs(writes);
2932
+ for (const output of Object.values(outputs)) logger.log(`✓ ${output}`);
2933
+ const themeBindings = members.map(member => bindings.get(member.theme.name));
2934
+ const relOutDir = path.relative(cwd, outDir) || '.';
2935
+ const jsImport = importSpecifier(relOutDir, baseName);
2936
+ const cssImport = `${jsImport}.css`;
2937
+ logger.log(`
2938
+ Load the family CSS once, then select any member by theme identity:
2939
+ import { ${themeBindings.join(', ')} } from '${jsImport}';
2940
+ import '${cssImport}';
2941
+ Or load the same stylesheet natively:
2942
+ <link rel="stylesheet" href="${cssImport}" />
2943
+ `);
2944
+ const warnings = [...new Set(members.flatMap(member => member.warnings))];
2945
+ const unloadedFonts = [
2946
+ ...new Set(members.flatMap(member => member.unloadedFonts)),
2947
+ ];
2948
+ const notices = unloadedFonts.map(
2949
+ family =>
2950
+ `Font "${family}" is named by this theme family but not loaded — add a <link> or @font-face in your app (recipe: astryx docs typography)`,
2951
+ );
2952
+ for (const notice of notices) logger.log(` note: ${notice}`);
2953
+ return {
2954
+ type: 'theme.build',
2955
+ data: {
2956
+ name: root.theme.name,
2957
+ tokenCount: members.reduce((sum, member) => sum + member.tokenCount, 0),
2958
+ componentCount: members.reduce(
2959
+ (sum, member) => sum + member.componentCount,
2960
+ 0,
2961
+ ),
2962
+ sizeKB: parseFloat((Buffer.byteLength(css) / 1024).toFixed(1)),
2963
+ outputs,
2964
+ warnings,
2965
+ notices,
2966
+ },
2967
+ };
2968
+ }