@astryxdesign/cli 0.7.5-canary.dae1747 → 0.7.5-canary.dc5a8cf

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.
@@ -0,0 +1,134 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Built and runtime themes pass an inherited icon entry the same variants.
5
+ * @input Real themeBuild calls on a base theme with a function icon entry and a
6
+ * child that extends it with a wider `iconVariants` list.
7
+ * @output A native ESM load renders `<Icon variant>` under the built child and
8
+ * under the runtime child and compares the variant each entry received.
9
+ * @position `architecture:theme-compilation` INV15 for `spec:AST-087` FR4: an
10
+ * inherited entry keeps its defining theme's list, so a variant only the
11
+ * child lists never reaches it, built or runtime. The node project's global
12
+ * setup supplies the compiled core package.
13
+ */
14
+
15
+ import {expect, it} from 'vitest';
16
+ import {execFileSync} from 'node:child_process';
17
+ import * as fs from 'node:fs';
18
+ import * as path from 'node:path';
19
+ import {themeBuild} from './build.mjs';
20
+
21
+ it('passes an inherited entry only its defining theme variants in a built child, as at runtime', async () => {
22
+ const tmpDir = fs.mkdtempSync(
23
+ path.resolve(import.meta.dirname, '../../..', '.tmp-icon-entry-variants-'),
24
+ );
25
+ try {
26
+ for (const directory of ['base', 'child', 'unlisted']) {
27
+ fs.mkdirSync(path.join(tmpDir, directory));
28
+ }
29
+ const write = (file, source) =>
30
+ fs.writeFileSync(path.join(tmpDir, file), source);
31
+
32
+ write(
33
+ 'base/icons.mjs',
34
+ `import {createElement} from 'react';
35
+ export const icons = {
36
+ info: ({variant}) => createElement('svg', {'data-variant': variant ?? 'normal'}),
37
+ };
38
+ `,
39
+ );
40
+ write(
41
+ 'base/source.mjs',
42
+ `import {defineTheme} from '@astryxdesign/core/theme';
43
+ import {icons} from './icons.mjs';
44
+ export const baseTheme = defineTheme({
45
+ name: 'entry-variants-base', tokens: {}, iconVariants: ['outline'], icons,
46
+ });
47
+ `,
48
+ );
49
+ write(
50
+ 'child/source.mjs',
51
+ `import {defineTheme} from '@astryxdesign/core/theme';
52
+ import {baseTheme} from '../base/source.mjs';
53
+ export default defineTheme({
54
+ name: 'entry-variants-child', extends: baseTheme, tokens: {},
55
+ iconVariants: ['outline', 'filled'],
56
+ });
57
+ `,
58
+ );
59
+ // A defining theme with no list: the built module writes it as `[]`.
60
+ write(
61
+ 'unlisted/base.mjs',
62
+ `import {defineTheme} from '@astryxdesign/core/theme';
63
+ import {icons} from '../base/icons.mjs';
64
+ export const unlistedBase = defineTheme({
65
+ name: 'entry-variants-unlisted-base', tokens: {}, icons,
66
+ });
67
+ `,
68
+ );
69
+ write(
70
+ 'unlisted/source.mjs',
71
+ `import {defineTheme} from '@astryxdesign/core/theme';
72
+ import {unlistedBase} from './base.mjs';
73
+ export default defineTheme({
74
+ name: 'entry-variants-unlisted-child', extends: unlistedBase, tokens: {},
75
+ iconVariants: ['filled'],
76
+ });
77
+ `,
78
+ );
79
+ for (const source of ['child/source.mjs', 'unlisted/source.mjs']) {
80
+ const receipt = await themeBuild(source, {}, {cwd: tmpDir});
81
+ expect(receipt?.type).toBe('theme.build');
82
+ }
83
+
84
+ const output = execFileSync(
85
+ process.execPath,
86
+ [
87
+ '--input-type=module',
88
+ '--eval',
89
+ `import {createElement} from 'react';
90
+ import {renderToStaticMarkup} from 'react-dom/server';
91
+ import {Icon} from '@astryxdesign/core/Icon';
92
+ import {Theme} from '@astryxdesign/core/theme';
93
+ import {entryVariantsChildTheme as built} from './child/entry-variants-child.js';
94
+ import runtime from './child/source.mjs';
95
+ import {entryVariantsUnlistedChildTheme as unlistedBuilt} from './unlisted/entry-variants-unlisted-child.js';
96
+ import unlistedRuntime from './unlisted/source.mjs';
97
+ const received = (theme, variant) => {
98
+ const html = renderToStaticMarkup(
99
+ createElement(Theme, {theme}, createElement(Icon, {icon: 'info', variant})),
100
+ );
101
+ return /data-variant="([^"]+)"/.exec(html)?.[1] ?? null;
102
+ };
103
+ const result = {};
104
+ for (const [label, theme] of [
105
+ ['built', built],
106
+ ['runtime', runtime],
107
+ ['unlistedBuilt', unlistedBuilt],
108
+ ['unlistedRuntime', unlistedRuntime],
109
+ ]) {
110
+ result[label] = {
111
+ filled: received(theme, 'filled'),
112
+ outline: received(theme, 'outline'),
113
+ };
114
+ }
115
+ process.stdout.write(JSON.stringify(result));`,
116
+ ],
117
+ {cwd: tmpDir, stdio: ['ignore', 'pipe', 'pipe'], timeout: 20000},
118
+ );
119
+ const result = JSON.parse(String(output));
120
+
121
+ // The base never listed 'filled', so its entry draws normal artwork for
122
+ // it in the child; 'outline' is listed by both and reaches the entry.
123
+ expect(result.runtime).toEqual({filled: 'normal', outline: 'outline'});
124
+ expect(result.built).toEqual(result.runtime);
125
+ // A base with no list passes its entry no variant, even one its child lists.
126
+ expect(result.unlistedRuntime).toEqual({
127
+ filled: 'normal',
128
+ outline: 'normal',
129
+ });
130
+ expect(result.unlistedBuilt).toEqual(result.unlistedRuntime);
131
+ } finally {
132
+ fs.rmSync(tmpDir, {recursive: true, force: true});
133
+ }
134
+ });
@@ -58,7 +58,7 @@
58
58
 
59
59
  import * as fs from 'node:fs';
60
60
  import * as path from 'node:path';
61
- import {isBuiltin} from 'node:module';
61
+ import {createRequire, isBuiltin} from 'node:module';
62
62
  import {fileURLToPath, pathToFileURL} from 'node:url';
63
63
  import {parse} from '@babel/parser';
64
64
  import {createJiti} from 'jiti';
@@ -306,7 +306,9 @@ function realLocation(target) {
306
306
  * Core, so building with it keeps the CSS identical; and a CLI run one-off
307
307
  * (`npx @astryxdesign/cli`) has no Core beside it at all. Null when there is
308
308
  * 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.
309
+ * repository, a bare directory) or the same Core. A Core that is there but
310
+ * does not load, or lacks the functions the build calls, throws, naming it:
311
+ * building with another Core would not match the app's `<Theme>`.
310
312
  *
311
313
  * @param {string} cwd
312
314
  * @param {CoreBindings} cliCore - The CLI's own Core, from {@link loadCliCore}.
@@ -316,29 +318,36 @@ function realLocation(target) {
316
318
  */
317
319
  async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
318
320
  // 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));
321
+ const installed = findInstalledPackage(cwd, '@astryxdesign/core');
322
+ const dir = installed ?? (projectOnly ? null : fetchCarriedThemeCoreDir(cwd));
322
323
  const themeFile = dir ? importTarget(dir, './theme') : null;
323
324
  if (!dir || !themeFile) return null;
324
325
  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
- }
326
+ const own = cliCoreThemeFile();
327
+ if (own != null && realOrSelf(own) === realOrSelf(themeFile)) return null;
333
328
  }
334
329
  let themeModule;
335
330
  try {
336
331
  themeModule = await import(pathToFileURL(themeFile).href);
337
- } catch {
338
- return null;
332
+ } catch (error) {
333
+ throw new AstryxError(
334
+ installed == null
335
+ ? carriedCoreMessage(dir, /** @type {Error} */ (error))
336
+ : coreUnavailableMessage(cwd, /** @type {Error} */ (error)),
337
+ undefined,
338
+ ERROR_CODES.ERR_CORE_NOT_FOUND,
339
+ );
340
+ }
341
+ const missing = ['defineTheme', 'generateThemeRulesSplit'].filter(
342
+ name => typeof themeModule[name] !== 'function',
343
+ );
344
+ if (missing.length > 0) {
345
+ throw new AstryxError(
346
+ `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.`,
347
+ undefined,
348
+ ERROR_CODES.ERR_CORE_INCOMPATIBLE,
349
+ );
339
350
  }
340
- if (!themeModule.defineTheme || !themeModule.generateThemeRulesSplit)
341
- return null;
342
351
  let rootModule = null;
343
352
  const rootFile = importTarget(dir, '.');
344
353
  if (rootFile) {
@@ -359,6 +368,40 @@ async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
359
368
  };
360
369
  }
361
370
 
371
+ /**
372
+ * The file the CLI's own `@astryxdesign/core/theme` resolves to, or null when
373
+ * the CLI has no Core of its own (a one-off `npx` run).
374
+ * @returns {string | null}
375
+ */
376
+ function cliCoreThemeFile() {
377
+ try {
378
+ return fileURLToPath(import.meta.resolve('@astryxdesign/core/theme'));
379
+ } catch (error) {
380
+ const {code} = /** @type {NodeJS.ErrnoException} */ (error);
381
+ if (
382
+ code === 'ERR_MODULE_NOT_FOUND' ||
383
+ code === 'ERR_PACKAGE_PATH_NOT_EXPORTED'
384
+ ) {
385
+ return null;
386
+ }
387
+ throw error;
388
+ }
389
+ }
390
+
391
+ /**
392
+ * The error for a Core the answering copy carries (outside a project) that
393
+ * does not load.
394
+ * @param {string} dir
395
+ * @param {Error} importError
396
+ * @returns {string}
397
+ */
398
+ function carriedCoreMessage(dir, importError) {
399
+ return (
400
+ `Could not load the @astryxdesign/core this CLI release carries, at ${dir}.` +
401
+ `\n Import error: ${importError.message}`
402
+ );
403
+ }
404
+
362
405
  /** @type {Map<string, Awaited<ReturnType<typeof loadProjectCore>>>} */
363
406
  const _projectCores = new Map();
364
407
 
@@ -379,7 +422,7 @@ async function selectCore(cwd, {projectOnly = false} = {}) {
379
422
  // A global or cached copy's own Core is the carried one.
380
423
  if (projectOnly && !projectCore && carriesCore() && !cliCoreIsProjects(cwd)) {
381
424
  throw new AstryxError(
382
- "The project's Core isn't installed or does not load.",
425
+ "The project's Core isn't installed.",
383
426
  undefined,
384
427
  ERROR_CODES.ERR_CORE_NOT_FOUND,
385
428
  );
@@ -405,13 +448,11 @@ function carriesCore() {
405
448
  function cliCoreIsProjects(cwd) {
406
449
  const dir = findProjectCoreDir(cwd);
407
450
  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
- }
451
+ const own = cliCoreThemeFile();
452
+ const theirs = importTarget(dir, './theme');
453
+ return (
454
+ own != null && theirs != null && realOrSelf(own) === realOrSelf(theirs)
455
+ );
415
456
  }
416
457
 
417
458
  /**
@@ -1855,19 +1896,43 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
1855
1896
  commonJsPatch.undo();
1856
1897
  }
1857
1898
  } else {
1858
- mod = await jiti.import(filePath, {default: true});
1899
+ mod = await jiti.import(filePath);
1859
1900
  }
1860
1901
 
1861
- if (isThemeObject(mod)) return {theme: mod, exportName: 'default', degraded};
1862
-
1863
- if (mod && typeof mod === 'object') {
1864
- if (isThemeObject(mod.default)) {
1865
- return {theme: mod.default, exportName: 'default', degraded};
1866
- }
1902
+ // Both loads hand back the module. The theme is read from the module's own
1903
+ // exports, never from the module object itself: jiti's interop answers a
1904
+ // property the module lacks from its default export (and a missing
1905
+ // `default` with the module), so the module can pass for the theme while
1906
+ // its own keys hide the theme's fields.
1907
+ const isModule = mod != null && typeof mod === 'object';
1908
+ const hasDefault = isModule && Object.hasOwn(mod, 'default');
1909
+ const defaultExport = hasDefault ? mod.default : undefined;
1910
+ if (isThemeObject(defaultExport)) {
1911
+ return {theme: defaultExport, exportName: 'default', degraded};
1912
+ }
1913
+ if (isModule) {
1867
1914
  for (const [exportName, value] of Object.entries(mod)) {
1915
+ if (exportName === 'default' || exportName === 'module.exports') continue;
1868
1916
  if (isThemeObject(value)) return {theme: value, exportName, degraded};
1869
1917
  }
1870
1918
  }
1919
+ // A plain-object default export is the module's theme even when it has
1920
+ // no tokens of its own (local tokens, typography or component styles may
1921
+ // be all it defines), or no name: the build's validation says what it
1922
+ // lacks.
1923
+ if (isPlainObject(defaultExport)) {
1924
+ return {theme: defaultExport, exportName: 'default', degraded};
1925
+ }
1926
+ // A CommonJS module whose exports are the theme (`module.exports =
1927
+ // theme`) has no default of its own: interop answers `default` with
1928
+ // those exports, and without interop (a family build's loader) the module
1929
+ // is them.
1930
+ if (isModule && !hasDefault) {
1931
+ const exportsObject = mod.default ?? mod;
1932
+ if (isThemeObject(exportsObject)) {
1933
+ return {theme: exportsObject, exportName: 'default', degraded};
1934
+ }
1935
+ }
1871
1936
 
1872
1937
  throw new Error(
1873
1938
  `Could not find a defineTheme() result in ${filePath}.\n` +
@@ -1875,6 +1940,45 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
1875
1940
  );
1876
1941
  }
1877
1942
 
1943
+ /**
1944
+ * Whether the theme file's own folder resolves Core's theme entry, as the
1945
+ * theme's own `import ... from '@astryxdesign/core/theme'` would. A theme
1946
+ * outside any project (an empty folder, a fresh clone) does not, and is
1947
+ * handed the Core the CLI answers with instead, as a new project with that
1948
+ * Core would build it (`theme build` runs the same outside a project, spec
1949
+ * AST-081 FR3). Only a Core not installed there (MODULE_NOT_FOUND) reads as
1950
+ * no: an installed Core whose entry does not resolve is the theme's own, and
1951
+ * its load reports that.
1952
+ * @param {string} filePath
1953
+ * @returns {boolean}
1954
+ */
1955
+ function themeFolderResolvesCore(filePath) {
1956
+ try {
1957
+ createRequire(filePath).resolve('@astryxdesign/core/theme');
1958
+ return true;
1959
+ } catch (error) {
1960
+ const {code} = /** @type {NodeJS.ErrnoException} */ (error);
1961
+ if (code === 'MODULE_NOT_FOUND') return false;
1962
+ if (code === 'ERR_PACKAGE_PATH_NOT_EXPORTED') return true;
1963
+ throw error;
1964
+ }
1965
+ }
1966
+
1967
+ /**
1968
+ * A plain object, not an array or a module namespace: a theme module's
1969
+ * default export, read as its theme.
1970
+ * @param {any} value
1971
+ * @returns {boolean}
1972
+ */
1973
+ function isPlainObject(value) {
1974
+ return (
1975
+ value != null &&
1976
+ typeof value === 'object' &&
1977
+ !Array.isArray(value) &&
1978
+ value[Symbol.toStringTag] !== 'Module'
1979
+ );
1980
+ }
1981
+
1878
1982
  /**
1879
1983
  * @param {any} value
1880
1984
  * @returns {boolean}
@@ -1890,12 +1994,9 @@ function isThemeObject(value) {
1890
1994
  }
1891
1995
 
1892
1996
  /**
1893
- * Extract the theme definition from a JS/TS file.
1894
- * Tries jiti first (full TS support), falls back to regex+eval.
1895
- *
1896
- * The legacy fallback needs no interception: it evaluates the `defineTheme()`
1897
- * ARGUMENT, so what it returns is raw authored input with `adaptations` still
1898
- * on it — nothing has erased anything yet. It is therefore never degraded.
1997
+ * Extract the theme definition from a JS/TS file, through jiti (full TS
1998
+ * support). A module that does not load fails with its own error: the theme
1999
+ * is never read from the file's text instead.
1899
2000
  *
1900
2001
  * @param {string} filePath
1901
2002
  * @param {import('./core-interception.mjs').CoreInterception} [interception]
@@ -1906,18 +2007,12 @@ async function extractThemeDefinition(filePath, interception, /** @type {any} */
1906
2007
  try {
1907
2008
  return await importThemeModule(filePath, interception, loader);
1908
2009
  } catch (jitiError) {
1909
- try {
1910
- return {
1911
- theme: extractThemeDefinitionLegacy(filePath),
1912
- degraded: {topLevelAwait: false, commonJs: false},
1913
- };
1914
- } catch {
1915
- const je = /** @type {Error} */ (jitiError);
1916
- throw new Error(
1917
- `Failed to load theme from ${filePath}: ${je.message}\n` +
1918
- `Make sure all imports in the theme file are resolvable.`,
1919
- );
1920
- }
2010
+ const je = /** @type {Error} */ (jitiError);
2011
+ throw new Error(
2012
+ `Failed to load theme from ${filePath}: ${je.message}\n` +
2013
+ `Make sure all imports in the theme file are resolvable.`,
2014
+ {cause: jitiError},
2015
+ );
1921
2016
  }
1922
2017
  }
1923
2018
 
@@ -1963,45 +2058,6 @@ export async function validateThemePrivateInputs(
1963
2058
  }
1964
2059
  }
1965
2060
 
1966
- /**
1967
- * Fallback extraction via regex + eval.
1968
- * Only works for plain object literals — can't follow imports or variables.
1969
- * Never erase icon references: an unresolved registry must preserve the loader
1970
- * error instead of turning an incomplete theme into a successful build.
1971
- * @param {string} filePath
1972
- * @returns {any}
1973
- */
1974
- function extractThemeDefinitionLegacy(filePath) {
1975
- const content = fs.readFileSync(filePath, 'utf8');
1976
-
1977
- const defineMatch = content.match(/defineTheme\s*\(\s*({[\s\S]*?})\s*\)/);
1978
- if (!defineMatch) {
1979
- const defaultMatch = content.match(/export\s+default\s+({[\s\S]*?});/);
1980
- if (!defaultMatch) {
1981
- throw new Error(
1982
- `Could not find defineTheme() call or default export in ${filePath}.\n` +
1983
- `Expected: defineTheme({ name: '...', tokens: {...} })`,
1984
- );
1985
- }
1986
-
1987
- return eval(`(${defaultMatch[1]})`);
1988
- }
1989
-
1990
- let objStr = defineMatch[1];
1991
- objStr = objStr.replace(/\s+as\s+const/g, '');
1992
-
1993
- try {
1994
- return eval(`(${objStr})`);
1995
- } catch (e) {
1996
- const err = /** @type {Error} */ (e);
1997
- throw new Error(
1998
- `Failed to parse theme definition in ${filePath}: ${err.message}\n` +
1999
- `Make sure the defineTheme() argument is a plain object literal.`,
2000
- {cause: e},
2001
- );
2002
- }
2003
- }
2004
-
2005
2061
  /**
2006
2062
  * Extract a family member's named registry import from its source file.
2007
2063
  * Returns { importPath, exportName } or null when the theme names none.
@@ -2175,7 +2231,20 @@ function generateBuiltModule(
2175
2231
  serializeField('__adaptations', themeDef.__adaptations) +
2176
2232
  serializeField('__axes', themeDef.__axes ?? {}, true) +
2177
2233
  // An explicit empty list replaces an inherited one, so keep `[]`.
2178
- serializeField('iconVariants', themeDef.iconVariants, true);
2234
+ serializeField('iconVariants', themeDef.iconVariants, true) +
2235
+ // Each inherited function entry keeps its defining theme's list. JSON
2236
+ // drops `undefined`, so a defining theme with no list is written as `[]`,
2237
+ // which no variant matches either.
2238
+ serializeField(
2239
+ '__iconEntryVariants',
2240
+ themeDef.__iconEntryVariants &&
2241
+ Object.fromEntries(
2242
+ Object.entries(themeDef.__iconEntryVariants).map(([name, list]) => [
2243
+ name,
2244
+ list ?? [],
2245
+ ]),
2246
+ ),
2247
+ );
2179
2248
 
2180
2249
  return `${iconImport}${iconDeclaration}/**
2181
2250
  * ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
@@ -2604,13 +2673,15 @@ async function themeBuildInternal(
2604
2673
  }
2605
2674
  await selectCore(cwd, {projectOnly: projectCore});
2606
2675
 
2607
- // Standalone builds only need interception when an older Core could erase
2608
- // adaptations. Family preparation always supplies the same recorder as its
2676
+ // Standalone builds need interception when an older Core could erase
2677
+ // adaptations, and when the theme's folder has no Core of its own: its
2678
+ // imports of Core are then handed the Core this build selected, as family
2679
+ // builds' are. Family preparation always supplies the same recorder as its
2609
2680
  // shared loader so exact authored parent identity stays CLI-private instead
2610
2681
  // of becoming a public DefinedTheme field.
2611
2682
  const interception =
2612
2683
  options.__familyInterception ??
2613
- (_generateAdaptationCSS
2684
+ (_generateAdaptationCSS && themeFolderResolvesCore(filePath)
2614
2685
  ? undefined
2615
2686
  : interceptCore(_coreThemeModule, _coreRootModule));
2616
2687
 
@@ -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
 
@@ -27,6 +27,7 @@ import {
27
27
  import {
28
28
  themeBuild,
29
29
  validateComponentOverridesAgainstRegistry,
30
+ validateThemePrivateInputs,
30
31
  } from './build.mjs';
31
32
 
32
33
  // `themeBuild` captures core's generator once at module load. Wrap the two
@@ -212,6 +213,55 @@ describe('themeBuild() — receipt', () => {
212
213
  });
213
214
  });
214
215
 
216
+ describe.each(['mjs', 'ts'])('a .%s theme module with no theme export', ext => {
217
+ beforeEach(() => {
218
+ fs.writeFileSync(
219
+ path.join(tmpDir, `none.${ext}`),
220
+ 'export const notATheme = 42;\n',
221
+ );
222
+ });
223
+
224
+ it('fails the build as a module that does not load a theme', async () => {
225
+ const build = themeBuild(`none.${ext}`, {}, {cwd: tmpDir});
226
+ await expect(build).rejects.toThrow(
227
+ /Could not find a defineTheme\(\) result/,
228
+ );
229
+ await expect(build).rejects.toMatchObject({code: 'ERR_THEME_LOAD'});
230
+ });
231
+
232
+ it("fails doctor's private-input check the same way, rather than read its exports as a theme", async () => {
233
+ await expect(
234
+ validateThemePrivateInputs(`none.${ext}`, {cwd: tmpDir}),
235
+ ).rejects.toThrow(/Could not find a defineTheme\(\) result/);
236
+ });
237
+ });
238
+
239
+ describe('themeBuild() — a theme module that does not load', () => {
240
+ it('fails with the import error, rather than build the theme from the file text', async () => {
241
+ fs.writeFileSync(
242
+ path.join(tmpDir, 'unresolved.mjs'),
243
+ "import './missing-helper.mjs';\nexport default {name: 'unresolved', tokens: {'--color-bg': '#000'}};\n",
244
+ );
245
+ await expect(
246
+ themeBuild('unresolved.mjs', {}, {cwd: tmpDir}),
247
+ ).rejects.toThrow(
248
+ /Failed to load theme from .*unresolved\.mjs: .*missing-helper\.mjs/s,
249
+ );
250
+ expect(fs.existsSync(path.join(tmpDir, 'unresolved.css'))).toBe(false);
251
+ });
252
+
253
+ it('fails with the error the module throws, rather than build the theme from the file text', async () => {
254
+ fs.writeFileSync(
255
+ path.join(tmpDir, 'throws.mjs'),
256
+ "throw new Error('the theme module failed');\nexport default {name: 'throws', tokens: {'--color-bg': '#000'}};\n",
257
+ );
258
+ await expect(themeBuild('throws.mjs', {}, {cwd: tmpDir})).rejects.toThrow(
259
+ /the theme module failed/,
260
+ );
261
+ expect(fs.existsSync(path.join(tmpDir, 'throws.css'))).toBe(false);
262
+ });
263
+ });
264
+
215
265
  describe('themeBuild() — dropped declarations reach the receipt', () => {
216
266
  // Core's generator refuses a declaration whose value would end it early
217
267
  // (an unquoted `;` or brace, an unclosed string/comment/url). The runtime
@@ -156,6 +156,17 @@ brandTheme.iconVariants; // ['outline', 'filled']`,
156
156
  type: 'prose',
157
157
  text: 'A theme that `extends` another inherits its list unless it sets its own; a list it sets replaces the inherited one instead of merging with it.',
158
158
  },
159
+ {
160
+ type: 'prose',
161
+ text: "Request a variant with `Icon`'s `variant` prop. The entry receives it only when the active theme lists it; an entry the theme inherited also needs the theme that defined it to list it. Otherwise the entry receives `undefined` and draws its normal artwork, so an unlisted variant never breaks rendering. A `registerIcons()` entry receives the variants the active theme lists, and a node entry draws the same node for every variant. An icon component passed directly to `Icon` never receives `variant`, and `variant` is never written to the DOM: it selects artwork, so there is no theming selector for it.",
162
+ },
163
+ {
164
+ type: 'code',
165
+ lang: 'tsx',
166
+ label: 'Requesting a variant',
167
+ code: `<Icon icon="info" variant="filled" /> // brandTheme: the filled artwork
168
+ <Icon icon="info" /> // the normal artwork`,
169
+ },
159
170
  {
160
171
  type: 'prose',
161
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`.',
@@ -0,0 +1,140 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `astryx theme build` outside any project, as a separate process.
5
+ *
6
+ * A theme in a folder with no Core installed (an empty folder, a fresh clone)
7
+ * imports `defineTheme` from Core all the same: the build hands its imports
8
+ * the Core the CLI answers with, as a new project with that Core would build
9
+ * it (spec AST-081 FR3). The CLI runs as its own process, without the
10
+ * `NODE_PATH` a pnpm script sets (it reaches the repository's packages): in
11
+ * the test runner, or with that path, the theme's import would find the
12
+ * repository's Core, which a real run outside a project cannot.
13
+ */
14
+
15
+ import {afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
16
+ import * as fs from 'node:fs';
17
+ import * as os from 'node:os';
18
+ import * as path from 'node:path';
19
+ import {spawnSync} from 'node:child_process';
20
+ import {fileURLToPath} from 'node:url';
21
+ import {ensureCoreBuilt} from './ensure-core-built.mjs';
22
+
23
+ const CLI_BIN = fileURLToPath(new URL('../bin/astryx.mjs', import.meta.url));
24
+ const CORE_DIR = fileURLToPath(new URL('../../../../core', import.meta.url));
25
+
26
+ /** @param {string[]} args @param {string} cwd */
27
+ function runCliProcess(args, cwd) {
28
+ const {NODE_PATH: _repositoryPackages, ...env} = process.env;
29
+ const result = spawnSync(process.execPath, [CLI_BIN, ...args], {
30
+ cwd,
31
+ encoding: 'utf-8',
32
+ timeout: 60_000,
33
+ env,
34
+ });
35
+ if (result.error) throw result.error;
36
+ return result;
37
+ }
38
+
39
+ beforeAll(() => {
40
+ ensureCoreBuilt();
41
+ }, 200_000);
42
+
43
+ let tmpDir;
44
+ beforeEach(() => {
45
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-outside-'));
46
+ });
47
+ afterEach(() => {
48
+ fs.rmSync(tmpDir, {recursive: true, force: true});
49
+ });
50
+
51
+ /**
52
+ * A project beside the empty folder: its own package.json and Core (this
53
+ * repository's, linked), so the same theme builds there through the
54
+ * project's own resolution.
55
+ * @param {string} dir
56
+ */
57
+ function makeProject(dir) {
58
+ fs.mkdirSync(path.join(dir, 'node_modules', '@astryxdesign'), {
59
+ recursive: true,
60
+ });
61
+ fs.writeFileSync(
62
+ path.join(dir, 'package.json'),
63
+ '{"name": "theme-project", "private": true, "dependencies": {"@astryxdesign/core": "*"}}\n',
64
+ );
65
+ fs.symlinkSync(
66
+ CORE_DIR,
67
+ path.join(dir, 'node_modules', '@astryxdesign', 'core'),
68
+ 'junction',
69
+ );
70
+ }
71
+
72
+ describe('theme build outside any project builds a plain-object theme as a project does', () => {
73
+ const themes = {
74
+ typography: `export default {
75
+ name: 'plain-type',
76
+ tokens: {'--color-background': '#123456'},
77
+ typography: {body: {family: 'Helvetica', fallbacks: 'Arial, sans-serif'}},
78
+ };\n`,
79
+ 'local tokens and media surfaces': `export default {
80
+ name: 'plain-local',
81
+ tokens: {'--color-background': '#123456'},
82
+ localTokens: {'--ac-selection-ink': ['#0077b6', '#48cae4']},
83
+ components: {badge: {'variant:info': {backgroundColor: 'var(--ac-selection-ink)'}}},
84
+ onDark: {components: {badge: {'variant:info': {color: 'var(--ac-selection-ink)'}}}},
85
+ };\n`,
86
+ };
87
+ for (const [what, source] of Object.entries(themes)) {
88
+ for (const ext of ['mjs', 'ts']) {
89
+ it(`with ${what}, in a .${ext} file`, () => {
90
+ const name = /name: '([^']+)'/.exec(source)[1];
91
+ const project = path.join(tmpDir, 'project');
92
+ makeProject(project);
93
+ const outside = path.join(tmpDir, 'outside');
94
+ fs.mkdirSync(outside);
95
+ for (const dir of [project, outside]) {
96
+ fs.writeFileSync(path.join(dir, `theme.${ext}`), source);
97
+ const result = runCliProcess(['theme', 'build', `theme.${ext}`], dir);
98
+ expect(result.status, result.stderr + result.stdout).toBe(0);
99
+ }
100
+ expect(fs.readFileSync(path.join(outside, `${name}.css`), 'utf8')).toBe(
101
+ fs.readFileSync(path.join(project, `${name}.css`), 'utf8'),
102
+ );
103
+ });
104
+ }
105
+ }
106
+ });
107
+
108
+ describe('theme build outside any project', () => {
109
+ for (const ext of ['mjs', 'ts']) {
110
+ it(`builds a .${ext} theme that imports defineTheme from Core, with the Core the CLI answers with`, () => {
111
+ fs.writeFileSync(
112
+ path.join(tmpDir, `outside.${ext}`),
113
+ "import {defineTheme} from '@astryxdesign/core/theme';\n" +
114
+ "export default defineTheme({name: 'outside', tokens: {'--color-background': '#123456'}});\n",
115
+ );
116
+ const result = runCliProcess(
117
+ ['theme', 'build', `outside.${ext}`],
118
+ tmpDir,
119
+ );
120
+ expect(result.status, result.stderr + result.stdout).toBe(0);
121
+ expect(
122
+ fs.readFileSync(path.join(tmpDir, 'outside.css'), 'utf8'),
123
+ ).toContain('#123456');
124
+ });
125
+ }
126
+
127
+ for (const ext of ['mjs', 'ts']) {
128
+ it(`still fails a .${ext} module that defines no theme`, () => {
129
+ fs.writeFileSync(
130
+ path.join(tmpDir, `none.${ext}`),
131
+ 'export const notATheme = 42;\n',
132
+ );
133
+ const result = runCliProcess(['theme', 'build', `none.${ext}`], tmpDir);
134
+ expect(result.status).toBe(1);
135
+ expect(result.stderr + result.stdout).toMatch(
136
+ /Could not find a defineTheme\(\) result/,
137
+ );
138
+ });
139
+ }
140
+ });
@@ -65,12 +65,11 @@ const RUNNERS = {
65
65
  sites: ['importThemeArtifact'],
66
66
  },
67
67
  'api/theme/build/build.mjs': {
68
- runs: "theme source modules, through jiti; eval for legacy theme object literals; the project's installed Core",
68
+ runs: "theme source modules, through jiti; the project's installed Core",
69
69
  sites: [
70
70
  '.evalModule() ×2',
71
71
  '.import()',
72
72
  'createJiti ×5',
73
- 'eval ×2',
74
73
  'import(<computed>) ×3',
75
74
  ],
76
75
  },
@@ -218,10 +217,7 @@ const RUNNERS = {
218
217
  },
219
218
  'clients/cli/commands/hook.mjs': {
220
219
  runs: SELF_DOCS,
221
- sites: [
222
- 'import ../../../api/hook/hook.doc.mjs',
223
- 'import ./hook.doc.mjs',
224
- ],
220
+ sites: ['import ../../../api/hook/hook.doc.mjs', 'import ./hook.doc.mjs'],
225
221
  },
226
222
  'clients/cli/commands/init.mjs': {
227
223
  runs: SELF_DOCS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.7.5-canary.dae1747",
3
+ "version": "0.7.5-canary.dc5a8cf",
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.dae1747",
115
- "@astryxdesign/core": "0.7.5-canary.dae1747",
116
- "@astryxdesign/lab": "0.7.5-canary.dae1747",
117
- "@astryxdesign/theme-neutral": "0.7.5-canary.dae1747"
114
+ "@astryxdesign/charts": "0.7.5-canary.dc5a8cf",
115
+ "@astryxdesign/core": "0.7.5-canary.dc5a8cf",
116
+ "@astryxdesign/lab": "0.7.5-canary.dc5a8cf",
117
+ "@astryxdesign/theme-neutral": "0.7.5-canary.dc5a8cf"
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.dae1747",
135
- "@astryxdesign/core": "0.7.5-canary.dae1747",
136
- "@astryxdesign/lab": "0.7.5-canary.dae1747",
137
- "@astryxdesign/theme-neutral": "0.7.5-canary.dae1747",
134
+ "@astryxdesign/charts": "0.7.5-canary.dc5a8cf",
135
+ "@astryxdesign/core": "0.7.5-canary.dc5a8cf",
136
+ "@astryxdesign/lab": "0.7.5-canary.dc5a8cf",
137
+ "@astryxdesign/theme-neutral": "0.7.5-canary.dc5a8cf",
138
138
  "@heroicons/react": "^2.2.0",
139
139
  "@stylexjs/stylex": "^0.19.0",
140
140
  "@types/babel__core": "^7.20.5",