@astryxdesign/cli 0.7.15 → 0.7.16-canary.g07c77c0

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 (159) hide show
  1. package/README.md +5 -3
  2. package/api/build/_adapter.d.mts +1 -0
  3. package/api/build/blocks/blocks.d.mts +1 -0
  4. package/api/build/blocks/blocks.mjs +18 -1
  5. package/api/component/_adapter.d.mts +1 -1
  6. package/api/component/_adapter.mjs +28 -1
  7. package/api/doctor/_adapter.d.mts +17 -0
  8. package/api/doctor/_adapter.mjs +43 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.mjs +18 -4
  11. package/api/doctor/theme-checks.mjs +1 -1
  12. package/api/integration/add-contribution.mjs +3 -3
  13. package/api/integration/pack-check.mjs +14 -8
  14. package/api/integration/validate-integration.mjs +1 -1
  15. package/api/search/_adapter.mjs +15 -16
  16. package/api/search/_entries.d.mts +2 -1
  17. package/api/search/_entries.mjs +28 -1
  18. package/api/swizzle/_moduleGraph.mjs +1 -1
  19. package/api/theme/_adapter.d.mts +5 -2
  20. package/api/theme/_adapter.mjs +43 -12
  21. package/api/theme/_fork.mjs +1 -1
  22. package/api/theme/build/build.d.mts +116 -32
  23. package/api/theme/build/build.mjs +449 -102
  24. package/api/theme/eject/eject.mjs +22 -1
  25. package/api/theme/template/template.d.mts +19 -0
  26. package/api/theme/template/template.mjs +102 -25
  27. package/api/theme/theme.type.d.mts +5 -1
  28. package/api/theme/theme.type.mjs +2 -1
  29. package/api/theme/themeBuild.doc.mjs +3 -3
  30. package/api/theme/themeEject.doc.mjs +1 -1
  31. package/api/theme/themeTemplate.doc.mjs +9 -3
  32. package/api/theme-edit/_adapter.d.mts +32 -2
  33. package/api/theme-edit/_adapter.mjs +213 -36
  34. package/api/theme-edit/_check.d.mts +69 -3
  35. package/api/theme-edit/_check.mjs +1517 -218
  36. package/api/theme-edit/_color.d.mts +2 -8
  37. package/api/theme-edit/_color.mjs +292 -219
  38. package/api/theme-edit/_compiler.d.mts +1 -0
  39. package/api/theme-edit/_compiler.mjs +20 -1
  40. package/api/theme-edit/_context.d.mts +29 -0
  41. package/api/theme-edit/_context.mjs +426 -40
  42. package/api/theme-edit/_css.d.mts +60 -1
  43. package/api/theme-edit/_css.mjs +404 -28
  44. package/api/theme-edit/_edit.d.mts +9 -0
  45. package/api/theme-edit/_edit.mjs +1300 -135
  46. package/api/theme-edit/_how-commands.d.mts +11 -26
  47. package/api/theme-edit/_how-commands.mjs +30 -2
  48. package/api/theme-edit/_how-question.d.mts +7 -0
  49. package/api/theme-edit/_how-question.mjs +1304 -176
  50. package/api/theme-edit/_how.mjs +144 -30
  51. package/api/theme-edit/_overview.mjs +2 -0
  52. package/api/theme-edit/_palette.d.mts +11 -0
  53. package/api/theme-edit/_palette.mjs +194 -65
  54. package/api/theme-edit/_parts.d.mts +33 -0
  55. package/api/theme-edit/_parts.mjs +138 -9
  56. package/api/theme-edit/_png.d.mts +18 -0
  57. package/api/theme-edit/_png.mjs +95 -14
  58. package/api/theme-edit/_preview-app.d.mts +9 -0
  59. package/api/theme-edit/_preview-app.mjs +1191 -71
  60. package/api/theme-edit/_preview.d.mts +16 -3
  61. package/api/theme-edit/_preview.mjs +335 -30
  62. package/api/theme-edit/_project.d.mts +11 -0
  63. package/api/theme-edit/_project.mjs +46 -12
  64. package/api/theme-edit/_settings.d.mts +240 -5
  65. package/api/theme-edit/_settings.mjs +2561 -115
  66. package/api/theme-edit/_tables.d.mts +24 -0
  67. package/api/theme-edit/_tables.mjs +211 -149
  68. package/api/theme-edit/_vet.d.mts +42 -0
  69. package/api/theme-edit/_vet.mjs +144 -0
  70. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  71. package/api/theme-edit/theme-edit.type.mjs +1 -1
  72. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  73. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  74. package/api/upgrade/registry/registry.mjs +6 -1
  75. package/assets/codemods/parse.mjs +2 -2
  76. package/assets/docs/tree/single-component.doc.mjs +11 -2
  77. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  78. package/assets/docs.generated.json +2 -2
  79. package/assets/preview-app/next.config.mjs +7 -1
  80. package/assets/preview-app/package.json +1 -0
  81. package/assets/preview-app/src/app/globals.css +1 -0
  82. package/assets/self-audit.generated.json +1 -1
  83. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  84. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  85. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  86. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  87. package/assets/templates/components.generated.json +1 -1
  88. package/assets/templates/pages/dashboard/page.tsx +1 -1
  89. package/authoring/doctypes/_schema.d.mts +52 -5
  90. package/authoring/doctypes/_schema.mjs +62 -7
  91. package/authoring/doctypes/base/type.ts +10 -0
  92. package/authoring/doctypes/component/component.doc.mjs +1 -1
  93. package/authoring/doctypes/function/function.doc.mjs +6 -0
  94. package/authoring/doctypes/function/type.ts +3 -0
  95. package/authoring/doctypes/legacy.mjs +5 -1
  96. package/authoring/index.d.ts +1 -0
  97. package/authoring/shadcn/source-variants.d.mts +1 -1
  98. package/authoring/shadcn/source-variants.mjs +32 -10
  99. package/clients/cli/build-id.generated.json +1 -1
  100. package/clients/cli/commands/doctor.doc.mjs +2 -2
  101. package/clients/cli/commands/experimental/theme.mjs +237 -45
  102. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  103. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  105. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  106. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  108. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  109. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  110. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  111. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  112. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  113. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  114. package/clients/cli/commands/theme.mjs +190 -46
  115. package/clients/cli/formatters/index.mjs +7 -4
  116. package/clients/cli/lib/cli-error.mjs +9 -3
  117. package/clients/cli/lib/component-format.mjs +27 -9
  118. package/clients/cli/lib/json-shim.mjs +72 -2
  119. package/clients/cli/manifest.generated.json +1 -1
  120. package/clients/cli/run.mjs +49 -0
  121. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  122. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  123. package/foundation/agent-docs/agent-docs.mjs +3 -2
  124. package/foundation/config/config-writer.mjs +2 -2
  125. package/foundation/config/project.mjs +60 -14
  126. package/foundation/discovery/component-discovery.mjs +5 -17
  127. package/foundation/discovery/icon-set-writer.mjs +1 -1
  128. package/foundation/discovery/module-exports.mjs +1 -15
  129. package/foundation/discovery/template-adapter.mjs +44 -19
  130. package/foundation/discovery/template-source-tree.mjs +3 -16
  131. package/foundation/discovery/theme-discovery.d.mts +5 -1
  132. package/foundation/discovery/theme-discovery.mjs +30 -35
  133. package/foundation/fs/exact-codec.d.mts +35 -0
  134. package/foundation/fs/exact-codec.mjs +148 -0
  135. package/foundation/fs/gather-cache.d.mts +15 -5
  136. package/foundation/fs/gather-cache.mjs +123 -30
  137. package/foundation/fs/paths.d.mts +39 -0
  138. package/foundation/fs/paths.mjs +44 -11
  139. package/foundation/fs/read-record.mjs +11 -1
  140. package/foundation/integrations/contribution-fixes.mjs +1 -16
  141. package/foundation/integrations/may-have-integrations.mjs +3 -2
  142. package/foundation/integrations/public-imports.mjs +1 -1
  143. package/foundation/render/embedded-imports.mjs +1 -1
  144. package/foundation/render/host-exit.d.mts +8 -0
  145. package/foundation/render/host-exit.mjs +11 -0
  146. package/foundation/render/page-host.mjs +56 -10
  147. package/foundation/render/page-worker.mjs +14 -0
  148. package/foundation/render/render-page.mjs +37 -2
  149. package/foundation/response/error-codes.d.mts +2 -1
  150. package/foundation/response/error-codes.d.ts +1 -0
  151. package/foundation/response/error-codes.doc.mjs +5 -0
  152. package/foundation/response/error-codes.mjs +3 -0
  153. package/foundation/response/json.d.mts +15 -0
  154. package/foundation/response/json.mjs +52 -1
  155. package/foundation/response/response-types.doc.mjs +1 -1
  156. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  157. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  158. package/foundation/xle/browser.d.mts +2 -2
  159. 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,20 @@ import {
24
25
  } from './_catalog.mjs';
25
26
  import {
26
27
  catalogVariants,
27
- isItemOf,
28
+ demoProps,
29
+ needsParent,
28
30
  renderDir,
29
31
  renderGenerated,
30
32
  } from './_parts.mjs';
31
33
  import {OVERVIEW_SECTIONS} from './_overview.mjs';
32
34
  import {camel, fontPackages, modesOf, themeFiles, shown} from './_settings.mjs';
33
35
  import {writeWhole} from './_palette.mjs';
36
+ import {cliVersion} from '../../foundation/release/run-context.mjs';
34
37
  import {importPathOf, installLine} from './_project.mjs';
35
- import {COLOR_PROP_PARTS, DIRECT, P} from './_tables.mjs';
38
+ import {COLOR_PROP_PARTS, DIRECT, P, wordTable} from './_tables.mjs';
36
39
  import {extractImportedPackages} from '../../foundation/discovery/template-needs.mjs';
37
40
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
41
+ import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
38
42
 
39
43
  const TEMPLATES_DIR = path.resolve(
40
44
  path.dirname(fileURLToPath(import.meta.url)),
@@ -185,9 +189,26 @@ function inParentOf(project, name) {
185
189
  const info = project.components[name];
186
190
  if (!info?.subComponentOf) return tree => tree;
187
191
  const wrapper = info.wrapper;
192
+ // A part of a parent that shows inline (a dialog's header) renders inside
193
+ // that parent shown open and inline, as Core's docs show it: alone, it
194
+ // acts as in a modal one (a dialog header takes focus as it mounts).
195
+ const of = info.subComponentOf;
196
+ const parent = project.components[of];
197
+ if (!wrapper && parent?.props?.isInline && parent.props.isOpen) {
198
+ const props = Object.fromEntries(
199
+ Object.entries(demoProps(project, of) ?? {}).filter(
200
+ ([k]) => k !== 'children',
201
+ ),
202
+ );
203
+ return tree => ({
204
+ __element: of,
205
+ props: {...props, isOpen: true, isInline: true},
206
+ children: [tree],
207
+ });
208
+ }
188
209
  // A part its parent does not list as an item, such as a heading of the
189
210
  // text family, renders on its own.
190
- if (!wrapper) return isItemOf(project, name) ? null : tree => tree;
211
+ if (!wrapper) return needsParent(project, name) ? null : tree => tree;
191
212
  if (project.components[wrapper.component]?.wrapper) return null;
192
213
  const props = Object.fromEntries(
193
214
  Object.entries(wrapper.props).filter(([k]) => !OPEN_PROPS.includes(k)),
@@ -214,6 +235,59 @@ function templateFiles(imports) {
214
235
  });
215
236
  }
216
237
 
238
+ /**
239
+ * The fonts stylesheet of the theme a theme is built on, when its package
240
+ * ships one (`@astryxdesign/theme-neutral/fonts.css` loads Figtree): naming
241
+ * a family does not load it, and the base theme's families apply until the
242
+ * theme sets its own. Once the theme's build names none of the families the
243
+ * sheet loads, it is left out.
244
+ * @param {import('./_settings.mjs').Ctx} ctx
245
+ * @param {import('./_settings.mjs').ThemeData} data
246
+ * @returns {string[]}
247
+ */
248
+ export function baseFontsCss(ctx, data) {
249
+ if (!data.like) return [];
250
+ const pkg = `@astryxdesign/theme-${data.like}`;
251
+ const sheet = `${pkg}/fonts.css`;
252
+ // Read off disk: the package must export the sheet for an app to import
253
+ // it.
254
+ const found = findNodeModulesPackage(ctx.project.cwd, pkg);
255
+ /** @type {string} */
256
+ let text;
257
+ try {
258
+ if (!found) return [];
259
+ const exportsMap = JSON.parse(
260
+ fs.readFileSync(path.join(found.packageDir, 'package.json'), 'utf8'),
261
+ ).exports;
262
+ if (
263
+ !exportsMap ||
264
+ typeof exportsMap !== 'object' ||
265
+ !('./fonts.css' in exportsMap)
266
+ )
267
+ return [];
268
+ text = fs.readFileSync(path.join(found.packageDir, 'fonts.css'), 'utf8');
269
+ } catch {
270
+ return [];
271
+ }
272
+ // The families the sheet loads; with the theme's build at hand, the sheet
273
+ // is imported only while the build still names one of them.
274
+ const families = [...text.matchAll(/family=([^:&'")]+)/g)].map(m =>
275
+ decodeURIComponent(m[1].replace(/\+/g, ' ')),
276
+ );
277
+ /** @type {string | null} */
278
+ let built = null;
279
+ try {
280
+ built = fs.readFileSync(themeFiles(ctx.project.cwd, data.name).css, 'utf8');
281
+ } catch {
282
+ // Not built yet: the base families may still apply.
283
+ }
284
+ if (built != null && families.length) {
285
+ const css = built;
286
+ if (!families.some(f => css.includes(f))) return [];
287
+ }
288
+ return [sheet];
289
+ }
290
+
217
291
  /**
218
292
  * How a generated page imports the theme: its built module, its stylesheet,
219
293
  * and the stylesheets of open fonts the project has installed.
@@ -235,13 +309,162 @@ export function themeImports(ctx, slug, data, fromDir) {
235
309
  .map(x => `${x.pkg}/index.css`);
236
310
  return {
237
311
  module: rel(f.js),
238
- css: [rel(f.css), ...fonts],
312
+ css: [rel(f.css), ...baseFontsCss(ctx, data), ...fonts],
239
313
  mode: /** @type {'system' | 'light' | 'dark'} */ (
240
314
  modes.length > 1 ? 'system' : modes[0]
241
315
  ),
242
316
  };
243
317
  }
244
318
 
319
+ /**
320
+ * The inputs a page was rendered from and a hash of the page above it,
321
+ * recorded at the end of the page.
322
+ */
323
+ const RENDER_STAMP = /<!-- astryx: render of ([0-9a-f]{24}) ([0-9a-f]{16}) -->/;
324
+
325
+ /** @type {Map<string, string>} */
326
+ const treeKeys = new Map();
327
+
328
+ /**
329
+ * A cheap fingerprint of the files a package runs from: each file's path,
330
+ * size and modification time under its folder (node_modules left out), so a
331
+ * linked or patched copy with the same version reads as another. Once per
332
+ * process for each folder.
333
+ * @param {string | null | undefined} dir
334
+ * @returns {string}
335
+ */
336
+ function treeKey(dir) {
337
+ if (!dir) return 'none';
338
+ const known = treeKeys.get(dir);
339
+ if (known) return known;
340
+ const h = createHash('sha256');
341
+ /** @param {string} d */
342
+ const walk = d => {
343
+ let entries;
344
+ try {
345
+ entries = fs.readdirSync(d, {withFileTypes: true});
346
+ } catch {
347
+ return;
348
+ }
349
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
350
+ for (const e of entries) {
351
+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue;
352
+ const p = path.join(d, e.name);
353
+ if (e.isDirectory()) walk(p);
354
+ else if (e.isFile()) {
355
+ try {
356
+ const st = fs.statSync(p);
357
+ h.update(`${path.relative(dir, p)}\0${st.size}\0${st.mtimeMs}\0`);
358
+ } catch {
359
+ // Gone meanwhile.
360
+ }
361
+ }
362
+ }
363
+ };
364
+ walk(dir);
365
+ const key = h.digest('hex').slice(0, 16);
366
+ treeKeys.set(dir, key);
367
+ return key;
368
+ }
369
+
370
+ /**
371
+ * The folder of an installed package, resolved from the project, or null.
372
+ * @param {string} cwd
373
+ * @param {string} name
374
+ */
375
+ function packageDirOf(cwd, name) {
376
+ try {
377
+ return findNodeModulesPackage(cwd, name)?.packageDir ?? null;
378
+ } catch {
379
+ return null;
380
+ }
381
+ }
382
+
383
+ /** @param {string} text */
384
+ const bodyHash = text =>
385
+ createHash('sha256').update(text).digest('hex').slice(0, 16);
386
+
387
+ /**
388
+ * A key for everything a page render reads: the CLI, Core (its version and
389
+ * stylesheet, and the files it runs from), the base theme package's files,
390
+ * the generated page source, and the theme's built stylesheet and module.
391
+ * The same key means the same page.
392
+ * @param {import('./_project.mjs').ThemeProject} project
393
+ * @param {string} slug
394
+ * @param {string} source
395
+ * @param {string | null | undefined} [like] the base theme
396
+ * @returns {string}
397
+ */
398
+ function renderKey(project, slug, source, like) {
399
+ const f = themeFiles(project.cwd, slug);
400
+ const h = createHash('sha256')
401
+ .update(cliVersion())
402
+ .update('\0')
403
+ .update(String(project.coreKey ?? ''))
404
+ .update('\0')
405
+ .update(treeKey(path.join(project.coreDir, 'dist')))
406
+ .update('\0')
407
+ .update(
408
+ like
409
+ ? treeKey(packageDirOf(project.cwd, `@astryxdesign/theme-${like}`))
410
+ : 'none',
411
+ )
412
+ .update('\0')
413
+ .update(source);
414
+ for (const file of [f.css, f.js]) {
415
+ h.update('\0');
416
+ try {
417
+ h.update(fs.readFileSync(file));
418
+ } catch {
419
+ h.update('missing');
420
+ }
421
+ }
422
+ return h.digest('hex').slice(0, 24);
423
+ }
424
+
425
+ /**
426
+ * Whether `out` is a page rendered from `key` (a no-op show renders
427
+ * nothing again).
428
+ * @param {string} out
429
+ * @param {string} key
430
+ */
431
+ function renderedFrom(out, key) {
432
+ try {
433
+ const st = fs.lstatSync(out);
434
+ if (!st.isFile()) return false;
435
+ const text = fs.readFileSync(out, 'utf8');
436
+ const m = RENDER_STAMP.exec(text);
437
+ // The page above the comment is the one rendered: an edit by hand, or
438
+ // a comment pasted under another page, is rendered again.
439
+ // Nothing may follow the comment but the sheet's own build stamp
440
+ // (written after it by show): text added after it is rendered over.
441
+ const after = m
442
+ ? text
443
+ .slice(m.index + m[0].length)
444
+ .replace(/<!-- astryx: sheet of build [0-9a-f]{16} -->/, '')
445
+ : '';
446
+ return (
447
+ m != null &&
448
+ m[1] === key &&
449
+ after.trim() === '' &&
450
+ m[2] === bodyHash(text.slice(0, m.index).trimEnd())
451
+ );
452
+ } catch {
453
+ return false;
454
+ }
455
+ }
456
+
457
+ /**
458
+ * The page with its render key recorded at its end (after the closing tag:
459
+ * a comment before the doctype would put it in quirks mode).
460
+ * @param {string} html
461
+ * @param {string} key
462
+ */
463
+ const withRenderKey = (html, key) => {
464
+ const body = html.replace(RENDER_STAMP, '').trimEnd();
465
+ return `${body}\n<!-- astryx: render of ${key} ${bodyHash(body)} -->\n`;
466
+ };
467
+
245
468
  /**
246
469
  * Render the sample app page with the theme to themes/<slug>/preview.html.
247
470
  * @param {import('./_settings.mjs').Ctx} ctx
@@ -263,10 +486,13 @@ export async function renderPreview(ctx, slug, data) {
263
486
  layout: 'page',
264
487
  title: `${slug}: sample page`,
265
488
  });
266
- const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
267
489
  const out = themeFiles(project.cwd, slug).preview;
490
+ // Rendered from the same inputs before: the page is as it would be.
491
+ const key = renderKey(project, slug, source, data.like);
492
+ if (renderedFrom(out, key)) return shown(project.cwd, out);
493
+ const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
268
494
  // Written whole and renamed in, never through a link.
269
- writeWhole(out, html);
495
+ writeWhole(out, withRenderKey(html, key));
270
496
  return shown(project.cwd, out);
271
497
  }
272
498
 
@@ -288,12 +514,6 @@ export async function renderSheet(ctx, slug, data, options = {}) {
288
514
  layout: 'sheet',
289
515
  title: `${slug}: every component${options.group ? ` (${options.group})` : ''}`,
290
516
  });
291
- const {html} = await renderGenerated(
292
- project,
293
- `sheet-${slug}.mjs`,
294
- source,
295
- templateFiles(imports),
296
- );
297
517
  // One section goes to its own file, so the full sheet stays whole.
298
518
  const full = themeFiles(project.cwd, slug).sheet;
299
519
  const out =
@@ -301,9 +521,23 @@ export async function renderSheet(ctx, slug, data, options = {}) {
301
521
  (options.group
302
522
  ? path.join(path.dirname(full), `sheet-${options.group}.html`)
303
523
  : full);
524
+ const key = renderKey(project, slug, source, data.like);
525
+ const result = {
526
+ file: shown(project.cwd, out),
527
+ components: new Set(items.map(i => i.name)).size,
528
+ skipped,
529
+ };
530
+ // Rendered from the same inputs before: the sheet is as it would be.
531
+ if (renderedFrom(out, key)) return result;
532
+ const {html} = await renderGenerated(
533
+ project,
534
+ `sheet-${slug}.mjs`,
535
+ source,
536
+ templateFiles(imports),
537
+ );
304
538
  fs.mkdirSync(path.dirname(out), {recursive: true});
305
539
  // Written whole and renamed in, never through a link.
306
- writeWhole(out, html);
540
+ writeWhole(out, withRenderKey(html, key));
307
541
  return {
308
542
  file: shown(project.cwd, out),
309
543
  components: new Set(items.map(i => i.name)).size,
@@ -460,11 +694,11 @@ function componentTable(project, trees) {
460
694
  const SAFE = [
461
695
  '/** Shows a short note for a component that throws, so the rest of the page renders. */',
462
696
  'class Safe extends React.Component<{name: string, children: React.ReactNode}, {failed: boolean}> {',
463
- ' state = {failed: false};',
697
+ ' override state = {failed: false};',
464
698
  ' static getDerivedStateFromError() {',
465
699
  ' return {failed: true};',
466
700
  ' }',
467
- ' render() {',
701
+ ' override render() {',
468
702
  ' return this.state.failed ? <div className="tp-note">{this.props.name} could not render here</div> : this.props.children;',
469
703
  ' }',
470
704
  '}',
@@ -567,10 +801,12 @@ const usesSource = v =>
567
801
  Object.values(/** @type {object} */ (v)).some(usesSource);
568
802
 
569
803
  /** 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
- });
804
+ const GROUP_TITLES = wordTable(
805
+ /** @type {Record<string, string>} */ ({
806
+ data: 'data display',
807
+ overlays: 'overlays (shown open)',
808
+ }),
809
+ );
574
810
 
575
811
  /**
576
812
  * A cell with the component's name. A cell whose parts show nothing on
@@ -650,7 +886,19 @@ const PAGE_SKIP = new Set([
650
886
  * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} [options]
651
887
  * @returns {{source: string, components: number}}
652
888
  */
653
- export function componentsPageSource(project, {theme = null, C} = {}) {
889
+ export function componentsPageSource(project, options = {}) {
890
+ // A name that Core's docs lack resolves by walking Core's source tree. One
891
+ // listing cache reads each folder once for the page, not once per name.
892
+ return withListingCache(() => componentsPage(project, options));
893
+ }
894
+
895
+ /**
896
+ * {@link componentsPageSource}'s work, inside its listing cache.
897
+ * @param {import('./_project.mjs').ThemeProject} project
898
+ * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} options
899
+ * @returns {{source: string, components: number}}
900
+ */
901
+ function componentsPage(project, {theme = null, C}) {
654
902
  const items = showcaseItems(project, undefined)
655
903
  .items.filter(
656
904
  it =>
@@ -727,10 +975,22 @@ export function componentsPageSource(project, {theme = null, C} = {}) {
727
975
  * boundary, so one part that throws never blanks the page. The preview
728
976
  * route is the app shell, so the page has no shell of its own.
729
977
  * @param {import('./_project.mjs').ThemeProject} project
730
- * @param {{theme?: string | null}} [options]
978
+ * @param {{theme?: string | null, colors?: boolean}} [options] `colors`:
979
+ * the preview has a Colors page, so the header points to it
731
980
  * @returns {string}
732
981
  */
733
- export function overviewPageSource(project, {theme = null} = {}) {
982
+ export function overviewPageSource(project, options = {}) {
983
+ // One listing cache for the page's names, as componentsPageSource holds.
984
+ return withListingCache(() => overviewPage(project, options));
985
+ }
986
+
987
+ /**
988
+ * {@link overviewPageSource}'s work, inside its listing cache.
989
+ * @param {import('./_project.mjs').ThemeProject} project
990
+ * @param {{theme?: string | null, colors?: boolean}} options
991
+ * @returns {string}
992
+ */
993
+ function overviewPage(project, {theme = null, colors = false}) {
734
994
  const sections = OVERVIEW_SECTIONS.map(x => ({
735
995
  title: x.title,
736
996
  tree: /** @type {import('./_catalog.mjs').Tree | undefined} */ (
@@ -786,8 +1046,38 @@ export function overviewPageSource(project, {theme = null} = {}) {
786
1046
  ' React.useEffect(() => {',
787
1047
  ' if (!ref.current) return;',
788
1048
  ' 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')}.`);",
1049
+ " const first = (token: string) => (style.getPropertyValue(token).split(',')[0] ?? '').replace(/[\"']/g, '').trim() || 'default';",
1050
+ ' // A family the browser does not have measures as its fallback does.',
1051
+ ' const GENERIC = /^(default|serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-[a-z-]+|math|emoji|fangsong)$/i;',
1052
+ ' const missing = (family: string) => {',
1053
+ ' if (GENERIC.test(family)) return false;',
1054
+ " const ctx = document.createElement('canvas').getContext('2d');",
1055
+ ' if (!ctx) return false;',
1056
+ " const sample = 'mmmmmmmmmwwwwwww1234567890';",
1057
+ " return ['monospace', 'serif'].every(fallback => {",
1058
+ ' ctx.font = `48px ${fallback}`;',
1059
+ ' const plain = ctx.measureText(sample).width;',
1060
+ ' ctx.font = `48px "${family}", ${fallback}`;',
1061
+ ' return ctx.measureText(sample).width === plain;',
1062
+ ' });',
1063
+ ' };',
1064
+ ' const shown = (token: string) => { const f = first(token); return missing(f) ? `${f} (not installed here)` : f; };',
1065
+ " const write = () => setFonts(`Body: ${shown('--font-family-body')}. Headings: ${shown('--font-family-heading')}.`);",
1066
+ ' write();',
1067
+ ' // Read again when the theme changes live (a stylesheet or theme',
1068
+ ' // update while the page is open) and when a font finishes loading.',
1069
+ ' document.fonts?.ready.then(write);',
1070
+ " document.fonts?.addEventListener?.('loadingdone', write);",
1071
+ ' let queued = 0;',
1072
+ ' const soon = () => { if (!queued) queued = requestAnimationFrame(() => { queued = 0; write(); }); };',
1073
+ ' const watch = new MutationObserver(soon);',
1074
+ ' watch.observe(document.head, {childList: true, subtree: true, characterData: true});',
1075
+ " watch.observe(document.documentElement, {attributes: true, subtree: true, attributeFilter: ['style', 'class', 'data-theme']});",
1076
+ ' return () => {',
1077
+ ' watch.disconnect();',
1078
+ ' cancelAnimationFrame(queued);',
1079
+ " document.fonts?.removeEventListener?.('loadingdone', write);",
1080
+ ' };',
791
1081
  ' }, []);',
792
1082
  ' return (',
793
1083
  " <div ref={ref} style={{color: 'var(--color-text-secondary)', fontSize: 13}}>",
@@ -812,7 +1102,12 @@ export function overviewPageSource(project, {theme = null} = {}) {
812
1102
  ' {s.name}',
813
1103
  ' </div>',
814
1104
  ' ))}',
815
- ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1105
+ // The Colors page is there only for a theme with generated colors.
1106
+ ...(colors
1107
+ ? [
1108
+ ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1109
+ ]
1110
+ : []),
816
1111
  ' </div>',
817
1112
  ' </header>',
818
1113
  body,
@@ -839,7 +1134,6 @@ export function colorsPageSource({slug, module, seeds, uses}) {
839
1134
  '// `astryx experimental theme editor set` rewrites it with every change.',
840
1135
  "'use client';",
841
1136
  '',
842
- "import * as React from 'react';",
843
1137
  ];
844
1138
  const text = {color: 'var(--color-text-primary)'};
845
1139
  const page = {
@@ -891,7 +1185,7 @@ export function colorsPageSource({slug, module, seeds, uses}) {
891
1185
  " <h2 style={{margin: 0, fontSize: 20, textTransform: 'capitalize'}}>",
892
1186
  ' {name}',
893
1187
  ' {SEEDS[name] ? (',
894
- " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, color: 'var(--color-text-secondary)'}}>",
1188
+ " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, textTransform: 'none', color: 'var(--color-text-secondary)'}}>",
895
1189
  ' from {SEEDS[name]}',
896
1190
  ' </span>',
897
1191
  ' ) : null}',
@@ -984,7 +1278,7 @@ export function previewRouteSource({
984
1278
  ' ))}',
985
1279
  ' </SideNav>',
986
1280
  ' }>',
987
- ' <current.Page />',
1281
+ ' {ready ? <current.Page /> : null}',
988
1282
  ' </AppShell>',
989
1283
  ' </div>',
990
1284
  ];
@@ -999,7 +1293,13 @@ export function previewRouteSource({
999
1293
  "import {TopNav} from '@astryxdesign/core/TopNav';",
1000
1294
  ...(theme
1001
1295
  ? [
1002
- "import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';",
1296
+ // The mode switch only for a theme with both modes: an import the
1297
+ // route does not draw fails an app with noUnusedLocals.
1298
+ ...(mode.length
1299
+ ? [
1300
+ "import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';",
1301
+ ]
1302
+ : []),
1003
1303
  "import {Theme} from '@astryxdesign/core/theme';",
1004
1304
  `import {${camelName(theme.name)}Theme as theme} from ${JSON.stringify(theme.module.replace(/\.js$/, ''))};`,
1005
1305
  ...theme.css.map(c => `import ${JSON.stringify(c)};`),
@@ -1028,6 +1328,10 @@ export function previewRouteSource({
1028
1328
  '',
1029
1329
  'export default function ThemePreviewPage() {',
1030
1330
  ' const [page, setPage] = React.useState(PAGES[0]?.id);',
1331
+ // Pages render only in the browser: some components crash a server
1332
+ // render, and Next prerenders a client page's first state.
1333
+ ' const [ready, setReady] = React.useState(false);',
1334
+ ' React.useEffect(() => setReady(true), []);',
1031
1335
  ...(theme
1032
1336
  ? [
1033
1337
  oneMode
@@ -1035,7 +1339,8 @@ export function previewRouteSource({
1035
1339
  : " const [mode, setMode] = React.useState<Mode>('system');",
1036
1340
  ]
1037
1341
  : []),
1038
- ' const current = PAGES.find(p => p.id === page) ?? PAGES[0];',
1342
+ // The route always has a page; the cast keeps noUncheckedIndexedAccess apps building.
1343
+ ' const current = (PAGES.find(p => p.id === page) ?? PAGES[0]) as (typeof PAGES)[number];',
1039
1344
  ' return (',
1040
1345
  ...(theme
1041
1346
  ? [' <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
  /**