@astryxdesign/cli 0.7.5-canary.6906beb → 0.7.5-canary.70ea859

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.
@@ -27,6 +27,17 @@ describe('hook.detail leaf', () => {
27
27
  expect(Array.isArray(res.data.returns)).toBe(true);
28
28
  }, SLOW);
29
29
 
30
+ it('resolves useCombobox from the Selector entry point with its field props and the requirements it names', async () => {
31
+ const res = await detail('useCombobox', {cwd: REPO});
32
+ expect(res.data.importPath).toBe('@astryxdesign/core/Selector');
33
+ expect(res.data.returns.map(entry => entry.name)).toEqual(
34
+ expect.arrayContaining(['getFieldProps', 'getListboxProps', 'getOptionProps']),
35
+ );
36
+ expect(res.data.usage.accessibility?.map(entry => entry.requirement)).toEqual(
37
+ [1, 2, 3, 4, 5, 6, 7].map(n => `AST-075 FR${n}`),
38
+ );
39
+ }, SLOW);
40
+
30
41
  it('throws ERR_UNKNOWN_HOOK with fuzzy suggestions for an unknown hook', async () => {
31
42
  let err;
32
43
  try {
@@ -0,0 +1,499 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Built themes carry function icon entries and resolve them as runtime.
5
+ * @input Real themeBuild and themeBuildFamily calls on source themes whose icon
6
+ * registries hold functions of `{size, variant}` and that list icon variants:
7
+ * a child under a replaced list, a theme extending a built module, a theme
8
+ * extending a package theme, and a family.
9
+ * @output Native ESM loads that render `<Icon>` for every request a theme's
10
+ * entries can receive under the built and the runtime theme, read the public
11
+ * icon views, and a TypeScript program that extends a built theme.
12
+ * @position `architecture:theme-compilation` INV15 and `spec:AST-087` FR3,
13
+ * FR18, and FR19 for theme build. The node project's global setup supplies
14
+ * the compiled core package.
15
+ */
16
+
17
+ import {afterEach, beforeEach, describe, expect, it} from 'vitest';
18
+ import {execFileSync} from 'node:child_process';
19
+ import * as fs from 'node:fs';
20
+ import * as path from 'node:path';
21
+ import ts from 'typescript';
22
+ import {themeBuild, themeBuildFamily} from './build.mjs';
23
+
24
+ const SIZES = ['xsm', 'sm', 'md', 'lg'];
25
+
26
+ let tmpDir;
27
+ beforeEach(() => {
28
+ // Under the CLI package, so core, React, and TypeScript resolve both in the
29
+ // theme loader and in the native artifact checks.
30
+ tmpDir = fs.mkdtempSync(
31
+ path.resolve(import.meta.dirname, '../../..', '.tmp-icon-functions-'),
32
+ );
33
+ });
34
+ afterEach(() => {
35
+ fs.rmSync(tmpDir, {recursive: true, force: true});
36
+ });
37
+
38
+ /** @param {string} file @param {string} source */
39
+ function write(file, source) {
40
+ fs.mkdirSync(path.dirname(path.join(tmpDir, file)), {recursive: true});
41
+ fs.writeFileSync(path.join(tmpDir, file), source);
42
+ }
43
+
44
+ /** A registry module whose function entries label what they were asked for. */
45
+ function writeRegistry(file, exportName, entries) {
46
+ write(
47
+ file,
48
+ `import {createElement} from 'react';
49
+ const draw = label => ({size, variant}) =>
50
+ createElement('svg', {'data-icon': label + ':' + size + ':' + (variant ?? 'normal')});
51
+ export const ${exportName} = {
52
+ ${Object.entries(entries)
53
+ .map(([key, label]) =>
54
+ label.startsWith('node:')
55
+ ? ` ${JSON.stringify(key)}: createElement('svg', {'data-icon': ${JSON.stringify(label.slice(5))}}),`
56
+ : ` ${JSON.stringify(key)}: draw(${JSON.stringify(label)}),`,
57
+ )
58
+ .join('\n')}
59
+ };
60
+ `,
61
+ );
62
+ }
63
+
64
+ /** The base, its child under a replaced list, and their registries. */
65
+ function writeLineage() {
66
+ writeRegistry('base/icons.mjs', 'baseIcons', {
67
+ info: 'base-info',
68
+ close: 'base-close',
69
+ check: 'node:base-check',
70
+ 'parity:mark': 'base-mark',
71
+ });
72
+ write(
73
+ 'base/source.mjs',
74
+ `import {defineTheme} from '@astryxdesign/core/theme';
75
+ import {baseIcons} from './icons.mjs';
76
+ export const baseTheme = defineTheme({
77
+ name: 'parity-base', tokens: {}, iconVariants: ['outline', 'filled'], icons: baseIcons,
78
+ });
79
+ export default baseTheme;
80
+ `,
81
+ );
82
+ writeRegistry('child/icons.mjs', 'childIcons', {
83
+ close: 'child-close',
84
+ menu: 'child-menu',
85
+ });
86
+ write(
87
+ 'child/source.mjs',
88
+ `import {defineTheme} from '@astryxdesign/core/theme';
89
+ import {baseTheme} from '../base/source.mjs';
90
+ import {childIcons} from './icons.mjs';
91
+ export const childTheme = defineTheme({
92
+ name: 'parity-child', extends: baseTheme, tokens: {},
93
+ iconVariants: ['filled', 'bold'], icons: childIcons,
94
+ });
95
+ export default childTheme;
96
+ `,
97
+ );
98
+ }
99
+
100
+ /** @param {string} file */
101
+ async function buildAndCheck(file) {
102
+ const built = await themeBuild(file, {}, {cwd: tmpDir});
103
+ expect(built?.type).toBe('theme.build');
104
+ const checked = await themeBuild(file, {check: true}, {cwd: tmpDir});
105
+ expect(checked?.data.upToDate).toBe(true);
106
+ return built;
107
+ }
108
+
109
+ /**
110
+ * Load built and runtime themes with native Node and report, for each pair,
111
+ * what `<Icon>` renders for every request and what the public reads return.
112
+ * The requests are every key a theme draws × the four sizes × no variant and
113
+ * each name any theme here lists, so unlisted names are covered too.
114
+ *
115
+ * @param {Array<{label: string, built: string, runtime: string}>} pairs -
116
+ * Module specifiers with `#export` suffixes, relative to the fixture root.
117
+ */
118
+ function inspect(pairs) {
119
+ const load = specifier => {
120
+ const [file, name] = specifier.split('#');
121
+ return `(await import(${JSON.stringify(file)}))[${JSON.stringify(name)}]`;
122
+ };
123
+ const output = execFileSync(
124
+ process.execPath,
125
+ [
126
+ '--input-type=module',
127
+ '--eval',
128
+ `import {createElement, isValidElement} from 'react';
129
+ import {renderToStaticMarkup} from 'react-dom/server';
130
+ import {Icon, getIcon, getIconRegistry} from '@astryxdesign/core/Icon';
131
+ import {Theme} from '@astryxdesign/core/theme';
132
+ const SIZES = ${JSON.stringify(SIZES)};
133
+ const VARIANTS = [undefined, 'outline', 'filled', 'bold'];
134
+ const label = node => {
135
+ if (node == null) return null;
136
+ if (!isValidElement(node)) return 'not-a-node:' + typeof node;
137
+ return node.props['data-icon'];
138
+ };
139
+ const rendered = (theme, icon, size, variant) => {
140
+ const html = renderToStaticMarkup(
141
+ createElement(Theme, {theme}, createElement(Icon, {icon, size, variant})),
142
+ );
143
+ return /data-icon="([^"]+)"/.exec(html)?.[1] ?? null;
144
+ };
145
+ const describe = theme => {
146
+ const keys = Object.keys(theme.icons ?? {}).sort();
147
+ const requests = {};
148
+ for (const key of keys) {
149
+ for (const size of SIZES) {
150
+ for (const variant of VARIANTS) {
151
+ requests[key + '|' + size + '|' + (variant ?? '-')] = rendered(theme, key, size, variant);
152
+ }
153
+ }
154
+ }
155
+ return {
156
+ keys,
157
+ requests,
158
+ icons: Object.fromEntries(keys.map(key => [key, label(theme.icons[key])])),
159
+ getIcon: Object.fromEntries(keys.map(key => [key, label(getIcon(key, theme))])),
160
+ registry: Object.fromEntries(
161
+ Object.entries(getIconRegistry(theme))
162
+ .filter(([key]) => keys.includes(key))
163
+ .map(([key, node]) => [key, label(node)]),
164
+ ),
165
+ iconVariants: theme.iconVariants ?? null,
166
+ };
167
+ };
168
+ const result = {};
169
+ ${pairs
170
+ .map(
171
+ ({label, built, runtime}) => `{
172
+ const built = ${load(built)};
173
+ const runtime = ${load(runtime)};
174
+ const mod = await import(${JSON.stringify(built.split('#')[0])});
175
+ const reexports = Object.entries(mod).filter(([name]) => name !== ${JSON.stringify(built.split('#')[1])});
176
+ result[${JSON.stringify(label)}] = {
177
+ built: describe(built),
178
+ runtime: describe(runtime),
179
+ reexportIsNodeView: reexports.length === 0 ? null : reexports.every(([, value]) => value === built.icons),
180
+ };
181
+ }`,
182
+ )
183
+ .join('\n')}
184
+ process.stdout.write(JSON.stringify(result));`,
185
+ ],
186
+ {cwd: tmpDir, encoding: 'utf8', timeout: 60000},
187
+ );
188
+ return JSON.parse(output);
189
+ }
190
+
191
+ describe('built themes keep function icon entries', () => {
192
+ it('resolve every request as the runtime theme does, including an inherited entry under a replaced list', async () => {
193
+ writeLineage();
194
+ await buildAndCheck('base/source.mjs');
195
+ await buildAndCheck('child/source.mjs');
196
+ // A grandchild extends the BUILT child module.
197
+ write(
198
+ 'grandchild/source.mjs',
199
+ `import {defineTheme} from '@astryxdesign/core/theme';
200
+ import {parityChildTheme} from '../child/parity-child.js';
201
+ export default defineTheme({name: 'parity-grandchild', extends: parityChildTheme, tokens: {}});
202
+ `,
203
+ );
204
+ await buildAndCheck('grandchild/source.mjs');
205
+
206
+ const result = inspect([
207
+ {
208
+ label: 'base',
209
+ built: './base/parity-base.js#parityBaseTheme',
210
+ runtime: './base/source.mjs#default',
211
+ },
212
+ {
213
+ label: 'child',
214
+ built: './child/parity-child.js#parityChildTheme',
215
+ runtime: './child/source.mjs#default',
216
+ },
217
+ {
218
+ label: 'grandchild',
219
+ built: './grandchild/parity-grandchild.js#parityGrandchildTheme',
220
+ runtime: './grandchild/source.mjs#default',
221
+ },
222
+ ]);
223
+
224
+ for (const {built, runtime, reexportIsNodeView} of Object.values(result)) {
225
+ // INV15: built resolution and public views match runtime.
226
+ expect(built).toEqual(runtime);
227
+ expect(reexportIsNodeView).not.toBe(false);
228
+ }
229
+
230
+ const child = result.child.built;
231
+ expect(child.keys).toEqual([
232
+ 'check',
233
+ 'close',
234
+ 'info',
235
+ 'menu',
236
+ 'parity:mark',
237
+ ]);
238
+ for (const size of SIZES) {
239
+ // The child's own entry receives the names the child lists.
240
+ expect(child.requests[`close|${size}|bold`]).toBe(
241
+ `child-close:${size}:bold`,
242
+ );
243
+ expect(child.requests[`close|${size}|filled`]).toBe(
244
+ `child-close:${size}:filled`,
245
+ );
246
+ expect(child.requests[`close|${size}|outline`]).toBe(
247
+ `child-close:${size}:normal`,
248
+ );
249
+ // The inherited entry keeps its defining theme's list: 'outline' is no
250
+ // longer listed by the child, and the base never listed 'bold'.
251
+ expect(child.requests[`info|${size}|filled`]).toBe(
252
+ `base-info:${size}:filled`,
253
+ );
254
+ expect(child.requests[`info|${size}|outline`]).toBe(
255
+ `base-info:${size}:normal`,
256
+ );
257
+ expect(child.requests[`info|${size}|bold`]).toBe(
258
+ `base-info:${size}:normal`,
259
+ );
260
+ expect(child.requests[`info|${size}|-`]).toBe(`base-info:${size}:normal`);
261
+ // A node entry renders the same node for every request.
262
+ expect(child.requests[`check|${size}|filled`]).toBe('base-check');
263
+ }
264
+ expect(result.grandchild.built.requests).toEqual(child.requests);
265
+
266
+ // FR18: public reads are React nodes, each function read at md.
267
+ expect(child.icons).toEqual({
268
+ check: 'base-check',
269
+ close: 'child-close:md:normal',
270
+ info: 'base-info:md:normal',
271
+ menu: 'child-menu:md:normal',
272
+ 'parity:mark': 'base-mark:md:normal',
273
+ });
274
+ expect(child.getIcon).toEqual(child.icons);
275
+ expect(child.registry).toEqual({
276
+ check: 'base-check',
277
+ close: 'child-close:md:normal',
278
+ info: 'base-info:md:normal',
279
+ menu: 'child-menu:md:normal',
280
+ });
281
+ expect(result.base.reexportIsNodeView).toBe(true);
282
+ expect(result.child.reexportIsNodeView).toBe(true);
283
+ });
284
+
285
+ it('keeps the function entries of a package theme it extends', async () => {
286
+ const pkg = 'node_modules/@fixture/function-icons';
287
+ write(
288
+ `${pkg}/package.json`,
289
+ JSON.stringify({
290
+ name: '@fixture/function-icons',
291
+ type: 'module',
292
+ exports: './index.mjs',
293
+ }),
294
+ );
295
+ writeRegistry(`${pkg}/icons.mjs`, 'packageIcons', {info: 'package-info'});
296
+ write(
297
+ `${pkg}/index.mjs`,
298
+ `import {defineTheme} from '@astryxdesign/core/theme';
299
+ import {packageIcons} from './icons.mjs';
300
+ export const packageTheme = defineTheme({
301
+ name: 'parity-package', tokens: {}, iconVariants: ['filled'], icons: packageIcons,
302
+ });
303
+ `,
304
+ );
305
+ write(
306
+ 'package-child.mjs',
307
+ `import {defineTheme} from '@astryxdesign/core/theme';
308
+ import {packageTheme} from '@fixture/function-icons';
309
+ export default defineTheme({name: 'parity-package-child', extends: packageTheme, tokens: {}});
310
+ `,
311
+ );
312
+ await buildAndCheck('package-child.mjs');
313
+
314
+ const {packageChild} = inspect([
315
+ {
316
+ label: 'packageChild',
317
+ built: './parity-package-child.js#parityPackageChildTheme',
318
+ runtime: './package-child.mjs#default',
319
+ },
320
+ ]);
321
+
322
+ expect(packageChild.built).toEqual(packageChild.runtime);
323
+ for (const size of SIZES) {
324
+ expect(packageChild.built.requests[`info|${size}|filled`]).toBe(
325
+ `package-info:${size}:filled`,
326
+ );
327
+ }
328
+ expect(packageChild.built.icons).toEqual({info: 'package-info:md:normal'});
329
+ });
330
+
331
+ it('keeps function entries in a family build', async () => {
332
+ writeLineage();
333
+ // A member that sets no icons of its own inherits the child's entries.
334
+ write(
335
+ 'inherit/source.mjs',
336
+ `import {defineTheme} from '@astryxdesign/core/theme';
337
+ import {childTheme} from '../child/source.mjs';
338
+ export default defineTheme({name: 'parity-inherit', extends: childTheme, tokens: {}});
339
+ `,
340
+ );
341
+ const receipt = await themeBuildFamily(
342
+ ['base/source.mjs', 'child/source.mjs', 'inherit/source.mjs'],
343
+ {familyKey: 'parity-family'},
344
+ {cwd: tmpDir},
345
+ );
346
+ expect(receipt?.type).toBe('theme.build');
347
+ const familyModule = `./${receipt.data.outputs.js}`;
348
+
349
+ const result = inspect([
350
+ {
351
+ label: 'base',
352
+ built: `${familyModule}#parityBaseTheme`,
353
+ runtime: './base/source.mjs#default',
354
+ },
355
+ {
356
+ label: 'child',
357
+ built: `${familyModule}#parityChildTheme`,
358
+ runtime: './child/source.mjs#default',
359
+ },
360
+ {
361
+ label: 'inherit',
362
+ built: `${familyModule}#parityInheritTheme`,
363
+ runtime: './inherit/source.mjs#default',
364
+ },
365
+ ]);
366
+
367
+ expect(result.base.built).toEqual(result.base.runtime);
368
+ expect(result.child.built).toEqual(result.child.runtime);
369
+ expect(result.inherit.built).toEqual(result.inherit.runtime);
370
+ expect(result.inherit.built.requests).toEqual(result.child.built.requests);
371
+ expect(result.child.built.requests['info|sm|filled']).toBe(
372
+ 'base-info:sm:filled',
373
+ );
374
+ expect(result.child.built.requests['info|sm|outline']).toBe(
375
+ 'base-info:sm:normal',
376
+ );
377
+ });
378
+ });
379
+
380
+ describe('the node view never captures a registry binding', () => {
381
+ it.each(['entries', 'nodes', 'name', 'entry', 'Object'])(
382
+ 'loads a built theme whose registry is imported as `%s`',
383
+ async binding => {
384
+ writeRegistry('icons.mjs', 'registry', {info: 'bound-info'});
385
+ write(
386
+ 'bound.mjs',
387
+ `import {defineTheme} from '@astryxdesign/core/theme';
388
+ import {registry as ${binding}} from './icons.mjs';
389
+ export default defineTheme({
390
+ name: 'bound', tokens: {}, iconVariants: ['filled'], icons: ${binding},
391
+ });
392
+ `,
393
+ );
394
+ await buildAndCheck('bound.mjs');
395
+
396
+ const {bound} = inspect([
397
+ {
398
+ label: 'bound',
399
+ built: './bound.js#boundTheme',
400
+ runtime: './bound.mjs#default',
401
+ },
402
+ ]);
403
+ expect(bound.built).toEqual(bound.runtime);
404
+ expect(bound.built.icons).toEqual({info: 'bound-info:md:normal'});
405
+ expect(bound.built.requests['info|lg|filled']).toBe(
406
+ 'bound-info:lg:filled',
407
+ );
408
+ expect(bound.reexportIsNodeView).toBe(true);
409
+ },
410
+ );
411
+ });
412
+
413
+ describe('a built theme types its icon variants', () => {
414
+ it('lets a theme extending the built module type `variant` by its list', async () => {
415
+ writeLineage();
416
+ await buildAndCheck('base/source.mjs');
417
+
418
+ const variants = fs.readFileSync(
419
+ path.join(tmpDir, 'base/parity-base.variants.d.ts'),
420
+ 'utf8',
421
+ );
422
+ expect(variants).toContain("declare module '@astryxdesign/core/Icon'");
423
+ expect(variants).toContain("'outline': true;");
424
+ expect(variants).toContain("'filled': true;");
425
+
426
+ write(
427
+ 'consumer.ts',
428
+ `import {defineTheme} from '@astryxdesign/core/theme';
429
+ import type {IconVariant} from '@astryxdesign/core/Icon';
430
+ import {parityBaseTheme} from './base/parity-base.js';
431
+
432
+ type Equal<A, B> =
433
+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
434
+
435
+ defineTheme({
436
+ name: 'consumer',
437
+ extends: parityBaseTheme,
438
+ icons: {
439
+ info: ({variant}) => {
440
+ const exact: Equal<typeof variant, 'outline' | 'filled' | undefined> = true;
441
+ return exact ? null : null;
442
+ },
443
+ // @ts-expect-error -- 'bold' is not a name the built theme lists.
444
+ close: ({variant}) => (variant === 'bold' ? null : null),
445
+ },
446
+ });
447
+
448
+ // The built theme's augmentation adds its names to IconVariant.
449
+ export const listed: IconVariant = 'filled';
450
+ // @ts-expect-error -- no theme here lists 'bold'.
451
+ export const unlisted: IconVariant = 'bold';
452
+ `,
453
+ );
454
+ const program = ts.createProgram([path.join(tmpDir, 'consumer.ts')], {
455
+ strict: true,
456
+ noEmit: true,
457
+ skipLibCheck: true,
458
+ target: ts.ScriptTarget.ES2022,
459
+ module: ts.ModuleKind.ESNext,
460
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
461
+ types: [],
462
+ });
463
+ const diagnostics = ts
464
+ .getPreEmitDiagnostics(program)
465
+ .filter(diagnostic => diagnostic.file?.fileName.endsWith('consumer.ts'))
466
+ .map(diagnostic =>
467
+ ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
468
+ );
469
+ expect(diagnostics).toEqual([]);
470
+ });
471
+ });
472
+
473
+ describe('a function the build cannot carry fails the build', () => {
474
+ it.each([
475
+ [
476
+ 'an inline function entry',
477
+ `icons: {info: ({size}) => createElement('svg', {'data-size': size})}`,
478
+ ],
479
+ [
480
+ 'a function beside a spread registry',
481
+ `icons: {...baseIcons, info: () => null}`,
482
+ ],
483
+ ])('rejects %s before writing', async (_label, iconsField) => {
484
+ writeRegistry('icons.mjs', 'baseIcons', {close: 'base-close'});
485
+ write(
486
+ 'inline.mjs',
487
+ `import {createElement} from 'react';
488
+ import {defineTheme} from '@astryxdesign/core/theme';
489
+ import {baseIcons} from './icons.mjs';
490
+ export default defineTheme({name: 'inline-functions', tokens: {}, ${iconsField}});
491
+ `,
492
+ );
493
+
494
+ await expect(
495
+ themeBuild('inline.mjs', {}, {cwd: tmpDir}),
496
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
497
+ expect(fs.readdirSync(tmpDir).sort()).toEqual(['icons.mjs', 'inline.mjs']);
498
+ });
499
+ });
@@ -12,8 +12,10 @@
12
12
  * build emits the exact CSS the `<Theme>` runtime does), writes:
13
13
  * - A CSS file with token overrides and component styles
14
14
  * - A CSS declaration module for strict side-effect imports
15
- * - A JS module that re-exports the built theme (+ icon registry)
16
- * - A .d.ts (plus an optional .variants.d.ts for custom prop values)
15
+ * - A JS module that re-exports the built theme (+ icon registry); function
16
+ * icon entries stay functions for `Icon`, beside a node view of the registry
17
+ * - A .d.ts (plus an optional .variants.d.ts for custom prop values and the
18
+ * theme's icon variant names)
17
19
  *
18
20
  * It performs the writes and returns a `theme.build` receipt — its `warnings`
19
21
  * carry override problems and every declaration core's generator dropped
@@ -306,7 +308,9 @@ function realLocation(target) {
306
308
  * Core, so building with it keeps the CSS identical; and a CLI run one-off
307
309
  * (`npx @astryxdesign/cli`) has no Core beside it at all. Null when there is
308
310
  * nothing better than the CLI's own import: no installed Core (the Astryx
309
- * repository, a bare directory), the same Core, or one that does not load.
311
+ * repository, a bare directory) or the same Core. A Core that is there but
312
+ * does not load, or lacks the functions the build calls, throws, naming it:
313
+ * building with another Core would not match the app's `<Theme>`.
310
314
  *
311
315
  * @param {string} cwd
312
316
  * @param {CoreBindings} cliCore - The CLI's own Core, from {@link loadCliCore}.
@@ -316,29 +320,36 @@ function realLocation(target) {
316
320
  */
317
321
  async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
318
322
  // Outside a project, the Core the answering copy carries (spec AST-081 FR3).
319
- const dir =
320
- findInstalledPackage(cwd, '@astryxdesign/core') ??
321
- (projectOnly ? null : fetchCarriedThemeCoreDir(cwd));
323
+ const installed = findInstalledPackage(cwd, '@astryxdesign/core');
324
+ const dir = installed ?? (projectOnly ? null : fetchCarriedThemeCoreDir(cwd));
322
325
  const themeFile = dir ? importTarget(dir, './theme') : null;
323
326
  if (!dir || !themeFile) return null;
324
327
  if (cliCore.themeModule) {
325
- try {
326
- const own = fileURLToPath(
327
- import.meta.resolve('@astryxdesign/core/theme'),
328
- );
329
- if (realOrSelf(own) === realOrSelf(themeFile)) return null;
330
- } catch {
331
- // The CLI's own Core cannot be located; load the project's.
332
- }
328
+ const own = cliCoreThemeFile();
329
+ if (own != null && realOrSelf(own) === realOrSelf(themeFile)) return null;
333
330
  }
334
331
  let themeModule;
335
332
  try {
336
333
  themeModule = await import(pathToFileURL(themeFile).href);
337
- } catch {
338
- return null;
334
+ } catch (error) {
335
+ throw new AstryxError(
336
+ installed == null
337
+ ? carriedCoreMessage(dir, /** @type {Error} */ (error))
338
+ : coreUnavailableMessage(cwd, /** @type {Error} */ (error)),
339
+ undefined,
340
+ ERROR_CODES.ERR_CORE_NOT_FOUND,
341
+ );
342
+ }
343
+ const missing = ['defineTheme', 'generateThemeRulesSplit'].filter(
344
+ name => typeof themeModule[name] !== 'function',
345
+ );
346
+ if (missing.length > 0) {
347
+ throw new AstryxError(
348
+ `The @astryxdesign/core at ${path.relative(cwd, dir) || '.'} does not export ${missing.join(' or ')} from its \`./theme\` entry, which \`${formatCliCommand('theme build')}\` calls. Update it.`,
349
+ undefined,
350
+ ERROR_CODES.ERR_CORE_INCOMPATIBLE,
351
+ );
339
352
  }
340
- if (!themeModule.defineTheme || !themeModule.generateThemeRulesSplit)
341
- return null;
342
353
  let rootModule = null;
343
354
  const rootFile = importTarget(dir, '.');
344
355
  if (rootFile) {
@@ -359,6 +370,40 @@ async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
359
370
  };
360
371
  }
361
372
 
373
+ /**
374
+ * The file the CLI's own `@astryxdesign/core/theme` resolves to, or null when
375
+ * the CLI has no Core of its own (a one-off `npx` run).
376
+ * @returns {string | null}
377
+ */
378
+ function cliCoreThemeFile() {
379
+ try {
380
+ return fileURLToPath(import.meta.resolve('@astryxdesign/core/theme'));
381
+ } catch (error) {
382
+ const {code} = /** @type {NodeJS.ErrnoException} */ (error);
383
+ if (
384
+ code === 'ERR_MODULE_NOT_FOUND' ||
385
+ code === 'ERR_PACKAGE_PATH_NOT_EXPORTED'
386
+ ) {
387
+ return null;
388
+ }
389
+ throw error;
390
+ }
391
+ }
392
+
393
+ /**
394
+ * The error for a Core the answering copy carries (outside a project) that
395
+ * does not load.
396
+ * @param {string} dir
397
+ * @param {Error} importError
398
+ * @returns {string}
399
+ */
400
+ function carriedCoreMessage(dir, importError) {
401
+ return (
402
+ `Could not load the @astryxdesign/core this CLI release carries, at ${dir}.` +
403
+ `\n Import error: ${importError.message}`
404
+ );
405
+ }
406
+
362
407
  /** @type {Map<string, Awaited<ReturnType<typeof loadProjectCore>>>} */
363
408
  const _projectCores = new Map();
364
409
 
@@ -379,7 +424,7 @@ async function selectCore(cwd, {projectOnly = false} = {}) {
379
424
  // A global or cached copy's own Core is the carried one.
380
425
  if (projectOnly && !projectCore && carriesCore() && !cliCoreIsProjects(cwd)) {
381
426
  throw new AstryxError(
382
- "The project's Core isn't installed or does not load.",
427
+ "The project's Core isn't installed.",
383
428
  undefined,
384
429
  ERROR_CODES.ERR_CORE_NOT_FOUND,
385
430
  );
@@ -405,13 +450,11 @@ function carriesCore() {
405
450
  function cliCoreIsProjects(cwd) {
406
451
  const dir = findProjectCoreDir(cwd);
407
452
  if (!dir) return false;
408
- try {
409
- const own = fileURLToPath(import.meta.resolve('@astryxdesign/core/theme'));
410
- const theirs = importTarget(dir, './theme');
411
- return theirs != null && realOrSelf(own) === realOrSelf(theirs);
412
- } catch {
413
- return false;
414
- }
453
+ const own = cliCoreThemeFile();
454
+ const theirs = importTarget(dir, './theme');
455
+ return (
456
+ own != null && theirs != null && realOrSelf(own) === realOrSelf(theirs)
457
+ );
415
458
  }
416
459
 
417
460
  /**
@@ -1536,12 +1579,21 @@ async function validateAdaptationEnrollment(themeDef) {
1536
1579
  * generating a `declare module` block for them would be dead code — those are
1537
1580
  * skipped.
1538
1581
  *
1539
- * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef - Theme definition (resolved by defineTheme)
1582
+ * A theme that lists `iconVariants` also augments `IconVariantMap` in
1583
+ * `@astryxdesign/core/Icon` with those names, when the installed core declares
1584
+ * it, so `<Icon variant>` accepts them (spec:AST-087 FR3).
1585
+ *
1586
+ * @param {{components?: Record<string, Record<string, Record<string, unknown>>>, iconVariants?: readonly string[]}} themeDef - Theme definition (resolved by defineTheme)
1540
1587
  * @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed
1541
1588
  */
1542
1589
  async function generateVariantDeclarationsAsync(themeDef) {
1543
1590
  const componentLayers = getThemeComponentLayers(themeDef);
1544
- if (componentLayers.length === 0) {
1591
+ const iconVariantNames =
1592
+ Array.isArray(themeDef.iconVariants) &&
1593
+ componentHasAugmentableInterface('Icon', 'IconVariantMap')
1594
+ ? [...new Set(themeDef.iconVariants)]
1595
+ : [];
1596
+ if (componentLayers.length === 0 && iconVariantNames.length === 0) {
1545
1597
  return null;
1546
1598
  }
1547
1599
 
@@ -1577,7 +1629,7 @@ async function generateVariantDeclarationsAsync(themeDef) {
1577
1629
  const hasCustom = Object.values(customValues).some(props =>
1578
1630
  Object.values(props).some(values => values.size > 0),
1579
1631
  );
1580
- if (!hasCustom) return null;
1632
+ if (!hasCustom && iconVariantNames.length === 0) return null;
1581
1633
 
1582
1634
  const sections = ['// Generated by astryx theme build', 'export {};', ''];
1583
1635
 
@@ -1617,6 +1669,17 @@ async function generateVariantDeclarationsAsync(themeDef) {
1617
1669
  }
1618
1670
  }
1619
1671
 
1672
+ if (iconVariantNames.length > 0) {
1673
+ sections.push(`declare module '@astryxdesign/core/Icon' {`);
1674
+ sections.push(' interface IconVariantMap {');
1675
+ for (const name of iconVariantNames) {
1676
+ sections.push(` ${tsStringLiteral(name)}: true;`);
1677
+ }
1678
+ sections.push(' }');
1679
+ sections.push('}');
1680
+ sections.push('');
1681
+ }
1682
+
1620
1683
  // If every custom value targeted a non-augmentable prop, there's nothing to
1621
1684
  // emit beyond the header — return null so no `.variants.d.ts` is written.
1622
1685
  const hasEmittedAugmentation = sections.some(line =>
@@ -2057,6 +2120,53 @@ function extractRegistryInfo(filePath, field) {
2057
2120
  return null;
2058
2121
  }
2059
2122
 
2123
+ /**
2124
+ * Whether a theme's icon entries include a function of `{size, variant}`.
2125
+ * @param {Record<string, unknown> | null | undefined} entries
2126
+ * @returns {boolean}
2127
+ */
2128
+ function hasFunctionIconEntry(entries) {
2129
+ return Object.values(entries ?? {}).some(
2130
+ entry => typeof entry === 'function',
2131
+ );
2132
+ }
2133
+
2134
+ /**
2135
+ * A built theme's icon entries: a theme from defineTheme keeps them in
2136
+ * `__icons` when any is a function (its `icons` is the node view); otherwise
2137
+ * `icons` holds them.
2138
+ * @param {any} theme
2139
+ * @returns {Record<string, unknown> | undefined}
2140
+ */
2141
+ function themeIconEntries(theme) {
2142
+ return theme?.__icons ?? theme?.icons;
2143
+ }
2144
+
2145
+ /**
2146
+ * The generated code that reads a registry's entries as React nodes, each
2147
+ * function entry read at `{size: 'md'}` like core's public reads. It never
2148
+ * passes the registry to a call, so a theme extending the built module can
2149
+ * still trace the registry through its `__icons` field, and it reads no
2150
+ * global, which a registry import could shadow. The registry expression runs
2151
+ * where only `entriesName` and `nodesName` are declared, both names the
2152
+ * registry imports cannot use.
2153
+ * @param {string} entries - Expression for the registry's entries.
2154
+ * @param {string} entriesName - A reserved local name.
2155
+ * @param {string} nodesName - A reserved local name.
2156
+ * @returns {string}
2157
+ */
2158
+ function iconNodesExpression(entries, entriesName, nodesName) {
2159
+ return `(() => {
2160
+ const ${entriesName} = ${entries};
2161
+ const ${nodesName} = {};
2162
+ for (const name in ${entriesName}) {
2163
+ const entry = ${entriesName}[name];
2164
+ ${nodesName}[name] = typeof entry === 'function' ? entry({size: 'md'}) : entry;
2165
+ }
2166
+ return ${nodesName};
2167
+ })()`;
2168
+ }
2169
+
2060
2170
  /**
2061
2171
  * Generate a minimal JS module for a built theme.
2062
2172
  * Includes the theme name, marker, and re-exports the icon registry.
@@ -2078,6 +2188,11 @@ function extractRegistryInfo(filePath, field) {
2078
2188
  * not given, direct registry specifiers are preserved, and inherited relative
2079
2189
  * imports are rebased from the base module to the theme entry's directory.
2080
2190
  *
2191
+ * When an icon entry is a function of `{size, variant}`, the module keeps the
2192
+ * registry as `__icons`, which `Icon` resolves at the size and variant it
2193
+ * renders, and the theme's `icons` and the re-exported registry are the node
2194
+ * view, each function read at `{size: 'md'}` as `DefinedTheme['icons']` is.
2195
+ *
2081
2196
  * @param {any} themeDef
2082
2197
  * @param {import('./icon-imports.mjs').IconImports | null} iconInfo
2083
2198
  * @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
@@ -2126,12 +2241,28 @@ function generateBuiltModule(
2126
2241
  ? `const ${iconInfo.exportName} = ${iconInfo.expression};\n`
2127
2242
  : '';
2128
2243
  const iconsExpression = moduleOptions.iconsExpression ?? iconInfo?.exportName;
2129
- const iconsField = iconsExpression ? ` icons: ${iconsExpression},` : '';
2244
+ const iconNodes =
2245
+ iconsExpression && hasFunctionIconEntry(themeIconEntries(themeDef))
2246
+ ? `${themeBinding}IconNodes`
2247
+ : null;
2248
+ const iconNodesDeclaration =
2249
+ iconNodes && iconsExpression
2250
+ ? `const ${iconNodes} = ${iconNodesExpression(iconsExpression, `${themeBinding}IconEntries`, iconNodes)};\n`
2251
+ : '';
2252
+ const iconsField = iconNodes
2253
+ ? ` icons: ${iconNodes},\n __icons: ${iconsExpression},`
2254
+ : iconsExpression
2255
+ ? ` icons: ${iconsExpression},`
2256
+ : '';
2130
2257
  const indicatorsField = moduleOptions.indicatorsExpression
2131
2258
  ? `\n indicators: ${moduleOptions.indicatorsExpression},`
2132
2259
  : '';
2133
2260
  const iconReExport =
2134
- iconInfo && exportIcons ? `\nexport { ${iconInfo.exportName} };\n` : '';
2261
+ iconInfo && exportIcons
2262
+ ? iconNodes
2263
+ ? `\nexport { ${iconNodes} as ${iconInfo.exportName} };\n`
2264
+ : `\nexport { ${iconInfo.exportName} };\n`
2265
+ : '';
2135
2266
 
2136
2267
  // Resolve token values — tuples become light-dark() strings
2137
2268
  /** @type {Record<string, unknown>} */
@@ -2205,7 +2336,7 @@ function generateBuiltModule(
2205
2336
  ),
2206
2337
  );
2207
2338
 
2208
- return `${iconImport}${iconDeclaration}/**
2339
+ return `${iconImport}${iconDeclaration}${iconNodesDeclaration}/**
2209
2340
  * ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
2210
2341
  * Import the CSS file alongside this module:
2211
2342
  *
@@ -2255,7 +2386,39 @@ export declare const ${iconInfo.exportName}: IconRegistry;
2255
2386
  (typeOptions.includeThemeImport ?? true)
2256
2387
  ? `import type { DefinedTheme } from '@astryxdesign/core/theme';\n`
2257
2388
  : '';
2258
- return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: DefinedTheme;\n`;
2389
+ return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: ${builtThemeType(themeDef)};\n`;
2390
+ }
2391
+
2392
+ /**
2393
+ * A TypeScript string literal type for `value`.
2394
+ * @param {string} value
2395
+ * @returns {string}
2396
+ */
2397
+ function tsStringLiteral(value) {
2398
+ const inner = JSON.stringify(value)
2399
+ .slice(1, -1)
2400
+ .replace(/\\"/g, '"')
2401
+ .replace(/'/g, "\\'");
2402
+ return `'${inner}'`;
2403
+ }
2404
+
2405
+ /**
2406
+ * The declared type of a built theme. A theme that lists icon variants
2407
+ * carries core's type-only `__iconVariant` marker with those names, so a theme
2408
+ * that extends the built one types its icon entries' `variant` by the list,
2409
+ * exactly as it would extending the source theme.
2410
+ * SYNC: packages/core/src/theme/defineTheme.ts (ResolvedDefinedTheme)
2411
+ * @param {any} themeDef
2412
+ * @returns {string}
2413
+ */
2414
+ function builtThemeType(themeDef) {
2415
+ const names = themeDef.iconVariants;
2416
+ if (!Array.isArray(names)) return 'DefinedTheme';
2417
+ const variant =
2418
+ names.length > 0
2419
+ ? [...new Set(names)].map(tsStringLiteral).join(' | ')
2420
+ : 'never';
2421
+ return `DefinedTheme & { __iconVariant?(variant: ${variant}): void }`;
2259
2422
  }
2260
2423
 
2261
2424
  // =============================================================================
@@ -2729,10 +2892,26 @@ async function themeBuildInternal(
2729
2892
  // Family preparation keeps its own named-import registry contract, which
2730
2893
  // themeBuildFamily checks against the selected members' graph.
2731
2894
  const standaloneIcons = !options.__prepareFamily;
2895
+ // Function icon entries stay functions in the built module, beside a node
2896
+ // view bound to `<theme>IconNodes` and computed from `<theme>IconEntries`.
2897
+ const functionEntries =
2898
+ hasFunctionIconEntry(themeIconEntries(themeDef)) ||
2899
+ hasFunctionIconEntry(themeIconEntries(themeDef.extends));
2900
+ /** @param {boolean} reserveIconNodes */
2901
+ const reservedNames = reserveIconNodes => [
2902
+ `${toIdentifier(themeDef.name)}Theme`,
2903
+ ...(reserveIconNodes
2904
+ ? [
2905
+ `${toIdentifier(themeDef.name)}ThemeIconNodes`,
2906
+ `${toIdentifier(themeDef.name)}ThemeIconEntries`,
2907
+ ]
2908
+ : []),
2909
+ ];
2732
2910
  const iconResolution = {
2733
2911
  readSource: (/** @type {string} */ file) => fs.readFileSync(file, 'utf8'),
2734
2912
  resolveModule: resolveThemeModule,
2735
- reservedNames: [`${toIdentifier(themeDef.name)}Theme`],
2913
+ reservedNames: reservedNames(functionEntries),
2914
+ functionEntries,
2736
2915
  rawInput: 'extends' in themeDef,
2737
2916
  hasIcons:
2738
2917
  Object.keys(themeDef.icons ?? {}).length > 0 ||
@@ -2856,9 +3035,14 @@ async function themeBuildInternal(
2856
3035
  !iconInfo &&
2857
3036
  Object.keys(resolvedTheme.icons ?? {}).length > 0
2858
3037
  ) {
3038
+ const resolvedFunctionEntries = hasFunctionIconEntry(
3039
+ themeIconEntries(resolvedTheme),
3040
+ );
2859
3041
  iconInfo = await resolveIconImports(filePath, themeExportName, {
2860
3042
  ...iconResolution,
2861
3043
  hasIcons: true,
3044
+ functionEntries: resolvedFunctionEntries,
3045
+ reservedNames: reservedNames(resolvedFunctionEntries),
2862
3046
  });
2863
3047
  }
2864
3048
  // An opaque package base can legitimately have no icons. Its .icons
@@ -3121,7 +3305,7 @@ async function themeBuildInternal(
3121
3305
  );
3122
3306
  const dtsContent =
3123
3307
  generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
3124
- generateBuiltTypes(themeDef, iconInfo, variantsFileName);
3308
+ generateBuiltTypes(resolvedTheme || themeDef, iconInfo, variantsFileName);
3125
3309
 
3126
3310
  const unloadedFonts = [
3127
3311
  ...new Set([
@@ -3568,8 +3752,16 @@ export async function themeBuildFamily(
3568
3752
  ['icons', member.iconInfo],
3569
3753
  ['indicators', member.indicatorInfo],
3570
3754
  ]) {
3571
- const value = member.theme[field];
3572
- const inherited = member.sourceParent?.[field];
3755
+ // A theme with a function entry gets its own node view of `icons`, so
3756
+ // an inherit-only member is recognized by its entries.
3757
+ const value =
3758
+ field === 'icons'
3759
+ ? themeIconEntries(member.theme)
3760
+ : member.theme[field];
3761
+ const inherited =
3762
+ field === 'icons'
3763
+ ? themeIconEntries(member.sourceParent)
3764
+ : member.sourceParent?.[field];
3573
3765
  if (
3574
3766
  value &&
3575
3767
  Object.keys(value).length > 0 &&
@@ -3640,7 +3832,14 @@ export async function themeBuildFamily(
3640
3832
  // prettier-ignore
3641
3833
  for (const registry of [icon, indicator]) if (registry.info) registryImports.push({specifier: registry.specifier ?? registry.info.importPath, exportName: registry.info.exportName});
3642
3834
  const ownIcons = icon.info ? `${themeBinding}Icons` : null;
3643
- const inheritedIcons = parentBinding ? `${parentBinding}.icons` : null;
3835
+ // A parent with function entries keeps them in `__icons`; its `icons`
3836
+ // is the node view.
3837
+ const parent = members.find(
3838
+ other => other.theme.name === member.parentName,
3839
+ );
3840
+ const inheritedIcons = parentBinding
3841
+ ? `${parentBinding}.${hasFunctionIconEntry(themeIconEntries(parent?.theme)) ? '__icons' : 'icons'}`
3842
+ : null;
3644
3843
  const ownIndicators = indicator.info ? `${themeBinding}Indicators` : null;
3645
3844
  const inheritedIndicators = parentBinding
3646
3845
  ? `${parentBinding}.indicators`
@@ -7,15 +7,26 @@
7
7
  * app's `<Theme>` runs on the app's Core either way, so the build loads the
8
8
  * project's installed `@astryxdesign/core` when it differs from the CLI's own.
9
9
  * When there is no Core to use, the error names the fix for where it ran:
10
- * install it in an app, build it in the Astryx repository.
10
+ * install it in an app, build it in the Astryx repository. An installed Core
11
+ * that does not load, or lacks the functions the build calls, fails the build,
12
+ * naming it, rather than leave the build to the CLI's own Core.
11
13
  */
12
14
 
13
- import {afterEach, beforeEach, describe, expect, it} from 'vitest';
15
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
14
16
  import * as fs from 'node:fs';
15
17
  import * as os from 'node:os';
16
18
  import * as path from 'node:path';
17
19
  import {fileURLToPath, pathToFileURL} from 'node:url';
18
20
  import {coreUnavailableMessage, themeBuild} from './build.mjs';
21
+ import {fetchCarriedThemeCoreDir} from '../_adapter.mjs';
22
+
23
+ vi.mock('../_adapter.mjs', async importOriginal => {
24
+ const actual = /** @type {Record<string, any>} */ (await importOriginal());
25
+ return {
26
+ ...actual,
27
+ fetchCarriedThemeCoreDir: vi.fn(actual.fetchCarriedThemeCoreDir),
28
+ };
29
+ });
19
30
 
20
31
  const HERE = path.dirname(fileURLToPath(import.meta.url));
21
32
  const REPO_ROOT = path.resolve(HERE, '../../../../..');
@@ -53,9 +64,10 @@ afterEach(() => {
53
64
  * entry as it is imported. Its `exports` map lists `source` first, as Core's
54
65
  * own does, so the build must skip that condition to find the runtime file.
55
66
  * @param {string} dir
56
- * @param {{broken?: boolean}} [options]
67
+ * @param {{broken?: boolean, themeModule?: string}} [options] `themeModule`
68
+ * replaces the theme entry's source
57
69
  */
58
- function installCore(dir, {broken = false} = {}) {
70
+ function installCore(dir, {broken = false, themeModule} = {}) {
59
71
  const core = path.join(dir, 'node_modules', '@astryxdesign', 'core');
60
72
  fs.mkdirSync(core, {recursive: true});
61
73
  fs.writeFileSync(
@@ -82,12 +94,29 @@ function installCore(dir, {broken = false} = {}) {
82
94
  `globalThis.__astryxProjectCoreLoads = [...(globalThis.__astryxProjectCoreLoads ?? []), '${entry}'];\n`;
83
95
  fs.writeFileSync(
84
96
  path.join(core, 'theme.mjs'),
85
- module('theme', 'theme/index.js'),
97
+ themeModule ?? module('theme', 'theme/index.js'),
86
98
  );
87
99
  fs.writeFileSync(path.join(core, 'root.mjs'), module('root', 'index.js'));
88
100
  return core;
89
101
  }
90
102
 
103
+ describe('theme build outside a project, with the Core this CLI release carries', () => {
104
+ it('fails naming a carried Core that does not load, rather than build with the CLI’s own', async () => {
105
+ const carried = installCore(makeDir(), {broken: true});
106
+ vi.mocked(fetchCarriedThemeCoreDir).mockReturnValueOnce(carried);
107
+ const bare = makeDir();
108
+ const build = themeBuild('ocean.mjs', {}, {cwd: bare});
109
+ await expect(build).rejects.toMatchObject({
110
+ code: 'ERR_CORE_NOT_FOUND',
111
+ message: expect.stringContaining(
112
+ `Could not load the @astryxdesign/core this CLI release carries, at ${carried}`,
113
+ ),
114
+ });
115
+ await expect(build).rejects.toThrow(/Import error: this Core is broken/);
116
+ expect(fs.existsSync(path.join(bare, 'ocean.css'))).toBe(false);
117
+ });
118
+ });
119
+
91
120
  describe('theme build generates with the Core the project installed', () => {
92
121
  it('loads the app’s installed Core when it differs from the CLI’s own', async () => {
93
122
  const app = makeDir();
@@ -114,11 +143,37 @@ describe('theme build generates with the Core the project installed', () => {
114
143
  expect(fs.existsSync(path.join(bare, 'ocean.css'))).toBe(true);
115
144
  });
116
145
 
117
- it('keeps the CLI’s own Core when the installed one does not load', async () => {
146
+ it('fails naming an installed Core that does not load, rather than build with the CLI’s own', async () => {
118
147
  const app = makeDir();
119
148
  installCore(app, {broken: true});
120
- await themeBuild('ocean.mjs', {}, {cwd: app});
121
- expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(true);
149
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toMatchObject(
150
+ {
151
+ code: 'ERR_CORE_NOT_FOUND',
152
+ message: expect.stringContaining(
153
+ `Could not load the @astryxdesign/core installed at ${path.join('node_modules', '@astryxdesign', 'core')}`,
154
+ ),
155
+ },
156
+ );
157
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toThrow(
158
+ /Import error: this Core is broken/,
159
+ );
160
+ expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(false);
161
+ });
162
+
163
+ it('fails naming an installed Core without the functions the build calls, rather than build with the CLI’s own', async () => {
164
+ const app = makeDir();
165
+ installCore(app, {
166
+ themeModule: 'export const defineTheme = theme => theme;\n',
167
+ });
168
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toMatchObject(
169
+ {
170
+ code: 'ERR_CORE_INCOMPATIBLE',
171
+ message: expect.stringContaining(
172
+ 'does not export generateThemeRulesSplit',
173
+ ),
174
+ },
175
+ );
176
+ expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(false);
122
177
  });
123
178
  });
124
179
 
@@ -6,13 +6,18 @@
6
6
  * Local base themes are traced to their registry imports. Package bases remain
7
7
  * public theme imports, so their implementation and private files stay private.
8
8
  *
9
+ * A theme whose resolved icon entries include a function keeps them: a package
10
+ * base is read for its entries (`__icons`) as well as its node-valued `icons`,
11
+ * and a built base module's `__icons` field is followed instead of `icons`.
12
+ *
9
13
  * @param {string} filePath
10
14
  * @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
15
+ * @param {{hasIcons: boolean, functionEntries?: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
12
16
  * @returns {Promise<IconImports | null>}
13
17
  */
14
- export function resolveIconImports(filePath: string, exportName: string | undefined, { hasIcons, readSource, resolveModule, reservedNames, rawInput }: {
18
+ export function resolveIconImports(filePath: string, exportName: string | undefined, { hasIcons, functionEntries, readSource, resolveModule, reservedNames, rawInput, }: {
15
19
  hasIcons: boolean;
20
+ functionEntries?: boolean;
16
21
  readSource: (filename: string) => string;
17
22
  resolveModule: (specifier: string, fromFile: string) => string | Promise<string>;
18
23
  reservedNames?: string[];
@@ -35,11 +40,16 @@ export type RegistryReference = {
35
40
  binding: any;
36
41
  members: string[];
37
42
  };
43
+ /**
44
+ * `entries` marks a package theme read for its icon entries: its node-valued
45
+ * `icons` merged with the `__icons` that hold its function entries, if any.
46
+ */
38
47
  export type RegistryPlan = {
39
48
  kind: "registry";
40
49
  ref: RegistryReference;
41
50
  preferredName: string;
42
51
  override?: boolean;
52
+ entries?: boolean;
43
53
  } | {
44
54
  kind: "merge";
45
55
  base: RegistryPlan;
@@ -24,7 +24,11 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
24
24
  */
25
25
 
26
26
  /** @typedef {{kind: 'reference', module: any, binding: any, members: string[]}} RegistryReference */
27
- /** @typedef {{kind: 'registry', ref: RegistryReference, preferredName: string, override?: boolean} | {kind: 'merge', base: RegistryPlan, own: RegistryPlan}} RegistryPlan */
27
+ /**
28
+ * `entries` marks a package theme read for its icon entries: its node-valued
29
+ * `icons` merged with the `__icons` that hold its function entries, if any.
30
+ * @typedef {{kind: 'registry', ref: RegistryReference, preferredName: string, override?: boolean, entries?: boolean} | {kind: 'merge', base: RegistryPlan, own: RegistryPlan}} RegistryPlan
31
+ */
28
32
 
29
33
  /** @param {any} node */
30
34
  function unwrap(node) {
@@ -98,15 +102,26 @@ function invalidRegistry(name, reason = '') {
98
102
  * Local base themes are traced to their registry imports. Package bases remain
99
103
  * public theme imports, so their implementation and private files stay private.
100
104
  *
105
+ * A theme whose resolved icon entries include a function keeps them: a package
106
+ * base is read for its entries (`__icons`) as well as its node-valued `icons`,
107
+ * and a built base module's `__icons` field is followed instead of `icons`.
108
+ *
101
109
  * @param {string} filePath
102
110
  * @param {string | undefined} exportName
103
- * @param {{hasIcons: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
111
+ * @param {{hasIcons: boolean, functionEntries?: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
104
112
  * @returns {Promise<IconImports | null>}
105
113
  */
106
114
  export async function resolveIconImports(
107
115
  filePath,
108
116
  exportName,
109
- {hasIcons, readSource, resolveModule, reservedNames = [], rawInput = false},
117
+ {
118
+ hasIcons,
119
+ functionEntries = false,
120
+ readSource,
121
+ resolveModule,
122
+ reservedNames = [],
123
+ rawInput = false,
124
+ },
110
125
  ) {
111
126
  if (exportName === undefined) {
112
127
  if (!hasIcons) return null;
@@ -391,11 +406,16 @@ export async function resolveIconImports(
391
406
 
392
407
  /** @param {RegistryReference} ref @returns {RegistryPlan} */
393
408
  function packageTheme(ref) {
394
- return {
395
- kind: 'registry',
396
- ref: {...ref, members: [...ref.members, 'icons']},
397
- preferredName: 'themeIcons',
398
- };
409
+ // A theme's `icons` is node-valued; its function entries live in
410
+ // `__icons`. Read both only when the built theme needs its functions, so
411
+ // a theme without them keeps its existing output.
412
+ return functionEntries
413
+ ? {kind: 'registry', ref, preferredName: 'themeIcons', entries: true}
414
+ : {
415
+ kind: 'registry',
416
+ ref: {...ref, members: [...ref.members, 'icons']},
417
+ preferredName: 'themeIcons',
418
+ };
399
419
  }
400
420
 
401
421
  /** @param {any} module @param {string} name @param {boolean} [rejectOpaque] @returns {Promise<RegistryPlan | null>} */
@@ -513,7 +533,7 @@ export async function resolveIconImports(
513
533
  : propertyName(item.key);
514
534
  if (key === null)
515
535
  invalidRegistry(undefined, 'Computed theme keys cannot be resolved.');
516
- if (!['icons', 'extends'].includes(key)) continue;
536
+ if (!['icons', '__icons', 'extends'].includes(key)) continue;
517
537
  if (
518
538
  !['ObjectProperty', 'Property'].includes(item.type) ||
519
539
  item.method ||
@@ -566,7 +586,9 @@ export async function resolveIconImports(
566
586
  }
567
587
  const config = await fields(module, node);
568
588
  const baseField = config.get('extends');
569
- const iconField = config.get('icons');
589
+ // A built module keeps its function entries in `__icons` beside its
590
+ // node-valued `icons`; the entries are the registry to carry.
591
+ const iconField = config.get('__icons') ?? config.get('icons');
570
592
  const base = baseField
571
593
  ? await theme(baseField.module, baseField.node)
572
594
  : null;
@@ -655,10 +677,13 @@ export async function resolveIconImports(
655
677
  localName,
656
678
  });
657
679
  }
658
- const expression = ref.members.reduce(
680
+ const target = ref.members.reduce(
659
681
  (result, member) => `${result}[${JSON.stringify(member)}]`,
660
682
  localName,
661
683
  );
684
+ const expression = value.entries
685
+ ? `{...${target}["icons"], ...${target}["__icons"]}`
686
+ : target;
662
687
  return {
663
688
  expression,
664
689
  preferredName:
@@ -136,6 +136,8 @@ export const docs = {
136
136
  {type: 'prose', text: 'In the example above, the generated theme imports `./icons.mjs` from `dist`. If the second command is skipped, `theme build` can still succeed, but loading or bundling the generated module fails because `dist/icons.mjs` is missing. `--icons-specifier` changes the emitted import; it does not create or verify the target file. Match the specifier to a module that resolves from the generated JS file.'},
137
137
  {type: 'prose', text: 'Without `--icons-specifier`, the detected source import specifier is emitted unchanged. In the default flow without `--out`, a bundler can resolve an extensionless `./icons` to the neighboring `icons.tsx` source, but Node ESM does not perform that lookup and reports `ERR_MODULE_NOT_FOUND`. Moving the output with `--out` also changes where relative imports resolve from.'},
138
138
  {type: 'prose', text: 'Keep `react` and the icon library external so the registry does not bundle its own copies of those dependencies.'},
139
+ {type: 'prose', text: "A registry entry can be a function of `{size, variant}`. The built theme keeps the function, so `Icon` asks it for the size and variant it renders, as the runtime theme does, including for entries inherited from a built or package theme. The built theme's `icons` field and the registry its module re-exports are React nodes, with each function read at size `md`. A function written in the theme file itself cannot be carried, so the build fails; move it into the registry module."},
140
+ {type: 'prose', text: "A theme that lists `iconVariants` also writes an `IconVariantMap` augmentation into `<theme>.variants.d.ts`, so `Icon`'s `variant` accepts those names wherever the theme's types load. Its declaration carries the list too, so a theme that extends the built theme types `variant` in its icon entries by that list."},
139
141
  ],
140
142
  },
141
143
  {
@@ -169,7 +169,7 @@ brandTheme.iconVariants; // ['outline', 'filled']`,
169
169
  },
170
170
  {
171
171
  type: 'prose',
172
- text: 'An application declares the variant names it uses by augmenting `IconVariantMap` from `@astryxdesign/core/Icon`. `IconVariant` is those names, and an entry passed to `registerIcons()` receives `variant` typed as `IconVariant`.',
172
+ text: 'An application declares the variant names it uses by augmenting `IconVariantMap` from `@astryxdesign/core/Icon`. `IconVariant` is those names, and an entry passed to `registerIcons()` receives `variant` typed as `IconVariant`. `astryx theme build` writes this augmentation for a built theme\'s list.',
173
173
  },
174
174
  {
175
175
  type: 'code',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.7.5-canary.6906beb",
3
+ "version": "0.7.5-canary.70ea859",
4
4
  "displayName": "CLI",
5
5
  "description": "Scaffold projects, browse templates, generate themes, and get agent-ready docs from the command line.",
6
6
  "author": "Meta Open Source",
@@ -111,10 +111,10 @@
111
111
  "zod": "^4.4.3"
112
112
  },
113
113
  "peerDependencies": {
114
- "@astryxdesign/charts": "0.7.5-canary.6906beb",
115
- "@astryxdesign/core": "0.7.5-canary.6906beb",
116
- "@astryxdesign/lab": "0.7.5-canary.6906beb",
117
- "@astryxdesign/theme-neutral": "0.7.5-canary.6906beb"
114
+ "@astryxdesign/charts": "0.7.5-canary.70ea859",
115
+ "@astryxdesign/core": "0.7.5-canary.70ea859",
116
+ "@astryxdesign/lab": "0.7.5-canary.70ea859",
117
+ "@astryxdesign/theme-neutral": "0.7.5-canary.70ea859"
118
118
  },
119
119
  "peerDependenciesMeta": {
120
120
  "@astryxdesign/charts": {
@@ -131,10 +131,10 @@
131
131
  }
132
132
  },
133
133
  "devDependencies": {
134
- "@astryxdesign/charts": "0.7.5-canary.6906beb",
135
- "@astryxdesign/core": "0.7.5-canary.6906beb",
136
- "@astryxdesign/lab": "0.7.5-canary.6906beb",
137
- "@astryxdesign/theme-neutral": "0.7.5-canary.6906beb",
134
+ "@astryxdesign/charts": "0.7.5-canary.70ea859",
135
+ "@astryxdesign/core": "0.7.5-canary.70ea859",
136
+ "@astryxdesign/lab": "0.7.5-canary.70ea859",
137
+ "@astryxdesign/theme-neutral": "0.7.5-canary.70ea859",
138
138
  "@heroicons/react": "^2.2.0",
139
139
  "@stylexjs/stylex": "^0.19.0",
140
140
  "@types/babel__core": "^7.20.5",