@astryxdesign/cli 0.7.15 → 0.7.16-canary.g22213fd

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 (222) hide show
  1. package/README.md +6 -4
  2. package/api/build/_adapter.d.mts +10 -0
  3. package/api/build/_adapter.mjs +24 -0
  4. package/api/build/blocks/blocks.d.mts +1 -0
  5. package/api/build/blocks/blocks.mjs +18 -1
  6. package/api/build/kit/shell.weights.json +1 -0
  7. package/api/build/kit/shellcall.d.mts +26 -0
  8. package/api/build/kit/shellcall.mjs +87 -0
  9. package/api/build/kit/start.mjs +67 -4
  10. package/api/build/kit/weights.d.mts +15 -0
  11. package/api/build/kit/weights.mjs +27 -0
  12. package/api/component/__fixtures__/resolutions/modules.txt +1 -1
  13. package/api/component/_adapter.d.mts +1 -1
  14. package/api/component/_adapter.mjs +28 -1
  15. package/api/doctor/_adapter.d.mts +38 -2
  16. package/api/doctor/_adapter.mjs +76 -1
  17. package/api/doctor/built-checks.mjs +1 -1
  18. package/api/doctor/doctor.d.mts +26 -0
  19. package/api/doctor/doctor.doc.mjs +1 -1
  20. package/api/doctor/doctor.mjs +156 -11
  21. package/api/doctor/theme-checks.mjs +163 -18
  22. package/api/icon/_adapter.d.mts +7 -3
  23. package/api/icon/_adapter.mjs +12 -3
  24. package/api/icon/icon.type.d.mts +15 -0
  25. package/api/icon/icon.type.mjs +10 -3
  26. package/api/icon/iconUse.doc.mjs +19 -5
  27. package/api/icon/list/list.mjs +7 -1
  28. package/api/icon/use/use.d.mts +8 -5
  29. package/api/icon/use/use.mjs +95 -13
  30. package/api/init/run/run.mjs +1 -0
  31. package/api/integration/add-contribution.mjs +3 -3
  32. package/api/integration/pack-check.mjs +14 -8
  33. package/api/integration/validate-integration.mjs +1 -1
  34. package/api/search/_adapter.mjs +15 -16
  35. package/api/search/_entries.d.mts +2 -1
  36. package/api/search/_entries.mjs +28 -1
  37. package/api/swizzle/_moduleGraph.mjs +1 -1
  38. package/api/template/template.type.d.mts +6 -2
  39. package/api/template/template.type.mjs +2 -1
  40. package/api/theme/_adapter.d.mts +5 -2
  41. package/api/theme/_adapter.mjs +59 -14
  42. package/api/theme/_fork.mjs +1 -1
  43. package/api/theme/build/build.d.mts +120 -32
  44. package/api/theme/build/build.mjs +471 -111
  45. package/api/theme/eject/eject.mjs +22 -1
  46. package/api/theme/generateTonalPalette.doc.mjs +2 -2
  47. package/api/theme/palette/generate/generator.mjs +141 -2
  48. package/api/theme/template/template.d.mts +19 -0
  49. package/api/theme/template/template.mjs +102 -25
  50. package/api/theme/theme.type.d.mts +44 -1
  51. package/api/theme/theme.type.mjs +23 -1
  52. package/api/theme/themeBuild.doc.mjs +4 -4
  53. package/api/theme/themeEject.doc.mjs +1 -1
  54. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  55. package/api/theme/themeTemplate.doc.mjs +9 -3
  56. package/api/theme-edit/_adapter.d.mts +33 -2
  57. package/api/theme-edit/_adapter.mjs +276 -41
  58. package/api/theme-edit/_check.d.mts +93 -4
  59. package/api/theme-edit/_check.mjs +1712 -223
  60. package/api/theme-edit/_color.d.mts +2 -8
  61. package/api/theme-edit/_color.mjs +292 -219
  62. package/api/theme-edit/_compiler.d.mts +1 -0
  63. package/api/theme-edit/_compiler.mjs +20 -1
  64. package/api/theme-edit/_context.d.mts +31 -1
  65. package/api/theme-edit/_context.mjs +445 -41
  66. package/api/theme-edit/_css.d.mts +60 -1
  67. package/api/theme-edit/_css.mjs +404 -28
  68. package/api/theme-edit/_edit.d.mts +25 -0
  69. package/api/theme-edit/_edit.mjs +1620 -154
  70. package/api/theme-edit/_how-commands.d.mts +11 -26
  71. package/api/theme-edit/_how-commands.mjs +30 -2
  72. package/api/theme-edit/_how-question.d.mts +15 -0
  73. package/api/theme-edit/_how-question.mjs +1469 -194
  74. package/api/theme-edit/_how.mjs +144 -30
  75. package/api/theme-edit/_marks.d.mts +13 -0
  76. package/api/theme-edit/_marks.mjs +15 -0
  77. package/api/theme-edit/_overview.mjs +2 -0
  78. package/api/theme-edit/_palette.d.mts +38 -0
  79. package/api/theme-edit/_palette.mjs +306 -73
  80. package/api/theme-edit/_parts.d.mts +33 -0
  81. package/api/theme-edit/_parts.mjs +138 -9
  82. package/api/theme-edit/_png.d.mts +18 -0
  83. package/api/theme-edit/_png.mjs +95 -14
  84. package/api/theme-edit/_preview-app.d.mts +55 -1
  85. package/api/theme-edit/_preview-app.mjs +1552 -101
  86. package/api/theme-edit/_preview.d.mts +71 -3
  87. package/api/theme-edit/_preview.mjs +565 -35
  88. package/api/theme-edit/_project.d.mts +15 -0
  89. package/api/theme-edit/_project.mjs +68 -13
  90. package/api/theme-edit/_settings.d.mts +299 -5
  91. package/api/theme-edit/_settings.mjs +2806 -158
  92. package/api/theme-edit/_tables.d.mts +24 -0
  93. package/api/theme-edit/_tables.mjs +212 -150
  94. package/api/theme-edit/_vet.d.mts +42 -0
  95. package/api/theme-edit/_vet.mjs +144 -0
  96. package/api/theme-edit/theme-edit.type.d.mts +31 -2
  97. package/api/theme-edit/theme-edit.type.mjs +10 -2
  98. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  99. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  100. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  101. package/api/upgrade/registry/registry.mjs +6 -1
  102. package/assets/codemods/parse.mjs +2 -2
  103. package/assets/docs/author-a-theme.doc.mjs +1 -1
  104. package/assets/docs/theme.doc.dense.mjs +1 -1
  105. package/assets/docs/theme.doc.mjs +1 -1
  106. package/assets/docs/theme.doc.zh.mjs +4 -3
  107. package/assets/docs/tree/define-the-theme.doc.mjs +1 -1
  108. package/assets/docs/tree/icon-sets.doc.mjs +63 -8
  109. package/assets/docs/tree/single-component.doc.mjs +11 -2
  110. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  111. package/assets/docs.generated.json +2 -2
  112. package/assets/preview-app/next.config.mjs +7 -1
  113. package/assets/preview-app/package.json +1 -0
  114. package/assets/preview-app/src/app/globals.css +1 -0
  115. package/assets/self-audit.generated.json +1 -1
  116. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.doc.mjs +21 -0
  117. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.tsx +62 -0
  118. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  119. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  120. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  121. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  122. package/assets/templates/components.generated.json +1 -1
  123. package/assets/templates/pages/ai-chat/page.tsx +20 -2
  124. package/assets/templates/pages/dashboard/page.tsx +1 -1
  125. package/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json +2 -0
  126. package/authoring/config/config.doc.mjs +8 -0
  127. package/authoring/config/parse.d.mts +1 -0
  128. package/authoring/config/parse.mjs +12 -0
  129. package/authoring/config/type.ts +8 -0
  130. package/authoring/doctypes/_schema.d.mts +52 -5
  131. package/authoring/doctypes/_schema.mjs +62 -7
  132. package/authoring/doctypes/base/type.ts +10 -0
  133. package/authoring/doctypes/component/component.doc.mjs +1 -1
  134. package/authoring/doctypes/function/function.doc.mjs +6 -0
  135. package/authoring/doctypes/function/type.ts +3 -0
  136. package/authoring/doctypes/icon-set/icon-set-data.doc.mjs +3 -3
  137. package/authoring/doctypes/legacy.mjs +5 -1
  138. package/authoring/index.d.ts +1 -0
  139. package/authoring/shadcn/source-variants.d.mts +1 -1
  140. package/authoring/shadcn/source-variants.mjs +32 -10
  141. package/clients/cli/build-id.generated.json +1 -1
  142. package/clients/cli/commands/doctor.doc.mjs +2 -2
  143. package/clients/cli/commands/experimental/icon.mjs +61 -6
  144. package/clients/cli/commands/experimental/theme.mjs +244 -45
  145. package/clients/cli/commands/experimental-icon-use.doc.mjs +12 -5
  146. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  147. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  148. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  149. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  150. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  151. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  152. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  153. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  154. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  155. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  156. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  157. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  158. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  159. package/clients/cli/commands/theme.doc.mjs +7 -2
  160. package/clients/cli/commands/theme.mjs +222 -55
  161. package/clients/cli/commands.generated.json +1 -1
  162. package/clients/cli/formatters/index.mjs +7 -4
  163. package/clients/cli/index.mjs +25 -5
  164. package/clients/cli/lib/cli-error.mjs +9 -3
  165. package/clients/cli/lib/component-format.mjs +27 -9
  166. package/clients/cli/lib/json-shim.mjs +72 -2
  167. package/clients/cli/manifest.generated.json +1 -1
  168. package/clients/cli/run.mjs +49 -0
  169. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  170. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  171. package/foundation/agent-docs/agent-docs.mjs +4 -3
  172. package/foundation/config/config-writer.d.mts +23 -0
  173. package/foundation/config/config-writer.mjs +152 -58
  174. package/foundation/config/project.mjs +103 -16
  175. package/foundation/discovery/component-discovery.mjs +11 -22
  176. package/foundation/discovery/icon-set-checks.mjs +164 -48
  177. package/foundation/discovery/icon-set-discovery.d.mts +38 -5
  178. package/foundation/discovery/icon-set-discovery.mjs +50 -6
  179. package/foundation/discovery/icon-set-theme-maps.d.mts +59 -0
  180. package/foundation/discovery/icon-set-theme-maps.mjs +95 -0
  181. package/foundation/discovery/icon-set-writer.d.mts +2 -3
  182. package/foundation/discovery/icon-set-writer.mjs +58 -17
  183. package/foundation/discovery/module-exports.mjs +1 -15
  184. package/foundation/discovery/template-adapter.mjs +44 -19
  185. package/foundation/discovery/template-icons.d.mts +27 -10
  186. package/foundation/discovery/template-icons.mjs +142 -26
  187. package/foundation/discovery/template-source-tree.mjs +3 -16
  188. package/foundation/discovery/theme-discovery.d.mts +30 -1
  189. package/foundation/discovery/theme-discovery.mjs +109 -50
  190. package/foundation/fs/exact-codec.d.mts +35 -0
  191. package/foundation/fs/exact-codec.mjs +148 -0
  192. package/foundation/fs/gather-cache.d.mts +15 -5
  193. package/foundation/fs/gather-cache.mjs +129 -31
  194. package/foundation/fs/paths.d.mts +39 -0
  195. package/foundation/fs/paths.mjs +44 -11
  196. package/foundation/fs/read-record.mjs +11 -1
  197. package/foundation/integrations/autolink.d.mts +4 -2
  198. package/foundation/integrations/autolink.mjs +4 -2
  199. package/foundation/integrations/cli-requirement.d.mts +16 -5
  200. package/foundation/integrations/cli-requirement.mjs +27 -6
  201. package/foundation/integrations/contribution-fixes.mjs +1 -16
  202. package/foundation/integrations/may-have-integrations.mjs +7 -3
  203. package/foundation/integrations/missing-dependency.d.mts +9 -0
  204. package/foundation/integrations/missing-dependency.mjs +100 -0
  205. package/foundation/integrations/public-imports.mjs +1 -1
  206. package/foundation/render/embedded-imports.mjs +1 -1
  207. package/foundation/render/host-exit.d.mts +8 -0
  208. package/foundation/render/host-exit.mjs +11 -0
  209. package/foundation/render/page-host.mjs +56 -10
  210. package/foundation/render/page-worker.mjs +14 -0
  211. package/foundation/render/render-page.mjs +37 -2
  212. package/foundation/response/error-codes.d.mts +2 -1
  213. package/foundation/response/error-codes.d.ts +1 -0
  214. package/foundation/response/error-codes.doc.mjs +5 -0
  215. package/foundation/response/error-codes.mjs +3 -0
  216. package/foundation/response/json.d.mts +15 -0
  217. package/foundation/response/json.mjs +52 -1
  218. package/foundation/response/response-types.doc.mjs +1 -1
  219. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  220. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  221. package/foundation/xle/browser.d.mts +2 -2
  222. package/package.json +7 -6
@@ -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,28 @@ 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
- import {camel, fontPackages, modesOf, themeFiles, shown} from './_settings.mjs';
34
+ import {
35
+ FOLDER_JUNK,
36
+ folderIsEmpty,
37
+ camel,
38
+ fontPackages,
39
+ modesOf,
40
+ themeFiles,
41
+ shown,
42
+ } from './_settings.mjs';
33
43
  import {writeWhole} from './_palette.mjs';
44
+ import {cliVersion} from '../../foundation/release/run-context.mjs';
34
45
  import {importPathOf, installLine} from './_project.mjs';
35
- import {COLOR_PROP_PARTS, DIRECT, P} from './_tables.mjs';
46
+ import {COLOR_PROP_PARTS, DIRECT, P, wordTable} from './_tables.mjs';
36
47
  import {extractImportedPackages} from '../../foundation/discovery/template-needs.mjs';
37
48
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
49
+ import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
38
50
 
39
51
  const TEMPLATES_DIR = path.resolve(
40
52
  path.dirname(fileURLToPath(import.meta.url)),
@@ -185,9 +197,26 @@ function inParentOf(project, name) {
185
197
  const info = project.components[name];
186
198
  if (!info?.subComponentOf) return tree => tree;
187
199
  const wrapper = info.wrapper;
200
+ // A part of a parent that shows inline (a dialog's header) renders inside
201
+ // that parent shown open and inline, as Core's docs show it: alone, it
202
+ // acts as in a modal one (a dialog header takes focus as it mounts).
203
+ const of = info.subComponentOf;
204
+ const parent = project.components[of];
205
+ if (!wrapper && parent?.props?.isInline && parent.props.isOpen) {
206
+ const props = Object.fromEntries(
207
+ Object.entries(demoProps(project, of) ?? {}).filter(
208
+ ([k]) => k !== 'children',
209
+ ),
210
+ );
211
+ return tree => ({
212
+ __element: of,
213
+ props: {...props, isOpen: true, isInline: true},
214
+ children: [tree],
215
+ });
216
+ }
188
217
  // A part its parent does not list as an item, such as a heading of the
189
218
  // text family, renders on its own.
190
- if (!wrapper) return isItemOf(project, name) ? null : tree => tree;
219
+ if (!wrapper) return needsParent(project, name) ? null : tree => tree;
191
220
  if (project.components[wrapper.component]?.wrapper) return null;
192
221
  const props = Object.fromEntries(
193
222
  Object.entries(wrapper.props).filter(([k]) => !OPEN_PROPS.includes(k)),
@@ -214,6 +243,59 @@ function templateFiles(imports) {
214
243
  });
215
244
  }
216
245
 
246
+ /**
247
+ * The fonts stylesheet of the theme a theme is built on, when its package
248
+ * ships one (`@astryxdesign/theme-neutral/fonts.css` loads Figtree): naming
249
+ * a family does not load it, and the base theme's families apply until the
250
+ * theme sets its own. Once the theme's build names none of the families the
251
+ * sheet loads, it is left out.
252
+ * @param {import('./_settings.mjs').Ctx} ctx
253
+ * @param {import('./_settings.mjs').ThemeData} data
254
+ * @returns {string[]}
255
+ */
256
+ export function baseFontsCss(ctx, data) {
257
+ if (!data.like) return [];
258
+ const pkg = `@astryxdesign/theme-${data.like}`;
259
+ const sheet = `${pkg}/fonts.css`;
260
+ // Read off disk: the package must export the sheet for an app to import
261
+ // it.
262
+ const found = findNodeModulesPackage(ctx.project.cwd, pkg);
263
+ /** @type {string} */
264
+ let text;
265
+ try {
266
+ if (!found) return [];
267
+ const exportsMap = JSON.parse(
268
+ fs.readFileSync(path.join(found.packageDir, 'package.json'), 'utf8'),
269
+ ).exports;
270
+ if (
271
+ !exportsMap ||
272
+ typeof exportsMap !== 'object' ||
273
+ !('./fonts.css' in exportsMap)
274
+ )
275
+ return [];
276
+ text = fs.readFileSync(path.join(found.packageDir, 'fonts.css'), 'utf8');
277
+ } catch {
278
+ return [];
279
+ }
280
+ // The families the sheet loads; with the theme's build at hand, the sheet
281
+ // is imported only while the build still names one of them.
282
+ const families = [...text.matchAll(/family=([^:&'")]+)/g)].map(m =>
283
+ decodeURIComponent(m[1].replace(/\+/g, ' ')),
284
+ );
285
+ /** @type {string | null} */
286
+ let built = null;
287
+ try {
288
+ built = fs.readFileSync(themeFiles(ctx.project.cwd, data.name).css, 'utf8');
289
+ } catch {
290
+ // Not built yet: the base families may still apply.
291
+ }
292
+ if (built != null && families.length) {
293
+ const css = built;
294
+ if (!families.some(f => css.includes(f))) return [];
295
+ }
296
+ return [sheet];
297
+ }
298
+
217
299
  /**
218
300
  * How a generated page imports the theme: its built module, its stylesheet,
219
301
  * and the stylesheets of open fonts the project has installed.
@@ -235,7 +317,7 @@ export function themeImports(ctx, slug, data, fromDir) {
235
317
  .map(x => `${x.pkg}/index.css`);
236
318
  return {
237
319
  module: rel(f.js),
238
- css: [rel(f.css), ...fonts],
320
+ css: [rel(f.css), ...baseFontsCss(ctx, data), ...fonts],
239
321
  mode: /** @type {'system' | 'light' | 'dark'} */ (
240
322
  modes.length > 1 ? 'system' : modes[0]
241
323
  ),
@@ -243,13 +325,162 @@ export function themeImports(ctx, slug, data, fromDir) {
243
325
  }
244
326
 
245
327
  /**
246
- * Render the sample app page with the theme to themes/<slug>/preview.html.
328
+ * The inputs a page was rendered from and a hash of the page above it,
329
+ * recorded at the end of the page.
330
+ */
331
+ const RENDER_STAMP = /<!-- astryx: render of ([0-9a-f]{24}) ([0-9a-f]{16}) -->/;
332
+
333
+ /** @type {Map<string, string>} */
334
+ const treeKeys = new Map();
335
+
336
+ /**
337
+ * A cheap fingerprint of the files a package runs from: each file's path,
338
+ * size and modification time under its folder (node_modules left out), so a
339
+ * linked or patched copy with the same version reads as another. Once per
340
+ * process for each folder.
341
+ * @param {string | null | undefined} dir
342
+ * @returns {string}
343
+ */
344
+ function treeKey(dir) {
345
+ if (!dir) return 'none';
346
+ const known = treeKeys.get(dir);
347
+ if (known) return known;
348
+ const h = createHash('sha256');
349
+ /** @param {string} d */
350
+ const walk = d => {
351
+ let entries;
352
+ try {
353
+ entries = fs.readdirSync(d, {withFileTypes: true});
354
+ } catch {
355
+ return;
356
+ }
357
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
358
+ for (const e of entries) {
359
+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue;
360
+ const p = path.join(d, e.name);
361
+ if (e.isDirectory()) walk(p);
362
+ else if (e.isFile()) {
363
+ try {
364
+ const st = fs.statSync(p);
365
+ h.update(`${path.relative(dir, p)}\0${st.size}\0${st.mtimeMs}\0`);
366
+ } catch {
367
+ // Gone meanwhile.
368
+ }
369
+ }
370
+ }
371
+ };
372
+ walk(dir);
373
+ const key = h.digest('hex').slice(0, 16);
374
+ treeKeys.set(dir, key);
375
+ return key;
376
+ }
377
+
378
+ /**
379
+ * The folder of an installed package, resolved from the project, or null.
380
+ * @param {string} cwd
381
+ * @param {string} name
382
+ */
383
+ function packageDirOf(cwd, name) {
384
+ try {
385
+ return findNodeModulesPackage(cwd, name)?.packageDir ?? null;
386
+ } catch {
387
+ return null;
388
+ }
389
+ }
390
+
391
+ /** @param {string} text */
392
+ const bodyHash = text =>
393
+ createHash('sha256').update(text).digest('hex').slice(0, 16);
394
+
395
+ /**
396
+ * A key for everything a page render reads: the CLI, Core (its version and
397
+ * stylesheet, and the files it runs from), the base theme package's files,
398
+ * the generated page source, and the theme's built stylesheet and module.
399
+ * The same key means the same page.
400
+ * @param {import('./_project.mjs').ThemeProject} project
401
+ * @param {string} slug
402
+ * @param {string} source
403
+ * @param {string | null | undefined} [like] the base theme
404
+ * @returns {string}
405
+ */
406
+ function renderKey(project, slug, source, like) {
407
+ const f = themeFiles(project.cwd, slug);
408
+ const h = createHash('sha256')
409
+ .update(cliVersion())
410
+ .update('\0')
411
+ .update(String(project.coreKey ?? ''))
412
+ .update('\0')
413
+ .update(treeKey(path.join(project.coreDir, 'dist')))
414
+ .update('\0')
415
+ .update(
416
+ like
417
+ ? treeKey(packageDirOf(project.cwd, `@astryxdesign/theme-${like}`))
418
+ : 'none',
419
+ )
420
+ .update('\0')
421
+ .update(source);
422
+ for (const file of [f.css, f.js]) {
423
+ h.update('\0');
424
+ try {
425
+ h.update(fs.readFileSync(file));
426
+ } catch {
427
+ h.update('missing');
428
+ }
429
+ }
430
+ return h.digest('hex').slice(0, 24);
431
+ }
432
+
433
+ /**
434
+ * Whether `out` is a page rendered from `key` (a no-op show renders
435
+ * nothing again).
436
+ * @param {string} out
437
+ * @param {string} key
438
+ */
439
+ function renderedFrom(out, key) {
440
+ try {
441
+ const st = fs.lstatSync(out);
442
+ if (!st.isFile()) return false;
443
+ const text = fs.readFileSync(out, 'utf8');
444
+ const m = RENDER_STAMP.exec(text);
445
+ // The page above the comment is the one rendered: an edit by hand, or
446
+ // a comment pasted under another page, is rendered again.
447
+ // Nothing may follow the comment but the sheet's own build stamp
448
+ // (written after it by show): text added after it is rendered over.
449
+ const after = m
450
+ ? text
451
+ .slice(m.index + m[0].length)
452
+ .replace(/<!-- astryx: sheet of build [0-9a-f]{16} -->/, '')
453
+ : '';
454
+ return (
455
+ m != null &&
456
+ m[1] === key &&
457
+ after.trim() === '' &&
458
+ m[2] === bodyHash(text.slice(0, m.index).trimEnd())
459
+ );
460
+ } catch {
461
+ return false;
462
+ }
463
+ }
464
+
465
+ /**
466
+ * The page with its render key recorded at its end (after the closing tag:
467
+ * a comment before the doctype would put it in quirks mode).
468
+ * @param {string} html
469
+ * @param {string} key
470
+ */
471
+ const withRenderKey = (html, key) => {
472
+ const body = html.replace(RENDER_STAMP, '').trimEnd();
473
+ return `${body}\n<!-- astryx: render of ${key} ${bodyHash(body)} -->\n`;
474
+ };
475
+
476
+ /**
477
+ * The sample page source of a theme's preview.html, its file, and the key
478
+ * of the inputs it is rendered from.
247
479
  * @param {import('./_settings.mjs').Ctx} ctx
248
480
  * @param {string} slug
249
481
  * @param {import('./_settings.mjs').ThemeData} data
250
- * @returns {Promise<string>} the file written, as shown
251
482
  */
252
- export async function renderPreview(ctx, slug, data) {
483
+ function previewInputs(ctx, slug, data) {
253
484
  const {project} = ctx;
254
485
  const imports = /** @type {Record<string, string>} */ ({});
255
486
  for (const n of elementNames(SAMPLE_PAGE)) {
@@ -263,10 +494,41 @@ export async function renderPreview(ctx, slug, data) {
263
494
  layout: 'page',
264
495
  title: `${slug}: sample page`,
265
496
  });
266
- const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
267
497
  const out = themeFiles(project.cwd, slug).preview;
498
+ return {source, out, key: renderKey(project, slug, source, data.like)};
499
+ }
500
+
501
+ /**
502
+ * Whether themes/<slug>/preview.html was rendered from the theme as it is
503
+ * now (the same check renderPreview makes before it renders again).
504
+ * @param {import('./_settings.mjs').Ctx} ctx
505
+ * @param {string} slug
506
+ * @param {import('./_settings.mjs').ThemeData} data
507
+ */
508
+ export function previewIsCurrent(ctx, slug, data) {
509
+ try {
510
+ const {out, key} = previewInputs(ctx, slug, data);
511
+ return renderedFrom(out, key);
512
+ } catch {
513
+ return false;
514
+ }
515
+ }
516
+
517
+ /**
518
+ * Render the sample app page with the theme to themes/<slug>/preview.html.
519
+ * @param {import('./_settings.mjs').Ctx} ctx
520
+ * @param {string} slug
521
+ * @param {import('./_settings.mjs').ThemeData} data
522
+ * @returns {Promise<string>} the file written, as shown
523
+ */
524
+ export async function renderPreview(ctx, slug, data) {
525
+ const {project} = ctx;
526
+ const {source, out, key} = previewInputs(ctx, slug, data);
527
+ // Rendered from the same inputs before: the page is as it would be.
528
+ if (renderedFrom(out, key)) return shown(project.cwd, out);
529
+ const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
268
530
  // Written whole and renamed in, never through a link.
269
- writeWhole(out, html);
531
+ writeWhole(out, withRenderKey(html, key));
270
532
  return shown(project.cwd, out);
271
533
  }
272
534
 
@@ -288,12 +550,6 @@ export async function renderSheet(ctx, slug, data, options = {}) {
288
550
  layout: 'sheet',
289
551
  title: `${slug}: every component${options.group ? ` (${options.group})` : ''}`,
290
552
  });
291
- const {html} = await renderGenerated(
292
- project,
293
- `sheet-${slug}.mjs`,
294
- source,
295
- templateFiles(imports),
296
- );
297
553
  // One section goes to its own file, so the full sheet stays whole.
298
554
  const full = themeFiles(project.cwd, slug).sheet;
299
555
  const out =
@@ -301,9 +557,23 @@ export async function renderSheet(ctx, slug, data, options = {}) {
301
557
  (options.group
302
558
  ? path.join(path.dirname(full), `sheet-${options.group}.html`)
303
559
  : full);
560
+ const key = renderKey(project, slug, source, data.like);
561
+ const result = {
562
+ file: shown(project.cwd, out),
563
+ components: new Set(items.map(i => i.name)).size,
564
+ skipped,
565
+ };
566
+ // Rendered from the same inputs before: the sheet is as it would be.
567
+ if (renderedFrom(out, key)) return result;
568
+ const {html} = await renderGenerated(
569
+ project,
570
+ `sheet-${slug}.mjs`,
571
+ source,
572
+ templateFiles(imports),
573
+ );
304
574
  fs.mkdirSync(path.dirname(out), {recursive: true});
305
575
  // Written whole and renamed in, never through a link.
306
- writeWhole(out, html);
576
+ writeWhole(out, withRenderKey(html, key));
307
577
  return {
308
578
  file: shown(project.cwd, out),
309
579
  components: new Set(items.map(i => i.name)).size,
@@ -460,11 +730,11 @@ function componentTable(project, trees) {
460
730
  const SAFE = [
461
731
  '/** Shows a short note for a component that throws, so the rest of the page renders. */',
462
732
  'class Safe extends React.Component<{name: string, children: React.ReactNode}, {failed: boolean}> {',
463
- ' state = {failed: false};',
733
+ ' override state = {failed: false};',
464
734
  ' static getDerivedStateFromError() {',
465
735
  ' return {failed: true};',
466
736
  ' }',
467
- ' render() {',
737
+ ' override render() {',
468
738
  ' return this.state.failed ? <div className="tp-note">{this.props.name} could not render here</div> : this.props.children;',
469
739
  ' }',
470
740
  '}',
@@ -567,10 +837,12 @@ const usesSource = v =>
567
837
  Object.values(/** @type {object} */ (v)).some(usesSource);
568
838
 
569
839
  /** 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
- });
840
+ const GROUP_TITLES = wordTable(
841
+ /** @type {Record<string, string>} */ ({
842
+ data: 'data display',
843
+ overlays: 'overlays (shown open)',
844
+ }),
845
+ );
574
846
 
575
847
  /**
576
848
  * A cell with the component's name. A cell whose parts show nothing on
@@ -650,7 +922,19 @@ const PAGE_SKIP = new Set([
650
922
  * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} [options]
651
923
  * @returns {{source: string, components: number}}
652
924
  */
653
- export function componentsPageSource(project, {theme = null, C} = {}) {
925
+ export function componentsPageSource(project, options = {}) {
926
+ // A name that Core's docs lack resolves by walking Core's source tree. One
927
+ // listing cache reads each folder once for the page, not once per name.
928
+ return withListingCache(() => componentsPage(project, options));
929
+ }
930
+
931
+ /**
932
+ * {@link componentsPageSource}'s work, inside its listing cache.
933
+ * @param {import('./_project.mjs').ThemeProject} project
934
+ * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} options
935
+ * @returns {{source: string, components: number}}
936
+ */
937
+ function componentsPage(project, {theme = null, C}) {
654
938
  const items = showcaseItems(project, undefined)
655
939
  .items.filter(
656
940
  it =>
@@ -727,10 +1011,22 @@ export function componentsPageSource(project, {theme = null, C} = {}) {
727
1011
  * boundary, so one part that throws never blanks the page. The preview
728
1012
  * route is the app shell, so the page has no shell of its own.
729
1013
  * @param {import('./_project.mjs').ThemeProject} project
730
- * @param {{theme?: string | null}} [options]
1014
+ * @param {{theme?: string | null, colors?: boolean}} [options] `colors`:
1015
+ * the preview has a Colors page, so the header points to it
731
1016
  * @returns {string}
732
1017
  */
733
- export function overviewPageSource(project, {theme = null} = {}) {
1018
+ export function overviewPageSource(project, options = {}) {
1019
+ // One listing cache for the page's names, as componentsPageSource holds.
1020
+ return withListingCache(() => overviewPage(project, options));
1021
+ }
1022
+
1023
+ /**
1024
+ * {@link overviewPageSource}'s work, inside its listing cache.
1025
+ * @param {import('./_project.mjs').ThemeProject} project
1026
+ * @param {{theme?: string | null, colors?: boolean}} options
1027
+ * @returns {string}
1028
+ */
1029
+ function overviewPage(project, {theme = null, colors = false}) {
734
1030
  const sections = OVERVIEW_SECTIONS.map(x => ({
735
1031
  title: x.title,
736
1032
  tree: /** @type {import('./_catalog.mjs').Tree | undefined} */ (
@@ -786,8 +1082,38 @@ export function overviewPageSource(project, {theme = null} = {}) {
786
1082
  ' React.useEffect(() => {',
787
1083
  ' if (!ref.current) return;',
788
1084
  ' 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')}.`);",
1085
+ " const first = (token: string) => (style.getPropertyValue(token).split(',')[0] ?? '').replace(/[\"']/g, '').trim() || 'default';",
1086
+ ' // A family the browser does not have measures as its fallback does.',
1087
+ ' const GENERIC = /^(default|serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-[a-z-]+|math|emoji|fangsong)$/i;',
1088
+ ' const missing = (family: string) => {',
1089
+ ' if (GENERIC.test(family)) return false;',
1090
+ " const ctx = document.createElement('canvas').getContext('2d');",
1091
+ ' if (!ctx) return false;',
1092
+ " const sample = 'mmmmmmmmmwwwwwww1234567890';",
1093
+ " return ['monospace', 'serif'].every(fallback => {",
1094
+ ' ctx.font = `48px ${fallback}`;',
1095
+ ' const plain = ctx.measureText(sample).width;',
1096
+ ' ctx.font = `48px "${family}", ${fallback}`;',
1097
+ ' return ctx.measureText(sample).width === plain;',
1098
+ ' });',
1099
+ ' };',
1100
+ ' const shown = (token: string) => { const f = first(token); return missing(f) ? `${f} (not installed here)` : f; };',
1101
+ " const write = () => setFonts(`Body: ${shown('--font-family-body')}. Headings: ${shown('--font-family-heading')}.`);",
1102
+ ' write();',
1103
+ ' // Read again when the theme changes live (a stylesheet or theme',
1104
+ ' // update while the page is open) and when a font finishes loading.',
1105
+ ' document.fonts?.ready.then(write);',
1106
+ " document.fonts?.addEventListener?.('loadingdone', write);",
1107
+ ' let queued = 0;',
1108
+ ' const soon = () => { if (!queued) queued = requestAnimationFrame(() => { queued = 0; write(); }); };',
1109
+ ' const watch = new MutationObserver(soon);',
1110
+ ' watch.observe(document.head, {childList: true, subtree: true, characterData: true});',
1111
+ " watch.observe(document.documentElement, {attributes: true, subtree: true, attributeFilter: ['style', 'class', 'data-theme']});",
1112
+ ' return () => {',
1113
+ ' watch.disconnect();',
1114
+ ' cancelAnimationFrame(queued);',
1115
+ " document.fonts?.removeEventListener?.('loadingdone', write);",
1116
+ ' };',
791
1117
  ' }, []);',
792
1118
  ' return (',
793
1119
  " <div ref={ref} style={{color: 'var(--color-text-secondary)', fontSize: 13}}>",
@@ -812,7 +1138,12 @@ export function overviewPageSource(project, {theme = null} = {}) {
812
1138
  ' {s.name}',
813
1139
  ' </div>',
814
1140
  ' ))}',
815
- ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1141
+ // The Colors page is there only for a theme with generated colors.
1142
+ ...(colors
1143
+ ? [
1144
+ ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1145
+ ]
1146
+ : []),
816
1147
  ' </div>',
817
1148
  ' </header>',
818
1149
  body,
@@ -839,7 +1170,6 @@ export function colorsPageSource({slug, module, seeds, uses}) {
839
1170
  '// `astryx experimental theme editor set` rewrites it with every change.',
840
1171
  "'use client';",
841
1172
  '',
842
- "import * as React from 'react';",
843
1173
  ];
844
1174
  const text = {color: 'var(--color-text-primary)'};
845
1175
  const page = {
@@ -891,7 +1221,7 @@ export function colorsPageSource({slug, module, seeds, uses}) {
891
1221
  " <h2 style={{margin: 0, fontSize: 20, textTransform: 'capitalize'}}>",
892
1222
  ' {name}',
893
1223
  ' {SEEDS[name] ? (',
894
- " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, color: 'var(--color-text-secondary)'}}>",
1224
+ " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, textTransform: 'none', color: 'var(--color-text-secondary)'}}>",
895
1225
  ' from {SEEDS[name]}',
896
1226
  ' </span>',
897
1227
  ' ) : null}',
@@ -980,11 +1310,13 @@ export function previewRouteSource({
980
1310
  ' sideNav={',
981
1311
  ' <SideNav>',
982
1312
  ' {PAGES.map(p => (',
983
- ' <SideNavItem key={p.id} label={p.label} isSelected={p.id === current.id} onClick={() => setPage(p.id)} />',
1313
+ // Only a plain left click switches the page in place; a modified or
1314
+ // middle click opens the page's URL as a link does (a new tab).
1315
+ ' <SideNavItem key={p.id} label={p.label} isSelected={p.id === current.id} href={`?page=${p.id}`} onClick={e => { if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; e.preventDefault(); go(p.id); }} />',
984
1316
  ' ))}',
985
1317
  ' </SideNav>',
986
1318
  ' }>',
987
- ' <current.Page />',
1319
+ ' {ready ? <current.Page /> : null}',
988
1320
  ' </AppShell>',
989
1321
  ' </div>',
990
1322
  ];
@@ -999,7 +1331,13 @@ export function previewRouteSource({
999
1331
  "import {TopNav} from '@astryxdesign/core/TopNav';",
1000
1332
  ...(theme
1001
1333
  ? [
1002
- "import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';",
1334
+ // The mode switch only for a theme with both modes: an import the
1335
+ // route does not draw fails an app with noUnusedLocals.
1336
+ ...(mode.length
1337
+ ? [
1338
+ "import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';",
1339
+ ]
1340
+ : []),
1003
1341
  "import {Theme} from '@astryxdesign/core/theme';",
1004
1342
  `import {${camelName(theme.name)}Theme as theme} from ${JSON.stringify(theme.module.replace(/\.js$/, ''))};`,
1005
1343
  ...theme.css.map(c => `import ${JSON.stringify(c)};`),
@@ -1028,6 +1366,26 @@ export function previewRouteSource({
1028
1366
  '',
1029
1367
  'export default function ThemePreviewPage() {',
1030
1368
  ' const [page, setPage] = React.useState(PAGES[0]?.id);',
1369
+ // Each page has its own URL (?page=<id>), so a link, a reload, the back
1370
+ // button or a screenshot reaches any page; the page renders after mount.
1371
+ " const fromUrl = () => new URLSearchParams(window.location.search).get('page');",
1372
+ ' React.useEffect(() => {',
1373
+ // A URL with no (or an unknown) ?page shows the first page, as a reload does.
1374
+ ' const sync = () => { const id = fromUrl(); setPage(id && PAGES.some(p => p.id === id) ? id : PAGES[0]?.id); };',
1375
+ ' sync();',
1376
+ " window.addEventListener('popstate', sync);",
1377
+ " return () => window.removeEventListener('popstate', sync);",
1378
+ ' }, []);',
1379
+ ' const go = (id: string) => {',
1380
+ ' setPage(id);',
1381
+ ' const url = new URL(window.location.href);',
1382
+ " url.searchParams.set('page', id);",
1383
+ " window.history.pushState(null, '', url);",
1384
+ ' };',
1385
+ // Pages render only in the browser: some components crash a server
1386
+ // render, and Next prerenders a client page's first state.
1387
+ ' const [ready, setReady] = React.useState(false);',
1388
+ ' React.useEffect(() => setReady(true), []);',
1031
1389
  ...(theme
1032
1390
  ? [
1033
1391
  oneMode
@@ -1035,7 +1393,8 @@ export function previewRouteSource({
1035
1393
  : " const [mode, setMode] = React.useState<Mode>('system');",
1036
1394
  ]
1037
1395
  : []),
1038
- ' const current = PAGES.find(p => p.id === page) ?? PAGES[0];',
1396
+ // The route always has a page; the cast keeps noUncheckedIndexedAccess apps building.
1397
+ ' const current = (PAGES.find(p => p.id === page) ?? PAGES[0]) as (typeof PAGES)[number];',
1039
1398
  ' return (',
1040
1399
  ...(theme
1041
1400
  ? [' <Theme theme={theme} mode={mode}>', ...shell, ' </Theme>']
@@ -1165,3 +1524,174 @@ function chromeBinary() {
1165
1524
  }
1166
1525
  return null;
1167
1526
  }
1527
+
1528
+ /** The first line of every file the editor writes into a theme's app copy. */
1529
+ export {APP_COPY_MARK} from './_marks.mjs';
1530
+ import {APP_COPY_MARK} from './_marks.mjs';
1531
+
1532
+ /**
1533
+ * The app's copy of an editor theme: a standard local theme in
1534
+ * src/themes/<theme>/ (a descriptor, a source that re-exports the built
1535
+ * module, the built module, its stylesheet and font stylesheet), the shape
1536
+ * `astryx theme add <theme>` reads, so the theme goes into the app with the
1537
+ * stable theme commands. It is written again after every build of the
1538
+ * theme, never edited by hand. A folder there that is not the editor's own
1539
+ * copy is left alone: returns null then, else the folder.
1540
+ * The built module and stylesheet are written whole: a local theme's source
1541
+ * may import only files inside its own folder.
1542
+ * @param {import('./_settings.mjs').Ctx} ctx
1543
+ * @param {string} slug
1544
+ * @param {import('./_settings.mjs').ThemeData} data
1545
+ * @returns {string | null}
1546
+ */
1547
+ export function writeAppCopy(ctx, slug, data) {
1548
+ return writeAppCopyAt(
1549
+ ctx.project.cwd,
1550
+ slug,
1551
+ themeImports(
1552
+ ctx,
1553
+ slug,
1554
+ data,
1555
+ path.join(ctx.project.cwd, 'src', 'themes', slug),
1556
+ ).css.slice(1),
1557
+ );
1558
+ }
1559
+
1560
+ /**
1561
+ * {@link writeAppCopy} with the font stylesheets given, or null to keep the
1562
+ * copy's own (a compile, which changes no setting).
1563
+ * @param {string} cwd
1564
+ * @param {string} slug
1565
+ * @param {string[] | null} fontsCss
1566
+ * @returns {string | null}
1567
+ */
1568
+ export function writeAppCopyAt(cwd, slug, fontsCss) {
1569
+ const f = themeFiles(cwd, slug);
1570
+ const dir = path.join(cwd, 'src', 'themes', slug);
1571
+ const name = `${camel(slug)}Theme`;
1572
+ const first = !fs.existsSync(path.join(dir, `${name}.doc.mjs`));
1573
+ if (!fs.existsSync(f.js) || !fs.existsSync(f.css)) return null;
1574
+ // The copy's source, as the stable build's header names it.
1575
+ const source = `src/themes/${slug}/${name}.ts`;
1576
+ // Only the editor's own copy is written over.
1577
+ if (appCopyBlocker(cwd, slug) !== null) return null;
1578
+ const head = (/** @type {string} */ open, /** @type {string} */ close) =>
1579
+ `${open} ${APP_COPY_MARK} after every build of themes/${slug}/; do not edit it here. Change the theme with the editor. ${close}\n`;
1580
+ const keptFonts = path.join(dir, `${slug}.fonts.css`);
1581
+ const fonts =
1582
+ fontsCss ??
1583
+ (fs.existsSync(keptFonts)
1584
+ ? [
1585
+ ...fs.readFileSync(keptFonts, 'utf8').matchAll(/@import "([^"]+)";/g),
1586
+ ].map(m => m[1])
1587
+ : []);
1588
+ // A built file as `theme build` of the copy's source writes it: the
1589
+ // editor's build of the same theme, with the header naming that source.
1590
+ const asBuilt = (/** @type {string} */ text) =>
1591
+ text
1592
+ .replace(/^( \* Source: ).*$/m, `$1${source}`)
1593
+ .replace(/^( \* Command: ).*$/m, `$1astryx theme build ${source}`);
1594
+ /** @type {Record<string, string>} */
1595
+ const built = {};
1596
+ for (const ext of APP_COPY_BUILT) {
1597
+ const from = path.join(f.dir, `${slug}${ext}`);
1598
+ if (fs.existsSync(from))
1599
+ built[`${slug}${ext}`] = asBuilt(fs.readFileSync(from, 'utf8'));
1600
+ }
1601
+ const files = {
1602
+ [`${name}.doc.mjs`]: `${head('//', '')}\n/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {\n type: 'theme',\n name: ${JSON.stringify(slug)},\n displayName: ${JSON.stringify(slug)},\n description: ${JSON.stringify(`The ${slug} theme, made with the theme editor (themes/${slug}/).`)},\n maintained: false,\n};\n`,
1603
+ [`${name}.ts`]: `${head('//', '')}export {${name}} from './${slug}';\n`,
1604
+ ...built,
1605
+ ...(fonts.length
1606
+ ? {
1607
+ [`${slug}.fonts.css`]: `${head('/*', '*/')}${fonts.map(c => `@import ${JSON.stringify(c)};`).join('\n')}\n`,
1608
+ }
1609
+ : {}),
1610
+ };
1611
+ fs.mkdirSync(dir, {recursive: true});
1612
+ for (const [n, text] of Object.entries(files)) {
1613
+ const file = path.join(dir, n);
1614
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === text) continue;
1615
+ writeWhole(file, text);
1616
+ }
1617
+ // A file an earlier copy had (a font stylesheet no longer needed) goes;
1618
+ // system files stay.
1619
+ for (const n of fs.readdirSync(dir))
1620
+ if (!(n in files) && !FOLDER_JUNK.has(n))
1621
+ fs.rmSync(path.join(dir, n), {force: true});
1622
+ // The first write is named in the command's result; later ones are not.
1623
+ if (first)
1624
+ FIRST_COPIES.set(
1625
+ `${path.resolve(cwd)}\0${slug}`,
1626
+ Object.keys(files)
1627
+ .sort()
1628
+ .map(n =>
1629
+ path.relative(cwd, path.join(dir, n)).split(path.sep).join('/'),
1630
+ ),
1631
+ );
1632
+ return dir;
1633
+ }
1634
+
1635
+ /**
1636
+ * Why the editor will not write a theme's app copy, or null when it will:
1637
+ * the folder is not there yet, or its descriptor carries the editor's mark
1638
+ * and it holds only the copy's own files (system files such as .DS_Store
1639
+ * aside). Otherwise the name of what is in the way (a file of yours), or
1640
+ * the folder itself when it is not the editor's copy. Built bytes are not
1641
+ * compared, so a stable rebuild of the copy leaves it the editor's. The one
1642
+ * test the copy's writer and `wiring` both use.
1643
+ * @param {string} cwd
1644
+ * @param {string} slug
1645
+ * @returns {string | null}
1646
+ */
1647
+ export function appCopyBlocker(cwd, slug) {
1648
+ const dir = path.join(cwd, 'src', 'themes', slug);
1649
+ const name = `${camel(slug)}Theme`;
1650
+ const rel = path.relative(cwd, dir).split(path.sep).join('/');
1651
+ if (folderIsEmpty(dir)) return null;
1652
+ /** @type {string[]} */
1653
+ let names;
1654
+ try {
1655
+ names = fs.readdirSync(dir);
1656
+ } catch {
1657
+ return rel;
1658
+ }
1659
+ /** @type {boolean} */
1660
+ let marked;
1661
+ try {
1662
+ marked = fs
1663
+ .readFileSync(path.join(dir, `${name}.doc.mjs`), 'utf8')
1664
+ .includes(APP_COPY_MARK);
1665
+ } catch {
1666
+ marked = false;
1667
+ }
1668
+ if (!marked) return rel;
1669
+ const own = new Set([
1670
+ `${name}.doc.mjs`,
1671
+ `${name}.ts`,
1672
+ `${slug}.fonts.css`,
1673
+ ...APP_COPY_BUILT.map(ext => `${slug}${ext}`),
1674
+ ]);
1675
+ const other = names.find(n => !own.has(n) && !FOLDER_JUNK.has(n));
1676
+ return other ? `${rel}/${other}` : null;
1677
+ }
1678
+
1679
+ /** The build outputs of a theme, by their ending after `<theme>`. */
1680
+ const APP_COPY_BUILT = ['.css', '.css.d.ts', '.js', '.d.ts', '.variants.d.ts'];
1681
+
1682
+ /** App copies written for the first time in this process, by app and theme. @type {Map<string, string[]>} */
1683
+ const FIRST_COPIES = new Map();
1684
+
1685
+ /**
1686
+ * The files of a theme's app copy when this command wrote it for the first
1687
+ * time (then forgotten, so one result names them), else null.
1688
+ * @param {string} cwd
1689
+ * @param {string} slug
1690
+ * @returns {string[] | null}
1691
+ */
1692
+ export function takeFirstAppCopy(cwd, slug) {
1693
+ const key = `${path.resolve(cwd)}\0${slug}`;
1694
+ const wrote = FIRST_COPIES.get(key) ?? null;
1695
+ FIRST_COPIES.delete(key);
1696
+ return wrote;
1697
+ }