@astryxdesign/cli 0.7.14 → 0.7.15-canary.g79b95eb

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 (129) hide show
  1. package/api/doctor/_adapter.d.mts +1 -0
  2. package/api/doctor/_adapter.mjs +8 -0
  3. package/api/doctor/_authoring-audit.d.mts +42 -0
  4. package/api/doctor/_authoring-audit.mjs +106 -0
  5. package/api/doctor/doctor.d.mts +7 -0
  6. package/api/doctor/doctor.mjs +24 -39
  7. package/api/search/_adapter.mjs +124 -3
  8. package/api/search/_candidate-score.mjs +63 -9
  9. package/api/search/_entries.d.mts +10 -0
  10. package/api/search/_entries.mjs +68 -1
  11. package/api/search/_gather-templates.d.mts +11 -0
  12. package/api/search/_gather-templates.mjs +22 -2
  13. package/api/search/_words.mjs +26 -6
  14. package/api/swizzle/copy/copy.mjs +1 -1
  15. package/api/theme/_adapter.mjs +20 -9
  16. package/api/theme/build/build.d.mts +15 -1
  17. package/api/theme/build/build.mjs +132 -32
  18. package/api/theme/targets/targets.d.mts +8 -0
  19. package/api/theme/targets/targets.mjs +14 -1
  20. package/api/theme/themeBuild.doc.mjs +6 -3
  21. package/api/theme/themeEject.doc.mjs +3 -3
  22. package/api/theme/themeTargets.doc.mjs +1 -1
  23. package/api/theme-edit/_adapter.d.mts +46 -3
  24. package/api/theme-edit/_adapter.mjs +372 -109
  25. package/api/theme-edit/_check.d.mts +6 -3
  26. package/api/theme-edit/_check.mjs +665 -87
  27. package/api/theme-edit/_color.mjs +4 -2
  28. package/api/theme-edit/_compiler.d.mts +2 -1
  29. package/api/theme-edit/_compiler.mjs +27 -13
  30. package/api/theme-edit/_context.d.mts +2 -1
  31. package/api/theme-edit/_context.mjs +47 -8
  32. package/api/theme-edit/_edit.d.mts +9 -3
  33. package/api/theme-edit/_edit.mjs +484 -66
  34. package/api/theme-edit/_how-commands.d.mts +33 -7
  35. package/api/theme-edit/_how-commands.mjs +57 -45
  36. package/api/theme-edit/_how-question.d.mts +4 -0
  37. package/api/theme-edit/_how-question.mjs +1004 -223
  38. package/api/theme-edit/_how.mjs +96 -9
  39. package/api/theme-edit/_palette.d.mts +38 -13
  40. package/api/theme-edit/_palette.mjs +620 -223
  41. package/api/theme-edit/_parts.mjs +63 -7
  42. package/api/theme-edit/_png.d.mts +4 -4
  43. package/api/theme-edit/_png.mjs +4 -2
  44. package/api/theme-edit/_preview-app.d.mts +6 -0
  45. package/api/theme-edit/_preview-app.mjs +1194 -207
  46. package/api/theme-edit/_preview.mjs +2 -2
  47. package/api/theme-edit/_project.d.mts +12 -1
  48. package/api/theme-edit/_project.mjs +37 -6
  49. package/api/theme-edit/_settings.d.mts +104 -33
  50. package/api/theme-edit/_settings.mjs +818 -118
  51. package/api/theme-edit/_tables.d.mts +7 -0
  52. package/api/theme-edit/_tables.mjs +61 -0
  53. package/api/theme-edit/theme-edit.type.d.mts +11 -1
  54. package/api/theme-edit/theme-edit.type.mjs +4 -3
  55. package/api/theme-edit/themeEditHow.doc.mjs +6 -0
  56. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  57. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  58. package/api/theme-edit/themeEditPreviewList.doc.mjs +1 -1
  59. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
  60. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  61. package/api/upgrade/_adapter.d.mts +1 -0
  62. package/assets/codemods/run-codemod.mjs +61 -0
  63. package/assets/codemods/runner.mjs +5 -4
  64. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
  65. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
  66. package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
  67. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
  68. package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
  69. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
  70. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
  71. package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
  72. package/assets/docs/tree/calendars.doc.mjs +1 -3
  73. package/assets/docs.generated.json +2 -1
  74. package/assets/self-audit.generated.json +1 -0
  75. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
  76. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
  77. package/assets/templates/components.generated.json +1 -1
  78. package/clients/cli/bin/astryx.mjs +19 -15
  79. package/clients/cli/build-id.generated.json +1 -0
  80. package/clients/cli/commands/ensure-core-built.mjs +12 -5
  81. package/clients/cli/commands/experimental/theme.mjs +178 -78
  82. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  83. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
  84. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
  85. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  86. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  87. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  88. package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
  89. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  90. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  91. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
  92. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
  93. package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
  94. package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
  95. package/clients/cli/commands/manifest.mjs +5 -2
  96. package/clients/cli/commands/theme.mjs +118 -22
  97. package/clients/cli/index.mjs +9 -3
  98. package/clients/cli/lib/manifest.mjs +37 -0
  99. package/clients/cli/lib/resolve-theme.mjs +2 -1
  100. package/clients/cli/manifest.generated.json +1 -0
  101. package/foundation/discovery/module-exports.mjs +16 -2
  102. package/foundation/discovery/stored-self-audit.d.mts +31 -0
  103. package/foundation/discovery/stored-self-audit.mjs +119 -0
  104. package/foundation/discovery/template-adapter.d.mts +48 -2
  105. package/foundation/discovery/template-adapter.mjs +51 -19
  106. package/foundation/discovery/template-needs.d.mts +6 -0
  107. package/foundation/discovery/template-needs.mjs +20 -1
  108. package/foundation/discovery/template-source-tree.d.mts +7 -0
  109. package/foundation/discovery/template-source-tree.mjs +15 -0
  110. package/foundation/discovery/theme-discovery.d.mts +2 -1
  111. package/foundation/discovery/theme-discovery.mjs +2 -8
  112. package/foundation/discovery/theme-module-extensions.d.mts +18 -0
  113. package/foundation/discovery/theme-module-extensions.mjs +30 -0
  114. package/foundation/doc-compiler/import.mjs +12 -11
  115. package/foundation/doc-compiler/stored-docs.d.mts +18 -12
  116. package/foundation/doc-compiler/stored-docs.mjs +52 -19
  117. package/foundation/env/private-dir.d.mts +17 -0
  118. package/foundation/env/private-dir.mjs +42 -0
  119. package/foundation/fs/gather-cache.d.mts +108 -0
  120. package/foundation/fs/gather-cache.mjs +716 -0
  121. package/foundation/fs/module-loader.mjs +7 -1
  122. package/foundation/fs/read-record.d.mts +31 -1
  123. package/foundation/fs/read-record.mjs +93 -6
  124. package/foundation/integrations/validate-contributions.mjs +24 -11
  125. package/foundation/release/cache.d.mts +11 -2
  126. package/foundation/release/cache.mjs +59 -10
  127. package/foundation/release/folder-lock.d.mts +21 -0
  128. package/foundation/release/folder-lock.mjs +171 -0
  129. package/package.json +8 -6
@@ -33,40 +33,57 @@
33
33
 
34
34
  import {createHash} from 'node:crypto';
35
35
  import * as fs from 'node:fs';
36
- import * as os from 'node:os';
37
36
  import * as path from 'node:path';
38
37
  import * as edit from './_edit.mjs';
38
+ import {themeCacheRoot} from './_project.mjs';
39
39
  import * as preview from './_preview-app.mjs';
40
40
  import {AstryxError} from '../error.mjs';
41
41
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
42
42
  import {
43
43
  findAstryxProject,
44
44
  findPackageRoot,
45
- findProjectCoreDir,
46
45
  } from '../../foundation/fs/paths.mjs';
47
46
  import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
48
- import {tryLock} from '../../foundation/release/cache.mjs';
49
- import {q} from './_settings.mjs';
47
+ import {withFolderLock} from '../../foundation/release/folder-lock.mjs';
48
+ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
49
+ import {LIKE} from './_tables.mjs';
50
50
 
51
- export {themeEditHow, parsePoints} from './_how.mjs';
52
- import {isPicture as howPicture} from './_how.mjs';
51
+ export {parsePoints} from './_how.mjs';
52
+ import {themeEditHow as howAt} from './_how.mjs';
53
53
 
54
54
  /**
55
- * Whether `how`'s first word names a picture, as the API decides it, for
56
- * the command line's own argument checks. The file system is read here.
57
- * @param {string} word
58
- * @param {string} [cwd]
55
+ * `how`, run at the project root like the other editor commands, so a
56
+ * subfolder finds the app's themes. A picture named from the subfolder
57
+ * keeps pointing where it was named.
58
+ * @param {string} subject
59
+ * @param {import('./theme-edit.type.mjs').ThemeEditHowOptions} [options]
60
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditHowResponse>}
59
61
  */
60
- export const isHowPicture = (word, cwd = process.cwd()) =>
61
- howPicture(word, cwd);
62
+ export async function themeEditHow(subject, options = {}) {
63
+ const from = options.cwd ?? process.cwd();
64
+ const o = atRoot(options);
65
+ /** A file named from the subfolder, as a path from anywhere. @param {unknown} name */
66
+ const here = name =>
67
+ typeof name === 'string' &&
68
+ name !== '' &&
69
+ !path.isAbsolute(name) &&
70
+ path.resolve(from) !== o.cwd &&
71
+ fs.existsSync(path.resolve(from, name)) &&
72
+ fs.statSync(path.resolve(from, name)).isFile()
73
+ ? path.resolve(from, name)
74
+ : name;
75
+ // The CLI passes the words as typed: the first may be that picture too.
76
+ const words = o.words?.length
77
+ ? [String(here(o.words[0])), ...o.words.slice(1)]
78
+ : o.words;
79
+ return howAt(/** @type {string} */ (here(subject)), {
80
+ ...o,
81
+ ...(words ? {words} : {}),
82
+ });
83
+ }
62
84
 
63
- /**
64
- * Whether a file named on the command line exists, read here.
65
- * @param {string} file
66
- * @param {string} [cwd]
67
- */
68
- export const fileExists = (file, cwd = process.cwd()) =>
69
- fs.existsSync(path.resolve(cwd, file));
85
+ /** The built-in themes a theme can build on (`--like`). */
86
+ export const builtInThemes = () => [...LIKE];
70
87
 
71
88
  /**
72
89
  * The project a command acts on: the Astryx project at or above `cwd`, found
@@ -109,7 +126,7 @@ export function projectRoot(cwd) {
109
126
  `${path.relative(start, file) || 'package.json'} is a package that does not use Astryx; the app that does is ${path.relative(start, project) || '.'}. Run the command from there, so the theme lands in that app. Nothing was written.`,
110
127
  [
111
128
  {
112
- name: `cd ${q(path.relative(start, project))}`,
129
+ name: `cd ${quoteCommandArgument(path.relative(start, project))}`,
113
130
  reason: 'do this first',
114
131
  },
115
132
  ],
@@ -119,12 +136,6 @@ export function projectRoot(cwd) {
119
136
  return project ?? start;
120
137
  }
121
138
 
122
- /** The locks this process holds now. */
123
- const HELD = new Set();
124
-
125
- /** @param {number} ms */
126
- const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
127
-
128
139
  /**
129
140
  * Where a project's locks are: the `.cache` of the node_modules holding
130
141
  * the Core the command reads (the project's own, or a workspace root's), shared by
@@ -139,10 +150,9 @@ function lockDir(root) {
139
150
  // The Core the command reads decides where; outside a project there is
140
151
  // none, and no lock.
141
152
  if (isOutsideProject(root)) return null;
142
- const core = findProjectCoreDir(root);
143
- if (!core) return null;
144
- const modules = path.dirname(path.dirname(core));
145
- const dir = path.join(modules, '.cache', 'astryx-theme', 'locks');
153
+ const cache = themeCacheRoot(root);
154
+ if (!cache) return null;
155
+ const dir = path.join(cache, 'locks');
146
156
  try {
147
157
  fs.mkdirSync(dir, {recursive: true});
148
158
  fs.accessSync(dir, fs.constants.W_OK);
@@ -165,97 +175,82 @@ function lockDir(root) {
165
175
  * @template T
166
176
  * @param {string} root
167
177
  * @param {string} name
168
- * @param {() => Promise<T>} fn
178
+ * @param {(locked: boolean) => Promise<T>} fn called with whether the lock
179
+ * is held
180
+ * @param {boolean} [bestEffort] a command that can run read-only runs
181
+ * without the lock when it cannot be taken (a read-only node_modules),
182
+ * told so, and then writes nothing
169
183
  * @returns {Promise<T>}
170
184
  */
171
- async function withLock(root, name, fn) {
172
- const dir = lockDir(root);
173
- if (!dir) return fn();
174
- const key = createHash('sha256').update(root).digest('hex').slice(0, 16);
175
- const lock = path.join(dir, `${key}-${name}.lock`);
176
- const ownerFile = path.join(lock, 'owner.json');
177
- /** @returns {any} */
178
- const owner = () => {
179
- try {
180
- return JSON.parse(fs.readFileSync(ownerFile, 'utf8'));
181
- } catch {
182
- return null;
183
- }
184
- };
185
- // A lock naming this very process on this computer, that this process
186
- // does not hold, is left from a process that had this pid before (a
187
- // container restarted).
188
- const held = owner();
189
- if (
190
- held?.pid === process.pid &&
191
- held?.host === os.hostname() &&
192
- !HELD.has(lock)
193
- )
194
- fs.rmSync(lock, {recursive: true, force: true});
185
+ async function withLock(root, name, fn, bestEffort = false) {
186
+ /** @type {string | null} */
187
+ let dir;
195
188
  try {
196
- // The release cache's lock: made with mkdir (one taker wins), and a
197
- // holder that stopped is taken over by a rename (one taker wins).
198
- for (let waited = 0; !tryLock(lock); waited += 50) {
199
- if (waited > 30_000) {
200
- const o = owner();
201
- throw new AstryxError(
202
- `Another command is changing ${name.replace(/^theme-/, '')} and did not finish within 30 seconds${o ? ` (process ${o.pid} on ${o.host}, for ${Math.round((Date.now() - Number(o.at)) / 1000)} s)` : ''}. Nothing was changed; run this command again. If no astryx command is running, the lock is left from one that stopped: remove the folder ${lock}.`,
203
- [],
204
- ERROR_CODES.ERR_THEME_BUSY,
205
- );
206
- }
207
- await sleep(50);
208
- }
189
+ dir = lockDir(root);
209
190
  } catch (e) {
210
- if (e instanceof AstryxError) throw e;
211
- throw new AstryxError(
212
- `Could not take the lock ${lock} (${/** @type {any} */ (e).code ?? String(e)}). Nothing was changed; fix the folder, then run the command again.`,
213
- [],
214
- ERROR_CODES.ERR_WRITE_FAILED,
215
- );
191
+ if (bestEffort) return fn(false);
192
+ throw e;
216
193
  }
217
- HELD.add(lock);
218
- const mine = fs.existsSync(ownerFile)
219
- ? fs.readFileSync(ownerFile, 'utf8')
220
- : null;
221
- // Only this command's own lock is removed, never one another took over.
222
- const release = () => {
194
+ if (!dir) return fn(true);
195
+ // The lock is named for the project as seen from the lock folder (which
196
+ // lives in the project's own node_modules), not by the path this command
197
+ // was given: one project reached through two paths (a bind mount, a
198
+ // devcontainer) has one lock.
199
+ /** @param {string} p */
200
+ const real = p => {
223
201
  try {
224
- const now = fs.existsSync(ownerFile)
225
- ? fs.readFileSync(ownerFile, 'utf8')
226
- : null;
227
- if (now === mine) fs.rmSync(lock, {recursive: true, force: true});
202
+ return fs.realpathSync(p);
228
203
  } catch {
229
- // Gone already.
204
+ return path.resolve(p);
230
205
  }
231
206
  };
232
- // Stopped by a signal, the lock still goes.
233
- const onSignal = (/** @type {NodeJS.Signals} */ sig) => {
234
- release();
235
- process.kill(process.pid, sig);
236
- };
237
- process.once('exit', release);
238
- process.once('SIGINT', onSignal);
239
- process.once('SIGTERM', onSignal);
207
+ const key = createHash('sha256')
208
+ .update(path.relative(real(dir), real(root)).split(path.sep).join('/'))
209
+ .digest('hex')
210
+ .slice(0, 16);
211
+ const lock = path.join(dir, `${key}-${name}.lock`);
212
+ // The release cache's lock, held with its lease while the command runs
213
+ // (foundation/release/folder-lock.mjs). A lock naming this pid is never
214
+ // taken over on that ground alone: two containers on one checkout can
215
+ // both be pid 1.
216
+ let started = false;
240
217
  try {
241
- return await fn();
218
+ return await withFolderLock(
219
+ lock,
220
+ async () => {
221
+ started = true;
222
+ return fn(true);
223
+ },
224
+ {
225
+ onBusy: (o, held) => {
226
+ throw new AstryxError(
227
+ `Another command has been changing ${name.replace(/^theme-/, '')} for 30 seconds${o ? ` (process ${o.pid} on ${o.host}${held != null ? `, holding it ${held} s` : ''})` : ''}. Nothing was changed; run this command again. If no astryx command is running, the lock is left from one that stopped: remove the folder ${lock}.`,
228
+ [],
229
+ ERROR_CODES.ERR_THEME_BUSY,
230
+ );
231
+ },
232
+ },
233
+ );
242
234
  } catch (e) {
235
+ if (e instanceof AstryxError) throw e;
236
+ const code = /** @type {any} */ (e)?.code;
237
+ if (!started) {
238
+ if (bestEffort) return fn(false);
239
+ throw new AstryxError(
240
+ `Could not take the lock ${lock} (${code ?? String(e)}). Nothing was changed; fix the folder, then run the command again.`,
241
+ [],
242
+ ERROR_CODES.ERR_WRITE_FAILED,
243
+ );
244
+ }
243
245
  // A folder that cannot be written (no permission, a full or read-only
244
246
  // disk) is a documented refusal, not a crash.
245
- const code = /** @type {any} */ (e)?.code;
246
- if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS'].includes(code))
247
+ if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO'].includes(code))
247
248
  throw new AstryxError(
248
- `Could not write ${path.relative(root, /** @type {any} */ (e).path ?? '') || 'the theme files'}: ${code === 'ENOSPC' ? 'the disk is full' : code === 'EROFS' ? 'the disk is read-only' : 'no permission'}. Free the space or fix the permission, then run the command again; a refused change is undone.`,
249
+ `Could not write ${path.relative(root, /** @type {any} */ (e).path ?? '') || 'the theme files'}: ${code === 'ENOSPC' ? 'the disk is full' : code === 'EROFS' ? 'the disk is read-only' : code === 'EIO' ? 'the disk could not be read or written' : 'no permission'}. ${code === 'EROFS' ? 'Make the folder writable' : code === 'EIO' ? 'Check the disk' : 'Free the space or fix the permission'}, then run the command again; a refused change is undone.`,
249
250
  [],
250
251
  ERROR_CODES.ERR_WRITE_FAILED,
251
252
  );
252
253
  throw e;
253
- } finally {
254
- release();
255
- HELD.delete(lock);
256
- process.removeListener('exit', release);
257
- process.removeListener('SIGINT', onSignal);
258
- process.removeListener('SIGTERM', onSignal);
259
254
  }
260
255
  }
261
256
 
@@ -320,13 +315,92 @@ function absolute(result, root, from) {
320
315
  * @param {(o: O & {cwd: string}) => Promise<T>} fn
321
316
  * @returns {Promise<T>}
322
317
  */
323
- async function inProject(options, lock, fn) {
318
+ async function inProject(options, lock, fn, bestEffort = false) {
324
319
  const from = options.cwd ?? process.cwd();
325
320
  const o = atRoot(options);
326
- const r = lock ? await withLock(o.cwd, lock, () => fn(o)) : await fn(o);
327
- return absolute(r, o.cwd, from);
321
+ try {
322
+ // Without the lock (it cannot be taken), a read-only command writes
323
+ // nothing.
324
+ const r = lock
325
+ ? await withLock(
326
+ o.cwd,
327
+ lock,
328
+ locked => fn(locked ? o : {...o, readOnly: true}),
329
+ bestEffort,
330
+ )
331
+ : await fn(o);
332
+ return absolute(r, o.cwd, from);
333
+ } catch (e) {
334
+ throw fromCaller(e, o.cwd, from);
335
+ }
336
+ }
337
+
338
+ /**
339
+ * A refusal whose suggested preview commands name folders as the person
340
+ * types them where they ran the command: a `--path` and a `preview app`
341
+ * folder, read from the project root, are written from the caller's
342
+ * folder.
343
+ * @param {any} e
344
+ * @param {string} root
345
+ * @param {string} from
346
+ */
347
+ function fromCaller(e, root, from) {
348
+ if (path.resolve(from) === root || !Array.isArray(e?.suggestions)) return e;
349
+ const ARG = String.raw`('(?:[^']|'\\'')*'|"[^"]*"|[^\s'"]+)`;
350
+ /** @param {string} v */
351
+ const unquote = v =>
352
+ v.startsWith("'")
353
+ ? v.slice(1, -1).replace(/'\\''/g, "'")
354
+ : v.startsWith('"')
355
+ ? v.slice(1, -1)
356
+ : v;
357
+ /** @param {string} v */
358
+ const rel = v =>
359
+ /^<.*>$/.test(v)
360
+ ? v
361
+ : quoteCommandArgument(
362
+ path.relative(path.resolve(from), path.resolve(root, unquote(v))) ||
363
+ '.',
364
+ );
365
+ for (const s of e.suggestions) {
366
+ if (typeof s?.name !== 'string') continue;
367
+ if (!s.name.startsWith('astryx experimental theme preview ')) continue;
368
+ s.name = s.name
369
+ .replace(
370
+ new RegExp(`(--path )${ARG}`, 'g'),
371
+ (
372
+ /** @type {string} */ _m,
373
+ /** @type {string} */ flag,
374
+ /** @type {string} */ v,
375
+ ) => flag + rel(v),
376
+ )
377
+ .replace(
378
+ new RegExp(`^(astryx experimental theme preview app )${ARG}`),
379
+ (
380
+ /** @type {string} */ _m,
381
+ /** @type {string} */ cmd,
382
+ /** @type {string} */ v,
383
+ ) => cmd + rel(v),
384
+ );
385
+ }
386
+ return e;
328
387
  }
329
388
 
389
+ /**
390
+ * Options for a preview command, with a way to hold a theme's lock while
391
+ * the preview builds that theme.
392
+ * @template {{cwd: string}} O
393
+ * @param {O} o
394
+ * @returns {any}
395
+ */
396
+ const withThemeLock = o => ({
397
+ ...o,
398
+ lockTheme: (
399
+ /** @type {string} */ slug,
400
+ /** @type {() => Promise<any>} */ fn,
401
+ ) => withLock(o.cwd, lockName(slug), fn),
402
+ });
403
+
330
404
  /** @type {typeof edit.themeEditNew} */
331
405
  export const themeEditNew = (name, options = {}) =>
332
406
  inProject(options, lockName(name), o => edit.themeEditNew(name, o));
@@ -340,11 +414,11 @@ export const themeEditUndo = (theme, options = {}) =>
340
414
  inProject(options, lockName(theme), o => edit.themeEditUndo(theme, o));
341
415
  /** @type {typeof edit.themeEditShow} */
342
416
  export const themeEditShow = (theme, options = {}) =>
343
- inProject(options, lockName(theme), o => edit.themeEditShow(theme, o));
417
+ inProject(options, lockName(theme), o => edit.themeEditShow(theme, o), true);
344
418
  /** @type {typeof preview.themeEditPreviewAdd} */
345
419
  export const themeEditPreviewAdd = (description, options = {}) =>
346
420
  inProject(options, 'preview', o =>
347
- preview.themeEditPreviewAdd(description, o),
421
+ preview.themeEditPreviewAdd(description, withThemeLock(o)),
348
422
  );
349
423
  /**
350
424
  * `preview app` runs from the project root, with `dir` kept pointing where
@@ -364,6 +438,7 @@ export const themeEditPreviewApp = (dir, options = {}) => {
364
438
  : dir,
365
439
  o,
366
440
  ),
441
+ true,
367
442
  );
368
443
  };
369
444
  /** @type {typeof preview.themeEditPreviewList} */
@@ -371,4 +446,192 @@ export const themeEditPreviewList = (options = {}) =>
371
446
  inProject(options, null, async o => preview.themeEditPreviewList(o));
372
447
  /** @type {typeof preview.themeEditPreviewRemove} */
373
448
  export const themeEditPreviewRemove = (page, options = {}) =>
374
- inProject(options, 'preview', o => preview.themeEditPreviewRemove(page, o));
449
+ inProject(options, 'preview', o =>
450
+ preview.themeEditPreviewRemove(page, withThemeLock(o)),
451
+ );
452
+
453
+ /**
454
+ * The theme an editor theme path or name names, or null: `themes/<slug>/`
455
+ * holding `<slug>.settings.json`.
456
+ * @param {string} root
457
+ * @param {string} word a path or a name
458
+ */
459
+ function editorThemeOf(root, word) {
460
+ const m = /(?:^|[\\/])themes[\\/]([a-z][a-z0-9-]*)(?:[\\/]|$)/.exec(word);
461
+ const slug = m ? m[1] : /^[a-z][a-z0-9-]*$/.test(word) ? word : null;
462
+ return slug &&
463
+ fs.existsSync(path.join(root, 'themes', slug, `${slug}.settings.json`))
464
+ ? slug
465
+ : null;
466
+ }
467
+
468
+ /**
469
+ * A clearer refusal for a theme the editor made, named to list, add, use,
470
+ * remove or eject: those commands work on package themes, and the editor
471
+ * theme is used by importing its module. Null for any other refusal.
472
+ * @param {AstryxError} err
473
+ * @param {string} cwd
474
+ * @returns {AstryxError | null}
475
+ */
476
+ export function editorThemeRefusal(err, cwd) {
477
+ // A refused compile ends here: its theme locks go now, not at exit.
478
+ void releaseCompileHold?.();
479
+ if (
480
+ err.code !== ERROR_CODES.ERR_UNKNOWN_THEME &&
481
+ !/unknown theme|is not added|not a theme package/i.test(err.message)
482
+ )
483
+ return null;
484
+ const root = projectRoot(cwd);
485
+ const named = /"([a-z][a-z0-9-]*)"|'([a-z][a-z0-9-]*)'/.exec(err.message);
486
+ const slug = named ? editorThemeOf(root, named[1] ?? named[2]) : null;
487
+ if (!slug) return null;
488
+ return new AstryxError(
489
+ `${slug} is a theme the editor made (themes/${slug}/), not a theme package, so list, add, use, remove and eject do not take it. Import its module (themes/${slug}/${slug}.js) where the app picks its theme, or change it with the editor.`,
490
+ [
491
+ {
492
+ name: `astryx experimental theme editor show ${slug}`,
493
+ reason: 'see the theme',
494
+ },
495
+ ],
496
+ ERROR_CODES.ERR_UNKNOWN_THEME,
497
+ );
498
+ }
499
+
500
+ /**
501
+ * A refusal before `compile` runs on an editor theme's files, or null: the
502
+ * editor's generated settings are not a theme source, `--family` does not
503
+ * take an editor theme, and `--check` checks an editor theme by the editor's
504
+ * own rules (waiting for a change in progress).
505
+ * @param {string[]} files
506
+ * @param {{cwd: string, check?: boolean, family?: boolean}} options
507
+ * @returns {Promise<AstryxError | null>}
508
+ */
509
+ export async function editorCompileProblem(files, {cwd, check, family}) {
510
+ const root = projectRoot(cwd);
511
+ for (const file of files) {
512
+ const slug = editorThemeOf(root, path.resolve(cwd, file));
513
+ if (!slug) continue;
514
+ const source = `themes/${slug}/${slug}.theme.ts`;
515
+ if (/\.settings\.(ts|json)$/.test(file))
516
+ return new AstryxError(
517
+ `${file} is the editor's own settings for ${slug}, not a theme source; compile the theme source.`,
518
+ [
519
+ {
520
+ name: `astryx experimental theme compile ${quoteCommandArgument(source)}`,
521
+ reason: 'do this instead',
522
+ },
523
+ ],
524
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
525
+ );
526
+ if (family)
527
+ return new AstryxError(
528
+ `${slug} is a theme the editor made; --family builds package theme families, not editor themes. Compile it on its own.`,
529
+ [
530
+ {
531
+ name: `astryx experimental theme compile ${quoteCommandArgument(source)}`,
532
+ reason: 'do this instead',
533
+ },
534
+ ],
535
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
536
+ );
537
+ {
538
+ // A check waits for a change in progress, so it never reads one half
539
+ // written. A plain compile builds the theme source, which reads the
540
+ // generated settings: when those no longer match the settings, it
541
+ // would report ok without them.
542
+ // `compile` holds the lock already while it runs (editorThemeHold).
543
+ const why = COMPILE_HELD.has(`${root}\0${slug}`)
544
+ ? await edit.editorStale(root, slug)
545
+ : await withLock(root, lockName(slug), () =>
546
+ edit.editorStale(root, slug),
547
+ );
548
+ if (why && !check)
549
+ return new AstryxError(
550
+ `${slug}'s generated settings do not match its settings (${why}), so compile would build the old ones. The editor builds it from its settings.`,
551
+ [
552
+ {
553
+ name: `astryx experimental theme editor show ${slug}`,
554
+ reason: 'do this instead',
555
+ },
556
+ ],
557
+ ERROR_CODES.ERR_THEME_INVALID,
558
+ );
559
+ if (why)
560
+ return new AstryxError(
561
+ `${slug} is not up to date: ${why}. The editor builds it again from its settings.`,
562
+ [
563
+ {
564
+ name: `astryx experimental theme editor show ${slug}`,
565
+ reason: 'build it again',
566
+ },
567
+ ],
568
+ ERROR_CODES.ERR_THEME_INVALID,
569
+ );
570
+ }
571
+ }
572
+ return null;
573
+ }
574
+
575
+ /** The editor themes a running `compile` holds the lock of, by project and name. */
576
+ const COMPILE_HELD = new Set();
577
+
578
+ /** @type {(() => Promise<void>) | null} The release of the running compile's hold. */
579
+ let releaseCompileHold = null;
580
+
581
+ /**
582
+ * Hold the theme lock of every editor theme among the files while
583
+ * `compile` builds or checks them, so it never reads a change half
584
+ * written. Resolves to the release.
585
+ * @param {string[]} files
586
+ * @param {{cwd: string}} options
587
+ * @returns {Promise<() => Promise<void>>}
588
+ */
589
+ export async function editorThemeHold(files, {cwd}) {
590
+ // Two compiles of one theme in one process: the second waits for the
591
+ // lock like any other command.
592
+ const root = projectRoot(cwd);
593
+ const slugs = [
594
+ ...new Set(
595
+ files.map(f => editorThemeOf(root, path.resolve(cwd, f))).filter(Boolean),
596
+ ),
597
+ ].sort();
598
+ /** @type {Array<() => Promise<void>>} */
599
+ const releases = [];
600
+ const releaseAll = async () => {
601
+ if (releaseCompileHold === releaseAll) releaseCompileHold = null;
602
+ for (const r of releases.splice(0).reverse()) await r();
603
+ };
604
+ releaseCompileHold = releaseAll;
605
+ for (const slug of /** @type {string[]} */ (slugs)) {
606
+ /** @type {() => void} */
607
+ let release = () => {};
608
+ const held = new Promise(r => {
609
+ release = () => r(undefined);
610
+ });
611
+ /** @type {(e?: unknown) => void} */
612
+ let ready = () => {};
613
+ const got = new Promise(r => {
614
+ ready = r;
615
+ });
616
+ const key = `${root}\0${slug}`;
617
+ const done = withLock(root, lockName(slug), async () => {
618
+ COMPILE_HELD.add(key);
619
+ ready();
620
+ try {
621
+ await held;
622
+ } finally {
623
+ COMPILE_HELD.delete(key);
624
+ }
625
+ }).catch(e => ready(e));
626
+ const err = await got;
627
+ if (err) {
628
+ await releaseAll();
629
+ throw err;
630
+ }
631
+ releases.push(async () => {
632
+ release();
633
+ await done;
634
+ });
635
+ }
636
+ return releaseAll;
637
+ }
@@ -17,12 +17,13 @@
17
17
  * @param {string} slug
18
18
  * @param {import('./_settings.mjs').ThemeData} data
19
19
  * @param {string} [skip]
20
- * @returns {{setting: import('./_settings.mjs').Setting, why: string} | null}
20
+ * @returns {Array<{setting: import('./_settings.mjs').Setting, why: string, scope?: boolean}>} every saved setting the editor no longer accepts
21
21
  */
22
- export function storedTokenProblem(ctx: import("./_settings.mjs").Ctx, slug: string, data: import("./_settings.mjs").ThemeData, skip?: string): {
22
+ export function storedProblems(ctx: import("./_settings.mjs").Ctx, slug: string, data: import("./_settings.mjs").ThemeData, skip?: string): Array<{
23
23
  setting: import("./_settings.mjs").Setting;
24
24
  why: string;
25
- } | null;
25
+ scope?: boolean;
26
+ }>;
26
27
  /**
27
28
  * A value of a type to put in a suggestion, so a suggested command runs.
28
29
  * @param {string} type
@@ -41,6 +42,7 @@ export function exampleOf(type: string, name: string): string;
41
42
  * @returns {import('./_settings.mjs').Setting}
42
43
  */
43
44
  export function checkSetting(ctx: import("./_settings.mjs").Ctx, slug: string, data: import("./_settings.mjs").ThemeData, thing: string, value: string | undefined, flags: SetFlags, unset?: boolean): import("./_settings.mjs").Setting;
45
+ export { lengthPx };
44
46
  /** The aspects `how` answers at the whole-theme level. */
45
47
  export const ASPECTS: string[];
46
48
  export type SetFlags = {
@@ -50,3 +52,4 @@ export type SetFlags = {
50
52
  mode?: string | undefined;
51
53
  only?: boolean | undefined;
52
54
  };
55
+ import { lengthPx } from './_settings.mjs';