@astryxdesign/cli 0.7.15 → 0.7.16-canary.g3aa244b

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 (163) 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 +35 -0
  8. package/api/doctor/_adapter.mjs +69 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.d.mts +18 -0
  11. package/api/doctor/doctor.doc.mjs +1 -1
  12. package/api/doctor/doctor.mjs +104 -4
  13. package/api/doctor/theme-checks.mjs +6 -10
  14. package/api/integration/add-contribution.mjs +3 -3
  15. package/api/integration/pack-check.mjs +14 -8
  16. package/api/integration/validate-integration.mjs +1 -1
  17. package/api/search/_adapter.mjs +15 -16
  18. package/api/search/_entries.d.mts +2 -1
  19. package/api/search/_entries.mjs +28 -1
  20. package/api/swizzle/_moduleGraph.mjs +1 -1
  21. package/api/theme/_adapter.d.mts +5 -2
  22. package/api/theme/_adapter.mjs +43 -12
  23. package/api/theme/_fork.mjs +1 -1
  24. package/api/theme/build/build.d.mts +116 -32
  25. package/api/theme/build/build.mjs +449 -102
  26. package/api/theme/eject/eject.mjs +22 -1
  27. package/api/theme/template/template.d.mts +19 -0
  28. package/api/theme/template/template.mjs +102 -25
  29. package/api/theme/theme.type.d.mts +5 -1
  30. package/api/theme/theme.type.mjs +2 -1
  31. package/api/theme/themeBuild.doc.mjs +3 -3
  32. package/api/theme/themeEject.doc.mjs +1 -1
  33. package/api/theme/themeTemplate.doc.mjs +9 -3
  34. package/api/theme-edit/_adapter.d.mts +32 -2
  35. package/api/theme-edit/_adapter.mjs +264 -40
  36. package/api/theme-edit/_check.d.mts +93 -4
  37. package/api/theme-edit/_check.mjs +1727 -223
  38. package/api/theme-edit/_color.d.mts +2 -8
  39. package/api/theme-edit/_color.mjs +292 -219
  40. package/api/theme-edit/_compiler.d.mts +1 -0
  41. package/api/theme-edit/_compiler.mjs +20 -1
  42. package/api/theme-edit/_context.d.mts +31 -1
  43. package/api/theme-edit/_context.mjs +445 -41
  44. package/api/theme-edit/_css.d.mts +60 -1
  45. package/api/theme-edit/_css.mjs +404 -28
  46. package/api/theme-edit/_edit.d.mts +25 -0
  47. package/api/theme-edit/_edit.mjs +1532 -149
  48. package/api/theme-edit/_how-commands.d.mts +11 -26
  49. package/api/theme-edit/_how-commands.mjs +30 -2
  50. package/api/theme-edit/_how-question.d.mts +7 -0
  51. package/api/theme-edit/_how-question.mjs +1304 -176
  52. package/api/theme-edit/_how.mjs +144 -30
  53. package/api/theme-edit/_overview.mjs +2 -0
  54. package/api/theme-edit/_palette.d.mts +38 -0
  55. package/api/theme-edit/_palette.mjs +305 -71
  56. package/api/theme-edit/_parts.d.mts +33 -0
  57. package/api/theme-edit/_parts.mjs +138 -9
  58. package/api/theme-edit/_png.d.mts +18 -0
  59. package/api/theme-edit/_png.mjs +95 -14
  60. package/api/theme-edit/_preview-app.d.mts +36 -1
  61. package/api/theme-edit/_preview-app.mjs +1415 -96
  62. package/api/theme-edit/_preview.d.mts +64 -3
  63. package/api/theme-edit/_preview.mjs +514 -31
  64. package/api/theme-edit/_project.d.mts +11 -0
  65. package/api/theme-edit/_project.mjs +46 -12
  66. package/api/theme-edit/_settings.d.mts +278 -5
  67. package/api/theme-edit/_settings.mjs +2741 -195
  68. package/api/theme-edit/_tables.d.mts +24 -0
  69. package/api/theme-edit/_tables.mjs +211 -149
  70. package/api/theme-edit/_vet.d.mts +42 -0
  71. package/api/theme-edit/_vet.mjs +144 -0
  72. package/api/theme-edit/theme-edit.type.d.mts +20 -2
  73. package/api/theme-edit/theme-edit.type.mjs +6 -2
  74. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  75. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  76. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  77. package/api/upgrade/registry/registry.mjs +6 -1
  78. package/assets/codemods/parse.mjs +2 -2
  79. package/assets/docs/tree/single-component.doc.mjs +11 -2
  80. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  81. package/assets/docs.generated.json +2 -2
  82. package/assets/preview-app/next.config.mjs +7 -1
  83. package/assets/preview-app/package.json +1 -0
  84. package/assets/preview-app/src/app/globals.css +1 -0
  85. package/assets/self-audit.generated.json +1 -1
  86. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  87. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  88. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  89. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  90. package/assets/templates/components.generated.json +1 -1
  91. package/assets/templates/pages/dashboard/page.tsx +1 -1
  92. package/authoring/doctypes/_schema.d.mts +52 -5
  93. package/authoring/doctypes/_schema.mjs +62 -7
  94. package/authoring/doctypes/base/type.ts +10 -0
  95. package/authoring/doctypes/component/component.doc.mjs +1 -1
  96. package/authoring/doctypes/function/function.doc.mjs +6 -0
  97. package/authoring/doctypes/function/type.ts +3 -0
  98. package/authoring/doctypes/legacy.mjs +5 -1
  99. package/authoring/index.d.ts +1 -0
  100. package/authoring/shadcn/source-variants.d.mts +1 -1
  101. package/authoring/shadcn/source-variants.mjs +32 -10
  102. package/clients/cli/build-id.generated.json +1 -1
  103. package/clients/cli/commands/doctor.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental/theme.mjs +239 -45
  105. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  106. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  108. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  109. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  110. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  111. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  112. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  113. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  114. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  115. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  116. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  117. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  118. package/clients/cli/commands/theme.mjs +190 -46
  119. package/clients/cli/formatters/index.mjs +7 -4
  120. package/clients/cli/lib/cli-error.mjs +9 -3
  121. package/clients/cli/lib/component-format.mjs +27 -9
  122. package/clients/cli/lib/json-shim.mjs +72 -2
  123. package/clients/cli/manifest.generated.json +1 -1
  124. package/clients/cli/run.mjs +49 -0
  125. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  126. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  127. package/foundation/agent-docs/agent-docs.mjs +3 -2
  128. package/foundation/config/config-writer.mjs +2 -2
  129. package/foundation/config/project.mjs +60 -14
  130. package/foundation/discovery/component-discovery.mjs +5 -17
  131. package/foundation/discovery/icon-set-writer.mjs +1 -1
  132. package/foundation/discovery/module-exports.mjs +1 -15
  133. package/foundation/discovery/template-adapter.mjs +44 -19
  134. package/foundation/discovery/template-source-tree.mjs +3 -16
  135. package/foundation/discovery/theme-discovery.d.mts +5 -1
  136. package/foundation/discovery/theme-discovery.mjs +61 -43
  137. package/foundation/fs/exact-codec.d.mts +35 -0
  138. package/foundation/fs/exact-codec.mjs +148 -0
  139. package/foundation/fs/gather-cache.d.mts +15 -5
  140. package/foundation/fs/gather-cache.mjs +129 -31
  141. package/foundation/fs/paths.d.mts +39 -0
  142. package/foundation/fs/paths.mjs +44 -11
  143. package/foundation/fs/read-record.mjs +11 -1
  144. package/foundation/integrations/contribution-fixes.mjs +1 -16
  145. package/foundation/integrations/may-have-integrations.mjs +3 -2
  146. package/foundation/integrations/public-imports.mjs +1 -1
  147. package/foundation/render/embedded-imports.mjs +1 -1
  148. package/foundation/render/host-exit.d.mts +8 -0
  149. package/foundation/render/host-exit.mjs +11 -0
  150. package/foundation/render/page-host.mjs +56 -10
  151. package/foundation/render/page-worker.mjs +14 -0
  152. package/foundation/render/render-page.mjs +37 -2
  153. package/foundation/response/error-codes.d.mts +2 -1
  154. package/foundation/response/error-codes.d.ts +1 -0
  155. package/foundation/response/error-codes.doc.mjs +5 -0
  156. package/foundation/response/error-codes.mjs +3 -0
  157. package/foundation/response/json.d.mts +15 -0
  158. package/foundation/response/json.mjs +52 -1
  159. package/foundation/response/response-types.doc.mjs +1 -1
  160. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  161. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  162. package/foundation/xle/browser.d.mts +2 -2
  163. package/package.json +7 -6
@@ -10,11 +10,14 @@
10
10
  * @position api/theme-edit — storage and compile for the theme commands
11
11
  */
12
12
 
13
+ import {parse as parseModule} from '@babel/parser';
13
14
  import {createHash} from 'node:crypto';
14
15
  import * as fs from 'node:fs';
16
+ import {coversProperty, cssNumber, longhandsOf} from './_css.mjs';
15
17
  import postcss from 'postcss';
16
18
  import {createRequire} from 'node:module';
17
19
  import * as path from 'node:path';
20
+ import {themeFileImports} from '../../foundation/discovery/theme-discovery.mjs';
18
21
  import {pathToFileURL} from 'node:url';
19
22
  import {cliVersion} from '../../foundation/release/run-context.mjs';
20
23
  import {AstryxError} from '../error.mjs';
@@ -39,9 +42,12 @@ import {
39
42
  TEXT_SIZE,
40
43
  TYPE_STYLES,
41
44
  familyOf,
45
+ WRAPPED_PARTS,
46
+ CARD_LIKE,
42
47
  } from './_tables.mjs';
43
48
  import {
44
49
  alphaOf,
50
+ colorProblem,
45
51
  compositeOver,
46
52
  isColorValue,
47
53
  isSafeValue,
@@ -63,11 +69,23 @@ import {
63
69
  lockHeld,
64
70
  removeEmptyFolder,
65
71
  writeWhole,
72
+ setOwnTokenReader,
73
+ readWrittenRecord,
74
+ writeWrittenRecord,
66
75
  } from './_palette.mjs';
76
+ import {EDITOR_STAMP, pngTexts} from './_png.mjs';
67
77
  import {MODAL, isColorToken} from './_compiler.mjs';
68
- import {baseResolved, baseThemeFile} from './_project.mjs';
78
+ import {
79
+ baseInstalled,
80
+ baseModule,
81
+ baseResolved,
82
+ baseThemeFile,
83
+ } from './_project.mjs';
69
84
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
70
85
 
86
+ // The palette reads the tokens the own source sets through this module.
87
+ setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
88
+
71
89
  /**
72
90
  * One setting the CLI owns.
73
91
  * @typedef {object} Setting
@@ -97,7 +115,7 @@ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
97
115
  /** What lifted secondary text sits on: the contrast check measures it there. */
98
116
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
99
117
 
100
- /** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler, unchecked?: string | null, uncheckedCode?: string | null, wrote?: Map<string, string | null>, base?: {light: Record<string, string>, dark: Record<string, string>, components?: Record<string, any>}, keepStops?: Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>> | null, keepRadii?: Record<string, string> | null}} Ctx */
118
+ /** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler, unchecked?: string | null, uncheckedCode?: string | null, wrote?: Map<string, string | null>, base?: {light: Record<string, string>, dark: Record<string, string>, components?: Record<string, any>}, keepStops?: Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>> | null, keepRadii?: Record<string, string> | null, derived?: Record<string, Array<{property: string, vars?: string[], replaces?: boolean, expand?: string}>>}} Ctx */
101
119
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
102
120
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
103
121
 
@@ -113,12 +131,17 @@ export const slugOk = s =>
113
131
  !windowsReserved(s);
114
132
 
115
133
  /**
116
- * A name Windows reserves for a device (con, nul, com1…): a folder named
117
- * so cannot be checked out there.
134
+ * A name Windows does not allow for a file or folder, so it cannot be
135
+ * checked out there: a device name (con, nul, com1, com¹…), a character
136
+ * Windows reserves (`<>:"|?*` and control characters), or a dot or space
137
+ * at the end.
118
138
  * @param {string} s
119
139
  */
120
140
  export const windowsReserved = s =>
121
- /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(s);
141
+ /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i.test(s) ||
142
+ // eslint-disable-next-line no-control-regex
143
+ /[<>:"|?*\u0000-\u001f]/.test(s) ||
144
+ /[. ]$/.test(s);
122
145
  /**
123
146
  * The theme name closest to what was typed: spaces and accents dropped,
124
147
  * lower case, anything else a dash.
@@ -167,10 +190,258 @@ export function themeFiles(cwd, slug) {
167
190
  preview: path.join(dir, 'preview.html'),
168
191
  sheet: path.join(dir, 'sheet.html'),
169
192
  previewPng: path.join(dir, 'preview.png'),
193
+ pictures: path.join(dir, `${slug}.pictures.json`),
170
194
  sheetPng: path.join(dir, 'sheet.png'),
171
195
  };
172
196
  }
173
197
 
198
+ /** Files a system or a tool puts in any folder; a folder of only these is empty. */
199
+ export const FOLDER_JUNK = new Set(['.DS_Store', '.gitkeep', 'Thumbs.db']);
200
+
201
+ /**
202
+ * Whether `dir` holds nothing of anyone's: absent, empty, or only system
203
+ * files (what `git rm -r` or a branch switch leaves). A path that is not a
204
+ * folder, or one that does not read, is not empty.
205
+ * @param {string} dir
206
+ */
207
+ export function folderIsEmpty(dir) {
208
+ if (!fs.existsSync(dir)) return true;
209
+ try {
210
+ return (
211
+ fs.lstatSync(dir).isDirectory() &&
212
+ fs.readdirSync(dir).every(n => FOLDER_JUNK.has(n))
213
+ );
214
+ } catch {
215
+ return false;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Whether a value fits what a dial takes, read from the dial's own list of
221
+ * values: a named rung in any case, or a value of the kind it names (a size,
222
+ * a color, a number). `set` still checks the value in full.
223
+ * @param {string} dial
224
+ * @param {string} value
225
+ */
226
+ export function dialValueFits(dial, value) {
227
+ const spec = DIALS[/** @type {keyof typeof DIALS} */ (dial)]?.values;
228
+ if (!spec) return false;
229
+ const v = String(value).trim();
230
+ if (v === '') return false;
231
+ return spec.split('|').some(option => {
232
+ if (!option.startsWith('<') && !option.startsWith('"'))
233
+ return option === v.toLowerCase();
234
+ if (option.startsWith('"')) return true;
235
+ if (option.includes('size')) return /^\d*\.?\d+(px|rem|em)$/.test(v);
236
+ // A color by the editor's own color check (a bare word only when it
237
+ // names a color).
238
+ if (option === '<color>') return colorProblem(v) == null;
239
+ if (option === '<0-100>') return /^\d{1,3}$/.test(v) && Number(v) <= 100;
240
+ if (option === '<number>') return /^\d*\.?\d+$/.test(v);
241
+ return false;
242
+ });
243
+ }
244
+
245
+ /** @param {string} file @returns {string | null} */
246
+ const contentHash = file => {
247
+ try {
248
+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
249
+ } catch {
250
+ return null;
251
+ }
252
+ };
253
+
254
+ /**
255
+ * Record files the editor just wrote into a theme folder.
256
+ * @param {string} cwd
257
+ * @param {string} slug
258
+ * @param {string[]} files
259
+ */
260
+ export function recordWritten(cwd, slug, files) {
261
+ const map = readWrittenRecord(cwd, slug);
262
+ for (const file of files) {
263
+ const hash = contentHash(file);
264
+ if (hash) map[path.basename(file)] = hash;
265
+ }
266
+ writeWrittenRecord(cwd, slug, map);
267
+ }
268
+
269
+ /**
270
+ * Whether the editor wrote this file in the theme folder and it is
271
+ * unchanged since.
272
+ * @param {string} cwd
273
+ * @param {string} slug
274
+ * @param {string} file
275
+ */
276
+ export function editorWrote(cwd, slug, file) {
277
+ const map = readWrittenRecord(cwd, slug);
278
+ const was = map[path.basename(file)];
279
+ // A recorded picture is the editor's only while it is as it wrote it: a
280
+ // picture changed after (re-saved by another tool, stamp and all) is the
281
+ // person's.
282
+ if (was) return was === contentHash(file);
283
+ // With no record of it, the picture's stamp names the theme it shows.
284
+ try {
285
+ return pngTexts(fs.readFileSync(file))[EDITOR_STAMP] === slug;
286
+ } catch {
287
+ return false;
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Adopt a picture an older editor took (before it recorded or stamped its
293
+ * pictures) into the record: only while the theme has no record at all, the
294
+ * name is one the editor writes, and the picture is the editor's 1280-pixel
295
+ * wide window. Returns whether it was adopted.
296
+ * @param {string} cwd
297
+ * @param {string} slug
298
+ * @param {string} file
299
+ */
300
+ export function adoptOlderPicture(cwd, slug, file) {
301
+ if (fs.existsSync(themeFiles(cwd, slug).pictures)) return false;
302
+ if (!/^(sheet|preview)(-[a-z-]+)?\.png$/.test(path.basename(file)))
303
+ return false;
304
+ /** @type {Buffer} */
305
+ let bytes;
306
+ try {
307
+ bytes = fs.readFileSync(file);
308
+ } catch {
309
+ return false;
310
+ }
311
+ // The width in the PNG header: the editor takes a 1280-pixel window.
312
+ if (
313
+ bytes.length < 24 ||
314
+ bytes.toString('latin1', 12, 16) !== 'IHDR' ||
315
+ bytes.readUInt32BE(16) !== 1280
316
+ )
317
+ return false;
318
+ recordWritten(cwd, slug, [file]);
319
+ return true;
320
+ }
321
+
322
+ /**
323
+ * Drop names from the record of what the editor wrote.
324
+ * @param {string} cwd
325
+ * @param {string} slug
326
+ * @param {string[]} names
327
+ */
328
+ function forgetWritten(cwd, slug, names) {
329
+ if (!names.length) return;
330
+ const map = readWrittenRecord(cwd, slug);
331
+ for (const n of names) delete map[n];
332
+ writeWrittenRecord(cwd, slug, map);
333
+ }
334
+
335
+ /**
336
+ * A name `new` takes, for a suggestion: `name` itself when it is valid, not a
337
+ * built-in theme and its folder is free; `my-<name>` for a built-in theme's
338
+ * name; else the first free numbered name.
339
+ * @param {string} cwd
340
+ * @param {string} name
341
+ */
342
+ export function usableNewName(cwd, name) {
343
+ const base = LIKE.includes(name) ? `my-${name}` : name;
344
+ return slugOk(base) && !fs.existsSync(themeFiles(cwd, base).dir)
345
+ ? base
346
+ : freeThemeName(cwd, base);
347
+ }
348
+
349
+ /**
350
+ * A theme name near `name` that is valid and whose folder is free: `name-2`,
351
+ * `name-3`, …, shortened to fit the name's length limit.
352
+ * @param {string} cwd
353
+ * @param {string} name
354
+ */
355
+ export function freeThemeName(cwd, name) {
356
+ for (let n = 2; n < 1000; n += 1) {
357
+ const suffix = `-${n}`;
358
+ const candidate = `${name.slice(0, 64 - suffix.length).replace(/-+$/, '')}${suffix}`;
359
+ if (slugOk(candidate) && !fs.existsSync(themeFiles(cwd, candidate).dir))
360
+ return candidate;
361
+ }
362
+ return '<another name>';
363
+ }
364
+
365
+ /**
366
+ * Why the editor cannot read one of its files, or null when it can (or the
367
+ * file is not there): a folder in the file's place, or no permission to read
368
+ * it. Bad content is a different problem, judged where the file is parsed.
369
+ * @param {string} file
370
+ * @returns {string | null}
371
+ */
372
+ export function unreadableReason(file) {
373
+ let st;
374
+ try {
375
+ st = fs.statSync(file);
376
+ } catch (e) {
377
+ const code = /** @type {any} */ (e)?.code;
378
+ return code === 'ENOENT' || code === 'ENOTDIR'
379
+ ? null
380
+ : `it cannot be read (${code ?? 'unknown error'})`;
381
+ }
382
+ if (st.isDirectory()) return 'it is a folder, not a file';
383
+ try {
384
+ fs.accessSync(file, fs.constants.R_OK);
385
+ } catch (e) {
386
+ return `it cannot be read (${/** @type {any} */ (e)?.code ?? 'no permission'}: permission denied)`;
387
+ }
388
+ return null;
389
+ }
390
+
391
+ /**
392
+ * Refuse, by name, when a file of the theme is a folder or cannot be read:
393
+ * every command reads them, and none should crash on one. The fix is to
394
+ * look at the file and give it back its place; a file is never deleted.
395
+ * @param {string} cwd
396
+ * @param {string} slug
397
+ */
398
+ export function refuseUnreadableFiles(cwd, slug) {
399
+ const f = themeFiles(cwd, slug);
400
+ // The files the editor reads (the settings, the source, the history) are
401
+ // named here; the files the build writes (with their types) by the
402
+ // build's own check, the same one show uses.
403
+ refuseUnreadable(cwd, [
404
+ ...builtFiles(cwd, slug, {name: slug, mode: 'both', settings: []}),
405
+ path.join(f.dir, `${slug}.variants.d.ts`),
406
+ ]);
407
+ for (const file of [f.settings, f.ts, f.history]) {
408
+ const why = unreadableReason(file);
409
+ if (why)
410
+ throw new AstryxError(
411
+ `${path.relative(cwd, file)} ${why}, so the theme cannot be read. Put the file back in its place (or give it read permission); nothing was changed.`,
412
+ [
413
+ {
414
+ name: `ls -la ${quoteCommandArgument(path.relative(cwd, file))}`,
415
+ reason: 'see what is there',
416
+ },
417
+ ],
418
+ ERROR_CODES.ERR_THEME_INVALID,
419
+ );
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Refuse when the app's themes/ is a file or a link to something other
425
+ * than a folder: every editor theme lives in themes/<name>/. The run lists
426
+ * what is there; the message says to rename or move it.
427
+ * @param {string} cwd
428
+ */
429
+ export function refuseThemesNotFolder(cwd) {
430
+ const root = path.join(cwd, 'themes');
431
+ const st = fs.lstatSync(root, {throwIfNoEntry: false});
432
+ if (!st) return;
433
+ const isDir =
434
+ st.isDirectory() ||
435
+ (st.isSymbolicLink() &&
436
+ fs.statSync(root, {throwIfNoEntry: false})?.isDirectory());
437
+ if (isDir) return;
438
+ refuse(
439
+ ERROR_CODES.ERR_FILE_EXISTS,
440
+ `themes in this app is ${st.isSymbolicLink() ? 'a link that does not lead to a folder' : 'a file, not a folder'}, so no editor theme can be read or made: every theme goes in themes/<name>/. Rename or move it, then run the command again.`,
441
+ {run: ['ls -la themes']},
442
+ );
443
+ }
444
+
174
445
  /**
175
446
  * The themes the editor made in the app (a settings file of its own), by
176
447
  * name, or with `changed` the one an editor command changed last first: the
@@ -183,6 +454,7 @@ export function themeFiles(cwd, slug) {
183
454
  export function editedThemes(cwd, order = 'name') {
184
455
  const root = path.join(cwd, 'themes');
185
456
  if (!fs.existsSync(root)) return [];
457
+ refuseThemesNotFolder(cwd);
186
458
  const names = fs
187
459
  .readdirSync(root)
188
460
  .filter(d => fs.existsSync(themeFiles(cwd, d).settings))
@@ -259,6 +531,29 @@ export function refuse(code, message, extra = {}) {
259
531
  throw new AstryxError(`${message} ${tail}`, suggestions, code);
260
532
  }
261
533
 
534
+ /**
535
+ * A theme name as typed, read the way the editor reads it: a path to its
536
+ * folder or a file in it (t.theme.ts, Brand.settings.json), in any case,
537
+ * names the theme. The result may still need slugFor.
538
+ * @param {unknown} s
539
+ * @returns {string}
540
+ */
541
+ export function typedThemeName(s) {
542
+ return (
543
+ String(s ?? '')
544
+ .trim()
545
+ .toLowerCase()
546
+ // ./t and .\t name the theme t.
547
+ .replace(/^(\.[\\/])+/, '')
548
+ .replace(/^.*themes[\\/]/, '')
549
+ .replace(/[\\/].*$/, '')
550
+ .replace(
551
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|css|js|ts)$/,
552
+ '',
553
+ )
554
+ );
555
+ }
556
+
262
557
  /**
263
558
  * The settings of a theme, or a refusal naming the command that makes it.
264
559
  * @param {string} cwd
@@ -273,19 +568,12 @@ export function loadTheme(
273
568
  slug,
274
569
  skip = /** @type {string | Partial<Setting>} */ (''),
275
570
  ) {
571
+ refuseThemesNotFolder(cwd);
276
572
  if (!slugOk(slug)) {
277
573
  // A path or a capital letter typed for a theme that exists names it.
278
574
  // A file name typed for the theme (t.theme.ts, Brand.settings.json)
279
575
  // names the theme.
280
- const plain = String(slug ?? '')
281
- .trim()
282
- .toLowerCase()
283
- .replace(/^.*themes[\\/]/, '')
284
- .replace(/[\\/].*$/, '')
285
- .replace(
286
- /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|css|js|ts)$/,
287
- '',
288
- );
576
+ const plain = typedThemeName(slug);
289
577
  const fixed = slugFor(plain);
290
578
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
291
579
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
@@ -309,6 +597,27 @@ export function loadTheme(
309
597
  },
310
598
  );
311
599
  }
600
+ // An empty name (an unset variable, a lone dash): no theme to guess
601
+ // from it, so the themes here are named instead of a new one.
602
+ if (!same && !/[a-z0-9]/i.test(String(slug ?? ''))) {
603
+ const have = fs.existsSync(themeFiles(cwd, 'x').root)
604
+ ? fs
605
+ .readdirSync(themeFiles(cwd, 'x').root)
606
+ .filter(
607
+ d => slugOk(d) && fs.existsSync(themeFiles(cwd, d).settings),
608
+ )
609
+ .sort()
610
+ : [];
611
+ refuse(
612
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
613
+ `The theme name is empty${String(slug ?? '').trim() ? ` ("${String(slug).slice(0, 20)}" has no letter or digit)` : ''}.${have.length ? ` Themes here: ${have.slice(0, 6).join(', ')}.` : ''}`,
614
+ {
615
+ run: have.length
616
+ ? have.slice(0, 3).map(t => `${P} show ${t}`)
617
+ : [`${P} new my-theme`],
618
+ },
619
+ );
620
+ }
312
621
  refuse(
313
622
  ERROR_CODES.ERR_INVALID_ARGUMENT,
314
623
  `"${String(slug ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
@@ -348,7 +657,55 @@ export function loadTheme(
348
657
  ERROR_CODES.ERR_UNKNOWN_THEME,
349
658
  stopped
350
659
  ? `themes/${slug} was left by a \`new\` that was stopped part way, so it has no settings yet. Run new again to finish it; files you added there are kept.`
351
- : `themes/${slug} has lost its settings (${slug}.settings.json is gone), but the editor made it. Run new to make it again: your own files there are kept${fs.existsSync(f.history) ? `, and \`undo ${slug}\` then steps back to the earlier settings` : ''}.`,
660
+ : `themes/${slug} has lost its settings (${slug}.settings.json is gone), but the editor made it. Run new to make it again: your own files there are kept${fs.existsSync(f.history) ? `, and \`undo ${slug}\` then steps back to the settings from before the last change (the last change itself is not kept)` : ''}.`,
661
+ {run: [`${P} new ${slug}`]},
662
+ );
663
+ // A folder copied or renamed by hand from an editor theme: its files
664
+ // still carry the old name (t.settings.json in themes/t2).
665
+ const copied =
666
+ !same && fs.existsSync(f.dir)
667
+ ? fs
668
+ .readdirSync(f.dir)
669
+ .map(n => /^(.+)\.settings\.json$/.exec(n)?.[1])
670
+ .find(n => n && n !== slug)
671
+ : undefined;
672
+ if (copied) {
673
+ const files = fs
674
+ .readdirSync(f.dir)
675
+ .filter(n => n.startsWith(`${copied}.`))
676
+ .sort();
677
+ const original = fs.existsSync(themeFiles(cwd, copied).settings);
678
+ refuse(
679
+ ERROR_CODES.ERR_UNKNOWN_THEME,
680
+ `themes/${slug} holds the editor files of a theme named ${copied} (${files.slice(0, 4).join(', ')}${files.length > 4 ? ', …' : ''}): it looks like a copy or rename of ${copied}. The editor reads a theme's files by its folder's name, so to edit it as ${slug}, rename each ${copied}.* file there to ${slug}.* (${files
681
+ .slice(0, 2)
682
+ .map(n => `${n} to ${slug}${n.slice(copied.length)}`)
683
+ .join(', ')}${files.length > 2 ? ', and so on' : ''})${
684
+ // The theme source names the theme inside it too: every step.
685
+ files.includes(`${copied}.theme.ts`)
686
+ ? `, then in ${slug}.theme.ts change './${copied}.settings' to './${slug}.settings', ${camel(copied)}Settings to ${camel(slug)}Settings (in the import and in extends), name: '${copied}' to name: '${slug}', and ${camel(copied)}Theme to ${camel(slug)}Theme`
687
+ : ''
688
+ }${original ? `; ${copied} itself is still in themes/${copied}` : ''}.`,
689
+ {
690
+ run: original
691
+ ? [`${P} show ${copied}`, `ls -la themes/${slug}`]
692
+ : [`ls -la themes/${slug}`],
693
+ },
694
+ );
695
+ }
696
+ // An empty theme folder (or one of system files only) holds no theme
697
+ // yet: `new` makes one there.
698
+ if (
699
+ !same &&
700
+ other &&
701
+ other[0] === f.dir &&
702
+ !LIKE.includes(slug) &&
703
+ fs.lstatSync(f.dir).isDirectory() &&
704
+ folderIsEmpty(f.dir)
705
+ )
706
+ refuse(
707
+ ERROR_CODES.ERR_UNKNOWN_THEME,
708
+ `themes/${slug} is an empty folder: there is no theme ${slug} yet. new makes it there.`,
352
709
  {run: [`${P} new ${slug}`]},
353
710
  );
354
711
  if (!same && (other || LIKE.includes(slug)))
@@ -357,20 +714,37 @@ export function loadTheme(
357
714
  `${other ? `${other[1]} is a theme the editor did not make (written by hand, or ejected)` : `${slug} is a built-in theme`}, so the editor does not change it. Make an editor theme with its own name instead${LIKE.includes(slug) ? `, on top of ${slug}` : ''}.`,
358
715
  {
359
716
  run: [
360
- `${P} new my-${slug}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
717
+ // The user's own theme on that base, when there is one, then a
718
+ // free valid name for a new one.
719
+ ...(fs.existsSync(themeFiles(cwd, `my-${slug}`).settings)
720
+ ? [`${P} show my-${slug}`]
721
+ : []),
722
+ `${P} new ${usableNewName(cwd, `my-${slug}`)}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
361
723
  ],
362
724
  },
363
725
  );
364
726
  refuse(
365
727
  ERROR_CODES.ERR_UNKNOWN_THEME,
366
728
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
367
- {
368
- didYouMean: same ? [same] : nearest(slug, have),
369
- run: same ? [`${P} show ${same}`] : [`${P} new ${slug}`],
370
- },
729
+ (() => {
730
+ const near = same ? [same] : nearest(slug, have);
731
+ // A theme near the name comes first; a new theme of the name as
732
+ // typed only after.
733
+ return {
734
+ didYouMean: near,
735
+ run: same
736
+ ? [`${P} show ${same}`]
737
+ : near.length
738
+ ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
739
+ : [`${P} new ${slug}`],
740
+ };
741
+ })(),
371
742
  );
372
743
  }
373
744
  refuseLinks(cwd, slug);
745
+ // A file of the theme that is a folder or cannot be read is named, never
746
+ // called damaged.
747
+ refuseUnreadableFiles(cwd, slug);
374
748
  // undo is offered only when there is a step to go back to.
375
749
  const steps = readHistory(f.history).steps.length;
376
750
  const recover = steps
@@ -472,22 +846,73 @@ export function loadTheme(
472
846
  );
473
847
  }
474
848
  // A bad mode or base is fixed by setting it.
849
+ // A value written in other letters (Dark-Only, Neutral) is the one meant.
850
+ const modeMeant = String(data?.mode ?? '')
851
+ .trim()
852
+ .toLowerCase();
853
+ const likeMeant = String(data?.like ?? '')
854
+ .trim()
855
+ .toLowerCase();
475
856
  const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
476
- ? `${P} set ${slug} mode both`
857
+ ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
477
858
  : /^base "/.test(problem ?? '')
478
- ? `${P} set ${slug} base none`
859
+ ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
479
860
  : null;
861
+ // A setting listed twice: setting it to one of its values, or undoing
862
+ // it, keeps one entry or none.
863
+ const twice = problem?.includes(' is listed twice (')
864
+ ? duplicated(data)
865
+ : null;
480
866
  if (problem)
481
867
  throw new AstryxError(
482
- `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : `Fix it by hand${recover.text}`}. Nothing was changed.`,
868
+ `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : twice ? `Set it to one of its values or undo it, or fix it by hand${recover.text}` : `Fix it by hand${recover.text}`}. Nothing was changed.`,
483
869
  fieldFix
484
870
  ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
485
- : recover.run,
871
+ : twice
872
+ ? [
873
+ ...twice.values
874
+ .filter(
875
+ v =>
876
+ typeof v === 'string' &&
877
+ !valueProblem({...twice.setting, value: v}),
878
+ )
879
+ .slice(0, 2)
880
+ .map(v => ({
881
+ name: `${P} set ${slug} ${undoArgs(twice.setting).replace(twice.setting.thing, `${twice.setting.thing} ${quoteCommandArgument(String(v))}`)}`,
882
+ reason: `keep ${v}`,
883
+ })),
884
+ {
885
+ name: `${P} undo ${slug} ${undoArgs(twice.setting)}`,
886
+ reason: 'remove both',
887
+ },
888
+ ...recover.run,
889
+ ]
890
+ : recover.run,
486
891
  ERROR_CODES.ERR_THEME_INVALID,
487
892
  );
488
893
  return data;
489
894
  }
490
895
 
896
+ /**
897
+ * The first setting listed more than once, with every value it is listed
898
+ * with, in order.
899
+ * @param {any} data
900
+ * @returns {{setting: any, values: unknown[]} | null}
901
+ */
902
+ function duplicated(data) {
903
+ /** @type {Map<string, any[]>} */
904
+ const byKey = new Map();
905
+ for (const s of data.settings ?? []) {
906
+ if (!s || typeof s.thing !== 'string') continue;
907
+ const key = keyOf(s);
908
+ byKey.set(key, [...(byKey.get(key) ?? []), s]);
909
+ }
910
+ for (const list of byKey.values())
911
+ if (list.length > 1)
912
+ return {setting: list[0], values: [...new Set(list.map(x => x.value))]};
913
+ return null;
914
+ }
915
+
491
916
  /**
492
917
  * What is wrong with settings data, or null: its shape, and each value with
493
918
  * the same rules `set` checks it by (without the installed Core), so a value
@@ -513,7 +938,15 @@ export function settingsProblem(
513
938
  if (!field && data.like != null && !LIKE.includes(data.like))
514
939
  return `base "${data.like}" is not a built-in theme (${LIKE.join(', ')})`;
515
940
  if (!Array.isArray(data.settings)) return 'settings is not a list';
516
- const keys = new Set();
941
+ // `lifted` is written by the build: a list of text, or absent.
942
+ if (
943
+ data.lifted != null &&
944
+ (!Array.isArray(data.lifted) ||
945
+ data.lifted.some((/** @type {unknown} */ x) => typeof x !== 'string'))
946
+ )
947
+ return `lifted is ${JSON.stringify(data.lifted)}, not a list of text (the build writes it; remove the field and the next build writes it again)`;
948
+ /** @type {Map<string, any>} */
949
+ const keys = new Map();
517
950
  for (const s of data.settings) {
518
951
  // A value or scope that is not text is a bad setting `undo` removes;
519
952
  // a setting with no name is damage.
@@ -524,8 +957,11 @@ export function settingsProblem(
524
957
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
525
958
  return `${s.thing} has mode "${s.mode}"`;
526
959
  const key = keyOf(s);
527
- if (keys.has(key)) return `${describe(s)} is listed twice`;
528
- keys.add(key);
960
+ // The command that changes or removes a setting listed twice keeps one
961
+ // value, or none, so it fixes the list.
962
+ if (keys.has(key) && !skips(s, skip))
963
+ return `${describe({...s, value: '?'}).replace(' = ?', '')} is listed twice (${JSON.stringify(keys.get(key).value)}, ${JSON.stringify(s.value)})`;
964
+ keys.set(key, s);
529
965
  if (skips(s, skip)) continue;
530
966
  const problem = valueProblem(s);
531
967
  if (problem) return problem;
@@ -606,56 +1042,693 @@ export function withoutBadValues(data) {
606
1042
  }
607
1043
 
608
1044
  /**
609
- * What is wrong with a setting's value, or null.
610
- * @param {any} s
611
- * @returns {string | null}
1045
+ * What is wrong with a setting's value, or null.
1046
+ * @param {any} s
1047
+ * @returns {string | null}
1048
+ */
1049
+ export function valueProblem(s) {
1050
+ if (typeof s.value !== 'string')
1051
+ return `${s.thing} has a value that is not text (${JSON.stringify(s.value)})`;
1052
+ for (const k of ['on', 'when', 'state', 'mode'])
1053
+ if (s[k] != null && typeof s[k] !== 'string')
1054
+ return `${s.thing} has a ${k} that is not text`;
1055
+ const scope = scopeProblem(s);
1056
+ if (scope) return scope;
1057
+ {
1058
+ const bad = `${s.thing} "${s.value}"`;
1059
+ // A font family name may hold an apostrophe (O'Reilly Sans): Core
1060
+ // quotes the family itself.
1061
+ const checked =
1062
+ s.source === 'dial' && s.thing === 'font'
1063
+ ? s.value.replace(/'/g, '')
1064
+ : s.value;
1065
+ if (!isSafeValue(checked)) return `${bad} cannot be a CSS value`;
1066
+ if (s.source === 'token') {
1067
+ if (s.mode && !isColorToken(s.thing))
1068
+ return `${s.thing} is set for ${s.mode} only, but only colors differ by mode`;
1069
+ if (new RegExp(`var\\(\\s*${s.thing}\\s*[,)]`, 'i').test(s.value))
1070
+ return `${bad} reads itself`;
1071
+ }
1072
+ if (s.source !== 'dial') return null;
1073
+ const d = DIALS[s.thing];
1074
+ if (!d) return `${s.thing} is not a dial`;
1075
+ // A color dial needs a fixed opaque seed, as `set` checks it: a
1076
+ // see-through, system or variable color generates no shades.
1077
+ if (PALETTE_DIALS.includes(s.thing) && isColorValue(s.value)) {
1078
+ const seed = colorProblem(s.value);
1079
+ if (seed) return `${bad} ${seed.message}`;
1080
+ }
1081
+ const words = d.values.split('|').filter(w => !w.startsWith('<'));
1082
+ const ok =
1083
+ s.thing === 'corners'
1084
+ ? words.includes(s.value) || /^\d+(\.\d+)?px$/.test(s.value)
1085
+ : s.thing === 'text-size'
1086
+ ? words.includes(s.value) ||
1087
+ (/^\d+(\.\d+)?$/.test(s.value) &&
1088
+ Number(s.value) >= 10 &&
1089
+ Number(s.value) <= 32)
1090
+ : s.thing === 'vibrancy'
1091
+ ? /^\d{1,3}$/.test(s.value) && Number(s.value) <= 100
1092
+ : PALETTE_DIALS.includes(s.thing)
1093
+ ? isColorValue(s.value)
1094
+ : s.thing === 'font'
1095
+ ? s.value.trim() !== ''
1096
+ : words.includes(s.value);
1097
+ if (!ok || s.value === 'more' || s.value === 'less')
1098
+ return `${bad} is not a value ${s.thing} takes (${d.values.replace('|more|less', '')})`;
1099
+ }
1100
+ return null;
1101
+ }
1102
+
1103
+ /**
1104
+ * The page-wide tokens a theme's own source sets: the keys of the top-level
1105
+ * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
1106
+ * with its value when that is plain text (else null). A token set only in a
1107
+ * scope (`onDark`, `components`) is not one: it does not apply page-wide.
1108
+ * @param {string} cwd
1109
+ * @param {string} slug
1110
+ * @returns {Map<string, string | null>}
1111
+ */
1112
+ function ownPageTokens(cwd, slug) {
1113
+ /** @type {Map<string, string | null>} */
1114
+ const out = new Map();
1115
+ /** @type {string} */
1116
+ let code;
1117
+ try {
1118
+ code = fs.readFileSync(themeFiles(cwd, slug).ts, 'utf8');
1119
+ } catch {
1120
+ return out;
1121
+ }
1122
+ /** @type {any} */
1123
+ let ast;
1124
+ try {
1125
+ ast = parseModule(code, {sourceType: 'module', plugins: ['typescript']});
1126
+ } catch {
1127
+ return out;
1128
+ }
1129
+ /** @param {any} node @returns {string | null} */
1130
+ const keyOf = node =>
1131
+ node?.type === 'StringLiteral'
1132
+ ? node.value
1133
+ : node?.type === 'Identifier'
1134
+ ? node.name
1135
+ : null;
1136
+ /** @param {any} node @returns {string | null} */
1137
+ const textOf = node =>
1138
+ node?.type === 'StringLiteral'
1139
+ ? node.value
1140
+ : node?.type === 'TemplateLiteral' && node.expressions.length === 0
1141
+ ? node.quasis.map((/** @type {any} */ q) => q.value.cooked).join('')
1142
+ : null;
1143
+ // Every const binding in the file, by name, so a value given by name
1144
+ // (tokens: mine, ...mine) is read as written.
1145
+ /** @type {Map<string, any>} */
1146
+ const consts = new Map();
1147
+ /** @type {any[]} */
1148
+ const calls = [];
1149
+ /** @param {any} node @param {any} owner the exported name, when exported */
1150
+ const visit = (node, owner = null) => {
1151
+ if (!node || typeof node !== 'object') return;
1152
+ if (node.type === 'VariableDeclarator' && node.id?.type === 'Identifier')
1153
+ consts.set(node.id.name, node.init);
1154
+ if (
1155
+ node.type === 'CallExpression' &&
1156
+ node.callee?.type === 'Identifier' &&
1157
+ node.callee.name === 'defineTheme' &&
1158
+ node.arguments?.[0]
1159
+ )
1160
+ calls.push({call: node, owner});
1161
+ for (const [k, v] of Object.entries(node)) {
1162
+ const nextOwner =
1163
+ node.type === 'VariableDeclarator' && k === 'init'
1164
+ ? (node.id?.name ?? owner)
1165
+ : node.type === 'ExportDefaultDeclaration'
1166
+ ? 'default'
1167
+ : owner;
1168
+ if (Array.isArray(v)) v.forEach(c => visit(c, nextOwner));
1169
+ else if (v && typeof v === 'object' && v.type) visit(v, nextOwner);
1170
+ }
1171
+ };
1172
+ visit(ast.program);
1173
+ /** @param {any} node @param {number} [depth] @returns {any} */
1174
+ const unwrap = (node, depth = 0) => {
1175
+ if (!node || depth > 20) return null;
1176
+ if (
1177
+ [
1178
+ 'TSAsExpression',
1179
+ 'TSSatisfiesExpression',
1180
+ 'TSNonNullExpression',
1181
+ 'TSTypeAssertion',
1182
+ 'ParenthesizedExpression',
1183
+ ].includes(node.type)
1184
+ )
1185
+ return unwrap(node.expression, depth + 1);
1186
+ if (node.type === 'Identifier' && consts.has(node.name))
1187
+ return unwrap(consts.get(node.name), depth + 1);
1188
+ return node;
1189
+ };
1190
+ // The theme the build loads: the defineTheme that names it, else the one
1191
+ // exported as <camel>Theme or by default, else the only one.
1192
+ const named = calls.find(({call}) => {
1193
+ const obj = unwrap(call.arguments[0]);
1194
+ return (
1195
+ obj?.type === 'ObjectExpression' &&
1196
+ obj.properties.some(
1197
+ (/** @type {any} */ p) =>
1198
+ p.type === 'ObjectProperty' &&
1199
+ keyOf(p.key) === 'name' &&
1200
+ textOf(unwrap(p.value)) === slug,
1201
+ )
1202
+ );
1203
+ });
1204
+ const chosen =
1205
+ named ??
1206
+ calls.find(
1207
+ c => c.owner === `${camel(slug)}Theme` || c.owner === 'default',
1208
+ ) ??
1209
+ (calls.length === 1 ? calls[0] : null);
1210
+ if (!chosen) return out;
1211
+ const def = unwrap(chosen.call.arguments[0]);
1212
+ if (def?.type !== 'ObjectExpression') return out;
1213
+ const tokensProp = def.properties.find(
1214
+ (/** @type {any} */ p) =>
1215
+ p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === 'tokens',
1216
+ );
1217
+ if (!tokensProp) return out;
1218
+ let unresolved = false;
1219
+ /** @param {any} node @param {number} depth */
1220
+ const collect = (node, depth) => {
1221
+ const obj = unwrap(node);
1222
+ if (obj?.type !== 'ObjectExpression' || depth > 20) {
1223
+ unresolved = true;
1224
+ return;
1225
+ }
1226
+ // Spreads and keys merge in order: a later one wins.
1227
+ for (const p of obj.properties) {
1228
+ if (p.type === 'SpreadElement') collect(p.argument, depth + 1);
1229
+ else if (p.type === 'ObjectProperty' && !p.computed) {
1230
+ const k = keyOf(p.key);
1231
+ if (k?.startsWith('--')) out.set(k, textOf(unwrap(p.value)));
1232
+ } else unresolved = true;
1233
+ }
1234
+ };
1235
+ collect(tokensProp.value, 0);
1236
+ // A value no read of the file can resolve (a call, an import) is read
1237
+ // from the build (ownTokens), and checked again after the next one.
1238
+ void unresolved;
1239
+ return out;
1240
+ }
1241
+
1242
+ /**
1243
+ * The var() loops among a theme's built top-level tokens, each with a key
1244
+ * that names it whatever token it starts from.
1245
+ * @param {string} cwd
1246
+ * @param {string} slug
1247
+ * @returns {Array<{key: string, path: string[], part?: string}>}
1248
+ */
1249
+ function builtLoops(cwd, slug) {
1250
+ const tokens = builtTopTokens(cwd, slug);
1251
+ /** @param {string} t */
1252
+ const refs = t =>
1253
+ [...String(tokens.get(t) ?? '').matchAll(/var\(\s*(--[a-z0-9-]+)/gi)].map(
1254
+ m => m[1],
1255
+ );
1256
+ /** @type {Array<{key: string, path: string[], part?: string}>} */
1257
+ const loops = [];
1258
+ const seen = new Set();
1259
+ for (const start of tokens.keys()) {
1260
+ /** @type {string[]} */
1261
+ const path = [];
1262
+ /** @param {string} t @returns {boolean} */
1263
+ const walk = t => {
1264
+ const at = path.indexOf(t);
1265
+ if (at >= 0) {
1266
+ const cycle = path.slice(at);
1267
+ const key = [...cycle].sort().join(' ');
1268
+ if (!seen.has(key)) {
1269
+ seen.add(key);
1270
+ loops.push({key, path: [...cycle, t]});
1271
+ }
1272
+ return true;
1273
+ }
1274
+ if (!tokens.has(t) || path.length > 50) return false;
1275
+ path.push(t);
1276
+ for (const r of refs(t)) if (walk(r)) return true;
1277
+ path.pop();
1278
+ return false;
1279
+ };
1280
+ walk(start);
1281
+ }
1282
+ // Inside one part: a part's own token reads the part's other own tokens
1283
+ // first, and a whole-theme one only as already resolved, so a loop there
1284
+ // closes among the part's own tokens.
1285
+ const js = themeFiles(cwd, slug).js;
1286
+ for (const part of blockKeys(js, ['components'])) {
1287
+ const plain = blockOf(js, ['components', part, 'base']);
1288
+ // Each state or variant rule of the part also has its plain rule.
1289
+ for (const scope of blockKeys(js, ['components', part])) {
1290
+ const own =
1291
+ scope === 'base' ? plain : blockOf(js, ['components', part, scope]);
1292
+ const block = new Map([...plain, ...own]);
1293
+ const where = scope === 'base' ? part : `${part} ${scope}`;
1294
+ for (const start of own.keys()) {
1295
+ if (!start.startsWith('--')) continue;
1296
+ /** @type {string[]} */
1297
+ const path = [];
1298
+ /** @param {string} t @returns {boolean} */
1299
+ const walk = t => {
1300
+ const at = path.indexOf(t);
1301
+ if (at >= 0) {
1302
+ const cycle = path.slice(at);
1303
+ const key = `${where}: ${[...cycle].sort().join(' ')}`;
1304
+ if (!seen.has(key)) {
1305
+ seen.add(key);
1306
+ loops.push({key, path: [...cycle, t], part: where});
1307
+ }
1308
+ return true;
1309
+ }
1310
+ if (!block.has(t) || path.length > 50) return false;
1311
+ path.push(t);
1312
+ for (const m of String(block.get(t) ?? '').matchAll(
1313
+ /var\(\s*(--[a-z0-9-]+)/gi,
1314
+ ))
1315
+ if (walk(m[1])) return true;
1316
+ path.pop();
1317
+ return false;
1318
+ };
1319
+ walk(start);
1320
+ }
1321
+ }
1322
+ }
1323
+ return loops;
1324
+ }
1325
+
1326
+ /**
1327
+ * The keys of one object in a built theme module (see blockOf).
1328
+ * @param {string} file
1329
+ * @param {string[]} keys
1330
+ * @returns {string[]}
1331
+ */
1332
+ function blockKeys(file, keys) {
1333
+ return [...blockOf(file, keys).keys()];
1334
+ }
1335
+
1336
+ /**
1337
+ * The top-level tokens of a theme's built module (<slug>.js), which the
1338
+ * build wrote as plain data, or an empty map.
1339
+ * @param {string} cwd
1340
+ * @param {string} slug
1341
+ * @returns {Map<string, string | null>}
1342
+ */
1343
+ function builtTopTokens(cwd, slug) {
1344
+ return topTokensOf(themeFiles(cwd, slug).js);
1345
+ }
1346
+
1347
+ /**
1348
+ * The tokens a base theme's own component rules for a part read through
1349
+ * var() (neutral's progress-bar reads --color-border-emphasized), from its
1350
+ * built module; an empty set when it is not installed.
1351
+ * @param {string} cwd
1352
+ * @param {string | null | undefined} like
1353
+ * @param {string} target
1354
+ * @returns {Set<string>}
1355
+ */
1356
+ export function baseComponentReads(cwd, like, target) {
1357
+ /** @type {Set<string>} */
1358
+ const out = new Set();
1359
+ const file = like ? baseModule(cwd, like) : null;
1360
+ if (!file) return out;
1361
+ try {
1362
+ const ast = /** @type {any} */ (
1363
+ parseModule(fs.readFileSync(file, 'utf8'), {sourceType: 'module'})
1364
+ );
1365
+ /** @param {any} node */
1366
+ const visit = node => {
1367
+ if (!node || typeof node !== 'object') return;
1368
+ if (
1369
+ node.type === 'ObjectProperty' &&
1370
+ (node.key?.name ?? node.key?.value) === 'components' &&
1371
+ node.value?.type === 'ObjectExpression'
1372
+ ) {
1373
+ const part = node.value.properties.find(
1374
+ (/** @type {any} */ p) => (p.key?.value ?? p.key?.name) === target,
1375
+ );
1376
+ if (part) {
1377
+ const text = JSON.stringify(part.value);
1378
+ for (const m of text.matchAll(/var\(\s*(--[a-z0-9-]+)/gi))
1379
+ out.add(m[1]);
1380
+ }
1381
+ return;
1382
+ }
1383
+ for (const v of Object.values(node))
1384
+ if (Array.isArray(v)) v.forEach(visit);
1385
+ else if (v && typeof v === 'object' && v.type) visit(v);
1386
+ };
1387
+ visit(ast.program);
1388
+ } catch {
1389
+ // Not one this reads.
1390
+ }
1391
+ return out;
1392
+ }
1393
+
1394
+ /**
1395
+ * The top-level tokens a base theme's built module gives (what the
1396
+ * editor's settings extend), or an empty map when it is not installed.
1397
+ * @param {string} cwd
1398
+ * @param {string | null | undefined} like
1399
+ * @returns {Map<string, string | null>}
1400
+ */
1401
+ export function baseTopTokens(cwd, like) {
1402
+ const file = like ? baseModule(cwd, like) : null;
1403
+ return file ? topTokensOf(file) : new Map();
1404
+ }
1405
+
1406
+ /**
1407
+ * The top-level tokens of a built theme module (plain data the build
1408
+ * wrote), or an empty map.
1409
+ * @param {string} file
1410
+ * @returns {Map<string, string | null>}
1411
+ */
1412
+ function topTokensOf(file) {
1413
+ /** @type {Map<string, string | null>} */
1414
+ const out = new Map();
1415
+ for (const [k, v] of blockOf(file, ['tokens']))
1416
+ if (k.startsWith('--')) out.set(k, v);
1417
+ return out;
1418
+ }
1419
+
1420
+ /**
1421
+ * One block of a built theme module (plain data the build wrote), by its
1422
+ * path from the theme object (`['tokens']`, `['components', 'card',
1423
+ * 'base']`): every key with its text value, a [light, dark] pair as the
1424
+ * build writes it, else null. An empty map when it is not there.
1425
+ * @param {string} file
1426
+ * @param {string[]} keys
1427
+ * @returns {Map<string, string | null>}
1428
+ */
1429
+ function blockOf(file, keys) {
1430
+ /** @type {Map<string, string | null>} */
1431
+ const out = new Map();
1432
+ try {
1433
+ const ast = /** @type {any} */ (
1434
+ parseModule(fs.readFileSync(file, 'utf8'), {
1435
+ sourceType: 'module',
1436
+ plugins: ['typescript'],
1437
+ })
1438
+ );
1439
+ for (const st of ast.program.body) {
1440
+ const decl = st.declaration?.declarations?.[0];
1441
+ /** @type {any} */
1442
+ let obj = decl?.init;
1443
+ // The generated settings module: defineTheme({...}).
1444
+ if (obj?.type === 'CallExpression') obj = obj.arguments?.[0];
1445
+ for (const key of keys)
1446
+ obj =
1447
+ obj?.type === 'ObjectExpression'
1448
+ ? obj.properties.find(
1449
+ (/** @type {any} */ p) => (p.key?.name ?? p.key?.value) === key,
1450
+ )?.value
1451
+ : undefined;
1452
+ if (obj?.type !== 'ObjectExpression') continue;
1453
+ for (const p of obj.properties) {
1454
+ const k = p.key?.value ?? p.key?.name;
1455
+ if (typeof k === 'string')
1456
+ out.set(
1457
+ k,
1458
+ p.value?.type === 'StringLiteral'
1459
+ ? p.value.value
1460
+ : // A [light, dark] pair, as the build writes it.
1461
+ p.value?.type === 'ArrayExpression' &&
1462
+ p.value.elements.length === 2 &&
1463
+ p.value.elements.every(
1464
+ (/** @type {any} */ e) => e?.type === 'StringLiteral',
1465
+ )
1466
+ ? `light-dark(${p.value.elements.map((/** @type {any} */ e) => e.value).join(', ')})`
1467
+ : null,
1468
+ );
1469
+ }
1470
+ if (out.size) break;
1471
+ }
1472
+ } catch {
1473
+ // No build yet, or not one this reads.
1474
+ }
1475
+ return out;
1476
+ }
1477
+
1478
+ /**
1479
+ * What a part's plain rule (its `base` block) holds in the theme as built
1480
+ * (the base theme's, the settings' and the own source's together), else in
1481
+ * the base theme alone when there is no build: tokens and properties by
1482
+ * name. Kebab-case property names, as the editor names them.
1483
+ * @param {string} cwd
1484
+ * @param {string} slug
1485
+ * @param {string | null | undefined} like
1486
+ * @param {string} part
1487
+ * @returns {Map<string, string | null>}
1488
+ */
1489
+ export function partRuleTokens(cwd, slug, like, part) {
1490
+ const built = blockOf(themeFiles(cwd, slug).js, ['components', part, 'base']);
1491
+ const baseFile = like ? baseModule(cwd, like) : null;
1492
+ const base = baseFile
1493
+ ? blockOf(baseFile, ['components', part, 'base'])
1494
+ : new Map();
1495
+ /** @type {Map<string, string | null>} */
1496
+ const out = new Map();
1497
+ for (const m of [base, built])
1498
+ for (const [k, v] of m)
1499
+ out.set(
1500
+ k.startsWith('--')
1501
+ ? k
1502
+ : k.replace(
1503
+ /[A-Z]/g,
1504
+ (/** @type {string} */ c) => `-${c.toLowerCase()}`,
1505
+ ),
1506
+ v,
1507
+ );
1508
+ return out;
1509
+ }
1510
+
1511
+ /**
1512
+ * The tokens and properties a theme's own source sets on a part's plain
1513
+ * rule, read from the build as ownTokens reads page-wide ones: what the
1514
+ * built rule holds that the settings module and the base theme do not give
1515
+ * as they are, and that the person's files name.
1516
+ * @param {string} cwd
1517
+ * @param {string} slug
1518
+ * @param {string} part
1519
+ * @param {string} [scope] the rule: `base` (the plain one), or a variant
1520
+ * such as `variant:primary`
1521
+ * @param {string | null} [state] a state block inside that rule (`:hover`)
1522
+ * @returns {Map<string, string | null>}
1523
+ */
1524
+ export function ownPartTokens(cwd, slug, part, scope = 'base', state = null) {
1525
+ const at = ['components', part, scope, ...(state ? [state] : [])];
1526
+ /** @type {Map<string, string | null>} */
1527
+ const out = new Map();
1528
+ const f = themeFiles(cwd, slug);
1529
+ /** @type {string} */
1530
+ let module;
1531
+ try {
1532
+ module = fs.readFileSync(f.settingsTs, 'utf8');
1533
+ } catch {
1534
+ return out;
1535
+ }
1536
+ const stamp = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1537
+ module,
1538
+ )?.[1];
1539
+ if (!stamp || stamp !== themeSourceHash(cwd, slug)) return out;
1540
+ const like = /\/\/ Built on @astryxdesign\/theme-([a-z0-9-]+) /.exec(
1541
+ module,
1542
+ )?.[1];
1543
+ const baseFile = like ? baseModule(cwd, like) : null;
1544
+ const base = baseFile ? blockOf(baseFile, at) : new Map();
1545
+ const settings = blockOf(f.settingsTs, at);
1546
+ const named = namedInOwnSource(cwd, slug);
1547
+ for (const [k, v] of blockOf(f.js, at)) {
1548
+ const given = settings.has(k) ? settings.get(k) : base.get(k);
1549
+ if (given !== v && named(k))
1550
+ out.set(
1551
+ k.startsWith('--')
1552
+ ? k
1553
+ : k.replace(
1554
+ /[A-Z]/g,
1555
+ (/** @type {string} */ c) => `-${c.toLowerCase()}`,
1556
+ ),
1557
+ v,
1558
+ );
1559
+ }
1560
+ return out;
1561
+ }
1562
+
1563
+ /**
1564
+ * The page-wide tokens the theme's own source sets, read from what the
1565
+ * build made of it: the built module's top-level tokens that the
1566
+ * generated settings module does not give as they are (the own source wins
1567
+ * over the settings it extends). The build evaluates the file, so any way
1568
+ * of writing it counts (a namespace import, a renamed defineTheme, a
1569
+ * template, a spread of a shared object). Only a build made from the
1570
+ * source as it is now is read; with none, the file is read as written.
1571
+ * Both are joined: a key either names is the source's.
1572
+ * @param {string} cwd
1573
+ * @param {string} slug
1574
+ * @returns {Map<string, string | null>}
1575
+ */
1576
+ function ownTokens(cwd, slug) {
1577
+ const out = new Map(ownPageTokens(cwd, slug));
1578
+ const fromBuild = builtOwnTokens(cwd, slug);
1579
+ if (fromBuild) for (const [k, v] of fromBuild) out.set(k, v);
1580
+ return out;
1581
+ }
1582
+
1583
+ /**
1584
+ * The tokens the own source sets, as the current build shows them, or null
1585
+ * when there is no build made from the source as it is now.
1586
+ * @param {string} cwd
1587
+ * @param {string} slug
1588
+ * @returns {Map<string, string | null> | null}
1589
+ */
1590
+ function builtOwnTokens(cwd, slug) {
1591
+ const f = themeFiles(cwd, slug);
1592
+ /** @type {string} */
1593
+ let module;
1594
+ try {
1595
+ module = fs.readFileSync(f.settingsTs, 'utf8');
1596
+ } catch {
1597
+ return null;
1598
+ }
1599
+ const built = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1600
+ module,
1601
+ )?.[1];
1602
+ if (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
1603
+ return null;
1604
+ // What the settings module gives each top-level token: a text value as
1605
+ // it is, a [light, dark] pair as a pair.
1606
+ /** @type {Map<string, string | 'pair' | 'other'>} */
1607
+ const settings = new Map();
1608
+ try {
1609
+ const ast = /** @type {any} */ (
1610
+ parseModule(module, {sourceType: 'module', plugins: ['typescript']})
1611
+ );
1612
+ /** @param {any} node */
1613
+ const visit = node => {
1614
+ if (!node || typeof node !== 'object') return;
1615
+ if (
1616
+ node.type === 'CallExpression' &&
1617
+ node.callee?.name === 'defineTheme' &&
1618
+ node.arguments?.[0]?.type === 'ObjectExpression'
1619
+ ) {
1620
+ const tokens = node.arguments[0].properties.find(
1621
+ (/** @type {any} */ p) =>
1622
+ (p.key?.value ?? p.key?.name) === 'tokens' &&
1623
+ p.value?.type === 'ObjectExpression',
1624
+ );
1625
+ for (const p of tokens?.value.properties ?? []) {
1626
+ const k = p.key?.value ?? p.key?.name;
1627
+ if (typeof k !== 'string') continue;
1628
+ settings.set(
1629
+ k,
1630
+ p.value?.type === 'StringLiteral'
1631
+ ? p.value.value
1632
+ : p.value?.type === 'ArrayExpression'
1633
+ ? 'pair'
1634
+ : 'other',
1635
+ );
1636
+ }
1637
+ return;
1638
+ }
1639
+ for (const v of Object.values(node))
1640
+ if (Array.isArray(v)) v.forEach(visit);
1641
+ else if (v && typeof v === 'object' && v.type) visit(v);
1642
+ };
1643
+ visit(ast.program);
1644
+ } catch {
1645
+ return null;
1646
+ }
1647
+ // What the base theme's built module gives: the tokens the settings
1648
+ // extend, which are no more the source's than the settings' are.
1649
+ const like = /\/\/ Built on @astryxdesign\/theme-([a-z0-9-]+) /.exec(
1650
+ module,
1651
+ )?.[1];
1652
+ const baseFile = like ? baseModule(cwd, like) : null;
1653
+ const base = baseFile ? topTokensOf(baseFile) : new Map();
1654
+ const named = namedInOwnSource(cwd, slug);
1655
+ /** @type {Map<string, string | null>} */
1656
+ const out = new Map();
1657
+ for (const [k, v] of builtTopTokens(cwd, slug)) {
1658
+ const given = settings.get(k);
1659
+ const own =
1660
+ given === undefined
1661
+ ? !base.has(k) || base.get(k) !== v
1662
+ : given === 'pair'
1663
+ ? !/^light-dark\(/.test(String(v ?? ''))
1664
+ : given !== 'other' && given !== v;
1665
+ if (own && named(k)) out.set(k, v);
1666
+ }
1667
+ return out;
1668
+ }
1669
+
1670
+ /**
1671
+ * Whether a token or property name appears in the person's theme files: a
1672
+ * value the build shows that no file of theirs names came from the
1673
+ * settings (a dial's typography, a lifted value), not from them.
1674
+ * @param {string} cwd
1675
+ * @param {string} slug
1676
+ * @returns {(name: string) => boolean}
1677
+ */
1678
+ function namedInOwnSource(cwd, slug) {
1679
+ const text = ownSourceFiles(cwd, slug)
1680
+ .map(file => {
1681
+ try {
1682
+ return fs.readFileSync(file, 'utf8');
1683
+ } catch {
1684
+ return '';
1685
+ }
1686
+ })
1687
+ .join('\n');
1688
+ // A font set through `typography` (heading: {family: ...}) names its
1689
+ // role there, not the token the build writes for it.
1690
+ const typography = /\btypography\b/.test(text);
1691
+ return name =>
1692
+ text.includes(name) ||
1693
+ (typography &&
1694
+ (/^--font-family-([a-z]+)$/.exec(name)?.[1] ?? '') !== '' &&
1695
+ text.includes(
1696
+ /** @type {string[]} */ (/^--font-family-([a-z]+)$/.exec(name))[1],
1697
+ )) ||
1698
+ (typography &&
1699
+ /^--text-([a-z]+)-\d*-?weight$/.test(name) &&
1700
+ text.includes(
1701
+ /** @type {string[]} */ (/^--text-([a-z]+)/.exec(name))[1],
1702
+ ) &&
1703
+ /weight/.test(text)) ||
1704
+ // A property may be written camelCase (borderRadius).
1705
+ (!name.startsWith('--') &&
1706
+ text.includes(name.replace(/-([a-z])/g, (_, c) => c.toUpperCase())));
1707
+ }
1708
+
1709
+ /**
1710
+ * The page-wide tokens a theme's own source sets itself (see ownTokens):
1711
+ * they win over the settings it extends.
1712
+ * @param {string} cwd
1713
+ * @param {string} slug
1714
+ * @returns {string[]}
1715
+ */
1716
+ export function ownSourceTokens(cwd, slug) {
1717
+ return [...ownTokens(cwd, slug).keys()];
1718
+ }
1719
+
1720
+ /**
1721
+ * The values a theme's own source gives page-wide tokens as plain text, by
1722
+ * token (see ownTokens).
1723
+ * @param {string} cwd
1724
+ * @param {string} slug
1725
+ * @returns {Record<string, string>}
612
1726
  */
613
- export function valueProblem(s) {
614
- if (typeof s.value !== 'string')
615
- return `${s.thing} has a value that is not text (${JSON.stringify(s.value)})`;
616
- for (const k of ['on', 'when', 'state', 'mode'])
617
- if (s[k] != null && typeof s[k] !== 'string')
618
- return `${s.thing} has a ${k} that is not text`;
619
- const scope = scopeProblem(s);
620
- if (scope) return scope;
621
- {
622
- const bad = `${s.thing} "${s.value}"`;
623
- // A font family name may hold an apostrophe (O'Reilly Sans): Core
624
- // quotes the family itself.
625
- const checked =
626
- s.source === 'dial' && s.thing === 'font'
627
- ? s.value.replace(/'/g, '')
628
- : s.value;
629
- if (!isSafeValue(checked)) return `${bad} cannot be a CSS value`;
630
- if (s.source === 'token') {
631
- if (s.mode && !isColorToken(s.thing))
632
- return `${s.thing} is set for ${s.mode} only, but only colors differ by mode`;
633
- if (new RegExp(`var\\(\\s*${s.thing}\\s*[,)]`, 'i').test(s.value))
634
- return `${bad} reads itself`;
635
- }
636
- if (s.source !== 'dial') return null;
637
- const d = DIALS[s.thing];
638
- if (!d) return `${s.thing} is not a dial`;
639
- const words = d.values.split('|').filter(w => !w.startsWith('<'));
640
- const ok =
641
- s.thing === 'corners'
642
- ? words.includes(s.value) || /^\d+(\.\d+)?px$/.test(s.value)
643
- : s.thing === 'text-size'
644
- ? words.includes(s.value) ||
645
- (/^\d+(\.\d+)?$/.test(s.value) &&
646
- Number(s.value) >= 10 &&
647
- Number(s.value) <= 32)
648
- : s.thing === 'vibrancy'
649
- ? /^\d{1,3}$/.test(s.value) && Number(s.value) <= 100
650
- : PALETTE_DIALS.includes(s.thing)
651
- ? isColorValue(s.value)
652
- : s.thing === 'font'
653
- ? s.value.trim() !== ''
654
- : words.includes(s.value);
655
- if (!ok || s.value === 'more' || s.value === 'less')
656
- return `${bad} is not a value ${s.thing} takes (${d.values.replace('|more|less', '')})`;
657
- }
658
- return null;
1727
+ export function ownSourceTokenValues(cwd, slug) {
1728
+ /** @type {Record<string, string>} */
1729
+ const out = {};
1730
+ for (const [k, v] of ownTokens(cwd, slug)) if (v != null) out[k] = v;
1731
+ return out;
659
1732
  }
660
1733
 
661
1734
  /**
@@ -723,7 +1796,11 @@ export {modesOf};
723
1796
  * @returns {number | null}
724
1797
  */
725
1798
  export function lengthPx(v) {
726
- const m = /^\s*(-?\d+(?:\.\d+)?|-?\.\d+)\s*(px|rem|em)?\s*$/i.exec(String(v));
1799
+ // A CSS number: a sign, digits with or without a fraction, an exponent.
1800
+ const m =
1801
+ /^\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)\s*(px|rem|em)?\s*$/i.exec(
1802
+ String(v),
1803
+ );
727
1804
  if (!m) return null;
728
1805
  const n = Number(m[1]);
729
1806
  return (m[2] ?? 'px').toLowerCase() === 'px' ? n : n * 16;
@@ -768,7 +1845,8 @@ export function fontOf(value) {
768
1845
  .split(',')
769
1846
  .map(x => x.trim())
770
1847
  .filter(Boolean);
771
- const family = unquote(parts[0] ?? v);
1848
+ // Runs of spaces or tabs inside a family name are one space.
1849
+ const family = familySpaces(unquote(parts[0] ?? v)).trim();
772
1850
  return {
773
1851
  family: cssFamily(family),
774
1852
  fallbacks:
@@ -779,6 +1857,19 @@ export function fontOf(value) {
779
1857
  };
780
1858
  }
781
1859
 
1860
+ /**
1861
+ * Spacing in a font family name as CSS reads a bare name: every Unicode
1862
+ * space (a no-break space, a thin space, a tab) is one space, a run of them
1863
+ * one, and zero-width and format characters (zero-width space, joiners,
1864
+ * word joiner, byte-order mark) are dropped.
1865
+ * @param {string} v
1866
+ */
1867
+ export function familySpaces(v) {
1868
+ return v
1869
+ .replace(/[\u200B-\u200D\u2060\uFEFF]/g, '')
1870
+ .replace(/[\s\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g, ' ');
1871
+ }
1872
+
782
1873
  /**
783
1874
  * A font family name as CSS reads it. A name that is a sequence of CSS
784
1875
  * identifiers stays bare; any other is quoted, or the browser drops the
@@ -789,6 +1880,7 @@ export function fontOf(value) {
789
1880
  * @param {boolean} [spaced]
790
1881
  */
791
1882
  export function cssFamily(name, spaced = false) {
1883
+ name = familySpaces(name);
792
1884
  const words = name.trim().split(/\s+/);
793
1885
  const ident = (/** @type {string} */ w) =>
794
1886
  /^-?(?:[A-Za-z_]|[\u0080-\uffff])(?:[\w-]|[\u0080-\uffff])*$/.test(w) &&
@@ -849,6 +1941,42 @@ function sealModule(text) {
849
1941
  );
850
1942
  }
851
1943
 
1944
+ /**
1945
+ * The staleness reason for an own source changed since the editor's build.
1946
+ * @param {string} slug
1947
+ */
1948
+ export function sourceChangedReason(slug) {
1949
+ return `${slug}.theme.ts or a module it imports changed since the last build`;
1950
+ }
1951
+
1952
+ /** The type tokens base themes set again for phones: families and weights. */
1953
+ export const PHONE_TYPE = /^--font-family|^--(text-[a-z0-9-]+|font)-weight/;
1954
+
1955
+ /**
1956
+ * Record in an editor theme's generated settings that they were built with
1957
+ * its own source as it is now, after `compile` built that source (the
1958
+ * settings do not depend on what the source sets), only in a module as the
1959
+ * editor wrote it.
1960
+ * @param {string} cwd
1961
+ * @param {string} slug
1962
+ * @returns {boolean} whether it was recorded
1963
+ */
1964
+ export function refreshSourceStamp(cwd, slug) {
1965
+ const f = themeFiles(cwd, slug);
1966
+ const ts = fs.readFileSync(f.settingsTs, 'utf8');
1967
+ if (moduleUnedited(ts) !== true) return false;
1968
+ const stamp = /\/\/ Built with (\S+\.theme\.ts) ([0-9a-f]{16})\./.exec(ts);
1969
+ if (!stamp) return false;
1970
+ const now = themeSourceHash(cwd, slug);
1971
+ if (stamp[2] === now) return true;
1972
+ const text = ts
1973
+ .replace(/\r\n/g, '\n')
1974
+ .replace(SEAL, '')
1975
+ .replace(stamp[0], `// Built with ${stamp[1]} ${now}.`);
1976
+ fs.writeFileSync(f.settingsTs, sealModule(text));
1977
+ return true;
1978
+ }
1979
+
852
1980
  /**
853
1981
  * Whether a generated module is as the editor wrote it: true, false for a
854
1982
  * hand edit, null for a module with no hash (an earlier editor's).
@@ -974,11 +2102,9 @@ export function compileTheme(ctx, data, base) {
974
2102
  /** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
975
2103
  const putTok = (name, v, mode) => {
976
2104
  const t = (tok[name] ??= {});
977
- // A one-mode theme writes the value of its mode to both sides.
978
- if (Array.isArray(v) && modeOnly) {
979
- t.light = t.dark = v[modeOnly === 'light' ? 0 : 1];
980
- return;
981
- }
2105
+ // A one-mode theme keeps both halves of a pair: its mode is the one the
2106
+ // app's <Theme> is given, and a region Core draws in the other mode
2107
+ // (a toast, a lightbox) still reads the other half.
982
2108
  if (Array.isArray(v)) {
983
2109
  if (!mode || mode === 'light') t.light = v[0];
984
2110
  if (!mode || mode === 'dark') t.dark = v[1];
@@ -1000,10 +2126,549 @@ export function compileTheme(ctx, data, base) {
1000
2126
  if (tg?.states.includes(s.state) && s.when == null) b = t[s.state] ??= {};
1001
2127
  else if (tg?.states.includes(s.state))
1002
2128
  b = t[`${s.when}+${s.state}`] ??= {};
1003
- else b = b[stateKey(s.state)] ??= {};
2129
+ else b = b[stateKey(s.state, wrapsOneControl(ctx, target))] ??= {};
1004
2130
  }
1005
2131
  return b;
1006
2132
  };
2133
+ /**
2134
+ * A padding on a part whose padding Core writes one variable per side
2135
+ * (its derivedVarRegistry's container expansion), as each side's value,
2136
+ * split at top-level spaces by the CSS shorthand rules: Core splits a
2137
+ * shorthand at every space, which cuts calc(4px + 2px) and loses a
2138
+ * fourth value. On the part itself the sides go as logical longhands,
2139
+ * which Core carries as they are; for a variant or state they go to the
2140
+ * side variables themselves, since Core writes one variable for equal
2141
+ * sides there and the part's own side variables would win over it.
2142
+ * Null for any other property or part.
2143
+ * @param {string} target @param {Setting} s
2144
+ * @returns {Record<string, string> | null}
2145
+ */
2146
+ const containerSides = (target, s) => {
2147
+ const prop = kebab(s.thing);
2148
+ if (
2149
+ s.mode ||
2150
+ !/^padding(-block|-inline|-left|-right|-top|-bottom|-block-start|-block-end|-inline-start|-inline-end)?$/.test(
2151
+ prop,
2152
+ )
2153
+ )
2154
+ return null;
2155
+ if (
2156
+ !(ctx.derived?.[target] ?? []).some(
2157
+ d => d.property === 'padding' && d.expand,
2158
+ )
2159
+ )
2160
+ return null;
2161
+ const scoped0 = s.when != null || s.state != null;
2162
+ // padding's initial value is 0, and padding does not inherit, so unset
2163
+ // is 0 too: on Core's side variables a keyword means no value at all.
2164
+ const value = /^(initial|unset)$/i.test(String(s.value).trim())
2165
+ ? '0'
2166
+ : String(s.value).trim();
2167
+ // A physical left or right stays physical, as Core keeps it (it maps
2168
+ // no physical side to a logical one but top and bottom, which it maps
2169
+ // itself): it is written as it is, and a later padding that covers it
2170
+ // takes it out of the block (below).
2171
+ const physical = /** @type {Record<string, string>} */ ({
2172
+ // One logical side is that side (its keyword resolved too).
2173
+ 'padding-block-start': 'block-start',
2174
+ 'padding-block-end': 'block-end',
2175
+ 'padding-inline-start': 'inline-start',
2176
+ 'padding-inline-end': 'inline-end',
2177
+ 'padding-top': 'block-start',
2178
+ 'padding-bottom': 'block-end',
2179
+ })[prop];
2180
+ if (physical)
2181
+ return {
2182
+ [scoped0
2183
+ ? `--astryx-${target}-padding-${physical}`
2184
+ : camel(`padding-${physical}`)]: value,
2185
+ };
2186
+ // A physical left or right is written as it is (its keyword resolved),
2187
+ // never split as an axis: there is no padding-left-start.
2188
+ if (prop === 'padding-left' || prop === 'padding-right')
2189
+ return {[camel(prop)]: value};
2190
+ const w = splitTop(value, ' ').map(x => x.trim());
2191
+ if (!w.length || w.length > (prop === 'padding' ? 4 : 2)) return null;
2192
+ const scoped = s.when != null || s.state != null;
2193
+ // Only what Core would split wrong is written side by side: math or a
2194
+ // function, four values with different left and right sides; and, for
2195
+ // a variant or state, any padding once the part sets a side itself.
2196
+ const coreSplitsWrong =
2197
+ value !== String(s.value).trim() ||
2198
+ /\(/.test(value) ||
2199
+ (prop === 'padding' && w.length === 4 && w[1] !== w[3]);
2200
+ const partSides = data.settings.some(
2201
+ x =>
2202
+ x !== s &&
2203
+ x.source === 'property' &&
2204
+ // The part's own, or a group's it is in.
2205
+ (x.on === s.on ||
2206
+ (FAMILIES[/** @type {string} */ (x.on)] ?? []).includes(target)) &&
2207
+ x.when == null &&
2208
+ x.state == null &&
2209
+ (/^padding-/.test(kebab(x.thing)) ||
2210
+ (kebab(x.thing) === 'padding' &&
2211
+ /\(|\S+\s+\S+\s+\S+\s+\S+/.test(x.value))),
2212
+ );
2213
+ // A side set on the part or its group: every side is written, so the
2214
+ // later setting wins as written.
2215
+ if (!coreSplitsWrong && !partSides) return null;
2216
+ /** @type {Record<string, string>} */
2217
+ const side = {};
2218
+ if (prop === 'padding') {
2219
+ const [top, right = top, bottom = top, left = right] = w;
2220
+ Object.assign(side, {
2221
+ 'block-start': top,
2222
+ 'inline-end': right,
2223
+ 'block-end': bottom,
2224
+ 'inline-start': left,
2225
+ });
2226
+ } else {
2227
+ const axis = prop.slice('padding-'.length);
2228
+ side[`${axis}-start`] = w[0];
2229
+ side[`${axis}-end`] = w[1] ?? w[0];
2230
+ }
2231
+ return Object.fromEntries(
2232
+ Object.entries(side).map(([k, v]) => [
2233
+ scoped ? `--astryx-${target}-padding-${k}` : camel(`padding-${k}`),
2234
+ v,
2235
+ ]),
2236
+ );
2237
+ };
2238
+ /**
2239
+ * A radius of more than one value on a part whose radius Core copies
2240
+ * into a variable for the content inside it (a card's full-bleed
2241
+ * children), as each corner's own radius, so Core writes no copy of the
2242
+ * whole value there (where one corner reads it, and `10px / 20px` or four
2243
+ * values are wrong). The inner variable takes one radius, the first
2244
+ * corner's across: Core gives the content one radius for every corner.
2245
+ * Null for any other property, part or a single radius.
2246
+ * @param {string} target @param {Setting} s
2247
+ * @returns {Record<string, string> | null}
2248
+ */
2249
+ const cornerRadii = (target, s) => {
2250
+ if (s.mode || kebab(s.thing) !== 'border-radius') return null;
2251
+ const vars = (ctx.derived?.[target] ?? []).find(
2252
+ d => d.property === 'borderRadius' && d.vars?.length,
2253
+ )?.vars;
2254
+ if (!vars) return null;
2255
+ const [across, down] = splitTop(String(s.value).trim(), '/').map(x =>
2256
+ splitTop(x.trim(), ' ').map(y => y.trim()),
2257
+ );
2258
+ if (!across?.length || (across.length === 1 && !down)) return null;
2259
+ /** @param {string[]} w top-left, top-right, bottom-right, bottom-left */
2260
+ const four = w => {
2261
+ const [tl, tr = tl, br = tl, bl = tr] = w;
2262
+ return [tl, tr, br, bl];
2263
+ };
2264
+ const h = four(across);
2265
+ const v = down?.length ? four(down) : null;
2266
+ const corner = (/** @type {number} */ i) =>
2267
+ v && v[i] !== h[i] ? `${h[i]} ${v[i]}` : h[i];
2268
+ // The whole radius as one value first, which Core turns into the
2269
+ // part's inner-corner variable itself (a theme writes no private
2270
+ // variable), then each corner, which the box shows.
2271
+ return {
2272
+ borderRadius: h[0],
2273
+ borderTopLeftRadius: corner(0),
2274
+ borderTopRightRadius: corner(1),
2275
+ borderBottomRightRadius: corner(2),
2276
+ borderBottomLeftRadius: corner(3),
2277
+ };
2278
+ };
2279
+ /**
2280
+ * A one-side logical padding on a part whose whole padding Core copies
2281
+ * into a variable of its own (a composer's or a menu's inner padding),
2282
+ * written for each direction (a left-to-right box's left is a
2283
+ * right-to-left box's right): Core feeds every logical padding into that
2284
+ * variable, so one side would set the whole box. Null for any other
2285
+ * property or part.
2286
+ * @param {string} target @param {Setting} s
2287
+ * @returns {Record<string, string | Record<string, string>> | null}
2288
+ */
2289
+ const boxSides = (target, s) => {
2290
+ const prop = kebab(s.thing);
2291
+ if (s.mode) return null;
2292
+ const derived = ctx.derived?.[target] ?? [];
2293
+ if (
2294
+ derived.some(d => d.property === 'padding' && d.expand) ||
2295
+ !derived.some(d => d.property === 'padding' && d.vars?.length)
2296
+ )
2297
+ return null;
2298
+ const SIDES = /** @type {Record<string, string[]>} */ ({
2299
+ 'padding-block-start': ['block-start'],
2300
+ 'padding-block-end': ['block-end'],
2301
+ 'padding-inline-start': ['inline-start'],
2302
+ 'padding-inline-end': ['inline-end'],
2303
+ 'padding-block': ['block-start', 'block-end'],
2304
+ 'padding-inline': ['inline-start', 'inline-end'],
2305
+ });
2306
+ const sides = SIDES[prop];
2307
+ if (!sides) return null;
2308
+ const w = splitTop(String(s.value).trim(), ' ').map(x => x.trim());
2309
+ // Each side for each direction: a block side is the top or bottom; an
2310
+ // inline side is the left in a left-to-right box and the right in a
2311
+ // right-to-left one, written under :dir(), where Core writes the
2312
+ // declarations as they are and feeds none into the whole-box variable.
2313
+ /** @type {Record<string, string>} */
2314
+ const plain = {};
2315
+ /** @type {Record<string, string>} */
2316
+ const ltr = {};
2317
+ /** @type {Record<string, string>} */
2318
+ const rtl = {};
2319
+ sides.forEach((side, i) => {
2320
+ const v = w[i] ?? w[0];
2321
+ if (side === 'block-start') plain.paddingTop = v;
2322
+ else if (side === 'block-end') plain.paddingBottom = v;
2323
+ else if (side === 'inline-start') {
2324
+ ltr.paddingLeft = v;
2325
+ rtl.paddingRight = v;
2326
+ } else {
2327
+ ltr.paddingRight = v;
2328
+ rtl.paddingLeft = v;
2329
+ }
2330
+ });
2331
+ return {
2332
+ ...plain,
2333
+ ...(Object.keys(ltr).length ? {':dir(ltr)': ltr, ':dir(rtl)': rtl} : {}),
2334
+ };
2335
+ };
2336
+ /**
2337
+ * A padding on a part whose visible box sits inside its themed wrapper,
2338
+ * as the padding variable that box reads, not the wrapper's own padding
2339
+ * (which would add a gap outside the box). Null for any other part.
2340
+ * @param {string} target @param {Setting} s
2341
+ * @returns {Record<string, string> | null}
2342
+ */
2343
+ const wrappedPadding = (target, s) => {
2344
+ if (s.mode || !WRAPPED_PARTS[target] || kebab(s.thing) !== 'padding')
2345
+ return null;
2346
+ const name = (ctx.derived?.[target] ?? []).find(
2347
+ d => d.property === 'padding' && d.vars?.length,
2348
+ )?.vars?.[0];
2349
+ // The box reads only Core's own variable, which a theme may not write,
2350
+ // and a padding property would pad the wrapper: nothing is written (a
2351
+ // saved one is refused, as set refuses it).
2352
+ return name ? {} : null;
2353
+ };
2354
+ /**
2355
+ * The prefix of the padding variables a part's box reads, for a part whose
2356
+ * padding Core writes to them (its derivedVarRegistry's container
2357
+ * expansion), or for one drawn by such a part (a clickable card is a
2358
+ * card); null for any other part.
2359
+ * @param {string} target
2360
+ */
2361
+ const padVars = target => {
2362
+ if (
2363
+ (ctx.derived?.[target] ?? []).some(
2364
+ d => d.property === 'padding' && d.expand,
2365
+ )
2366
+ )
2367
+ return `--astryx-${target}-padding`;
2368
+ return CARD_LIKE.includes(target) ? '--astryx-card-padding' : null;
2369
+ };
2370
+ /**
2371
+ * Padding settings per part and per scope (the block a setting writes
2372
+ * to), in the order they were made.
2373
+ * @type {Map<string, {target: string, s: Setting, list: Setting[]}>}
2374
+ */
2375
+ const padQueue = new Map();
2376
+ /** @param {Setting} s @param {string} target */
2377
+ const queuePadding = (s, target) => {
2378
+ const key = `${target}\0${s.when ?? ''}\0${s.state ?? ''}`;
2379
+ const q = padQueue.get(key) ?? {target, s, list: []};
2380
+ q.list.push(s);
2381
+ padQueue.set(key, q);
2382
+ };
2383
+ /**
2384
+ * One padding model: each scope's settings, in order, resolved to the
2385
+ * four logical sides for each direction (a physical left is the
2386
+ * inline-start in a left-to-right box and the inline-end in a
2387
+ * right-to-left one; the padding shorthand is physical too), then written
2388
+ * to the variables the part's box reads: a side the same in both
2389
+ * directions in the scope's own block, one that differs in a rule for
2390
+ * each direction (one level deep under a state). So the derived and
2391
+ * full-bleed values follow, and a variant or a state out-ranks the base
2392
+ * as Core's own rules do.
2393
+ */
2394
+ const emitPadding = () => {
2395
+ // The side variables written on a narrower selector (a variant, a
2396
+ // state, a clickable card), by the part whose variables they are, with
2397
+ // that selector: they inherit, so a plain one of those parts inside is
2398
+ // reset to its own fallback (below), never given a copy of a value.
2399
+ /** @type {Map<string, Map<string, Set<string>>>} */
2400
+ const narrow = new Map();
2401
+ /** A side as CSS reads it inside calc(): a bare 0 is no length. @param {string} v */
2402
+ const length = v => {
2403
+ const n = cssNumber(v);
2404
+ return n && n.unit === '' && n.value === 0 ? '0px' : v;
2405
+ };
2406
+ for (const {target, s, list} of padQueue.values()) {
2407
+ const prefix = /** @type {string} */ (padVars(target));
2408
+ const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2409
+ const scoped = target !== owner || s.when != null || s.state != null;
2410
+ /** @type {Record<'ltr' | 'rtl', Record<string, string>>} */
2411
+ const side = {ltr: {}, rtl: {}};
2412
+ for (const x of list) {
2413
+ const prop = kebab(x.thing);
2414
+ const raw = String(x.value).trim();
2415
+ // initial and unset leave the variable without a value, so the part
2416
+ // takes Core's own default for it.
2417
+ const value = /^(initial|unset)$/i.test(raw) ? 'initial' : raw;
2418
+ const w = splitTop(value, ' ').map(y => length(y.trim()));
2419
+ const one = length(value);
2420
+ for (const dir of /** @type {const} */ (['ltr', 'rtl'])) {
2421
+ const o = side[dir];
2422
+ const left = dir === 'ltr' ? 'inline-start' : 'inline-end';
2423
+ const right = dir === 'ltr' ? 'inline-end' : 'inline-start';
2424
+ if (prop === 'padding') {
2425
+ const [top, r = top, bottom = top, l = r] = w;
2426
+ Object.assign(o, {
2427
+ 'block-start': top,
2428
+ [right]: r,
2429
+ 'block-end': bottom,
2430
+ [left]: l,
2431
+ });
2432
+ } else if (prop === 'padding-block') {
2433
+ o['block-start'] = w[0];
2434
+ o['block-end'] = w[1] ?? w[0];
2435
+ } else if (prop === 'padding-inline') {
2436
+ o['inline-start'] = w[0];
2437
+ o['inline-end'] = w[1] ?? w[0];
2438
+ } else if (prop === 'padding-top') o['block-start'] = one;
2439
+ else if (prop === 'padding-bottom') o['block-end'] = one;
2440
+ else if (prop === 'padding-left') o[left] = one;
2441
+ else if (prop === 'padding-right') o[right] = one;
2442
+ else {
2443
+ const k = prop.slice('padding-'.length);
2444
+ if (/^(block|inline)-(start|end)$/.test(k)) o[k] = one;
2445
+ }
2446
+ }
2447
+ }
2448
+ /** @type {Record<string, string>} */
2449
+ let plain = {};
2450
+ /** @type {Record<string, string>} */
2451
+ const ltr = {};
2452
+ /** @type {Record<string, string>} */
2453
+ const rtl = {};
2454
+ for (const k of [
2455
+ 'block-start',
2456
+ 'block-end',
2457
+ 'inline-start',
2458
+ 'inline-end',
2459
+ ]) {
2460
+ const [a, b] = [side.ltr[k], side.rtl[k]];
2461
+ if (a != null && a === b) plain[`${prefix}-${k}`] = a;
2462
+ else {
2463
+ if (a != null) ltr[`${prefix}-${k}`] = a;
2464
+ if (b != null) rtl[`${prefix}-${k}`] = b;
2465
+ }
2466
+ }
2467
+ // On the part's own base, a side that is the same in both
2468
+ // directions is written as its logical padding property, which Core
2469
+ // lowers to the variables together with the base theme's and the own
2470
+ // source's padding in the same block: the later wins by key, and four
2471
+ // equal sides come out as the whole padding (a nested section keeps
2472
+ // following its parent's), whatever sides the base theme set.
2473
+ // Only the plain rule: a variant's or a state's rule written that way
2474
+ // would come out as the whole padding alone, which the base's own side
2475
+ // variables out-rank.
2476
+ const lowered = target === owner && !s.when && !s.state;
2477
+ if (lowered)
2478
+ plain = Object.fromEntries(
2479
+ Object.entries(plain).map(([k, v]) => [
2480
+ camel(`padding-${k.slice(prefix.length + 1)}`),
2481
+ v,
2482
+ ]),
2483
+ );
2484
+ // A part drawn by another (a clickable card) writes its sides for each
2485
+ // direction too, so a direction rule the card's own base has never
2486
+ // out-ranks it.
2487
+ if (target !== owner)
2488
+ for (const [k, v] of Object.entries(plain)) {
2489
+ ltr[k] ??= v;
2490
+ rtl[k] ??= v;
2491
+ }
2492
+ if (scoped) {
2493
+ const sel = narrowSelector(target, s);
2494
+ if (sel) {
2495
+ const bySel = narrow.get(owner) ?? new Map();
2496
+ const names = bySel.get(sel) ?? new Set();
2497
+ for (const k of [
2498
+ ...Object.keys(plain),
2499
+ ...Object.keys(ltr),
2500
+ ...Object.keys(rtl),
2501
+ ])
2502
+ names.add(k);
2503
+ bySel.set(sel, names);
2504
+ narrow.set(owner, bySel);
2505
+ }
2506
+ }
2507
+ for (const [k, v] of Object.entries(plain)) putComp(s, target, k, v);
2508
+ for (const [dir, rule] of /** @type {const} */ ([
2509
+ [':dir(ltr)', ltr],
2510
+ [':dir(rtl)', rtl],
2511
+ ]))
2512
+ if (Object.keys(rule).length) {
2513
+ const [b, key] = dirBlock(s, target, dir);
2514
+ b[key] = {...(b[key] ?? {}), ...rule};
2515
+ }
2516
+ }
2517
+ // A plain part inside a narrower one: each side the narrower selector
2518
+ // writes is reset (left without a value, so Core's own fallback holds),
2519
+ // on the part's own class at its own weight, before any base setting a
2520
+ // theme gives it (the part's own base, or a source of the user's own,
2521
+ // which comes later and so wins).
2522
+ for (const [owner, bySel] of narrow) {
2523
+ const b = ((theme.components[owner] ??= {}).base ??= {});
2524
+ // The variables Core writes on the part's own rule, from the base
2525
+ // theme's, the settings' and the own source's padding there: the
2526
+ // reset leaves those alone, so the part's own value always holds.
2527
+ const own = basePaddingVars(owner, b);
2528
+ for (const [sel, names] of bySel) {
2529
+ /** @type {Record<string, string>} */
2530
+ const reset = {};
2531
+ for (const name of names)
2532
+ if (!(name in b) && !own.has(name)) reset[name] = 'initial';
2533
+ if (Object.keys(reset).length) {
2534
+ const key = `:where(${sel} *)`;
2535
+ b[key] = {...(b[key] ?? {}), ...reset};
2536
+ }
2537
+ }
2538
+ }
2539
+ };
2540
+ /**
2541
+ * The padding variables Core writes on a part's plain rule, as Core lowers
2542
+ * the padding properties there (the base theme's, then the settings',
2543
+ * then the own source's, later keys winning): the whole padding when the
2544
+ * four sides are equal, else each side given (an inline pair as one).
2545
+ * @param {string} owner @param {Record<string, any>} mine
2546
+ * @returns {Set<string>}
2547
+ */
2548
+ const basePaddingVars = (owner, mine) => {
2549
+ const prefix = `--astryx-${owner}-padding`;
2550
+ /** @type {Array<[string, string]>} */
2551
+ const keys = [];
2552
+ const fromBase = /** @type {any} */ (base).components?.[owner]?.base ?? {};
2553
+ for (const [k, v] of Object.entries(fromBase))
2554
+ if (typeof v === 'string') keys.push([k, v]);
2555
+ for (const [k, v] of Object.entries(mine))
2556
+ if (typeof v === 'string') keys.push([k, v]);
2557
+ try {
2558
+ for (const [k, v] of ownPartTokens(ctx.project.cwd, data.name, owner))
2559
+ if (v != null && !k.startsWith('--')) keys.push([camel(k), v]);
2560
+ } catch {
2561
+ // No own source.
2562
+ }
2563
+ /** @type {Record<string, string | undefined>} */
2564
+ const r = {};
2565
+ for (const [k, v] of keys) {
2566
+ const w = splitTop(v.trim(), ' ');
2567
+ if (k === 'padding') {
2568
+ r.bs = w[0];
2569
+ r.in = w[1] ?? w[0];
2570
+ r.be = w[2] ?? w[0];
2571
+ delete r.is;
2572
+ delete r.ie;
2573
+ } else if (k === 'paddingBlock') {
2574
+ r.bs = w[0];
2575
+ r.be = w[1] ?? w[0];
2576
+ } else if (k === 'paddingInline') {
2577
+ if (w.length > 1) [r.is, r.ie] = w;
2578
+ else r.in = w[0];
2579
+ } else if (k === 'paddingTop' || k === 'paddingBlockStart') r.bs = v;
2580
+ else if (k === 'paddingBottom' || k === 'paddingBlockEnd') r.be = v;
2581
+ else if (k === 'paddingInlineStart') r.is = v;
2582
+ else if (k === 'paddingInlineEnd') r.ie = v;
2583
+ }
2584
+ const out = new Set(Object.keys(mine).filter(k => k.startsWith(prefix)));
2585
+ const is = r.is ?? r.in;
2586
+ const ie = r.ie ?? r.in;
2587
+ if (is != null && is === ie && r.bs === is && r.be === is) out.add(prefix);
2588
+ else {
2589
+ if (r.is != null || r.ie != null) {
2590
+ if (is != null) out.add(`${prefix}-inline-start`);
2591
+ if (ie != null) out.add(`${prefix}-inline-end`);
2592
+ } else if (r.in != null) out.add(`${prefix}-inline`);
2593
+ if (r.bs != null) out.add(`${prefix}-block-start`);
2594
+ if (r.be != null) out.add(`${prefix}-block-end`);
2595
+ }
2596
+ return out;
2597
+ };
2598
+ /**
2599
+ * The selector a narrower padding scope is written with (a clickable
2600
+ * card's class, a variant's attribute, a state's pseudo-class), or null
2601
+ * for a state Core writes as a block of its own.
2602
+ * @param {string} target @param {Setting} s
2603
+ */
2604
+ const narrowSelector = (target, s) => {
2605
+ const tg = ctx.project.target.get(target);
2606
+ if (s.state && tg?.states.includes(s.state)) return null;
2607
+ const [k, v] = s.when ? String(s.when).split(':') : [];
2608
+ return `.astryx-${target}${s.when ? `[data-${k}="${v}"]` : ''}${s.state ? stateKey(s.state, wrapsOneControl(ctx, target)) : ''}`;
2609
+ };
2610
+
2611
+ /**
2612
+ * Each part's blocks with its base first, and in each block the rules for
2613
+ * a direction before a state's: Core writes them in this order, and a
2614
+ * variant or a state comes after the base it out-ranks (rules of the same
2615
+ * weight win by order).
2616
+ */
2617
+ const orderBlocks = () => {
2618
+ /** @param {Record<string, any>} b @returns {Record<string, any>} */
2619
+ const dirFirst = b => {
2620
+ const keys = Object.keys(b);
2621
+ const plain = keys.filter(k => !k.startsWith(':'));
2622
+ const dirs = keys.filter(k => /^:dir\(/.test(k));
2623
+ const rest = keys.filter(k => k.startsWith(':') && !/^:dir\(/.test(k));
2624
+ return Object.fromEntries(
2625
+ [...plain, ...dirs, ...rest].map(k => [
2626
+ k,
2627
+ k.startsWith(':') && b[k] && typeof b[k] === 'object'
2628
+ ? dirFirst(b[k])
2629
+ : b[k],
2630
+ ]),
2631
+ );
2632
+ };
2633
+ // A part drawn by another (a clickable card) after the part drawing it,
2634
+ // so its own padding wins over the base's reset at the same weight.
2635
+ theme.components = Object.fromEntries([
2636
+ ...Object.entries(theme.components ?? {}).filter(
2637
+ ([t]) => !CARD_LIKE.includes(t),
2638
+ ),
2639
+ ...Object.entries(theme.components ?? {}).filter(([t]) =>
2640
+ CARD_LIKE.includes(t),
2641
+ ),
2642
+ ]);
2643
+ for (const [target, blocks] of Object.entries(theme.components ?? {})) {
2644
+ const keys = Object.keys(blocks);
2645
+ const ordered = keys.includes('base')
2646
+ ? ['base', ...keys.filter(k => k !== 'base')]
2647
+ : keys;
2648
+ theme.components[target] = Object.fromEntries(
2649
+ ordered.map(k => [
2650
+ k,
2651
+ blocks[k] && typeof blocks[k] === 'object'
2652
+ ? dirFirst(blocks[k])
2653
+ : blocks[k],
2654
+ ]),
2655
+ );
2656
+ }
2657
+ };
2658
+ /**
2659
+ * Where a per-direction rule goes for a setting, one level deep, as the
2660
+ * block and its key: in the setting's own block, or under a state Core
2661
+ * writes as a pseudo-class, beside that state with the direction after it.
2662
+ * @param {Setting} s @param {string} target @param {string} dir `:dir(ltr)`
2663
+ * @returns {[Record<string, any>, string]}
2664
+ */
2665
+ const dirBlock = (s, target, dir) => {
2666
+ const tg = ctx.project.target.get(target);
2667
+ if (!s.state || tg?.states.includes(s.state))
2668
+ return [block(s, target), dir];
2669
+ const parent = block({...s, state: undefined}, target);
2670
+ return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
2671
+ };
1007
2672
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
1008
2673
  const putComp = (s, target, prop, v) => {
1009
2674
  const b = block(s, target);
@@ -1095,7 +2760,7 @@ export function compileTheme(ctx, data, base) {
1095
2760
  for (const m of /** @type {const} */ (['light', 'dark']))
1096
2761
  if (!x.mode || x.mode === m) value[m] = {color: x.value};
1097
2762
  ((theme.components[target] ??= {})[key] ??= {})['--color-text-secondary'] =
1098
- liftValue(value, modeOnly);
2763
+ liftValue(value, null);
1099
2764
  }
1100
2765
  // `headings` owns heading weight and tracking whatever the order: `type`
1101
2766
  // sets them only where no `headings` setting does.
@@ -1256,9 +2921,93 @@ export function compileTheme(ctx, data, base) {
1256
2921
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
1257
2922
  else putTok(s.thing, s.value, s.mode);
1258
2923
  } else if (s.source === 'property') {
1259
- for (const t of parts) putComp(s, t, camel(s.thing), s.value);
2924
+ for (const t of parts) {
2925
+ // A padding on a part whose box reads Core's padding variables is
2926
+ // resolved with the rest of that part's padding, below.
2927
+ if (padVars(t) && /^padding(-|$)/.test(kebab(s.thing))) {
2928
+ queuePadding(s, t);
2929
+ continue;
2930
+ }
2931
+ const sides =
2932
+ wrappedPadding(t, s) ??
2933
+ containerSides(t, s) ??
2934
+ cornerRadii(t, s) ??
2935
+ boxSides(t, s);
2936
+ if (sides)
2937
+ for (const [k, v] of Object.entries(sides)) {
2938
+ // A per-direction block joins what that direction already has,
2939
+ // one level deep: under a state it is the state's own key with
2940
+ // the direction after it (`:hover:dir(ltr)`), which Core writes
2941
+ // as one rule.
2942
+ if (k.startsWith(':') && typeof v === 'object') {
2943
+ const [b, key] = dirBlock(s, t, k);
2944
+ b[key] = {...(b[key] ?? {}), ...v};
2945
+ } else putComp(s, t, k, /** @type {string} */ (v));
2946
+ }
2947
+ else putComp(s, t, camel(s.thing), s.value);
2948
+ // A later padding takes out what it covers that would beat it: a
2949
+ // physical side written as it is (a group's left under a later part
2950
+ // padding; left-to-right, inline-start is the left), and a side
2951
+ // written per direction, whose :dir() rule is more specific.
2952
+ {
2953
+ const prop = kebab(s.thing);
2954
+ /** @type {Record<string, Array<'paddingLeft' | 'paddingRight'>>} */
2955
+ const COVERS = {
2956
+ padding: ['paddingLeft', 'paddingRight'],
2957
+ 'padding-inline': ['paddingLeft', 'paddingRight'],
2958
+ 'padding-inline-start': ['paddingLeft'],
2959
+ 'padding-inline-end': ['paddingRight'],
2960
+ 'padding-left': [],
2961
+ 'padding-right': [],
2962
+ };
2963
+ const plain = COVERS[prop];
2964
+ if (plain) {
2965
+ const b = block(s, t);
2966
+ // A side written per direction leaves a physical side as it is:
2967
+ // its :dir(ltr) rule already wins in a left-to-right box, and in
2968
+ // a right-to-left one the physical left is still the left.
2969
+ const perDirection =
2970
+ !!sides && Object.keys(sides).some(x => x.startsWith(':'));
2971
+ if (!perDirection)
2972
+ for (const k of plain)
2973
+ if (b[k] != null && !(sides && k in sides)) delete b[k];
2974
+ // Per direction: a whole padding or inline padding covers both
2975
+ // sides in both directions; a physical side, that side in both.
2976
+ const dirSides =
2977
+ prop === 'padding' || prop === 'padding-inline'
2978
+ ? ['paddingLeft', 'paddingRight']
2979
+ : prop === 'padding-left'
2980
+ ? ['paddingLeft']
2981
+ : prop === 'padding-right'
2982
+ ? ['paddingRight']
2983
+ : [];
2984
+ if (
2985
+ dirSides.length &&
2986
+ !(sides && Object.keys(sides).some(x => x.startsWith(':')))
2987
+ )
2988
+ for (const d of [':dir(ltr)', ':dir(rtl)']) {
2989
+ const [db, key] = dirBlock(s, t, d);
2990
+ const rule = db[key];
2991
+ if (!rule) continue;
2992
+ for (const x of dirSides) delete rule[x];
2993
+ if (!Object.keys(rule).length) delete db[key];
2994
+ }
2995
+ }
2996
+ }
2997
+ // A part's own corner radii replace a single radius a group or an
2998
+ // earlier setting left in the same block, in their own order: the
2999
+ // whole radius (which Core turns into the content's radius) before
3000
+ // the corners, which the box shows.
3001
+ if (sides && 'borderTopLeftRadius' in sides) {
3002
+ const b = block(s, t);
3003
+ for (const k of Object.keys(sides)) delete b[k];
3004
+ Object.assign(b, sides);
3005
+ }
3006
+ }
1260
3007
  }
1261
3008
  }
3009
+ emitPadding();
3010
+ orderBlocks();
1262
3011
  // Core gives headings the body font when a theme sets only the body's:
1263
3012
  // a font for the body alone keeps the base theme's heading font.
1264
3013
  if (theme.typography?.body && !theme.typography.heading) {
@@ -1268,15 +3017,6 @@ export function compileTheme(ctx, data, base) {
1268
3017
  theme.typography.heading = {family: f.family, fallbacks: f.fallbacks};
1269
3018
  }
1270
3019
  }
1271
- // A one-mode theme looks the same whatever the system asks for: every
1272
- // color the theme does not set takes its mode's value from the base (or
1273
- // Core) on both sides.
1274
- if (modeOnly)
1275
- for (const k of Object.keys(/** @type {Record<string, string>} */ (TOKENS)))
1276
- if (MODAL.has(ctx.C.typeOf(k)) && !tok[k]) {
1277
- const v = base[modeOnly]?.[k];
1278
- if (v && !/var\(/.test(v)) putTok(k, v);
1279
- }
1280
3020
  // A scale steeper or flatter than the standard one changes the headings;
1281
3021
  // the steps below the base text size keep the standard ratio, so small
1282
3022
  // text stays as it was. An exact token setting still wins.
@@ -1323,21 +3063,30 @@ export function compileTheme(ctx, data, base) {
1323
3063
  theme.tokens[k] = l === d ? l : [l, d];
1324
3064
  }
1325
3065
  // Base themes set the type tokens again for phones (a coarse pointer
1326
- // below the lg width); an exact font family is written there too, so it
1327
- // applies on every screen. Sizes are not: phones keep their reading base.
1328
- const phone = Object.fromEntries(
1329
- data.settings
3066
+ // below the lg width); an exact font family or weight, and the headings
3067
+ // dial's weights, are written there too, so they apply on every screen.
3068
+ // Sizes are not: phones keep their reading base. (What the theme's own
3069
+ // source sets is not repeated: on phones the base theme's type comes
3070
+ // back for it, by Core contract; the notes name the fix.)
3071
+ const phone = Object.fromEntries([
3072
+ ...data.settings
1330
3073
  .filter(
1331
3074
  x =>
1332
3075
  x.source === 'token' &&
1333
3076
  !x.on &&
1334
3077
  !x.mode &&
1335
- // Families only: phones keep their own reading sizes.
1336
- /^--font-family/.test(x.thing) &&
3078
+ PHONE_TYPE.test(x.thing) &&
1337
3079
  !(modeOnly && x.mode && x.mode !== modeOnly),
1338
3080
  )
1339
3081
  .map(x => [x.thing, x.value]),
1340
- );
3082
+ ]);
3083
+ // The headings dial's weights, unless an exact token sets one.
3084
+ const headingsWeight = [...data.settings]
3085
+ .reverse()
3086
+ .find(x => x.thing === 'headings' && x.axis !== 'tracking' && !x.on);
3087
+ if (headingsWeight && HEADING_WEIGHTS[headingsWeight.value])
3088
+ for (const k of headingWeightTokens)
3089
+ phone[k] ??= HEADING_WEIGHTS[headingsWeight.value];
1341
3090
  if (Object.keys(phone).length)
1342
3091
  theme.adaptations = {
1343
3092
  rules: [
@@ -1367,9 +3116,10 @@ const SMALL_STEPS = /** @type {Array<[string, number]>} */ ([
1367
3116
  * Settings whose effect a later or stronger setting hides, with why: `type`
1368
3117
  * loses heading weight and tracking to `headings`.
1369
3118
  * @param {ThemeData} data
3119
+ * @param {Ctx | null} [ctx] with it, a later setting that reaches the parts through a spread counts too
1370
3120
  * @returns {Map<Setting, string>}
1371
3121
  */
1372
- export function maskedSettings(data) {
3122
+ export function maskedSettings(data, ctx = null) {
1373
3123
  /** @type {Map<Setting, string>} */
1374
3124
  const out = new Map();
1375
3125
  const axes = new Set(
@@ -1409,6 +3159,37 @@ export function maskedSettings(data) {
1409
3159
  `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
1410
3160
  );
1411
3161
  });
3162
+ // With the parts known: a later setting of the same thing that reaches
3163
+ // every part an earlier one styles (a member that spreads to its group,
3164
+ // the same part without --only), dial or CSS property, covers it too.
3165
+ if (ctx)
3166
+ data.settings.forEach((s, i) => {
3167
+ if (
3168
+ out.has(s) ||
3169
+ !s.on ||
3170
+ (s.source !== 'dial' && s.source !== 'property')
3171
+ )
3172
+ return;
3173
+ const mine = partsOf(ctx, s);
3174
+ if (!mine.length) return;
3175
+ const later = data.settings
3176
+ .slice(i + 1)
3177
+ .find(
3178
+ x =>
3179
+ x.thing === s.thing &&
3180
+ x.source === s.source &&
3181
+ x.on &&
3182
+ (x.when ?? '') === (s.when ?? '') &&
3183
+ (x.state ?? '') === (s.state ?? '') &&
3184
+ (x.mode ?? '') === (s.mode ?? '') &&
3185
+ mine.every(t => partsOf(ctx, x).includes(t)),
3186
+ );
3187
+ if (later)
3188
+ out.set(
3189
+ s,
3190
+ `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
3191
+ );
3192
+ });
1412
3193
  for (const s of data.settings) {
1413
3194
  if (s.thing !== 'type' || !axes.size) continue;
1414
3195
  const T = TYPE_STYLES[s.value];
@@ -1448,16 +3229,13 @@ export function findOverrides(cssText, theme) {
1448
3229
  'g',
1449
3230
  );
1450
3231
  // A shorthand and its longhands are one property: the last one set
1451
- // (background after background-color) is the one in effect.
1452
- // border-radius, border-collapse and border-spacing are not part of
1453
- // border.
1454
- const NOT_LONGHAND =
1455
- /^border-(radius|collapse|spacing)|^border-[a-z]+-radius$/;
3232
+ // (background after background-color) is the one in effect. Which
3233
+ // longhands a shorthand sets is MDN's data (background-blend-mode is
3234
+ // no part of background).
1456
3235
  /** @param {string} a @param {string} b */
1457
3236
  const sameProperty = (a, b) => {
1458
3237
  const [x, y] = [kebab(a), kebab(b)];
1459
- if (NOT_LONGHAND.test(x) || NOT_LONGHAND.test(y)) return x === y;
1460
- return x.startsWith(`${y}-`) || y.startsWith(`${x}-`) || x === y;
3238
+ return x === y || coversProperty(x, y) || coversProperty(y, x);
1461
3239
  };
1462
3240
  const last = props.filter(
1463
3241
  (p, i) => !props.slice(i + 1).some(later => sameProperty(later, p)),
@@ -1514,22 +3292,11 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1514
3292
  ? `${REF}${r.family}`
1515
3293
  : `${REF}${r.family ?? family}.${m}.${r.stop}${r.alpha ? `+${r.alpha}` : ''}`;
1516
3294
  const out = {...theme, name: `${slug}-settings`};
1517
- const only =
1518
- data.mode === 'light-only'
1519
- ? 'light'
1520
- : data.mode === 'dark-only'
1521
- ? 'dark'
1522
- : null;
3295
+ // A one-mode theme keeps both halves too (see compileTheme).
1523
3296
  if (pal && theme.tokens) {
1524
3297
  out.tokens = {...theme.tokens};
1525
3298
  for (const [k, v] of Object.entries(pal.tokens)) {
1526
3299
  const now = theme.tokens[k];
1527
- // A one-mode theme reads one shade, its mode's, on both sides.
1528
- if (only) {
1529
- if (now === v[only].color)
1530
- out.tokens[k] = refOf(v.family, only, v[only]);
1531
- continue;
1532
- }
1533
3300
  const [l, d] = Array.isArray(now) ? now : [now, now];
1534
3301
  if (l !== v.light.color || d !== v.dark.color) continue;
1535
3302
  out.tokens[k] = [
@@ -1544,15 +3311,13 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1544
3311
  for (const [target, key, ground] of LIFT_PARTS) {
1545
3312
  const lift = pal.lift[ground];
1546
3313
  if (!lift) continue;
1547
- const literal = liftValue(lift, only);
3314
+ const literal = liftValue(lift, null);
1548
3315
  /** A shade of the neutral palette as a reference; a color as it is. @param {'light' | 'dark'} m */
1549
3316
  const one = m => {
1550
3317
  const r = /** @type {any} */ (lift[m]);
1551
3318
  return r.family === 'literal' ? r.color : refOf('neutral', m, r);
1552
3319
  };
1553
- const refs = only
1554
- ? one(only)
1555
- : `light-dark(${one('light')}, ${one('dark')})`;
3320
+ const refs = `light-dark(${one('light')}, ${one('dark')})`;
1556
3321
  const block = out.components[target]?.[key];
1557
3322
  if (block?.['--color-text-secondary'] !== literal) continue;
1558
3323
  out.components[target] = {
@@ -1592,6 +3357,12 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1592
3357
  [
1593
3358
  `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
1594
3359
  `// Built from settings ${settingsStamp(data)}.`,
3360
+ // The theme source as it is when the build starts (the editor's
3361
+ // own when the build writes it), so an own change to it after the
3362
+ // build is told by content.
3363
+ ...(cwd
3364
+ ? [`// Built with ${slug}.theme.ts ${themeSourceHash(cwd, slug)}.`]
3365
+ : []),
1595
3366
  ...(like && cwd
1596
3367
  ? [
1597
3368
  `// Built on @astryxdesign/theme-${like} ${baseVersionOf(cwd, like) ?? 'unknown'}.`,
@@ -1615,6 +3386,130 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1615
3386
  );
1616
3387
  }
1617
3388
 
3389
+ /**
3390
+ * A hash of a theme's source file as the next build reads it: the file, or
3391
+ * the source the editor writes when there is none.
3392
+ * @param {string} cwd
3393
+ * @param {string} slug
3394
+ */
3395
+ function themeSourceHash(cwd, slug) {
3396
+ const f = themeFiles(cwd, slug);
3397
+ const hash = createHash('sha256');
3398
+ if (!fs.existsSync(f.ts)) {
3399
+ // The same as the file the build is about to write would hash.
3400
+ hash.update(`${path.basename(f.ts)}\0`);
3401
+ hash.update(themeModuleSource(slug));
3402
+ return hash.digest('hex').slice(0, 16);
3403
+ }
3404
+ for (const file of ownSourceFiles(cwd, slug)) {
3405
+ hash.update(`${path.relative(f.dir, file)}\0`);
3406
+ hash.update(fs.readFileSync(file));
3407
+ }
3408
+ return hash.digest('hex').slice(0, 16);
3409
+ }
3410
+
3411
+ /**
3412
+ * The theme source and every local module it reaches (an own helper such
3413
+ * as ./my-tokens), read the way theme discovery reads them: the person's
3414
+ * files. The editor's generated modules change with each build and are
3415
+ * judged by their own stamps.
3416
+ * @param {string} cwd
3417
+ * @param {string} slug
3418
+ * @returns {string[]}
3419
+ */
3420
+ function ownSourceFiles(cwd, slug) {
3421
+ const f = themeFiles(cwd, slug);
3422
+ if (!fs.existsSync(f.ts)) return [];
3423
+ const generated = new Set([f.settingsTs]);
3424
+ const seen = new Set();
3425
+ /** @type {string[]} */
3426
+ const files = [];
3427
+ const queue = [f.ts];
3428
+ while (queue.length) {
3429
+ const file = /** @type {string} */ (queue.shift());
3430
+ if (seen.has(file)) continue;
3431
+ seen.add(file);
3432
+ files.push(file);
3433
+ /** @type {string[]} */
3434
+ let specifiers = [];
3435
+ try {
3436
+ specifiers = themeFileImports(file, {withRequire: true});
3437
+ } catch {
3438
+ // A file that does not parse is hashed as it is; the build names it.
3439
+ }
3440
+ for (const spec of specifiers) {
3441
+ if (!spec.startsWith('.')) continue;
3442
+ const target = localModuleFile(path.dirname(file), spec);
3443
+ // Only the editor's own generated palette files are judged by their
3444
+ // stamps; any other file the theme reaches, in tokens/ too, is the
3445
+ // person's.
3446
+ if (
3447
+ target &&
3448
+ !generated.has(target) &&
3449
+ !isGeneratedPaletteFile(f.dir, slug, target)
3450
+ )
3451
+ queue.push(target);
3452
+ }
3453
+ }
3454
+ return files;
3455
+ }
3456
+
3457
+ /** The extensions a theme's local module may have, as the build reads them. */
3458
+ const MODULE_EXTENSIONS = [
3459
+ '.ts',
3460
+ '.tsx',
3461
+ '.mts',
3462
+ '.cts',
3463
+ '.js',
3464
+ '.jsx',
3465
+ '.mjs',
3466
+ '.cjs',
3467
+ ];
3468
+
3469
+ /**
3470
+ * The file a relative import names, resolved as TypeScript resolves it: a
3471
+ * JavaScript extension names its TypeScript source (`.js` → `.ts`/`.tsx`,
3472
+ * `.jsx` → `.tsx`, `.mjs` → `.mts`, `.cjs` → `.cts`), then the path as
3473
+ * written, with each module extension, and as a folder's index file.
3474
+ * @param {string} dir
3475
+ * @param {string} spec
3476
+ * @returns {string | undefined}
3477
+ */
3478
+ function localModuleFile(dir, spec) {
3479
+ const base = path.resolve(dir, spec);
3480
+ const ext = path.extname(base);
3481
+ const stem = base.slice(0, base.length - ext.length);
3482
+ const sourceFor = /** @type {Record<string, string[]>} */ ({
3483
+ '.js': ['.ts', '.tsx'],
3484
+ '.jsx': ['.tsx'],
3485
+ '.mjs': ['.mts'],
3486
+ '.cjs': ['.cts'],
3487
+ })[ext];
3488
+ return [
3489
+ ...(sourceFor ?? []).map(x => stem + x),
3490
+ base,
3491
+ ...MODULE_EXTENSIONS.map(x => base + x),
3492
+ ...MODULE_EXTENSIONS.map(x => path.join(base, `index${x}`)),
3493
+ ].find(p => fs.existsSync(p) && fs.statSync(p).isFile());
3494
+ }
3495
+
3496
+ /**
3497
+ * Whether a file is one of the palette files the editor generates in a
3498
+ * theme's tokens/ folder (`tokens/<slug>.palette*`).
3499
+ * @param {string} dir the theme folder
3500
+ * @param {string} slug
3501
+ * @param {string} file
3502
+ */
3503
+ function isGeneratedPaletteFile(dir, slug, file) {
3504
+ const rel = path.relative(path.join(dir, 'tokens'), file);
3505
+ return (
3506
+ !rel.startsWith('..') &&
3507
+ !path.isAbsolute(rel) &&
3508
+ !rel.includes(path.sep) &&
3509
+ rel.startsWith(`${slug}.palette`)
3510
+ );
3511
+ }
3512
+
1618
3513
  /**
1619
3514
  * The theme module, written once: it extends the generated settings and is
1620
3515
  * the person's own from then on, so hand edits in it survive every change.
@@ -1666,6 +3561,52 @@ export function themeSourceProblem(cwd, slug) {
1666
3561
  return null;
1667
3562
  }
1668
3563
 
3564
+ /**
3565
+ * Why the person's own theme source does not parse (its line and the
3566
+ * parser's message), or null when it parses or is not there.
3567
+ * @param {string} cwd
3568
+ * @param {string} slug
3569
+ * @returns {string | null}
3570
+ */
3571
+ export function themeSourceParseError(cwd, slug) {
3572
+ const f = themeFiles(cwd, slug);
3573
+ let code;
3574
+ try {
3575
+ code = fs.readFileSync(f.ts, 'utf8');
3576
+ } catch {
3577
+ return null;
3578
+ }
3579
+ try {
3580
+ parseModule(code, {sourceType: 'module', plugins: ['typescript']});
3581
+ return null;
3582
+ } catch (e) {
3583
+ const err = /** @type {any} */ (e);
3584
+ return `${slug}.theme.ts does not parse${err?.loc?.line ? ` (line ${err.loc.line})` : ''}: ${String(err?.message ?? e).replace(/\s*\(\d+:\d+\)\s*$/, '')}`;
3585
+ }
3586
+ }
3587
+
3588
+ /**
3589
+ * Refuse, before anything is written or removed, a command whose build
3590
+ * would load the person's own theme source when it does not parse: the
3591
+ * build would fail part way.
3592
+ * @param {string} cwd
3593
+ * @param {string} slug
3594
+ */
3595
+ export function refuseThemeParse(cwd, slug) {
3596
+ const why = themeSourceParseError(cwd, slug);
3597
+ if (why)
3598
+ throw new AstryxError(
3599
+ `${why}, so the theme cannot build. It is your own file: fix it, then run the command again. Nothing was changed.`,
3600
+ [
3601
+ {
3602
+ name: `cat ${path.posix.join('themes', slug, `${slug}.theme.ts`)}`,
3603
+ reason: 'see the file',
3604
+ },
3605
+ ],
3606
+ ERROR_CODES.ERR_THEME_INVALID,
3607
+ );
3608
+ }
3609
+
1669
3610
  /**
1670
3611
  * Refuse a build whose theme source cannot carry the settings, naming the
1671
3612
  * lines that put it back.
@@ -1673,6 +3614,7 @@ export function themeSourceProblem(cwd, slug) {
1673
3614
  * @param {string} slug
1674
3615
  */
1675
3616
  export function refuseThemeSource(cwd, slug) {
3617
+ refuseThemeParse(cwd, slug);
1676
3618
  const why = themeSourceProblem(cwd, slug);
1677
3619
  if (why)
1678
3620
  throw new AstryxError(
@@ -1682,6 +3624,162 @@ export function refuseThemeSource(cwd, slug) {
1682
3624
  );
1683
3625
  }
1684
3626
 
3627
+ /**
3628
+ * Refuse a [light, dark] pair the theme's own source gives a token that is
3629
+ * not a color (a font family, a size, a weight): the build would write
3630
+ * `light-dark()`, which browsers take only for colors. The editor refuses
3631
+ * `--mode` on those tokens for the same reason.
3632
+ * @param {Ctx} ctx
3633
+ * @param {string} cwd
3634
+ * @param {string} slug
3635
+ */
3636
+ function refuseOwnPairs(ctx, cwd, slug) {
3637
+ const f = themeFiles(cwd, slug);
3638
+ /** @type {string[]} */
3639
+ const bad = [];
3640
+ try {
3641
+ const ast = /** @type {any} */ (
3642
+ parseModule(fs.readFileSync(f.ts, 'utf8'), {
3643
+ sourceType: 'module',
3644
+ plugins: ['typescript'],
3645
+ })
3646
+ );
3647
+ /** @param {any} node */
3648
+ const visit = node => {
3649
+ if (!node || typeof node !== 'object') return;
3650
+ if (
3651
+ node.type === 'ObjectProperty' &&
3652
+ typeof (node.key?.value ?? node.key?.name) === 'string' &&
3653
+ String(node.key?.value ?? node.key?.name).startsWith('--') &&
3654
+ node.value?.type === 'ArrayExpression' &&
3655
+ node.value.elements.length === 2 &&
3656
+ // A pair holding a value that is not text is named by the value
3657
+ // checks, with the fix for that value.
3658
+ node.value.elements.every(
3659
+ (/** @type {any} */ e) =>
3660
+ e?.type === 'StringLiteral' || e?.type === 'TemplateLiteral',
3661
+ )
3662
+ ) {
3663
+ const k = String(node.key.value ?? node.key.name);
3664
+ const type = ctx.C.typeOf(k);
3665
+ // A size given as a bare number is named by the value check, with
3666
+ // the unit it needs.
3667
+ const unitless =
3668
+ type === 'size' &&
3669
+ node.value.elements.some(
3670
+ (/** @type {any} */ e) =>
3671
+ e?.type === 'StringLiteral' && /^\d*\.?\d+$/.test(e.value.trim()),
3672
+ );
3673
+ if (type !== 'color' && !unitless) bad.push(k);
3674
+ }
3675
+ for (const v of Object.values(node))
3676
+ if (Array.isArray(v)) v.forEach(visit);
3677
+ else if (v && typeof v === 'object' && v.type) visit(v);
3678
+ };
3679
+ visit(ast.program);
3680
+ } catch {
3681
+ return;
3682
+ }
3683
+ if (bad.length)
3684
+ throw new AstryxError(
3685
+ ownPairMessage(slug, [...new Set(bad)]),
3686
+ [
3687
+ {
3688
+ name: `grep -n -- ${quoteCommandArgument(bad[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
3689
+ reason: 'see the line',
3690
+ },
3691
+ ],
3692
+ ERROR_CODES.ERR_THEME_INVALID,
3693
+ );
3694
+ }
3695
+
3696
+ /**
3697
+ * The tokens that are not colors the theme as it builds now gives a
3698
+ * [light, dark] pair (light-dark()), however its file writes them (a
3699
+ * constant, `as const`, `satisfies`, a spread from an imported module):
3700
+ * read from a build made into the project's cache folder, never beside the
3701
+ * theme. Empty when it does not build there (the build names that itself).
3702
+ * @param {Ctx} ctx
3703
+ * @param {string} slug
3704
+ * @returns {Promise<string[]>}
3705
+ */
3706
+ export async function builtPairs(ctx, slug) {
3707
+ const {cwd} = ctx.project;
3708
+ const f = themeFiles(cwd, slug);
3709
+ // The build writes only inside the project: the cache folder when it is
3710
+ // there, else a hidden folder in the theme's (removed after).
3711
+ const name = `.${slug}.pairs-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
3712
+ const inside = !path.relative(cwd, ctx.project.cacheDir).startsWith('..');
3713
+ const dir = path.join(inside ? ctx.project.cacheDir : f.dir, name);
3714
+ const silent = logger.silent;
3715
+ logger.setSilent(true);
3716
+ try {
3717
+ fs.mkdirSync(dir, {recursive: true});
3718
+ await themeBuildForReport(
3719
+ shown(cwd, f.ts),
3720
+ {out: path.relative(cwd, path.join(dir, `${slug}.css`))},
3721
+ {cwd},
3722
+ {compact: true},
3723
+ );
3724
+ const js = fs
3725
+ .readdirSync(dir)
3726
+ .find(n => n.endsWith('.js') && !n.endsWith('.d.js'));
3727
+ if (!js) return [];
3728
+ return [...topTokensOf(path.join(dir, js))]
3729
+ .filter(
3730
+ ([k, v]) =>
3731
+ /^light-dark\(/.test(String(v ?? '')) && ctx.C.typeOf(k) !== 'color',
3732
+ )
3733
+ .map(([k]) => k);
3734
+ } catch {
3735
+ return [];
3736
+ } finally {
3737
+ logger.setSilent(silent);
3738
+ fs.rmSync(dir, {recursive: true, force: true});
3739
+ }
3740
+ }
3741
+
3742
+ /**
3743
+ * The refusal of a [light, dark] pair on tokens that are not colors.
3744
+ * @param {string} slug
3745
+ * @param {string[]} names
3746
+ */
3747
+ export function ownPairMessage(slug, names) {
3748
+ return `themes/${slug}/${slug}.theme.ts gives ${names.join(', ')} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors. Give ${names.length > 1 ? 'each' : 'it'} one value in ${slug}.theme.ts. Nothing was changed.`;
3749
+ }
3750
+
3751
+ /**
3752
+ * What runs after every build of a theme, set by the adapter (the app copy
3753
+ * of the theme): null until it is set.
3754
+ * @type {((ctx: Ctx, slug: string, data: ThemeData) => void) | null}
3755
+ */
3756
+ let afterBuild = null;
3757
+
3758
+ /**
3759
+ * Set what runs after every build of a theme.
3760
+ * @param {((ctx: Ctx, slug: string, data: ThemeData) => void) | null} fn
3761
+ */
3762
+ export function setAfterBuild(fn) {
3763
+ afterBuild = fn;
3764
+ }
3765
+
3766
+ /**
3767
+ * Builds whose after-build hook waits for the change to be saved: a change
3768
+ * that fails after its build puts its theme folder back, and its app copy
3769
+ * was never written.
3770
+ * @type {WeakSet<Ctx>}
3771
+ */
3772
+ const afterSave = new WeakSet();
3773
+
3774
+ /**
3775
+ * Hold the after-build hook for this command's builds: the command writes
3776
+ * the app copy itself once it succeeds (show).
3777
+ * @param {Ctx} ctx
3778
+ */
3779
+ export function holdAfterBuild(ctx) {
3780
+ afterSave.add(ctx);
3781
+ }
3782
+
1685
3783
  /**
1686
3784
  * Generate the theme source, build it with the theme build, then repeat any
1687
3785
  * part setting a more specific rule would beat and build again.
@@ -1694,6 +3792,7 @@ export async function buildTheme(ctx, slug, data) {
1694
3792
  const {cwd} = ctx.project;
1695
3793
  const f = themeFiles(cwd, slug);
1696
3794
  refuseThemeSource(cwd, slug);
3795
+ refuseOwnPairs(ctx, cwd, slug);
1697
3796
  if (data.like) baseThemeFile(ctx.project, data.like);
1698
3797
  const base = await baseResolved(ctx.project, data.like);
1699
3798
  fs.mkdirSync(f.dir, {recursive: true});
@@ -1737,23 +3836,26 @@ export async function buildTheme(ctx, slug, data) {
1737
3836
  if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
1738
3837
  });
1739
3838
  // Files an earlier build wrote that this one may not: the variants types
1740
- // of an older base, and section sheets of an older look.
3839
+ // of an older base, and the pictures the editor took of an older look.
3840
+ // Only a picture the editor recorded writing, unchanged since, goes: a
3841
+ // file of the user's is never touched. Section sheets stay, marked as
3842
+ // out of date like sheet.html.
1741
3843
  await step(() => {
3844
+ const pictures = fs.existsSync(f.dir)
3845
+ ? fs
3846
+ .readdirSync(f.dir)
3847
+ .filter(
3848
+ n =>
3849
+ /^(sheet|preview)(-[a-z-]+)?\.png$/.test(n) &&
3850
+ editorWrote(cwd, slug, path.join(f.dir, n)),
3851
+ )
3852
+ : [];
1742
3853
  for (const file of [
1743
3854
  path.join(f.dir, `${slug}.variants.d.ts`),
1744
- ...(fs.existsSync(f.dir)
1745
- ? fs
1746
- .readdirSync(f.dir)
1747
- // Section sheets, and every picture: all show the look before
1748
- // this build. The full sheet and the preview page are written
1749
- // again by the commands that make them.
1750
- .filter(n =>
1751
- /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
1752
- )
1753
- .map(n => path.join(f.dir, n))
1754
- : []),
3855
+ ...pictures.map(n => path.join(f.dir, n)),
1755
3856
  ])
1756
3857
  fs.rmSync(file, {force: true});
3858
+ forgetWritten(cwd, slug, pictures);
1757
3859
  });
1758
3860
  let receipt = await step(() => runBuild(ctx, slug));
1759
3861
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
@@ -1764,7 +3866,16 @@ export async function buildTheme(ctx, slug, data) {
1764
3866
  if (found.length) {
1765
3867
  for (const x of found) {
1766
3868
  const t = theme.components[x.target];
1767
- (t[x.key] ??= {})[x.prop] ??= x.value;
3869
+ // The base value goes before the variant's own declarations, so a
3870
+ // longhand or shorthand the variant sets itself (border-color after
3871
+ // a base border) still wins over it.
3872
+ const own = t[x.key] ?? {};
3873
+ // A variant that sets every longhand of the property itself needs
3874
+ // none of the base value (and a lifted radius would feed Core's copy
3875
+ // of it into the content's radius, after the variant's own).
3876
+ const longs = [...longhandsOf(kebab(x.prop))];
3877
+ if (longs.length && longs.every(l => camel(l) in own)) continue;
3878
+ t[x.key] = {[x.prop]: x.value, ...own};
1768
3879
  lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
1769
3880
  }
1770
3881
  await step(() => {
@@ -1783,6 +3894,12 @@ export async function buildTheme(ctx, slug, data) {
1783
3894
  ]
1784
3895
  .map(String)
1785
3896
  .filter(w => !/^Font "/.test(w));
3897
+ // The app's copy, a standard local theme `theme add` reads, follows the
3898
+ // build (written by the hook the adapter sets: it owns that write).
3899
+ if (afterBuild && !afterSave.has(ctx))
3900
+ await step(() => {
3901
+ afterBuild?.(ctx, slug, data);
3902
+ });
1786
3903
  return {warnings, lifted, notes};
1787
3904
  }
1788
3905
 
@@ -1808,6 +3925,46 @@ async function runBuild(ctx, slug) {
1808
3925
  }
1809
3926
  }
1810
3927
 
3928
+ /**
3929
+ * Why the built outputs differ from what the theme builds now: one that is
3930
+ * missing or changed by hand, found the way `compile --check` finds it
3931
+ * (the same build, compared and not written), or null when they match.
3932
+ * @param {Ctx} ctx
3933
+ * @param {string} slug
3934
+ * @returns {Promise<string | null>}
3935
+ */
3936
+ export async function outputsDrift(ctx, slug) {
3937
+ const {cwd} = ctx.project;
3938
+ const f = themeFiles(cwd, slug);
3939
+ const silent = logger.silent;
3940
+ logger.setSilent(true);
3941
+ try {
3942
+ const {receipt} = await themeBuildForReport(
3943
+ shown(cwd, f.ts),
3944
+ {check: true},
3945
+ {cwd},
3946
+ {compact: true},
3947
+ );
3948
+ const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
3949
+ if (!first) return null;
3950
+ const name = path.basename(String(first.path));
3951
+ return first.reason === 'missing'
3952
+ ? `${name} was missing`
3953
+ : `${name} differs from what the settings build, after an edit by hand or by another tool`;
3954
+ } catch (e) {
3955
+ // A theme source that does not load is named by its own checks; any
3956
+ // other failure means the outputs could not be compared: built again.
3957
+ const err = /** @type {any} */ (e);
3958
+ if (err instanceof AstryxError && err.code === ERROR_CODES.ERR_THEME_LOAD)
3959
+ return null;
3960
+ return `the outputs could not be checked (${String(err?.message ?? e)
3961
+ .split('\n')[0]
3962
+ .slice(0, 160)})`;
3963
+ } finally {
3964
+ logger.setSilent(silent);
3965
+ }
3966
+ }
3967
+
1811
3968
  /**
1812
3969
  * Resolved tokens of the built theme in both modes.
1813
3970
  * @param {Ctx} ctx
@@ -1855,10 +4012,41 @@ export async function resolvedTokens(ctx, slug) {
1855
4012
  v => v && typeof v === 'object' && typeof v.name === 'string',
1856
4013
  );
1857
4014
  const {core} = ctx.project;
1858
- const out = {
1859
- light: core.resolveThemeTokens(t, {mode: 'light'}),
1860
- dark: core.resolveThemeTokens(t, {mode: 'dark'}),
4015
+ // A token value an own theme source gives as a number (8 for 8px)
4016
+ // reads as its text, never as a crash.
4017
+ const asText = (/** @type {Record<string, unknown>} */ m) =>
4018
+ Object.fromEntries(
4019
+ Object.entries(m ?? {}).map(([k, v]) => [
4020
+ k,
4021
+ typeof v === 'string' ? v : String(v),
4022
+ ]),
4023
+ );
4024
+ // A token value that is not text (a number in an own theme source) is
4025
+ // named, never a crash.
4026
+ const resolve = (/** @type {'light' | 'dark'} */ mode) => {
4027
+ try {
4028
+ return asText(core.resolveThemeTokens(t, {mode}));
4029
+ } catch (e) {
4030
+ const bad = nonTextToken(t, ctx.C.typeOf);
4031
+ throw new AstryxError(
4032
+ bad
4033
+ ? nonTextMessage(ctx, slug, bad)
4034
+ : `${slug} could not be read: ${e instanceof Error ? e.message : String(e)}.`,
4035
+ [{name: `${P} how --list tokens`, reason: 'every token and its type'}],
4036
+ ERROR_CODES.ERR_THEME_INVALID,
4037
+ );
4038
+ }
1861
4039
  };
4040
+ // A pair that holds a value that is not text ([8, 8]) resolves, but
4041
+ // builds nothing a browser reads: named the same way.
4042
+ const pairBad = nonTextToken(t, ctx.C.typeOf);
4043
+ if (pairBad)
4044
+ throw new AstryxError(
4045
+ nonTextMessage(ctx, slug, pairBad),
4046
+ [{name: `${P} how --list tokens`, reason: 'every token and its type'}],
4047
+ ERROR_CODES.ERR_THEME_INVALID,
4048
+ );
4049
+ const out = {light: resolve('light'), dark: resolve('dark')};
1862
4050
  // The tokens each part sets for itself (the official themes lift
1863
4051
  // secondary text on some parts), for the contrast check; kept out of the
1864
4052
  // modes so nothing that lists the resolved tokens sees it.
@@ -1873,6 +4061,96 @@ export async function resolvedTokens(ctx, slug) {
1873
4061
  return out;
1874
4062
  }
1875
4063
 
4064
+ /**
4065
+ * The first token a built theme gives a value that is not text, alone or
4066
+ * in a [light, dark] pair, or null.
4067
+ * @param {any} t
4068
+ * @param {(name: string) => string} [typeOf] a token's type (size, color…)
4069
+ * @returns {[string, unknown, 'object' | 'pair' | 'unit' | 'value' | 'mode'] | null}
4070
+ */
4071
+ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4072
+ for (const [k, raw] of Object.entries(t?.tokens ?? {})) {
4073
+ // An object ({light, dark}) is not a value Core builds: it would write
4074
+ // [object Object].
4075
+ if (raw && typeof raw === 'object' && !Array.isArray(raw))
4076
+ return [k, raw, 'object'];
4077
+ // A built theme writes a pair as light-dark(). A half that was not text
4078
+ // comes out as nothing, null or a boolean; a bare number is text the
4079
+ // source may have quoted, and is wrong only for a size, which needs a
4080
+ // unit.
4081
+ const pair =
4082
+ typeof raw === 'string' ? /^light-dark\((.*)\)$/s.exec(raw.trim()) : null;
4083
+ // Split at the top-level comma: a half may hold commas (rgb(0, 0, 0)).
4084
+ const parts = pair ? splitTop(pair[1], ',').map(x => x.trim()) : [];
4085
+ if (pair && parts.length === 2) {
4086
+ const halves = parts;
4087
+ const missing = halves.some(x =>
4088
+ /^(|null|undefined|true|false)$/.test(x),
4089
+ );
4090
+ const unitless =
4091
+ typeOf(k) === 'size' &&
4092
+ halves.some(x => /^-?\d+(\.\d+)?$/.test(x) && Number(x) !== 0);
4093
+ if (missing || unitless) {
4094
+ const half = (/** @type {string} */ x) =>
4095
+ /^-?\d+(\.\d+)?$/.test(x)
4096
+ ? Number(x)
4097
+ : x === '' || x === 'undefined' || x === 'null'
4098
+ ? null
4099
+ : x === 'true' || x === 'false'
4100
+ ? x === 'true'
4101
+ : x;
4102
+ return [k, [half(parts[0]), half(parts[1])], missing ? 'pair' : 'unit'];
4103
+ }
4104
+ // light-dark() takes only colors: a pair on any other token (a size,
4105
+ // a font, a shadow) is dropped by the browser, however the theme
4106
+ // file wrote it (a constant, `as const`, an imported module).
4107
+ if (typeOf(k) !== 'color') return [k, parts, 'mode'];
4108
+ continue;
4109
+ }
4110
+ if (Array.isArray(raw)) {
4111
+ if (raw.length !== 2 || raw.some(x => typeof x !== 'string'))
4112
+ return [k, raw, 'pair'];
4113
+ if (typeOf(k) !== 'color') return [k, raw, 'mode'];
4114
+ continue;
4115
+ }
4116
+ if (typeof raw !== 'string') return [k, raw, 'value'];
4117
+ }
4118
+ return null;
4119
+ }
4120
+
4121
+ /**
4122
+ * Why a token value is not one, with a value of the token's own type to
4123
+ * write instead (a size in px, a weight as a number in quotes), or none.
4124
+ * @param {Ctx} ctx
4125
+ * @param {string} slug
4126
+ * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value' | 'mode')?]} bad
4127
+ */
4128
+ function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4129
+ const type = ctx.C.typeOf(name);
4130
+ if (kind === 'mode') return ownPairMessage(slug, [name]);
4131
+ if (kind === 'object')
4132
+ return `${slug}.theme.ts gives ${name} an object (${JSON.stringify(value)}); a token value is a CSS value in quotes, such as '8px' (only a color takes a [light, dark] pair).`;
4133
+ if (kind === 'unit') {
4134
+ const n = /** @type {unknown[]} */ (value).find(
4135
+ x => typeof x === 'number' && x !== 0,
4136
+ );
4137
+ return `${slug}.theme.ts gives ${name}, a size, a [light, dark] pair with a number without a unit (${/** @type {unknown[]} */ (value).join(', ')}); a size needs one, and is the same in light and dark, so give one value, such as '${n}px'.`;
4138
+ }
4139
+ const one = Array.isArray(value)
4140
+ ? value.find(x => typeof x !== 'string')
4141
+ : value;
4142
+ const example =
4143
+ typeof one === 'number'
4144
+ ? type === 'size'
4145
+ ? `'${one}px'`
4146
+ : `'${one}'`
4147
+ : null;
4148
+ const shape = Array.isArray(value)
4149
+ ? 'a [light, dark] pair of two CSS values in quotes'
4150
+ : 'a CSS value in quotes';
4151
+ return `${slug}.theme.ts gives ${name} the value ${JSON.stringify(value)}, which is not text: a token value is ${shape}${example ? ` (such as ${Array.isArray(value) ? `[${example}, ${example}]` : example})` : ''}.`;
4152
+ }
4153
+
1876
4154
  /**
1877
4155
  * Contrast problems this theme caused: text below 4.5:1 that was not as low
1878
4156
  * in the base theme. A part's own color or background setting, or a token
@@ -2050,7 +4328,7 @@ export async function contrastProblems(ctx, data, res) {
2050
4328
  })(),
2051
4329
  ...(unchecked.length
2052
4330
  ? [
2053
- `not checked: text on or in ${unchecked.slice(0, 3).join(', ')}${unchecked.length > 3 ? ` and ${unchecked.length - 3} more` : ''}, which ${unchecked.length === 1 ? 'is' : 'are'} not a fixed color`,
4331
+ `not checked: text on or in ${unchecked.slice(0, 3).join(', ')}${unchecked.length > 3 ? ` and ${unchecked.length - 3} more` : ''}, which the editor cannot read as one fixed color`,
2054
4332
  ]
2055
4333
  : []),
2056
4334
  ];
@@ -2118,7 +4396,9 @@ export function baseComponent(base, ctx, target, prop, s) {
2118
4396
  const states = ctx.project.target.get(target)?.states ?? [];
2119
4397
  b = states.includes(s.state)
2120
4398
  ? t[s.when == null ? s.state : `${s.when}+${s.state}`]
2121
- : (b?.[stateKey(s.state)] ?? b?.[`:${s.state}`]);
4399
+ : (b?.[stateKey(s.state, wrapsOneControl(ctx, target))] ??
4400
+ b?.[stateKey(s.state)] ??
4401
+ b?.[`:${s.state}`]);
2122
4402
  }
2123
4403
  const v = b?.[prop];
2124
4404
  return typeof v === 'string' ? v : null;
@@ -2184,15 +4464,64 @@ export function clearNewMarker(dir) {
2184
4464
 
2185
4465
  /**
2186
4466
  * The pseudo key a state writes in a part's styles. Core marks a disabled
2187
- * button, link, tab or menu item with aria-disabled (it stays focusable),
2188
- * and its own styles match both forms: so does the theme.
4467
+ * button, link or tab with aria-disabled (it stays focusable). A form
4468
+ * control styled on a wrapper (a typeahead, a complex selector) has its
4469
+ * input or button inside marked, so it also matches a disabled form
4470
+ * control inside it (never a list row); an action part that holds
4471
+ * children (a button group, a segmented control) never does, so one
4472
+ * disabled child never makes the whole part look disabled.
2189
4473
  * @param {string} state
4474
+ * @param {boolean} [wrapsControl]
2190
4475
  * @returns {string}
2191
4476
  */
2192
- export function stateKey(state) {
2193
- return state === 'disabled'
2194
- ? ':is(:disabled,[aria-disabled="true"])'
2195
- : `:${state}`;
4477
+ export function stateKey(state, wrapsControl = false) {
4478
+ if (state !== 'disabled') return `:${state}`;
4479
+ return wrapsControl
4480
+ ? ':is(:disabled,[aria-disabled="true"],:has(:is(input,button,select,textarea):is(:disabled,[aria-disabled="true"])))'
4481
+ : ':is(:disabled,[aria-disabled="true"])';
4482
+ }
4483
+
4484
+ /**
4485
+ * The component docs of a part: its own component's, and the one named like
4486
+ * the part (tab is Tab, under TabList), each with its name, for the ones the
4487
+ * project has.
4488
+ * @param {Ctx} ctx
4489
+ * @param {string} part
4490
+ * @returns {Array<{name: string, doc: any}>}
4491
+ */
4492
+ export function partComponentDocs(ctx, part) {
4493
+ const comps = /** @type {Record<string, any>} */ (
4494
+ ctx.project.components ?? {}
4495
+ );
4496
+ const pascal = part.replace(/(^|-)([a-z0-9])/g, (_, __, c) =>
4497
+ c.toUpperCase(),
4498
+ );
4499
+ return [ctx.project.target.get(part)?.component, pascal]
4500
+ .filter(n => n != null && comps[n])
4501
+ .map(n => ({
4502
+ name: /** @type {string} */ (n),
4503
+ doc: comps[/** @type {string} */ (n)],
4504
+ }));
4505
+ }
4506
+
4507
+ /**
4508
+ * Whether a part's styled element wraps one control: its component (or the
4509
+ * one named like the part) is a form control (Core's own category) that
4510
+ * takes a disabled prop. An action part that holds children (a button
4511
+ * group) never does.
4512
+ * @param {Ctx} ctx
4513
+ * @param {string} target
4514
+ */
4515
+ export function wrapsOneControl(ctx, target) {
4516
+ // One control: a form control with a disabled prop whose content is not
4517
+ // other elements (a radio list's items, an input group's or a field's
4518
+ // children each hold controls of their own).
4519
+ return partComponentDocs(ctx, target).some(
4520
+ ({doc: d}) =>
4521
+ /form/i.test(String(d.category ?? '')) &&
4522
+ Object.keys(d.props ?? {}).some(p => /disabled/i.test(p)) &&
4523
+ d.props?.children?.type !== 'ReactNode',
4524
+ );
2196
4525
  }
2197
4526
 
2198
4527
  /**
@@ -2303,8 +4632,22 @@ export const EDITOR_SUFFIXES = [
2303
4632
  'd.ts',
2304
4633
  'variants.d.ts',
2305
4634
  'history.json',
4635
+ 'pictures.json',
2306
4636
  ];
2307
4637
 
4638
+ /**
4639
+ * Whether a name in a theme folder is a file the editor writes: the
4640
+ * theme's generated files, settings, history, picture record, pages and
4641
+ * pictures, and its color config.
4642
+ * @param {string} slug
4643
+ * @param {string} n
4644
+ */
4645
+ export const isEditorFile = (slug, n) =>
4646
+ EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
4647
+ /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config(\.damaged(-\d+)?)?\.json)$/.test(
4648
+ n,
4649
+ );
4650
+
2308
4651
  /**
2309
4652
  * The files in a theme folder that the editor writes, by name: the
2310
4653
  * theme's generated files, its settings, history and pages, and its color
@@ -2318,11 +4661,7 @@ export const EDITOR_SUFFIXES = [
2318
4661
  function ownFiles(dir) {
2319
4662
  if (!fs.lstatSync(dir, {throwIfNoEntry: false})?.isDirectory()) return [];
2320
4663
  const slug = path.basename(dir);
2321
- const mine = (/** @type {string} */ n) =>
2322
- EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
2323
- /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config(\.damaged(-\d+)?)?\.json)$/.test(
2324
- n,
2325
- );
4664
+ const mine = (/** @type {string} */ n) => isEditorFile(slug, n);
2326
4665
  /** @type {string[]} */
2327
4666
  const out = [];
2328
4667
  for (const e of fs.readdirSync(dir, {withFileTypes: true}))
@@ -2394,8 +4733,12 @@ function restoreWritten(was, wrote) {
2394
4733
  continue;
2395
4734
  }
2396
4735
  const old = was.get(p);
2397
- if (old) writeWhole(p, old);
2398
- else fs.rmSync(p, {force: true});
4736
+ if (old) {
4737
+ // A folder the change removed (tokens/ once its palette went) comes
4738
+ // back with the file.
4739
+ fs.mkdirSync(path.dirname(p), {recursive: true});
4740
+ writeWhole(p, old);
4741
+ } else fs.rmSync(p, {force: true});
2399
4742
  } catch {
2400
4743
  failed.push(path.basename(p));
2401
4744
  }
@@ -2427,30 +4770,65 @@ export function refuseLinks(cwd, slug) {
2427
4770
  const f = themeFiles(cwd, slug);
2428
4771
  /** @param {string} p */
2429
4772
  const link = p => {
2430
- if (fs.lstatSync(p, {throwIfNoEntry: false})?.isSymbolicLink())
2431
- throw new AstryxError(
2432
- `${path.relative(cwd, p) || p} is a link; the editor writes a theme's own files only, never through a link. Replace the link with a copy of what it points to. Nothing was changed.`,
2433
- [
2434
- {
2435
- name: `cp -rL ${quoteCommandArgument(path.relative(cwd, p))} ${quoteCommandArgument(`${path.relative(cwd, p)}.copy`)}`,
2436
- reason: 'copy what it points to, then put the copy in its place',
2437
- },
2438
- ],
2439
- ERROR_CODES.ERR_THEME_INVALID,
2440
- );
4773
+ // A path under a file (themes written as a file) is not a link: its
4774
+ // own refusal names it.
4775
+ /** @type {fs.Stats | undefined} */
4776
+ let st;
4777
+ try {
4778
+ st = fs.lstatSync(p, {throwIfNoEntry: false});
4779
+ } catch {
4780
+ return;
4781
+ }
4782
+ if (!st?.isSymbolicLink()) return;
4783
+ const rel = path.relative(cwd, p) || p;
4784
+ /** @type {string} */
4785
+ let target;
4786
+ try {
4787
+ target = fs.readlinkSync(p);
4788
+ } catch {
4789
+ target = '';
4790
+ }
4791
+ // Named, with where it points; nothing is removed or moved for the
4792
+ // user.
4793
+ const gone = !fs.existsSync(p);
4794
+ throw new AstryxError(
4795
+ `${rel} is a link to ${target || 'another file'}${gone ? ', which does not exist' : ''}; the editor reads and writes a theme's own files only, never through a link. ${gone ? `Put ${target || 'that file'} back, then put` : 'Put'} a copy of it in place of the link. Nothing was changed.`,
4796
+ [
4797
+ {
4798
+ name: `ls -l ${quoteCommandArgument(path.relative(cwd, p))}`,
4799
+ reason: 'shows where the link points',
4800
+ },
4801
+ ],
4802
+ ERROR_CODES.ERR_THEME_INVALID,
4803
+ );
2441
4804
  };
2442
4805
  link(f.root);
2443
4806
  link(f.dir);
2444
- /** @param {string} d */
2445
- const walk = d => {
2446
- if (!fs.lstatSync(d, {throwIfNoEntry: false})?.isDirectory()) return;
2447
- for (const e of fs.readdirSync(d, {withFileTypes: true})) {
2448
- const p = path.join(d, e.name);
2449
- link(p);
2450
- if (e.isDirectory()) walk(p);
4807
+ // Only the files the editor reads or writes: a link to a file of the
4808
+ // user's (notes, a mockup) is theirs, and is left alone.
4809
+ const own = (/** @type {string} */ n) =>
4810
+ isEditorFile(slug, n) || n === `${slug}.theme.ts` || n === 'tokens';
4811
+ /** @type {string[]} */
4812
+ let names;
4813
+ try {
4814
+ names = fs.readdirSync(f.dir);
4815
+ } catch {
4816
+ return;
4817
+ }
4818
+ for (const n of names.filter(own)) {
4819
+ const p = path.join(f.dir, n);
4820
+ link(p);
4821
+ if (n === 'tokens') {
4822
+ /** @type {string[]} */
4823
+ let inner;
4824
+ try {
4825
+ inner = fs.readdirSync(p);
4826
+ } catch {
4827
+ inner = [];
4828
+ }
4829
+ for (const m of inner) link(path.join(p, m));
2451
4830
  }
2452
- };
2453
- walk(f.dir);
4831
+ }
2454
4832
  }
2455
4833
 
2456
4834
  /**
@@ -2483,15 +4861,12 @@ export function settingsStamp(data) {
2483
4861
  */
2484
4862
  export function staleBuild(cwd, slug, data) {
2485
4863
  const f = themeFiles(cwd, slug);
2486
- // The generated colors are part of the build when a color dial is set.
2487
- const colors = data.settings.some(
2488
- s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
2489
- )
2490
- ? [path.join(cwd, paletteFiles(slug).palette)]
2491
- : [];
2492
- const missing = [f.js, f.css, f.settingsTs, ...colors].find(
2493
- p => !fs.existsSync(p),
2494
- );
4864
+ const files = builtFiles(cwd, slug, data);
4865
+ // An output that cannot be read (its permissions, or a folder in its
4866
+ // place) is refused by name: the build cannot replace it either. That
4867
+ // includes the files a build writes only for some themes.
4868
+ refuseUnreadable(cwd, [...files, ...builtFiles(cwd, slug, data, true)]);
4869
+ const missing = files.find(p => !fs.existsSync(p));
2495
4870
  if (missing) return `${path.relative(f.dir, missing)} was missing`;
2496
4871
  const ts = fs.readFileSync(f.settingsTs, 'utf8');
2497
4872
  const stamp =
@@ -2510,6 +4885,16 @@ export function staleBuild(cwd, slug, data) {
2510
4885
  if (built && now && built !== now)
2511
4886
  return `@astryxdesign/theme-${data.like} is ${now} now, and the build was made on ${built}`;
2512
4887
  }
4888
+ // The generated module seals its own text: a hand edit inside it (the
4889
+ // file says not to) is built over from the settings, and said. Checked
4890
+ // after the stamps, whose reasons say more.
4891
+ if (moduleUnedited(ts) === false)
4892
+ return `${slug}.settings.ts was edited by hand, though it is generated from ${slug}.settings.json and says not to edit it`;
4893
+ // An own change to <slug>.theme.ts since the build (the file says it
4894
+ // wins over the settings) is built in.
4895
+ const source = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(ts);
4896
+ if (source && fs.existsSync(f.ts) && source[1] !== themeSourceHash(cwd, slug))
4897
+ return sourceChangedReason(slug);
2513
4898
  // By content, never by file times (an editor's re-save or a checkout
2514
4899
  // changes those): a generated module cut short, or built outputs whose
2515
4900
  // header names another CLI than the settings were written by (a build
@@ -2526,6 +4911,17 @@ export function staleBuild(cwd, slug, data) {
2526
4911
  })
2527
4912
  )
2528
4913
  return 'the last build did not finish (a command stopped while building)';
4914
+ // Outputs another theme's build wrote over (`compile other.theme.ts --out
4915
+ // themes/g/g.css`): their header names another source.
4916
+ const builtFrom = (/** @type {string} */ file) =>
4917
+ /^ \* Source: (.+)$/m
4918
+ .exec(fs.readFileSync(file, 'utf8').slice(0, 600))?.[1]
4919
+ ?.trim() ?? null;
4920
+ for (const file of [f.css, f.js]) {
4921
+ const from = builtFrom(file);
4922
+ if (from != null && path.basename(from) !== path.basename(f.ts))
4923
+ return `${path.basename(file)} was built from ${from}, not ${slug}.theme.ts`;
4924
+ }
2529
4925
  // A built stylesheet cut short (a crash, a bad merge) is built again, as
2530
4926
  // an unreadable built module is.
2531
4927
  try {
@@ -2536,6 +4932,79 @@ export function staleBuild(cwd, slug, data) {
2536
4932
  return null;
2537
4933
  }
2538
4934
 
4935
+ /**
4936
+ * Every file the editor's build of a theme writes, the one list staleness
4937
+ * reads: the generated settings module, the built stylesheet, module and
4938
+ * their types, and, with a color dial set, the generated color files.
4939
+ * @param {string} cwd
4940
+ * @param {string} slug
4941
+ * @param {ThemeData} data
4942
+ * @param {boolean} [some] the files a build writes only for some themes
4943
+ * (the variants types, for a theme with component variants) instead
4944
+ * @returns {string[]}
4945
+ */
4946
+ export function builtFiles(cwd, slug, data, some = false) {
4947
+ const f = themeFiles(cwd, slug);
4948
+ if (some) return [path.join(f.dir, `${slug}.variants.d.ts`)];
4949
+ const pal = paletteFiles(slug);
4950
+ const colors = data.settings.some(
4951
+ s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
4952
+ )
4953
+ ? [pal.palette, pal.refs, pal.receipt].map(p => path.join(cwd, p))
4954
+ : [];
4955
+ return [
4956
+ f.settingsTs,
4957
+ // The theme's own source: the editor writes it once, and every build
4958
+ // reads it, so one deleted by hand is written again.
4959
+ f.ts,
4960
+ f.css,
4961
+ f.js,
4962
+ path.join(f.dir, `${slug}.d.ts`),
4963
+ path.join(f.dir, `${slug}.css.d.ts`),
4964
+ ...colors,
4965
+ ];
4966
+ }
4967
+
4968
+ /**
4969
+ * Refuse, by name, a built file that is there but cannot be read: its
4970
+ * permissions, or a folder where the file goes.
4971
+ * @param {string} cwd
4972
+ * @param {string[]} files
4973
+ */
4974
+ function refuseUnreadable(cwd, files) {
4975
+ for (const file of files) {
4976
+ const st = fs.statSync(file, {throwIfNoEntry: false});
4977
+ if (!st) continue;
4978
+ const rel = shown(cwd, file);
4979
+ if (st.isDirectory())
4980
+ throw new AstryxError(
4981
+ `${rel} is a folder where the build writes a file, so the theme cannot be built. Move or rename the folder, then run the command again. Nothing was changed.`,
4982
+ [
4983
+ {
4984
+ name: `ls -la ${quoteCommandArgument(rel)}`,
4985
+ reason: 'see what is there',
4986
+ },
4987
+ ],
4988
+ ERROR_CODES.ERR_FILE_EXISTS,
4989
+ );
4990
+ try {
4991
+ fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);
4992
+ } catch (e) {
4993
+ const code = /** @type {any} */ (e)?.code ?? 'EACCES';
4994
+ throw new AstryxError(
4995
+ `${rel} cannot be read or replaced (${code}: its permissions), so the theme cannot be built. Give yourself read and write permission on it (chmod u+rw ${rel}), then run the command again. Nothing was changed.`,
4996
+ [
4997
+ {
4998
+ name: `ls -la ${quoteCommandArgument(rel)}`,
4999
+ reason: 'see its permissions',
5000
+ },
5001
+ ],
5002
+ ERROR_CODES.ERR_WRITE_FAILED,
5003
+ );
5004
+ }
5005
+ }
5006
+ }
5007
+
2539
5008
  /**
2540
5009
  * The installed version of a base theme package, or null.
2541
5010
  * @param {string} cwd
@@ -2572,6 +5041,19 @@ export const HISTORY_STEPS = 80;
2572
5041
  */
2573
5042
  export function readHistory(file) {
2574
5043
  if (!fs.existsSync(file)) return {steps: [], dropped: 0};
5044
+ // A history that cannot be read is not damaged: it is refused by name.
5045
+ const why = unreadableReason(file);
5046
+ if (why)
5047
+ throw new AstryxError(
5048
+ `${path.basename(file)} ${why}, so the undo history cannot be read. Give it back its place or its read permission; nothing was changed.`,
5049
+ [
5050
+ {
5051
+ name: `ls -la ${quoteCommandArgument(file)}`,
5052
+ reason: 'see what is there',
5053
+ },
5054
+ ],
5055
+ ERROR_CODES.ERR_THEME_INVALID,
5056
+ );
2575
5057
  /** @type {unknown} */
2576
5058
  let h;
2577
5059
  try {
@@ -2646,7 +5128,14 @@ export async function commitTheme(
2646
5128
  // A no-op change still mends a build that does not match the settings
2647
5129
  // (an undo stopped part way): it is built again, with no new step.
2648
5130
  const noop = history && same(parseSettings(snapBefore));
2649
- if (noop && fs.existsSync(f.js) && !staleBuild(cwd, slug, data))
5131
+ const stale =
5132
+ noop && fs.existsSync(f.js) ? staleBuild(cwd, slug, data) : null;
5133
+ // The no-op that mends one says what it built again.
5134
+ if (noop && stale)
5135
+ notes.push(
5136
+ `the build was not current (${stale}), so it was built again from the settings`,
5137
+ );
5138
+ if (noop && fs.existsSync(f.js) && !stale)
2650
5139
  return {
2651
5140
  changed: [],
2652
5141
  res: {light: {}, dark: {}},
@@ -2656,6 +5145,11 @@ export async function commitTheme(
2656
5145
  notes,
2657
5146
  unchanged: true,
2658
5147
  };
5148
+ // With no last build (deleted, never committed), nothing is compared.
5149
+ if (snapBefore && !fs.existsSync(f.js))
5150
+ notes.push(
5151
+ `there was no last build (${path.basename(f.js)} is missing), so the token changes are not listed; the theme is built again`,
5152
+ );
2659
5153
  const resBefore =
2660
5154
  snapBefore && fs.existsSync(f.js)
2661
5155
  ? await resolvedTokens(ctx, slug).catch(() => {
@@ -2668,7 +5162,9 @@ export async function commitTheme(
2668
5162
  })
2669
5163
  : null;
2670
5164
  const before = parseSettings(snapBefore);
2671
- const liftedBefore = new Set(before?.lifted ?? []);
5165
+ const liftedBefore = new Set(
5166
+ Array.isArray(before?.lifted) ? before.lifted : [],
5167
+ );
2672
5168
  // A change that leaves every color setting as it was keeps the shades the
2673
5169
  // theme already shows: a theme an earlier editor built keeps its colors
2674
5170
  // until a color, the mode or the base changes, and undo brings them back.
@@ -2728,6 +5224,12 @@ export async function commitTheme(
2728
5224
  fs.mkdirSync(f.dir, {recursive: true});
2729
5225
  /** @type {{warnings: string[], lifted: string[], notes: string[]}} */
2730
5226
  let built;
5227
+ // The token loops the last build had, so a change that adds one (through
5228
+ // tokens the own source sets in a way no read of the file follows) is
5229
+ // refused once the build shows it.
5230
+ const loopsBefore = new Set(builtLoops(cwd, slug).map(l => l.key));
5231
+ // The app copy is written once the change is saved, never before.
5232
+ afterSave.add(ctx);
2731
5233
  try {
2732
5234
  refuseIfLockLost();
2733
5235
  try {
@@ -2738,6 +5240,18 @@ export async function commitTheme(
2738
5240
  // The build writes its outputs itself: a lock lost meanwhile is seen
2739
5241
  // before anything else is written.
2740
5242
  refuseIfLockLost();
5243
+ const loop = builtLoops(cwd, slug).find(l => !loopsBefore.has(l.key));
5244
+ if (loop)
5245
+ throw new AstryxError(
5246
+ `${loop.path.join(' reads ')}${loop.part ? ` on ${loop.part}` : ''}: the change makes these tokens read each other (with what ${slug}.theme.ts or the base theme sets), so they would have no value at all. Nothing was changed.`,
5247
+ [
5248
+ {
5249
+ name: `${P} how ${loop.path[0].replace(/^--/, '')}`,
5250
+ reason: 'see what it takes',
5251
+ },
5252
+ ],
5253
+ ERROR_CODES.ERR_THEME_BAD_VALUE,
5254
+ );
2741
5255
  data.lifted = built.lifted;
2742
5256
  // The undo step and the settings are part of the change: written whole,
2743
5257
  // inside the rollback, the settings first. A command stopped between
@@ -2762,7 +5276,16 @@ export async function commitTheme(
2762
5276
  // Settings written whole: a `new` marker left beside them (a `new`
2763
5277
  // stopped after its theme was made) has nothing left to finish.
2764
5278
  clearNewMarker(f.dir);
5279
+ afterSave.delete(ctx);
5280
+ // The change is saved: its app copy follows. A copy that cannot be
5281
+ // written leaves the copy as it was; the change stands.
5282
+ try {
5283
+ afterBuild?.(ctx, slug, data);
5284
+ } catch (e) {
5285
+ if (/** @type {any} */ (e)?.lockLost) throw e;
5286
+ }
2765
5287
  } catch (e) {
5288
+ afterSave.delete(ctx);
2766
5289
  // A command that lost its lock while stopped owns none of these files
2767
5290
  // now: it puts nothing back and deletes nothing (that would undo the
2768
5291
  // other command's change).
@@ -2784,7 +5307,7 @@ export async function commitTheme(
2784
5307
  const code = /** @type {any} */ (e)?.code;
2785
5308
  if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO', 'EISDIR'].includes(code))
2786
5309
  throw new AstryxError(
2787
- `Could not write the theme files (${code}), so the change was undone. Free space or fix the permission, then run the command again.`,
5310
+ `Could not write the theme files (${code}), so the files were put back as they were. Free space or fix the permission, then run the command again. Nothing was changed.`,
2788
5311
  [
2789
5312
  {
2790
5313
  name: `ls -ld ${quoteCommandArgument(themeFiles(ctx.project.cwd, slug).dir)}`,
@@ -2800,9 +5323,27 @@ export async function commitTheme(
2800
5323
  e.code === ERROR_CODES.ERR_THEME_INVALID ||
2801
5324
  e.code === ERROR_CODES.ERR_PALETTE_GENERATION ||
2802
5325
  e.code === ERROR_CODES.ERR_WRITE_FAILED ||
2803
- e.code === ERROR_CODES.ERR_THEME_BUSY)
5326
+ e.code === ERROR_CODES.ERR_THEME_BUSY ||
5327
+ e.code === ERROR_CODES.ERR_THEME_BAD_VALUE)
2804
5328
  )
2805
5329
  throw e;
5330
+ // A folder where a built file goes: named for the editor, which has no
5331
+ // --out to pick.
5332
+ const folder =
5333
+ e instanceof AstryxError
5334
+ ? /^The output (.+) is a folder\./.exec(e.message)?.[1]
5335
+ : undefined;
5336
+ if (folder)
5337
+ throw new AstryxError(
5338
+ `${folder} is a folder, not a file, so the theme cannot be built. Put the file back in its place; nothing was changed.`,
5339
+ [
5340
+ {
5341
+ name: `ls -la ${quoteCommandArgument(folder)}`,
5342
+ reason: 'see what is there',
5343
+ },
5344
+ ],
5345
+ ERROR_CODES.ERR_THEME_INVALID,
5346
+ );
2806
5347
  const why = (e instanceof Error ? e.message : String(e))
2807
5348
  .split(`${cwd}${path.sep}`)
2808
5349
  .join('')
@@ -2812,12 +5353,17 @@ export async function commitTheme(
2812
5353
  .join(' | ');
2813
5354
  const own = why.includes(path.basename(f.ts));
2814
5355
  throw new AstryxError(
2815
- `The theme did not build, so the change was undone: ${why}${own ? ` (${shown(cwd, f.ts)} is your own file: fix it, then run the command again)` : ''}`,
5356
+ `The theme did not build, so the files were put back as they were: ${why}${own ? ` (${shown(cwd, f.ts)} is your own file: fix it, then run the command again)` : ''}. Nothing was changed.`,
2816
5357
  [
2817
- {
2818
- name: `${P} show ${slug}`,
2819
- reason: 'do this instead: see the settings as they are',
2820
- },
5358
+ own
5359
+ ? {
5360
+ name: `cat ${quoteCommandArgument(shown(cwd, f.ts))}`,
5361
+ reason: 'see your own file, then fix it',
5362
+ }
5363
+ : {
5364
+ name: `${P} show ${slug}`,
5365
+ reason: 'do this instead: see the settings as they are',
5366
+ },
2821
5367
  ],
2822
5368
  ERROR_CODES.ERR_THEME_INVALID,
2823
5369
  );