@astryxdesign/cli 0.7.15 → 0.7.16-canary.g56680f6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +5 -3
  2. package/api/component/_adapter.d.mts +1 -1
  3. package/api/component/_adapter.mjs +28 -1
  4. package/api/doctor/_adapter.d.mts +17 -0
  5. package/api/doctor/_adapter.mjs +35 -0
  6. package/api/doctor/doctor.mjs +18 -4
  7. package/api/integration/validate-integration.mjs +1 -1
  8. package/api/theme/_adapter.d.mts +5 -2
  9. package/api/theme/_adapter.mjs +43 -12
  10. package/api/theme/build/build.d.mts +15 -23
  11. package/api/theme/build/build.mjs +185 -39
  12. package/api/theme/eject/eject.mjs +22 -1
  13. package/api/theme/template/template.d.mts +19 -0
  14. package/api/theme/template/template.mjs +91 -19
  15. package/api/theme/theme.type.d.mts +5 -1
  16. package/api/theme/theme.type.mjs +2 -1
  17. package/api/theme/themeBuild.doc.mjs +3 -3
  18. package/api/theme/themeEject.doc.mjs +1 -1
  19. package/api/theme/themeTemplate.doc.mjs +9 -3
  20. package/api/theme-edit/_adapter.d.mts +21 -0
  21. package/api/theme-edit/_adapter.mjs +176 -22
  22. package/api/theme-edit/_check.d.mts +7 -0
  23. package/api/theme-edit/_check.mjs +1050 -173
  24. package/api/theme-edit/_color.d.mts +2 -8
  25. package/api/theme-edit/_color.mjs +292 -219
  26. package/api/theme-edit/_compiler.d.mts +1 -0
  27. package/api/theme-edit/_compiler.mjs +20 -1
  28. package/api/theme-edit/_context.d.mts +21 -0
  29. package/api/theme-edit/_context.mjs +235 -12
  30. package/api/theme-edit/_css.d.mts +50 -1
  31. package/api/theme-edit/_css.mjs +310 -28
  32. package/api/theme-edit/_edit.d.mts +9 -0
  33. package/api/theme-edit/_edit.mjs +907 -123
  34. package/api/theme-edit/_how-commands.d.mts +11 -26
  35. package/api/theme-edit/_how-commands.mjs +30 -2
  36. package/api/theme-edit/_how-question.d.mts +7 -0
  37. package/api/theme-edit/_how-question.mjs +1304 -176
  38. package/api/theme-edit/_how.mjs +144 -30
  39. package/api/theme-edit/_palette.d.mts +6 -0
  40. package/api/theme-edit/_palette.mjs +164 -62
  41. package/api/theme-edit/_parts.d.mts +16 -0
  42. package/api/theme-edit/_parts.mjs +49 -1
  43. package/api/theme-edit/_png.mjs +19 -14
  44. package/api/theme-edit/_preview-app.mjs +514 -27
  45. package/api/theme-edit/_preview.d.mts +11 -0
  46. package/api/theme-edit/_preview.mjs +245 -24
  47. package/api/theme-edit/_project.d.mts +11 -0
  48. package/api/theme-edit/_project.mjs +35 -9
  49. package/api/theme-edit/_settings.d.mts +122 -5
  50. package/api/theme-edit/_settings.mjs +1363 -71
  51. package/api/theme-edit/_tables.d.mts +19 -0
  52. package/api/theme-edit/_tables.mjs +205 -149
  53. package/api/theme-edit/_vet.d.mts +42 -0
  54. package/api/theme-edit/_vet.mjs +144 -0
  55. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  56. package/api/theme-edit/theme-edit.type.mjs +1 -1
  57. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  58. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  59. package/assets/docs/tree/single-component.doc.mjs +11 -2
  60. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  61. package/assets/docs.generated.json +2 -2
  62. package/assets/preview-app/next.config.mjs +7 -1
  63. package/assets/preview-app/src/app/globals.css +1 -0
  64. package/assets/self-audit.generated.json +1 -1
  65. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  66. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  67. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  68. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  69. package/assets/templates/components.generated.json +1 -1
  70. package/assets/templates/pages/dashboard/page.tsx +1 -1
  71. package/authoring/doctypes/_schema.d.mts +52 -5
  72. package/authoring/doctypes/_schema.mjs +62 -7
  73. package/authoring/doctypes/base/type.ts +10 -0
  74. package/authoring/doctypes/component/component.doc.mjs +1 -1
  75. package/authoring/doctypes/function/function.doc.mjs +6 -0
  76. package/authoring/doctypes/function/type.ts +3 -0
  77. package/authoring/doctypes/legacy.mjs +5 -1
  78. package/authoring/index.d.ts +1 -0
  79. package/clients/cli/build-id.generated.json +1 -1
  80. package/clients/cli/commands/doctor.doc.mjs +2 -2
  81. package/clients/cli/commands/experimental/theme.mjs +188 -37
  82. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  83. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  84. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  85. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  86. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  87. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  88. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  89. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  90. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  91. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  92. package/clients/cli/commands/theme.mjs +93 -10
  93. package/clients/cli/formatters/index.mjs +7 -4
  94. package/clients/cli/lib/cli-error.mjs +9 -3
  95. package/clients/cli/lib/component-format.mjs +27 -9
  96. package/clients/cli/lib/json-shim.mjs +40 -2
  97. package/clients/cli/manifest.generated.json +1 -1
  98. package/foundation/config/project.mjs +50 -14
  99. package/foundation/discovery/theme-discovery.d.mts +5 -1
  100. package/foundation/discovery/theme-discovery.mjs +24 -3
  101. package/foundation/fs/gather-cache.d.mts +9 -2
  102. package/foundation/fs/gather-cache.mjs +36 -10
  103. package/foundation/fs/paths.d.mts +16 -0
  104. package/foundation/fs/paths.mjs +25 -0
  105. package/foundation/render/host-exit.d.mts +8 -0
  106. package/foundation/render/host-exit.mjs +11 -0
  107. package/foundation/render/page-host.mjs +56 -10
  108. package/foundation/render/page-worker.mjs +14 -0
  109. package/foundation/render/render-page.mjs +37 -2
  110. package/foundation/response/error-codes.d.mts +2 -1
  111. package/foundation/response/error-codes.d.ts +1 -0
  112. package/foundation/response/error-codes.doc.mjs +5 -0
  113. package/foundation/response/error-codes.mjs +3 -0
  114. package/foundation/response/json.d.mts +15 -0
  115. package/foundation/response/json.mjs +52 -1
  116. package/foundation/response/response-types.doc.mjs +1 -1
  117. package/package.json +7 -6
@@ -1320,6 +1320,28 @@ export class Project {
1320
1320
  return integration?.issuesUrl;
1321
1321
  }
1322
1322
 
1323
+ /**
1324
+ * The passes that find every integration issue: template and component
1325
+ * replacement validity (over Core plus every integration), then each
1326
+ * integration's own checks.
1327
+ */
1328
+ async #runIssuePasses() {
1329
+ // Template replacement validity depends on the combined Core +
1330
+ // integration catalog. Resolve it first so issue results never depend
1331
+ // on which discovery method the caller happened to invoke earlier. Only
1332
+ // an integration's own templates can replace one, so with none, Core's
1333
+ // templates stay unread.
1334
+ if (this.#loadedIntegrations.some(hasTemplatesRoot)) {
1335
+ await this.templates();
1336
+ }
1337
+ // Component replacement validity likewise depends on Core plus every
1338
+ // integration's components.
1339
+ await this.componentReplacements();
1340
+ for (const integration of this.#loadedIntegrations) {
1341
+ await this.#collectIssues(integration);
1342
+ }
1343
+ }
1344
+
1323
1345
  /**
1324
1346
  * The accumulated integration issues (deduped by package, code, message).
1325
1347
  * When called directly, also validates any configured integration not yet
@@ -1332,20 +1354,34 @@ export class Project {
1332
1354
  // templates and components declare no replacement. A project with no
1333
1355
  // integration skips them.
1334
1356
  if (this.#loadedIntegrations.length > 0) {
1335
- // Template replacement validity depends on the combined Core +
1336
- // integration catalog. Resolve it first so issue results never depend
1337
- // on which discovery method the caller happened to invoke earlier. Only
1338
- // an integration's own templates can replace one, so with none, Core's
1339
- // templates stay unread.
1340
- if (this.#loadedIntegrations.some(hasTemplatesRoot)) {
1341
- await this.templates();
1342
- }
1343
- // Component replacement validity likewise depends on Core plus every
1344
- // integration's components.
1345
- await this.componentReplacements();
1346
- for (const integration of this.#loadedIntegrations) {
1347
- await this.#collectIssues(integration);
1348
- }
1357
+ // A function of the files the passes read and of the issues already
1358
+ // found (which the key holds): the kept gather stamps the files, so a
1359
+ // later run with every one unchanged reads the whole list back and
1360
+ // skips the passes, discovery included.
1361
+ const before = this.#issues.map(i => ({...i}));
1362
+ const all = await persistedGather(
1363
+ [
1364
+ 'project-issues',
1365
+ this.#cwd,
1366
+ // The Core the replacement pass reads: a carried Core for everyday
1367
+ // commands, the project's own for doctor.
1368
+ this.#core,
1369
+ this.coreDir() ?? null,
1370
+ this.#loadedIntegrations.map(
1371
+ integration => integration.__packageDir ?? integration.name ?? null,
1372
+ ),
1373
+ Boolean(this.#config.experimental?.iconSet),
1374
+ before,
1375
+ ],
1376
+ async () => {
1377
+ await this.#runIssuePasses();
1378
+ return this.#issues.map(i => ({...i}));
1379
+ },
1380
+ ISSUES_CODEC,
1381
+ );
1382
+ this.#issues = all.map((/** @type {ProjectIntegrationIssue} */ i) => ({
1383
+ ...i,
1384
+ }));
1349
1385
  }
1350
1386
  // Return a stable copy so callers can't mutate internal state.
1351
1387
  return this.#issues.map(i => ({...i}));
@@ -30,9 +30,13 @@ export function themeImportPackage(theme: DiscoveredTheme): string;
30
30
  /**
31
31
  * Every module a theme source file imports or re-exports, as written.
32
32
  * @param {string} file
33
+ * @param {{withRequire?: boolean}} [options] `withRequire`: also
34
+ * `require('./x')` and TypeScript `import x = require('./x')`.
33
35
  * @returns {string[]}
34
36
  */
35
- export function themeFileImports(file: string): string[];
37
+ export function themeFileImports(file: string, options?: {
38
+ withRequire?: boolean;
39
+ }): string[];
36
40
  /**
37
41
  * How messages about a theme descriptor name it.
38
42
  * @param {string} docPath
@@ -169,9 +169,11 @@ class ThemeRuntimeExportError extends Error {}
169
169
  * Every string specifier a module imports, re-exports, or imports dynamically.
170
170
  * @param {string} file
171
171
  * @param {any} jscodeshift
172
+ * @param {{withRequire?: boolean}} [options] `withRequire`: also
173
+ * `require('./x')` and TypeScript `import x = require('./x')`
172
174
  * @returns {string[]}
173
175
  */
174
- function moduleSpecifiers(file, jscodeshift) {
176
+ function moduleSpecifiers(file, jscodeshift, {withRequire = false} = {}) {
175
177
  const parser = /\.(?:ts|tsx|mts|cts)$/u.test(file) ? 'tsx' : 'babel';
176
178
  const j = jscodeshift.withParser(parser);
177
179
  const root = j(fs.readFileSync(file, 'utf-8'));
@@ -207,6 +209,23 @@ function moduleSpecifiers(file, jscodeshift) {
207
209
  specifiers.push(importPath.node.source.value);
208
210
  }
209
211
  });
212
+ if (withRequire) {
213
+ // CommonJS `require('./x')` and TypeScript `import x = require('./x')`.
214
+ root.find(j.CallExpression).forEach((/** @type {any} */ callPath) => {
215
+ const {callee, arguments: args} = callPath.node;
216
+ if (
217
+ callee?.type === 'Identifier' &&
218
+ callee.name === 'require' &&
219
+ typeof args?.[0]?.value === 'string'
220
+ )
221
+ specifiers.push(args[0].value);
222
+ });
223
+ root.find(j.TSImportEqualsDeclaration).forEach((/** @type {any} */ p) => {
224
+ const ref = p.node.moduleReference;
225
+ const value = ref?.expression?.value ?? ref?.argument?.value;
226
+ if (typeof value === 'string') specifiers.push(value);
227
+ });
228
+ }
210
229
 
211
230
  return specifiers;
212
231
  }
@@ -214,10 +233,12 @@ function moduleSpecifiers(file, jscodeshift) {
214
233
  /**
215
234
  * Every module a theme source file imports or re-exports, as written.
216
235
  * @param {string} file
236
+ * @param {{withRequire?: boolean}} [options] `withRequire`: also
237
+ * `require('./x')` and TypeScript `import x = require('./x')`.
217
238
  * @returns {string[]}
218
239
  */
219
- export function themeFileImports(file) {
220
- return moduleSpecifiers(file, sourceParser());
240
+ export function themeFileImports(file, options = {}) {
241
+ return moduleSpecifiers(file, sourceParser(), options);
221
242
  }
222
243
 
223
244
  /**
@@ -2,7 +2,9 @@
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
4
  /**
5
- * The running recorded run's reads and variables, for tests: null outside one.
5
+ * The running recorded run's reads and variables, or null outside one: for
6
+ * tests, and for a caller that keeps a value only in a recorded run (doctor's
7
+ * kept checks).
6
8
  * @returns {{reads: Map<string, string>, env: Map<string, string | null>} | null}
7
9
  */
8
10
  export function recordedRun(): {
@@ -39,9 +41,14 @@ export function recordRunFor<T>(argv: string[], fn: () => Promise<T>): Promise<T
39
41
  * tests; `recordRunFor` decides which runs are recorded.
40
42
  * @template T
41
43
  * @param {() => Promise<T>} fn
44
+ * @param {{armedThroughout?: boolean}} [options] - `armedThroughout`: record
45
+ * modules and variables until the run ends, not only until each gather
46
+ * ends, for a run whose later gathers read modules loaded in between.
42
47
  * @returns {Promise<T>}
43
48
  */
44
- export function recordRun<T>(fn: () => Promise<T>): Promise<T>;
49
+ export function recordRun<T>(fn: () => Promise<T>, { armedThroughout }?: {
50
+ armedThroughout?: boolean;
51
+ }): Promise<T>;
45
52
  /**
46
53
  * The gather `load` returns, or the one a run with the same key stored while
47
54
  * every input it read is unchanged (see the file header).
@@ -13,9 +13,12 @@
13
13
  * gathers fresh and stores that.
14
14
  * @position Used by search's adapter (api/search/_adapter.mjs) for the
15
15
  * catalog `search` and `build` rank, and by the project
16
- * (foundation/config/project.mjs) for each integration's contribution-check
17
- * results, which `component`, `template`, `theme`, `discover` and `search`
18
- * report. Gathers are kept only once the folder exists: the first such run
16
+ * (foundation/config/project.mjs) for its integration issues: each
17
+ * integration's contribution-check results and the whole list (with the
18
+ * template and component replacement passes), which `component`,
19
+ * `template`, `theme`, `discover` and `search` report, and by `doctor`
20
+ * (api/doctor/_adapter.mjs) for its file-only docs checks, in a run that
21
+ * records modules and variables to its end. Gathers are kept only once the folder exists: the first such run
19
22
  * on a machine just makes it, so a one-off run pays nothing to store one. Only a published CLI stores anything:
20
23
  * its build id (clients/cli/build-id.generated.json, written at `prepack`)
21
24
  * names its exact code, so a checkout, whose code may change between runs
@@ -67,6 +70,8 @@ const KEPT_COMMANDS = new Set([
67
70
  'template',
68
71
  'theme',
69
72
  'discover',
73
+ // The project check alone (no subcommand): its docs checks are kept.
74
+ 'doctor',
70
75
  ]);
71
76
 
72
77
  /** Where `prepack` writes the id of the package's exact contents. */
@@ -91,13 +96,16 @@ const UNSET = null;
91
96
  * their states, modules it loaded with theirs, and environment variables with
92
97
  * their values. Files and folders are recorded for the whole run; modules and
93
98
  * variables only while the run is armed: from its start to the end of its
94
- * first gather, and during each later gather. Null outside a recorded run.
95
- * @type {{reads: Map<string, string>, env: Map<string, string | null>, arm: () => boolean, disarm: () => void} | null}
99
+ * first gather, and during each later gather, or, in a run armed throughout
100
+ * (`doctor`), to its end. Null outside a recorded run.
101
+ * @type {{reads: Map<string, string>, env: Map<string, string | null>, arm: () => boolean, disarm: () => void, armedThroughout: boolean} | null}
96
102
  */
97
103
  let run = null;
98
104
 
99
105
  /**
100
- * The running recorded run's reads and variables, for tests: null outside one.
106
+ * The running recorded run's reads and variables, or null outside one: for
107
+ * tests, and for a caller that keeps a value only in a recorded run (doctor's
108
+ * kept checks).
101
109
  * @returns {{reads: Map<string, string>, env: Map<string, string | null>} | null}
102
110
  */
103
111
  export function recordedRun() {
@@ -225,6 +233,8 @@ export async function recordRunFor(argv, fn) {
225
233
  if (
226
234
  !command ||
227
235
  !KEPT_COMMANDS.has(command) ||
236
+ (command === 'doctor' &&
237
+ argv.filter(arg => !arg.startsWith('-')).length > 1) ||
228
238
  runsUnderPnp() ||
229
239
  currentUid() == null ||
230
240
  withoutRecording(buildId) == null ||
@@ -240,6 +250,10 @@ export async function recordRunFor(argv, fn) {
240
250
  // it, so a one-off run never pays to store one.
241
251
  const dir = cacheDirPath();
242
252
  if (!withoutRecording(() => fs.existsSync(dir))) {
253
+ // Once the per-user cache folder exists doctor uses it; it never makes
254
+ // it, so a doctor alone changes nothing on the machine (nor its own
255
+ // cache row).
256
+ if (command === 'doctor') return fn();
243
257
  try {
244
258
  withoutRecording(() => fs.mkdirSync(dir, {recursive: true, mode: 0o700}));
245
259
  } catch {
@@ -250,7 +264,10 @@ export async function recordRunFor(argv, fn) {
250
264
  // A folder the cache would refuse (not the user's own, open to others, a
251
265
  // link) leaves the run exactly as without the cache: no hook is installed.
252
266
  if (withoutRecording(gatherCacheDir) == null) return fn();
253
- return recordRun(fn);
267
+ // doctor's kept checks read docs modules that load between its gathers, so
268
+ // its run records modules and variables to the end, not only during each
269
+ // gather.
270
+ return recordRun(fn, {armedThroughout: command === 'doctor'});
254
271
  }
255
272
 
256
273
  /**
@@ -258,9 +275,12 @@ export async function recordRunFor(argv, fn) {
258
275
  * tests; `recordRunFor` decides which runs are recorded.
259
276
  * @template T
260
277
  * @param {() => Promise<T>} fn
278
+ * @param {{armedThroughout?: boolean}} [options] - `armedThroughout`: record
279
+ * modules and variables until the run ends, not only until each gather
280
+ * ends, for a run whose later gathers read modules loaded in between.
261
281
  * @returns {Promise<T>}
262
282
  */
263
- export async function recordRun(fn) {
283
+ export async function recordRun(fn, {armedThroughout = false} = {}) {
264
284
  const registerHooks = /** @type {any} */ (nodeModule).registerHooks;
265
285
  if (typeof registerHooks !== 'function' || run != null) return fn();
266
286
  /** @type {Map<string, string>} */
@@ -346,7 +366,7 @@ export async function recordRun(fn) {
346
366
  }
347
367
  };
348
368
  if (!arm()) return fn();
349
- run = {reads, env, arm, disarm};
369
+ run = {reads, env, arm, disarm, armedThroughout};
350
370
  try {
351
371
  return await recordReads(reads, fn, {exact: true});
352
372
  } finally {
@@ -509,7 +529,7 @@ export async function persistedGather(key, load, codec, keep = () => true) {
509
529
  try {
510
530
  return await gatherAt(key, load, codec, keep);
511
531
  } finally {
512
- if (--gatherDepth === 0) run?.disarm();
532
+ if (--gatherDepth === 0 && !run?.armedThroughout) run?.disarm();
513
533
  }
514
534
  }
515
535
 
@@ -761,6 +781,12 @@ export function runsUnderPnp() {
761
781
  * `pnp`: whether this run is under Yarn Plug'n'Play's loader (runsUnderPnp)
762
782
  */
763
783
  export function gatherCacheSummary() {
784
+ // The cache's own bookkeeping, never an input of what it keeps.
785
+ return withoutRecording(summarize);
786
+ }
787
+
788
+ /** @returns {{dir: string, bytes: number, entries: number, pnp: boolean} | null} */
789
+ function summarize() {
764
790
  if (buildId() == null) return null;
765
791
  const dir = gatherCacheDir();
766
792
  if (dir == null) return null;
@@ -68,6 +68,22 @@ export function findProjectCoreDir(startDir?: string): string | null;
68
68
  * @returns {string|null}
69
69
  */
70
70
  export function findPackageRoot(startDir: string): string | null;
71
+ /**
72
+ * A path a command writes in a project, read the same way by every theme
73
+ * command: from the working folder when given, from the project root (the
74
+ * nearest folder with a package.json, else the working folder) when not,
75
+ * and with a backslash as a folder separator on every platform.
76
+ * @param {string} cwd
77
+ * @param {string | undefined} typed the path as given, or undefined
78
+ * @param {string} fallback the path from the project root when none is given
79
+ * @returns {{projectDir: string, typed: string | undefined, relative: string}}
80
+ * `typed`: the path as given with `/`; `relative`: from the project root
81
+ */
82
+ export function projectWritePath(cwd: string, typed: string | undefined, fallback: string): {
83
+ projectDir: string;
84
+ typed: string | undefined;
85
+ relative: string;
86
+ };
71
87
  /**
72
88
  * The Astryx project `startDir` belongs to: the nearest folder at or above it
73
89
  * whose package.json declares an Astryx package (`@astryxdesign/*`, or the
@@ -339,6 +339,31 @@ export function findPackageRoot(startDir) {
339
339
  return null;
340
340
  }
341
341
 
342
+ /**
343
+ * A path a command writes in a project, read the same way by every theme
344
+ * command: from the working folder when given, from the project root (the
345
+ * nearest folder with a package.json, else the working folder) when not,
346
+ * and with a backslash as a folder separator on every platform.
347
+ * @param {string} cwd
348
+ * @param {string | undefined} typed the path as given, or undefined
349
+ * @param {string} fallback the path from the project root when none is given
350
+ * @returns {{projectDir: string, typed: string | undefined, relative: string}}
351
+ * `typed`: the path as given with `/`; `relative`: from the project root
352
+ */
353
+ export function projectWritePath(cwd, typed, fallback) {
354
+ const projectDir = findPackageRoot(cwd) ?? path.resolve(cwd);
355
+ const given = typed == null ? undefined : String(typed).replace(/\\/g, '/');
356
+ const absolute =
357
+ given == null ? path.join(projectDir, fallback) : path.resolve(cwd, given);
358
+ return {
359
+ projectDir,
360
+ typed: given,
361
+ relative: path.isAbsolute(given ?? '')
362
+ ? /** @type {string} */ (given)
363
+ : path.relative(projectDir, absolute) || '.',
364
+ };
365
+ }
366
+
342
367
  /**
343
368
  * The Astryx project `startDir` belongs to: the nearest folder at or above it
344
369
  * whose package.json declares an Astryx package (`@astryxdesign/*`, or the
@@ -0,0 +1,8 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ export namespace HOST_EXIT {
5
+ let disconnected: number;
6
+ let timeout: number;
7
+ let noChannel: number;
8
+ }
@@ -0,0 +1,11 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The exit codes of the render's host process (page-host.mjs) for each
5
+ * way it ends without sending an answer. render-page.mjs reads them to say
6
+ * why.
7
+ * @position foundation/render — imported by page-host.mjs and render-page.mjs
8
+ */
9
+
10
+ /** Exit codes for each way the host ends without sending an answer. */
11
+ export const HOST_EXIT = {disconnected: 70, timeout: 71, noChannel: 72};
@@ -9,26 +9,53 @@
9
9
  * when the CLI goes away (the IPC channel closes) or when its own time limit
10
10
  * passes, so a page that never finishes never outlives the CLI.
11
11
  *
12
+ * When the page ends without an answer, the host says why: the last stage the
13
+ * page reported, how long it ran, the memory left, and the last lines the page
14
+ * wrote to stderr. Each way the host itself ends without an answer has its own
15
+ * exit code (HOST_EXIT), so none of them reads as a clean exit.
16
+ *
12
17
  * @input argv[2]: JSON {entry, root, served, withoutSegmenter, timeoutMs}
13
- * @output one IPC message: the worker's answer, or {hostError: message}, or
14
- * {hostExit: code}
18
+ * @output one IPC message: the worker's answer, or {hostError, stage}, or
19
+ * {hostExit, reason, stage, elapsedMs, rssMb, freeMb, stderrTail}
15
20
  * @position foundation/render — started by render-page.mjs
16
21
  */
17
22
 
23
+ import * as os from 'node:os';
18
24
  import {Worker} from 'node:worker_threads';
25
+ import {HOST_EXIT} from './host-exit.mjs';
19
26
 
20
27
  /** @type {{entry: string, root: string, served: {dir: string, integrations: string[]} | null, withoutSegmenter: boolean, timeoutMs: number}} */
21
28
  const input = JSON.parse(process.argv[2] ?? '{}');
29
+ const started = Date.now();
30
+ let stage = 'starting';
31
+ let stderrTail = '';
32
+ let answered = false;
22
33
 
23
34
  /** @param {unknown} message */
24
35
  function answer(message) {
25
- if (!process.connected) process.exit(0);
36
+ if (answered) return;
37
+ answered = true;
38
+ if (!process.connected) process.exit(HOST_EXIT.noChannel);
26
39
  process.send?.(message, () => process.exit(0));
27
40
  }
28
41
 
29
- process.once('disconnect', () => process.exit(0));
42
+ /** What the page was doing and what it had left, for an end without an answer. */
43
+ function state() {
44
+ return {
45
+ stage,
46
+ elapsedMs: Date.now() - started,
47
+ rssMb: Math.round(process.memoryUsage().rss / 2 ** 20),
48
+ freeMb: Math.round(os.freemem() / 2 ** 20),
49
+ stderrTail: stderrTail.trim().split('\n').slice(-5).join('\n'),
50
+ };
51
+ }
52
+
53
+ process.once('disconnect', () => process.exit(HOST_EXIT.disconnected));
30
54
  // A margin past the CLI's own limit, so the CLI reports the timeout first.
31
- setTimeout(() => process.exit(0), input.timeoutMs + 5000);
55
+ setTimeout(() => {
56
+ answer({hostExit: null, reason: 'host-timeout', ...state()});
57
+ setTimeout(() => process.exit(HOST_EXIT.timeout), 1000).unref();
58
+ }, input.timeoutMs + 5000);
32
59
 
33
60
  const worker = new Worker(new URL('./page-worker.mjs', import.meta.url), {
34
61
  workerData: input,
@@ -37,9 +64,28 @@ const worker = new Worker(new URL('./page-worker.mjs', import.meta.url), {
37
64
  stderr: true,
38
65
  resourceLimits: {maxOldGenerationSizeMb: 4096},
39
66
  });
40
- // The page's own writes to stdout/stderr never reach the CLI's output.
67
+ // The page's own writes to stdout/stderr never reach the CLI's output; the
68
+ // last stderr lines go into the reason for an end without an answer.
41
69
  worker.stdout.resume();
42
- worker.stderr.resume();
43
- worker.once('message', answer);
44
- worker.once('error', (/** @type {any} */ error) => answer({hostError: String(error?.message ?? error)}));
45
- worker.once('exit', code => answer({hostExit: code}));
70
+ worker.stderr.setEncoding('utf8');
71
+ worker.stderr.on('data', (/** @type {string} */ chunk) => {
72
+ stderrTail = (stderrTail + chunk).slice(-4000);
73
+ });
74
+ worker.on('message', (/** @type {any} */ message) => {
75
+ // A progress note, not the answer.
76
+ if (
77
+ message &&
78
+ typeof message.stage === 'string' &&
79
+ Object.keys(message).length === 1
80
+ ) {
81
+ stage = message.stage;
82
+ return;
83
+ }
84
+ answer(message);
85
+ });
86
+ worker.once('error', (/** @type {any} */ error) =>
87
+ answer({hostError: String(error?.message ?? error), stage}),
88
+ );
89
+ worker.once('exit', code =>
90
+ answer({hostExit: code, reason: 'worker-ended', ...state()}),
91
+ );
@@ -835,10 +835,20 @@ function classify(e) {
835
835
  return fail('ERR_RENDER_FAILED', `The page threw while rendering: ${message.split('\n')[0]}`);
836
836
  }
837
837
 
838
+ /**
839
+ * Tell the host what the page is doing, so an end without an answer can say
840
+ * where it ended.
841
+ * @param {string} name
842
+ */
843
+ function reach(name) {
844
+ parentPort?.postMessage({stage: name});
845
+ }
846
+
838
847
  try {
839
848
  /** @type {any} */
840
849
  let mod;
841
850
  try {
851
+ reach('importing the page');
842
852
  mod = await jiti.import(entry);
843
853
  } catch (e) {
844
854
  classify(e);
@@ -857,6 +867,7 @@ try {
857
867
  /** @type {any} */
858
868
  let server;
859
869
  try {
870
+ reach('loading React');
860
871
  React = await jiti.import('react');
861
872
  createElement = React.createElement;
862
873
  useContext = React.useContext;
@@ -874,11 +885,13 @@ try {
874
885
  /** @type {false | 'error' | 'changed' | 'rerendered'} */
875
886
  let chartsAlone = false;
876
887
  try {
888
+ reach('rendering on the server');
877
889
  markup = server.renderToStaticMarkup(React.createElement(Page));
878
890
  if (charts.length > 0) {
879
891
  // Drawing the page again re-runs its code: what it prints then was
880
892
  // already reported by the server render.
881
893
  const printed = logs.length;
894
+ reach('drawing charts');
882
895
  ({markup, failed: chartsFailed, alone: chartsAlone} = await drawCharts(markup, Page));
883
896
  logs.length = printed;
884
897
  }
@@ -893,6 +906,7 @@ try {
893
906
  /** @type {string} */
894
907
  let css = '';
895
908
  if (stylexRules.length > 0) {
909
+ reach('compiling styles');
896
910
  css = stylexPlugin.processStylexRules(stylexRules, {useLayers: false});
897
911
  }
898
912
  parentPort?.postMessage({
@@ -27,6 +27,7 @@ import {sourceBlock} from './source-block.mjs';
27
27
  import {embeddedPathProblem} from './embedded-files.mjs';
28
28
  import {resolveServed} from './served-packages.mjs';
29
29
  import {CHART_CSS} from './charts.mjs';
30
+ import {HOST_EXIT} from './host-exit.mjs';
30
31
 
31
32
  /** How long one page may take to render before it is stopped. */
32
33
  export const RENDER_TIMEOUT_MS = 60_000;
@@ -273,6 +274,40 @@ function crashError(how, {crashed, withoutSegmenter}) {
273
274
  );
274
275
  }
275
276
 
277
+ /**
278
+ * The error for a page that ended without an answer, with why: the stage it
279
+ * reported last, how long it ran, the memory left, and its last stderr line.
280
+ * @param {any} message the host's {hostExit, reason, stage, elapsedMs, rssMb, freeMb, stderrTail}
281
+ */
282
+ function noAnswerError({hostExit, reason, stage, elapsedMs, rssMb, freeMb, stderrTail}) {
283
+ const detail = {reason, exit: hostExit, stage, elapsedMs, rssMb, freeMb, ...(stderrTail ? {stderrTail} : {})};
284
+ const where = stage ? ` while ${stage}` : '';
285
+ const seconds = Math.round((elapsedMs ?? 0) / 1000);
286
+ if (reason === 'host-timeout') {
287
+ return new RenderError('ERR_RENDER_TIMEOUT', `The page's process stopped at its own time limit${where}, after ${seconds} seconds, before this process read an answer.`, detail);
288
+ }
289
+ const last = stderrTail ? ` Its last output: ${String(stderrTail).split('\n').at(-1)}` : '';
290
+ return new RenderError(
291
+ 'ERR_RENDER_FAILED',
292
+ `The page stopped rendering without an answer (exit ${hostExit})${where}, after ${seconds} seconds, with ${freeMb} MB of memory free.${last}`,
293
+ detail,
294
+ );
295
+ }
296
+
297
+ /** The error for a host process that ended, without a signal, before it answered. */
298
+ function hostEndError(/** @type {number | null} */ code) {
299
+ if (code === HOST_EXIT.disconnected) {
300
+ return new RenderError('ERR_RENDER_FAILED', "The page's process lost its channel to this process and stopped without an answer.", {reason: 'disconnected', exit: code});
301
+ }
302
+ if (code === HOST_EXIT.noChannel) {
303
+ return new RenderError('ERR_RENDER_FAILED', "The page's process had no channel left to send its answer on.", {reason: 'no-channel', exit: code});
304
+ }
305
+ if (code === HOST_EXIT.timeout) {
306
+ return new RenderError('ERR_RENDER_TIMEOUT', "The page's process stopped at its own time limit before this process read an answer.", {reason: 'host-timeout', exit: code});
307
+ }
308
+ return new RenderError('ERR_RENDER_FAILED', `The page's process ended without an answer (exit ${code}).`, {reason: 'host-ended', exit: code});
309
+ }
310
+
276
311
  /**
277
312
  * Run the page in a host process (page-host.mjs), stopping it after
278
313
  * `timeoutMs`. The host runs the page in a worker thread, and it exits when
@@ -325,7 +360,7 @@ function runWorker(input, timeoutMs) {
325
360
  : new RenderError('ERR_RENDER_FAILED', `The page could not be rendered: ${text.split('\n')[0]}`),
326
361
  );
327
362
  } else if (message?.hostExit !== undefined) {
328
- reject(new RenderError('ERR_RENDER_FAILED', `The page stopped rendering without an answer (exit ${message.hostExit}).`));
363
+ reject(noAnswerError(message));
329
364
  } else {
330
365
  resolve(message);
331
366
  }
@@ -339,7 +374,7 @@ function runWorker(input, timeoutMs) {
339
374
  const crash = crashOf(code, signal);
340
375
  if (crash) resolve({crashed: crash});
341
376
  else if (signal) reject(crashError(signal, {crashed: false, withoutSegmenter: input.withoutSegmenter}));
342
- else reject(new RenderError('ERR_RENDER_FAILED', `The page stopped rendering without an answer (exit ${code}).`));
377
+ else reject(hostEndError(code));
343
378
  });
344
379
  });
345
380
  });
@@ -88,6 +88,7 @@ export function allErrorCodes(): string[];
88
88
  * | 'ERR_WRITE_FAILED'
89
89
  * | 'ERR_THEME_INVALID'
90
90
  * | 'ERR_THEME_LOAD'
91
+ * | 'ERR_THEME_STALE'
91
92
  * | 'ERR_PALETTE_GENERATION'
92
93
  * | 'ERR_VERSION_DETECT'
93
94
  * | 'ERR_INVALID_VERSION'
@@ -133,4 +134,4 @@ export const ERROR_CODES: Readonly<Record<ErrorCode, ErrorCode>>;
133
134
  /**
134
135
  * Stable error-code string union. Append-only.
135
136
  */
136
- export type ErrorCode = ("ERR_UNKNOWN" | "ERR_UNKNOWN_COMMAND" | "ERR_UNKNOWN_SUBCOMMAND" | "ERR_INVALID_OPTION" | "ERR_INVALID_ARGUMENT" | "ERR_MISSING_ARGUMENT" | "ERR_INVALID_LANG" | "ERR_INVALID_DETAIL" | "ERR_NODE_VERSION" | "ERR_CORE_NOT_FOUND" | "ERR_CORE_INCOMPATIBLE" | "ERR_UNKNOWN_COMPONENT" | "ERR_UNKNOWN_HOOK" | "ERR_UNKNOWN_TOPIC" | "ERR_UNKNOWN_SECTION" | "ERR_UNKNOWN_CATEGORY" | "ERR_UNKNOWN_TEMPLATE" | "ERR_AMBIGUOUS_TEMPLATE" | "ERR_AMBIGUOUS_COMPONENT" | "ERR_AMBIGUOUS_THEME" | "ERR_UNKNOWN_THEME" | "ERR_INTEGRATION_ROOT_CONFLICT" | "ERR_INTEGRATION_EXPORT_CONFLICT" | "ERR_UNKNOWN_PACKAGE" | "ERR_UNKNOWN_AGENT" | "ERR_UNKNOWN_FEATURE" | "ERR_UNKNOWN_CODEMOD" | "ERR_CODEMOD_FAILED" | "ERR_CODEMOD_PROTECTED" | "ERR_CODEMOD_PROTECTION_SOURCE" | "ERR_NOT_FOUND" | "ERR_NO_DOC" | "ERR_NO_SHOWCASE" | "ERR_NO_SOURCE" | "ERR_INVALID_DOC" | "ERR_FILE_NOT_FOUND" | "ERR_FILE_EXISTS" | "ERR_PATH_TRAVERSAL" | "ERR_WRITE_FAILED" | "ERR_THEME_INVALID" | "ERR_THEME_LOAD" | "ERR_PALETTE_GENERATION" | "ERR_VERSION_DETECT" | "ERR_INVALID_VERSION" | "ERR_DEP_MISSING" | "ERR_GH_CLI" | "ERR_UNKNOWN_POST" | "ERR_FETCH_FAILED" | "ERR_LAYOUT_PARSE" | "ERR_LAYOUT_INVALID" | "ERR_UNCLASSIFIED_EXIT" | "ERR_SIGNAL_TERMINATED" | "ERR_VERSIONS_UNAVAILABLE" | "ERR_PROJECT_REQUIRED" | "ERR_RENDER_COMPILE" | "ERR_RENDER_NO_DEFAULT_EXPORT" | "ERR_RENDER_MISSING_DEPENDENCY" | "ERR_RENDER_BROWSER_API" | "ERR_RENDER_ASSET_TOO_LARGE" | "ERR_RENDER_TIMEOUT" | "ERR_RENDER_FAILED" | "ERR_RENDER_NOT_ASTRYX" | "ERR_RENDER_SOURCE_DAMAGED" | "ERR_THEME_BAD_VALUE" | "ERR_THEME_NO_MODE" | "ERR_THEME_UNKNOWN_PART" | "ERR_THEME_UNKNOWN_VARIANT" | "ERR_THEME_UNKNOWN_STATE" | "ERR_THEME_PRIVATE_TOKEN" | "ERR_THEME_UNKNOWN_TOKEN" | "ERR_THEME_NO_EFFECT" | "ERR_THEME_NOT_CHECKED" | "ERR_THEME_BUSY" | "ERR_THEME_UNKNOWN_THING" | "ERR_THEME_NOT_SET" | "ERR_THEME_NOTHING_TO_UNDO");
137
+ export type ErrorCode = ("ERR_UNKNOWN" | "ERR_UNKNOWN_COMMAND" | "ERR_UNKNOWN_SUBCOMMAND" | "ERR_INVALID_OPTION" | "ERR_INVALID_ARGUMENT" | "ERR_MISSING_ARGUMENT" | "ERR_INVALID_LANG" | "ERR_INVALID_DETAIL" | "ERR_NODE_VERSION" | "ERR_CORE_NOT_FOUND" | "ERR_CORE_INCOMPATIBLE" | "ERR_UNKNOWN_COMPONENT" | "ERR_UNKNOWN_HOOK" | "ERR_UNKNOWN_TOPIC" | "ERR_UNKNOWN_SECTION" | "ERR_UNKNOWN_CATEGORY" | "ERR_UNKNOWN_TEMPLATE" | "ERR_AMBIGUOUS_TEMPLATE" | "ERR_AMBIGUOUS_COMPONENT" | "ERR_AMBIGUOUS_THEME" | "ERR_UNKNOWN_THEME" | "ERR_INTEGRATION_ROOT_CONFLICT" | "ERR_INTEGRATION_EXPORT_CONFLICT" | "ERR_UNKNOWN_PACKAGE" | "ERR_UNKNOWN_AGENT" | "ERR_UNKNOWN_FEATURE" | "ERR_UNKNOWN_CODEMOD" | "ERR_CODEMOD_FAILED" | "ERR_CODEMOD_PROTECTED" | "ERR_CODEMOD_PROTECTION_SOURCE" | "ERR_NOT_FOUND" | "ERR_NO_DOC" | "ERR_NO_SHOWCASE" | "ERR_NO_SOURCE" | "ERR_INVALID_DOC" | "ERR_FILE_NOT_FOUND" | "ERR_FILE_EXISTS" | "ERR_PATH_TRAVERSAL" | "ERR_WRITE_FAILED" | "ERR_THEME_INVALID" | "ERR_THEME_LOAD" | "ERR_THEME_STALE" | "ERR_PALETTE_GENERATION" | "ERR_VERSION_DETECT" | "ERR_INVALID_VERSION" | "ERR_DEP_MISSING" | "ERR_GH_CLI" | "ERR_UNKNOWN_POST" | "ERR_FETCH_FAILED" | "ERR_LAYOUT_PARSE" | "ERR_LAYOUT_INVALID" | "ERR_UNCLASSIFIED_EXIT" | "ERR_SIGNAL_TERMINATED" | "ERR_VERSIONS_UNAVAILABLE" | "ERR_PROJECT_REQUIRED" | "ERR_RENDER_COMPILE" | "ERR_RENDER_NO_DEFAULT_EXPORT" | "ERR_RENDER_MISSING_DEPENDENCY" | "ERR_RENDER_BROWSER_API" | "ERR_RENDER_ASSET_TOO_LARGE" | "ERR_RENDER_TIMEOUT" | "ERR_RENDER_FAILED" | "ERR_RENDER_NOT_ASTRYX" | "ERR_RENDER_SOURCE_DAMAGED" | "ERR_THEME_BAD_VALUE" | "ERR_THEME_NO_MODE" | "ERR_THEME_UNKNOWN_PART" | "ERR_THEME_UNKNOWN_VARIANT" | "ERR_THEME_UNKNOWN_STATE" | "ERR_THEME_PRIVATE_TOKEN" | "ERR_THEME_UNKNOWN_TOKEN" | "ERR_THEME_NO_EFFECT" | "ERR_THEME_NOT_CHECKED" | "ERR_THEME_BUSY" | "ERR_THEME_UNKNOWN_THING" | "ERR_THEME_NOT_SET" | "ERR_THEME_NOTHING_TO_UNDO");
@@ -47,6 +47,7 @@ export type ErrorCode =
47
47
  | 'ERR_WRITE_FAILED'
48
48
  | 'ERR_THEME_INVALID'
49
49
  | 'ERR_THEME_LOAD'
50
+ | 'ERR_THEME_STALE'
50
51
  | 'ERR_VERSION_DETECT'
51
52
  | 'ERR_INVALID_VERSION'
52
53
  | 'ERR_DEP_MISSING'
@@ -219,6 +219,11 @@ export const doc = {
219
219
  description:
220
220
  'A theme file could not be loaded / parsed into a defineTheme result.',
221
221
  },
222
+ {
223
+ value: 'ERR_THEME_STALE',
224
+ description:
225
+ '`theme build --check` found stale or missing outputs: exit 1, in the check result (`code`), not an error.',
226
+ },
222
227
  {
223
228
  value: 'ERR_PALETTE_GENERATION',
224
229
  description:
@@ -77,6 +77,7 @@
77
77
  * | 'ERR_WRITE_FAILED'
78
78
  * | 'ERR_THEME_INVALID'
79
79
  * | 'ERR_THEME_LOAD'
80
+ * | 'ERR_THEME_STALE'
80
81
  * | 'ERR_PALETTE_GENERATION'
81
82
  * | 'ERR_VERSION_DETECT'
82
83
  * | 'ERR_INVALID_VERSION'
@@ -219,6 +220,8 @@ export const ERROR_CODES = Object.freeze({
219
220
  ERR_THEME_INVALID: 'ERR_THEME_INVALID',
220
221
  /** A theme file could not be loaded / parsed into a defineTheme result. */
221
222
  ERR_THEME_LOAD: 'ERR_THEME_LOAD',
223
+ /** `--check` found built outputs stale or missing (a result, exit 1). */
224
+ ERR_THEME_STALE: 'ERR_THEME_STALE',
222
225
 
223
226
  // ── Palette generation ──────────────────────────────────────────
224
227
  /** A palette generation request or its constraints were invalid. */