@astryxdesign/cli 0.7.15 → 0.7.16-canary.g54dd64e

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 (123) 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/pack-check.mjs +13 -7
  8. package/api/integration/validate-integration.mjs +1 -1
  9. package/api/theme/_adapter.d.mts +5 -2
  10. package/api/theme/_adapter.mjs +43 -12
  11. package/api/theme/build/build.d.mts +64 -27
  12. package/api/theme/build/build.mjs +341 -69
  13. package/api/theme/eject/eject.mjs +22 -1
  14. package/api/theme/template/template.d.mts +19 -0
  15. package/api/theme/template/template.mjs +102 -25
  16. package/api/theme/theme.type.d.mts +5 -1
  17. package/api/theme/theme.type.mjs +2 -1
  18. package/api/theme/themeBuild.doc.mjs +3 -3
  19. package/api/theme/themeEject.doc.mjs +1 -1
  20. package/api/theme/themeTemplate.doc.mjs +9 -3
  21. package/api/theme-edit/_adapter.d.mts +33 -0
  22. package/api/theme-edit/_adapter.mjs +208 -31
  23. package/api/theme-edit/_check.d.mts +38 -0
  24. package/api/theme-edit/_check.mjs +1326 -211
  25. package/api/theme-edit/_color.d.mts +2 -8
  26. package/api/theme-edit/_color.mjs +292 -219
  27. package/api/theme-edit/_compiler.d.mts +1 -0
  28. package/api/theme-edit/_compiler.mjs +20 -1
  29. package/api/theme-edit/_context.d.mts +29 -0
  30. package/api/theme-edit/_context.mjs +329 -30
  31. package/api/theme-edit/_css.d.mts +60 -1
  32. package/api/theme-edit/_css.mjs +404 -28
  33. package/api/theme-edit/_edit.d.mts +9 -0
  34. package/api/theme-edit/_edit.mjs +1025 -126
  35. package/api/theme-edit/_how-commands.d.mts +11 -26
  36. package/api/theme-edit/_how-commands.mjs +30 -2
  37. package/api/theme-edit/_how-question.d.mts +7 -0
  38. package/api/theme-edit/_how-question.mjs +1304 -176
  39. package/api/theme-edit/_how.mjs +144 -30
  40. package/api/theme-edit/_overview.mjs +2 -0
  41. package/api/theme-edit/_palette.d.mts +11 -0
  42. package/api/theme-edit/_palette.mjs +194 -65
  43. package/api/theme-edit/_parts.d.mts +16 -0
  44. package/api/theme-edit/_parts.mjs +59 -7
  45. package/api/theme-edit/_png.mjs +19 -14
  46. package/api/theme-edit/_preview-app.d.mts +3 -0
  47. package/api/theme-edit/_preview-app.mjs +843 -45
  48. package/api/theme-edit/_preview.d.mts +16 -3
  49. package/api/theme-edit/_preview.mjs +310 -29
  50. package/api/theme-edit/_project.d.mts +11 -0
  51. package/api/theme-edit/_project.mjs +46 -12
  52. package/api/theme-edit/_settings.d.mts +178 -5
  53. package/api/theme-edit/_settings.mjs +2035 -86
  54. package/api/theme-edit/_tables.d.mts +24 -0
  55. package/api/theme-edit/_tables.mjs +211 -149
  56. package/api/theme-edit/_vet.d.mts +42 -0
  57. package/api/theme-edit/_vet.mjs +144 -0
  58. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  59. package/api/theme-edit/theme-edit.type.mjs +1 -1
  60. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  61. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  62. package/api/upgrade/registry/registry.mjs +6 -1
  63. package/assets/docs/tree/single-component.doc.mjs +11 -2
  64. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  65. package/assets/docs.generated.json +2 -2
  66. package/assets/preview-app/next.config.mjs +7 -1
  67. package/assets/preview-app/package.json +1 -0
  68. package/assets/preview-app/src/app/globals.css +1 -0
  69. package/assets/self-audit.generated.json +1 -1
  70. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  71. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  72. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  73. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  74. package/assets/templates/components.generated.json +1 -1
  75. package/assets/templates/pages/dashboard/page.tsx +1 -1
  76. package/authoring/doctypes/_schema.d.mts +52 -5
  77. package/authoring/doctypes/_schema.mjs +62 -7
  78. package/authoring/doctypes/base/type.ts +10 -0
  79. package/authoring/doctypes/component/component.doc.mjs +1 -1
  80. package/authoring/doctypes/function/function.doc.mjs +6 -0
  81. package/authoring/doctypes/function/type.ts +3 -0
  82. package/authoring/doctypes/legacy.mjs +5 -1
  83. package/authoring/index.d.ts +1 -0
  84. package/clients/cli/build-id.generated.json +1 -1
  85. package/clients/cli/commands/doctor.doc.mjs +2 -2
  86. package/clients/cli/commands/experimental/theme.mjs +190 -37
  87. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  88. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  89. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  90. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  91. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  92. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  93. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  94. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  95. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  96. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  97. package/clients/cli/commands/theme.mjs +168 -45
  98. package/clients/cli/formatters/index.mjs +7 -4
  99. package/clients/cli/lib/cli-error.mjs +9 -3
  100. package/clients/cli/lib/component-format.mjs +27 -9
  101. package/clients/cli/lib/json-shim.mjs +40 -2
  102. package/clients/cli/manifest.generated.json +1 -1
  103. package/clients/cli/run.mjs +49 -0
  104. package/foundation/config/project.mjs +50 -14
  105. package/foundation/discovery/theme-discovery.d.mts +5 -1
  106. package/foundation/discovery/theme-discovery.mjs +24 -3
  107. package/foundation/fs/gather-cache.d.mts +9 -2
  108. package/foundation/fs/gather-cache.mjs +79 -15
  109. package/foundation/fs/paths.d.mts +31 -0
  110. package/foundation/fs/paths.mjs +43 -10
  111. package/foundation/render/host-exit.d.mts +8 -0
  112. package/foundation/render/host-exit.mjs +11 -0
  113. package/foundation/render/page-host.mjs +56 -10
  114. package/foundation/render/page-worker.mjs +14 -0
  115. package/foundation/render/render-page.mjs +37 -2
  116. package/foundation/response/error-codes.d.mts +2 -1
  117. package/foundation/response/error-codes.d.ts +1 -0
  118. package/foundation/response/error-codes.doc.mjs +5 -0
  119. package/foundation/response/error-codes.mjs +3 -0
  120. package/foundation/response/json.d.mts +15 -0
  121. package/foundation/response/json.mjs +52 -1
  122. package/foundation/response/response-types.doc.mjs +1 -1
  123. package/package.json +7 -6
@@ -14,6 +14,17 @@ export function showcaseItems(project: import("./_project.mjs").ThemeProject, gr
14
14
  imports: Record<string, string>;
15
15
  skipped: string[];
16
16
  };
17
+ /**
18
+ * The fonts stylesheet of the theme a theme is built on, when its package
19
+ * ships one (`@astryxdesign/theme-neutral/fonts.css` loads Figtree): naming
20
+ * a family does not load it, and the base theme's families apply until the
21
+ * theme sets its own. Once the theme's build names none of the families the
22
+ * sheet loads, it is left out.
23
+ * @param {import('./_settings.mjs').Ctx} ctx
24
+ * @param {import('./_settings.mjs').ThemeData} data
25
+ * @returns {string[]}
26
+ */
27
+ export function baseFontsCss(ctx: import("./_settings.mjs").Ctx, data: import("./_settings.mjs").ThemeData): string[];
17
28
  /**
18
29
  * How a generated page imports the theme: its built module, its stylesheet,
19
30
  * and the stylesheets of open fonts the project has installed.
@@ -61,7 +72,7 @@ export function renderSheet(ctx: import("./_settings.mjs").Ctx, slug: string, da
61
72
  * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} [options]
62
73
  * @returns {{source: string, components: number}}
63
74
  */
64
- export function componentsPageSource(project: import("./_project.mjs").ThemeProject, { theme, C }?: {
75
+ export function componentsPageSource(project: import("./_project.mjs").ThemeProject, options?: {
65
76
  theme?: string | null;
66
77
  C?: import("./_compiler.mjs").Compiler;
67
78
  }): {
@@ -75,11 +86,13 @@ export function componentsPageSource(project: import("./_project.mjs").ThemeProj
75
86
  * boundary, so one part that throws never blanks the page. The preview
76
87
  * route is the app shell, so the page has no shell of its own.
77
88
  * @param {import('./_project.mjs').ThemeProject} project
78
- * @param {{theme?: string | null}} [options]
89
+ * @param {{theme?: string | null, colors?: boolean}} [options] `colors`:
90
+ * the preview has a Colors page, so the header points to it
79
91
  * @returns {string}
80
92
  */
81
- export function overviewPageSource(project: import("./_project.mjs").ThemeProject, { theme }?: {
93
+ export function overviewPageSource(project: import("./_project.mjs").ThemeProject, options?: {
82
94
  theme?: string | null;
95
+ colors?: boolean;
83
96
  }): string;
84
97
  /**
85
98
  * The source of the preview's Colors page: each generated color's shades in
@@ -12,6 +12,7 @@
12
12
  * @position api/theme-edit — previews and pictures
13
13
  */
14
14
 
15
+ import {createHash} from 'node:crypto';
15
16
  import * as fs from 'node:fs';
16
17
  import * as path from 'node:path';
17
18
  import {spawnSync} from 'node:child_process';
@@ -24,17 +25,19 @@ import {
24
25
  } from './_catalog.mjs';
25
26
  import {
26
27
  catalogVariants,
27
- isItemOf,
28
+ needsParent,
28
29
  renderDir,
29
30
  renderGenerated,
30
31
  } from './_parts.mjs';
31
32
  import {OVERVIEW_SECTIONS} from './_overview.mjs';
32
33
  import {camel, fontPackages, modesOf, themeFiles, shown} from './_settings.mjs';
33
34
  import {writeWhole} from './_palette.mjs';
35
+ import {cliVersion} from '../../foundation/release/run-context.mjs';
34
36
  import {importPathOf, installLine} from './_project.mjs';
35
- import {COLOR_PROP_PARTS, DIRECT, P} from './_tables.mjs';
37
+ import {COLOR_PROP_PARTS, DIRECT, P, wordTable} from './_tables.mjs';
36
38
  import {extractImportedPackages} from '../../foundation/discovery/template-needs.mjs';
37
39
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
40
+ import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
38
41
 
39
42
  const TEMPLATES_DIR = path.resolve(
40
43
  path.dirname(fileURLToPath(import.meta.url)),
@@ -187,7 +190,7 @@ function inParentOf(project, name) {
187
190
  const wrapper = info.wrapper;
188
191
  // A part its parent does not list as an item, such as a heading of the
189
192
  // text family, renders on its own.
190
- if (!wrapper) return isItemOf(project, name) ? null : tree => tree;
193
+ if (!wrapper) return needsParent(project, name) ? null : tree => tree;
191
194
  if (project.components[wrapper.component]?.wrapper) return null;
192
195
  const props = Object.fromEntries(
193
196
  Object.entries(wrapper.props).filter(([k]) => !OPEN_PROPS.includes(k)),
@@ -214,6 +217,59 @@ function templateFiles(imports) {
214
217
  });
215
218
  }
216
219
 
220
+ /**
221
+ * The fonts stylesheet of the theme a theme is built on, when its package
222
+ * ships one (`@astryxdesign/theme-neutral/fonts.css` loads Figtree): naming
223
+ * a family does not load it, and the base theme's families apply until the
224
+ * theme sets its own. Once the theme's build names none of the families the
225
+ * sheet loads, it is left out.
226
+ * @param {import('./_settings.mjs').Ctx} ctx
227
+ * @param {import('./_settings.mjs').ThemeData} data
228
+ * @returns {string[]}
229
+ */
230
+ export function baseFontsCss(ctx, data) {
231
+ if (!data.like) return [];
232
+ const pkg = `@astryxdesign/theme-${data.like}`;
233
+ const sheet = `${pkg}/fonts.css`;
234
+ // Read off disk: the package must export the sheet for an app to import
235
+ // it.
236
+ const found = findNodeModulesPackage(ctx.project.cwd, pkg);
237
+ /** @type {string} */
238
+ let text;
239
+ try {
240
+ if (!found) return [];
241
+ const exportsMap = JSON.parse(
242
+ fs.readFileSync(path.join(found.packageDir, 'package.json'), 'utf8'),
243
+ ).exports;
244
+ if (
245
+ !exportsMap ||
246
+ typeof exportsMap !== 'object' ||
247
+ !('./fonts.css' in exportsMap)
248
+ )
249
+ return [];
250
+ text = fs.readFileSync(path.join(found.packageDir, 'fonts.css'), 'utf8');
251
+ } catch {
252
+ return [];
253
+ }
254
+ // The families the sheet loads; with the theme's build at hand, the sheet
255
+ // is imported only while the build still names one of them.
256
+ const families = [...text.matchAll(/family=([^:&'")]+)/g)].map(m =>
257
+ decodeURIComponent(m[1].replace(/\+/g, ' ')),
258
+ );
259
+ /** @type {string | null} */
260
+ let built = null;
261
+ try {
262
+ built = fs.readFileSync(themeFiles(ctx.project.cwd, data.name).css, 'utf8');
263
+ } catch {
264
+ // Not built yet: the base families may still apply.
265
+ }
266
+ if (built != null && families.length) {
267
+ const css = built;
268
+ if (!families.some(f => css.includes(f))) return [];
269
+ }
270
+ return [sheet];
271
+ }
272
+
217
273
  /**
218
274
  * How a generated page imports the theme: its built module, its stylesheet,
219
275
  * and the stylesheets of open fonts the project has installed.
@@ -235,13 +291,162 @@ export function themeImports(ctx, slug, data, fromDir) {
235
291
  .map(x => `${x.pkg}/index.css`);
236
292
  return {
237
293
  module: rel(f.js),
238
- css: [rel(f.css), ...fonts],
294
+ css: [rel(f.css), ...baseFontsCss(ctx, data), ...fonts],
239
295
  mode: /** @type {'system' | 'light' | 'dark'} */ (
240
296
  modes.length > 1 ? 'system' : modes[0]
241
297
  ),
242
298
  };
243
299
  }
244
300
 
301
+ /**
302
+ * The inputs a page was rendered from and a hash of the page above it,
303
+ * recorded at the end of the page.
304
+ */
305
+ const RENDER_STAMP = /<!-- astryx: render of ([0-9a-f]{24}) ([0-9a-f]{16}) -->/;
306
+
307
+ /** @type {Map<string, string>} */
308
+ const treeKeys = new Map();
309
+
310
+ /**
311
+ * A cheap fingerprint of the files a package runs from: each file's path,
312
+ * size and modification time under its folder (node_modules left out), so a
313
+ * linked or patched copy with the same version reads as another. Once per
314
+ * process for each folder.
315
+ * @param {string | null | undefined} dir
316
+ * @returns {string}
317
+ */
318
+ function treeKey(dir) {
319
+ if (!dir) return 'none';
320
+ const known = treeKeys.get(dir);
321
+ if (known) return known;
322
+ const h = createHash('sha256');
323
+ /** @param {string} d */
324
+ const walk = d => {
325
+ let entries;
326
+ try {
327
+ entries = fs.readdirSync(d, {withFileTypes: true});
328
+ } catch {
329
+ return;
330
+ }
331
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
332
+ for (const e of entries) {
333
+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue;
334
+ const p = path.join(d, e.name);
335
+ if (e.isDirectory()) walk(p);
336
+ else if (e.isFile()) {
337
+ try {
338
+ const st = fs.statSync(p);
339
+ h.update(`${path.relative(dir, p)}\0${st.size}\0${st.mtimeMs}\0`);
340
+ } catch {
341
+ // Gone meanwhile.
342
+ }
343
+ }
344
+ }
345
+ };
346
+ walk(dir);
347
+ const key = h.digest('hex').slice(0, 16);
348
+ treeKeys.set(dir, key);
349
+ return key;
350
+ }
351
+
352
+ /**
353
+ * The folder of an installed package, resolved from the project, or null.
354
+ * @param {string} cwd
355
+ * @param {string} name
356
+ */
357
+ function packageDirOf(cwd, name) {
358
+ try {
359
+ return findNodeModulesPackage(cwd, name)?.packageDir ?? null;
360
+ } catch {
361
+ return null;
362
+ }
363
+ }
364
+
365
+ /** @param {string} text */
366
+ const bodyHash = text =>
367
+ createHash('sha256').update(text).digest('hex').slice(0, 16);
368
+
369
+ /**
370
+ * A key for everything a page render reads: the CLI, Core (its version and
371
+ * stylesheet, and the files it runs from), the base theme package's files,
372
+ * the generated page source, and the theme's built stylesheet and module.
373
+ * The same key means the same page.
374
+ * @param {import('./_project.mjs').ThemeProject} project
375
+ * @param {string} slug
376
+ * @param {string} source
377
+ * @param {string | null | undefined} [like] the base theme
378
+ * @returns {string}
379
+ */
380
+ function renderKey(project, slug, source, like) {
381
+ const f = themeFiles(project.cwd, slug);
382
+ const h = createHash('sha256')
383
+ .update(cliVersion())
384
+ .update('\0')
385
+ .update(String(project.coreKey ?? ''))
386
+ .update('\0')
387
+ .update(treeKey(path.join(project.coreDir, 'dist')))
388
+ .update('\0')
389
+ .update(
390
+ like
391
+ ? treeKey(packageDirOf(project.cwd, `@astryxdesign/theme-${like}`))
392
+ : 'none',
393
+ )
394
+ .update('\0')
395
+ .update(source);
396
+ for (const file of [f.css, f.js]) {
397
+ h.update('\0');
398
+ try {
399
+ h.update(fs.readFileSync(file));
400
+ } catch {
401
+ h.update('missing');
402
+ }
403
+ }
404
+ return h.digest('hex').slice(0, 24);
405
+ }
406
+
407
+ /**
408
+ * Whether `out` is a page rendered from `key` (a no-op show renders
409
+ * nothing again).
410
+ * @param {string} out
411
+ * @param {string} key
412
+ */
413
+ function renderedFrom(out, key) {
414
+ try {
415
+ const st = fs.lstatSync(out);
416
+ if (!st.isFile()) return false;
417
+ const text = fs.readFileSync(out, 'utf8');
418
+ const m = RENDER_STAMP.exec(text);
419
+ // The page above the comment is the one rendered: an edit by hand, or
420
+ // a comment pasted under another page, is rendered again.
421
+ // Nothing may follow the comment but the sheet's own build stamp
422
+ // (written after it by show): text added after it is rendered over.
423
+ const after = m
424
+ ? text
425
+ .slice(m.index + m[0].length)
426
+ .replace(/<!-- astryx: sheet of build [0-9a-f]{16} -->/, '')
427
+ : '';
428
+ return (
429
+ m != null &&
430
+ m[1] === key &&
431
+ after.trim() === '' &&
432
+ m[2] === bodyHash(text.slice(0, m.index).trimEnd())
433
+ );
434
+ } catch {
435
+ return false;
436
+ }
437
+ }
438
+
439
+ /**
440
+ * The page with its render key recorded at its end (after the closing tag:
441
+ * a comment before the doctype would put it in quirks mode).
442
+ * @param {string} html
443
+ * @param {string} key
444
+ */
445
+ const withRenderKey = (html, key) => {
446
+ const body = html.replace(RENDER_STAMP, '').trimEnd();
447
+ return `${body}\n<!-- astryx: render of ${key} ${bodyHash(body)} -->\n`;
448
+ };
449
+
245
450
  /**
246
451
  * Render the sample app page with the theme to themes/<slug>/preview.html.
247
452
  * @param {import('./_settings.mjs').Ctx} ctx
@@ -263,10 +468,13 @@ export async function renderPreview(ctx, slug, data) {
263
468
  layout: 'page',
264
469
  title: `${slug}: sample page`,
265
470
  });
266
- const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
267
471
  const out = themeFiles(project.cwd, slug).preview;
472
+ // Rendered from the same inputs before: the page is as it would be.
473
+ const key = renderKey(project, slug, source, data.like);
474
+ if (renderedFrom(out, key)) return shown(project.cwd, out);
475
+ const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
268
476
  // Written whole and renamed in, never through a link.
269
- writeWhole(out, html);
477
+ writeWhole(out, withRenderKey(html, key));
270
478
  return shown(project.cwd, out);
271
479
  }
272
480
 
@@ -288,12 +496,6 @@ export async function renderSheet(ctx, slug, data, options = {}) {
288
496
  layout: 'sheet',
289
497
  title: `${slug}: every component${options.group ? ` (${options.group})` : ''}`,
290
498
  });
291
- const {html} = await renderGenerated(
292
- project,
293
- `sheet-${slug}.mjs`,
294
- source,
295
- templateFiles(imports),
296
- );
297
499
  // One section goes to its own file, so the full sheet stays whole.
298
500
  const full = themeFiles(project.cwd, slug).sheet;
299
501
  const out =
@@ -301,9 +503,23 @@ export async function renderSheet(ctx, slug, data, options = {}) {
301
503
  (options.group
302
504
  ? path.join(path.dirname(full), `sheet-${options.group}.html`)
303
505
  : full);
506
+ const key = renderKey(project, slug, source, data.like);
507
+ const result = {
508
+ file: shown(project.cwd, out),
509
+ components: new Set(items.map(i => i.name)).size,
510
+ skipped,
511
+ };
512
+ // Rendered from the same inputs before: the sheet is as it would be.
513
+ if (renderedFrom(out, key)) return result;
514
+ const {html} = await renderGenerated(
515
+ project,
516
+ `sheet-${slug}.mjs`,
517
+ source,
518
+ templateFiles(imports),
519
+ );
304
520
  fs.mkdirSync(path.dirname(out), {recursive: true});
305
521
  // Written whole and renamed in, never through a link.
306
- writeWhole(out, html);
522
+ writeWhole(out, withRenderKey(html, key));
307
523
  return {
308
524
  file: shown(project.cwd, out),
309
525
  components: new Set(items.map(i => i.name)).size,
@@ -460,11 +676,11 @@ function componentTable(project, trees) {
460
676
  const SAFE = [
461
677
  '/** Shows a short note for a component that throws, so the rest of the page renders. */',
462
678
  'class Safe extends React.Component<{name: string, children: React.ReactNode}, {failed: boolean}> {',
463
- ' state = {failed: false};',
679
+ ' override state = {failed: false};',
464
680
  ' static getDerivedStateFromError() {',
465
681
  ' return {failed: true};',
466
682
  ' }',
467
- ' render() {',
683
+ ' override render() {',
468
684
  ' return this.state.failed ? <div className="tp-note">{this.props.name} could not render here</div> : this.props.children;',
469
685
  ' }',
470
686
  '}',
@@ -567,10 +783,12 @@ const usesSource = v =>
567
783
  Object.values(/** @type {object} */ (v)).some(usesSource);
568
784
 
569
785
  /** The heading of each group on the components page. */
570
- const GROUP_TITLES = /** @type {Record<string, string>} */ ({
571
- data: 'data display',
572
- overlays: 'overlays (shown open)',
573
- });
786
+ const GROUP_TITLES = wordTable(
787
+ /** @type {Record<string, string>} */ ({
788
+ data: 'data display',
789
+ overlays: 'overlays (shown open)',
790
+ }),
791
+ );
574
792
 
575
793
  /**
576
794
  * A cell with the component's name. A cell whose parts show nothing on
@@ -650,7 +868,19 @@ const PAGE_SKIP = new Set([
650
868
  * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} [options]
651
869
  * @returns {{source: string, components: number}}
652
870
  */
653
- export function componentsPageSource(project, {theme = null, C} = {}) {
871
+ export function componentsPageSource(project, options = {}) {
872
+ // A name that Core's docs lack resolves by walking Core's source tree. One
873
+ // listing cache reads each folder once for the page, not once per name.
874
+ return withListingCache(() => componentsPage(project, options));
875
+ }
876
+
877
+ /**
878
+ * {@link componentsPageSource}'s work, inside its listing cache.
879
+ * @param {import('./_project.mjs').ThemeProject} project
880
+ * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} options
881
+ * @returns {{source: string, components: number}}
882
+ */
883
+ function componentsPage(project, {theme = null, C}) {
654
884
  const items = showcaseItems(project, undefined)
655
885
  .items.filter(
656
886
  it =>
@@ -727,10 +957,22 @@ export function componentsPageSource(project, {theme = null, C} = {}) {
727
957
  * boundary, so one part that throws never blanks the page. The preview
728
958
  * route is the app shell, so the page has no shell of its own.
729
959
  * @param {import('./_project.mjs').ThemeProject} project
730
- * @param {{theme?: string | null}} [options]
960
+ * @param {{theme?: string | null, colors?: boolean}} [options] `colors`:
961
+ * the preview has a Colors page, so the header points to it
731
962
  * @returns {string}
732
963
  */
733
- export function overviewPageSource(project, {theme = null} = {}) {
964
+ export function overviewPageSource(project, options = {}) {
965
+ // One listing cache for the page's names, as componentsPageSource holds.
966
+ return withListingCache(() => overviewPage(project, options));
967
+ }
968
+
969
+ /**
970
+ * {@link overviewPageSource}'s work, inside its listing cache.
971
+ * @param {import('./_project.mjs').ThemeProject} project
972
+ * @param {{theme?: string | null, colors?: boolean}} options
973
+ * @returns {string}
974
+ */
975
+ function overviewPage(project, {theme = null, colors = false}) {
734
976
  const sections = OVERVIEW_SECTIONS.map(x => ({
735
977
  title: x.title,
736
978
  tree: /** @type {import('./_catalog.mjs').Tree | undefined} */ (
@@ -786,8 +1028,38 @@ export function overviewPageSource(project, {theme = null} = {}) {
786
1028
  ' React.useEffect(() => {',
787
1029
  ' if (!ref.current) return;',
788
1030
  ' const style = getComputedStyle(ref.current);',
789
- " const first = (token: string) => style.getPropertyValue(token).split(',')[0].replace(/[\"']/g, '').trim() || 'default';",
790
- " setFonts(`Body: ${first('--font-family-body')}. Headings: ${first('--font-family-heading')}.`);",
1031
+ " const first = (token: string) => (style.getPropertyValue(token).split(',')[0] ?? '').replace(/[\"']/g, '').trim() || 'default';",
1032
+ ' // A family the browser does not have measures as its fallback does.',
1033
+ ' const GENERIC = /^(default|serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-[a-z-]+|math|emoji|fangsong)$/i;',
1034
+ ' const missing = (family: string) => {',
1035
+ ' if (GENERIC.test(family)) return false;',
1036
+ " const ctx = document.createElement('canvas').getContext('2d');",
1037
+ ' if (!ctx) return false;',
1038
+ " const sample = 'mmmmmmmmmwwwwwww1234567890';",
1039
+ " return ['monospace', 'serif'].every(fallback => {",
1040
+ ' ctx.font = `48px ${fallback}`;',
1041
+ ' const plain = ctx.measureText(sample).width;',
1042
+ ' ctx.font = `48px "${family}", ${fallback}`;',
1043
+ ' return ctx.measureText(sample).width === plain;',
1044
+ ' });',
1045
+ ' };',
1046
+ ' const shown = (token: string) => { const f = first(token); return missing(f) ? `${f} (not installed here)` : f; };',
1047
+ " const write = () => setFonts(`Body: ${shown('--font-family-body')}. Headings: ${shown('--font-family-heading')}.`);",
1048
+ ' write();',
1049
+ ' // Read again when the theme changes live (a stylesheet or theme',
1050
+ ' // update while the page is open) and when a font finishes loading.',
1051
+ ' document.fonts?.ready.then(write);',
1052
+ " document.fonts?.addEventListener?.('loadingdone', write);",
1053
+ ' let queued = 0;',
1054
+ ' const soon = () => { if (!queued) queued = requestAnimationFrame(() => { queued = 0; write(); }); };',
1055
+ ' const watch = new MutationObserver(soon);',
1056
+ ' watch.observe(document.head, {childList: true, subtree: true, characterData: true});',
1057
+ " watch.observe(document.documentElement, {attributes: true, subtree: true, attributeFilter: ['style', 'class', 'data-theme']});",
1058
+ ' return () => {',
1059
+ ' watch.disconnect();',
1060
+ ' cancelAnimationFrame(queued);',
1061
+ " document.fonts?.removeEventListener?.('loadingdone', write);",
1062
+ ' };',
791
1063
  ' }, []);',
792
1064
  ' return (',
793
1065
  " <div ref={ref} style={{color: 'var(--color-text-secondary)', fontSize: 13}}>",
@@ -812,7 +1084,12 @@ export function overviewPageSource(project, {theme = null} = {}) {
812
1084
  ' {s.name}',
813
1085
  ' </div>',
814
1086
  ' ))}',
815
- ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1087
+ // The Colors page is there only for a theme with generated colors.
1088
+ ...(colors
1089
+ ? [
1090
+ ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1091
+ ]
1092
+ : []),
816
1093
  ' </div>',
817
1094
  ' </header>',
818
1095
  body,
@@ -839,7 +1116,6 @@ export function colorsPageSource({slug, module, seeds, uses}) {
839
1116
  '// `astryx experimental theme editor set` rewrites it with every change.',
840
1117
  "'use client';",
841
1118
  '',
842
- "import * as React from 'react';",
843
1119
  ];
844
1120
  const text = {color: 'var(--color-text-primary)'};
845
1121
  const page = {
@@ -891,7 +1167,7 @@ export function colorsPageSource({slug, module, seeds, uses}) {
891
1167
  " <h2 style={{margin: 0, fontSize: 20, textTransform: 'capitalize'}}>",
892
1168
  ' {name}',
893
1169
  ' {SEEDS[name] ? (',
894
- " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, color: 'var(--color-text-secondary)'}}>",
1170
+ " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, textTransform: 'none', color: 'var(--color-text-secondary)'}}>",
895
1171
  ' from {SEEDS[name]}',
896
1172
  ' </span>',
897
1173
  ' ) : null}',
@@ -984,7 +1260,7 @@ export function previewRouteSource({
984
1260
  ' ))}',
985
1261
  ' </SideNav>',
986
1262
  ' }>',
987
- ' <current.Page />',
1263
+ ' {ready ? <current.Page /> : null}',
988
1264
  ' </AppShell>',
989
1265
  ' </div>',
990
1266
  ];
@@ -1028,6 +1304,10 @@ export function previewRouteSource({
1028
1304
  '',
1029
1305
  'export default function ThemePreviewPage() {',
1030
1306
  ' const [page, setPage] = React.useState(PAGES[0]?.id);',
1307
+ // Pages render only in the browser: some components crash a server
1308
+ // render, and Next prerenders a client page's first state.
1309
+ ' const [ready, setReady] = React.useState(false);',
1310
+ ' React.useEffect(() => setReady(true), []);',
1031
1311
  ...(theme
1032
1312
  ? [
1033
1313
  oneMode
@@ -1035,7 +1315,8 @@ export function previewRouteSource({
1035
1315
  : " const [mode, setMode] = React.useState<Mode>('system');",
1036
1316
  ]
1037
1317
  : []),
1038
- ' const current = PAGES.find(p => p.id === page) ?? PAGES[0];',
1318
+ // The route always has a page; the cast keeps noUncheckedIndexedAccess apps building.
1319
+ ' const current = (PAGES.find(p => p.id === page) ?? PAGES[0]) as (typeof PAGES)[number];',
1039
1320
  ' return (',
1040
1321
  ...(theme
1041
1322
  ? [' <Theme theme={theme} mode={mode}>', ...shell, ' </Theme>']
@@ -32,6 +32,16 @@ export function openProject(cwd: string): Promise<ThemeProject>;
32
32
  * @returns {string | null}
33
33
  */
34
34
  export function importPathOf(project: ThemeProject, name: string): string | null;
35
+ /**
36
+ * The built module of a base's theme package, resolved the way the theme
37
+ * resolves it: from the project (an open project, or its folder, relative
38
+ * or not). Null when it is not installed there. The one base resolution:
39
+ * `new`, `set base`, `how` and every suggestion ask this.
40
+ * @param {ThemeProject | string} from
41
+ * @param {string} like
42
+ * @returns {string | null}
43
+ */
44
+ export function baseModule(from: ThemeProject | string, like: string): string | null;
35
45
  /**
36
46
  * The built-in theme package for a base, or a refusal naming its install line.
37
47
  * @param {ThemeProject} project
@@ -51,6 +61,7 @@ export function baseResolved(project: ThemeProject, like: string | undefined): P
51
61
  components: Record<string, any>;
52
62
  }>;
53
63
  export function literals(type: string): string[];
64
+ export function baseInstalled(from: ThemeProject | string, like: string): boolean;
54
65
  export type ThemeProject = {
55
66
  cwd: string;
56
67
  /**
@@ -22,6 +22,10 @@ import {collectThemingTargets} from '../../foundation/discovery/theming-targets.
22
22
  import {resolveImportPath} from '../../foundation/discovery/component-discovery.mjs';
23
23
  import {detectPackageManager} from '../../foundation/env/package-manager.mjs';
24
24
  import {findProjectCoreDir} from '../../foundation/fs/paths.mjs';
25
+ import {
26
+ oncePerListing,
27
+ withListingCache,
28
+ } from '../../foundation/fs/listing-cache.mjs';
25
29
 
26
30
  /**
27
31
  * @typedef {object} ThemeProject
@@ -278,11 +282,13 @@ export async function openProject(cwd) {
278
282
  // Not cached yet.
279
283
  }
280
284
  if (!docs) {
281
- docs = {
285
+ // Each component's import path walks Core's source tree. One listing
286
+ // cache reads each folder once for all of them.
287
+ docs = await withListingCache(async () => ({
282
288
  version: DOCS_VERSION,
283
289
  targets: await collectThemingTargets(path.join(coreDir, 'src')),
284
290
  components: await readComponents(coreDir),
285
- };
291
+ }));
286
292
  try {
287
293
  fs.mkdirSync(cacheDir, {recursive: true});
288
294
  fs.writeFileSync(docsFile, JSON.stringify(docs));
@@ -317,10 +323,40 @@ export async function openProject(cwd) {
317
323
  export function importPathOf(project, name) {
318
324
  const spec =
319
325
  project.components[name]?.importPath ??
320
- resolveImportPath(project.coreDir, name);
326
+ oncePerListing(`importPath ${project.coreDir} ${name}`, () =>
327
+ resolveImportPath(project.coreDir, name),
328
+ );
321
329
  return spec && spec !== '@astryxdesign/core' ? spec : null;
322
330
  }
323
331
 
332
+ /**
333
+ * The built module of a base's theme package, resolved the way the theme
334
+ * resolves it: from the project (an open project, or its folder, relative
335
+ * or not). Null when it is not installed there. The one base resolution:
336
+ * `new`, `set base`, `how` and every suggestion ask this.
337
+ * @param {ThemeProject | string} from
338
+ * @param {string} like
339
+ * @returns {string | null}
340
+ */
341
+ export function baseModule(from, like) {
342
+ const req =
343
+ typeof from === 'string'
344
+ ? createRequire(path.join(path.resolve(from), 'noop.js'))
345
+ : from.req;
346
+ try {
347
+ return req.resolve(`@astryxdesign/theme-${like}/built`);
348
+ } catch {
349
+ return null;
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Whether a base's theme package is installed in the project.
355
+ * @param {ThemeProject | string} from
356
+ * @param {string} like
357
+ */
358
+ export const baseInstalled = (from, like) => baseModule(from, like) != null;
359
+
324
360
  /**
325
361
  * The built-in theme package for a base, or a refusal naming its install line.
326
362
  * @param {ThemeProject} project
@@ -329,15 +365,13 @@ export function importPathOf(project, name) {
329
365
  */
330
366
  export function baseThemeFile(project, like) {
331
367
  const pkg = `@astryxdesign/theme-${like}`;
332
- try {
333
- return project.req.resolve(`${pkg}/built`);
334
- } catch {
335
- throw new AstryxError(
336
- `The ${like} theme is not installed, so a theme cannot build on it. Install ${pkg}, or build on no theme. Nothing was changed.`,
337
- [{name: installLine(project.cwd, [pkg]), reason: 'install it'}],
338
- ERROR_CODES.ERR_UNKNOWN_THEME,
339
- );
340
- }
368
+ const file = baseModule(project, like);
369
+ if (file) return file;
370
+ throw new AstryxError(
371
+ `The ${like} theme is not installed, so a theme cannot build on it. Install ${pkg}, or build on no theme. Nothing was changed.`,
372
+ [{name: installLine(project.cwd, [pkg]), reason: 'install it'}],
373
+ ERROR_CODES.ERR_UNKNOWN_THEME,
374
+ );
341
375
  }
342
376
 
343
377
  /**