@astryxdesign/cli 0.7.15 → 0.7.16-canary.g07c77c0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +5 -3
  2. package/api/build/_adapter.d.mts +1 -0
  3. package/api/build/blocks/blocks.d.mts +1 -0
  4. package/api/build/blocks/blocks.mjs +18 -1
  5. package/api/component/_adapter.d.mts +1 -1
  6. package/api/component/_adapter.mjs +28 -1
  7. package/api/doctor/_adapter.d.mts +17 -0
  8. package/api/doctor/_adapter.mjs +43 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.mjs +18 -4
  11. package/api/doctor/theme-checks.mjs +1 -1
  12. package/api/integration/add-contribution.mjs +3 -3
  13. package/api/integration/pack-check.mjs +14 -8
  14. package/api/integration/validate-integration.mjs +1 -1
  15. package/api/search/_adapter.mjs +15 -16
  16. package/api/search/_entries.d.mts +2 -1
  17. package/api/search/_entries.mjs +28 -1
  18. package/api/swizzle/_moduleGraph.mjs +1 -1
  19. package/api/theme/_adapter.d.mts +5 -2
  20. package/api/theme/_adapter.mjs +43 -12
  21. package/api/theme/_fork.mjs +1 -1
  22. package/api/theme/build/build.d.mts +116 -32
  23. package/api/theme/build/build.mjs +449 -102
  24. package/api/theme/eject/eject.mjs +22 -1
  25. package/api/theme/template/template.d.mts +19 -0
  26. package/api/theme/template/template.mjs +102 -25
  27. package/api/theme/theme.type.d.mts +5 -1
  28. package/api/theme/theme.type.mjs +2 -1
  29. package/api/theme/themeBuild.doc.mjs +3 -3
  30. package/api/theme/themeEject.doc.mjs +1 -1
  31. package/api/theme/themeTemplate.doc.mjs +9 -3
  32. package/api/theme-edit/_adapter.d.mts +32 -2
  33. package/api/theme-edit/_adapter.mjs +213 -36
  34. package/api/theme-edit/_check.d.mts +69 -3
  35. package/api/theme-edit/_check.mjs +1517 -218
  36. package/api/theme-edit/_color.d.mts +2 -8
  37. package/api/theme-edit/_color.mjs +292 -219
  38. package/api/theme-edit/_compiler.d.mts +1 -0
  39. package/api/theme-edit/_compiler.mjs +20 -1
  40. package/api/theme-edit/_context.d.mts +29 -0
  41. package/api/theme-edit/_context.mjs +426 -40
  42. package/api/theme-edit/_css.d.mts +60 -1
  43. package/api/theme-edit/_css.mjs +404 -28
  44. package/api/theme-edit/_edit.d.mts +9 -0
  45. package/api/theme-edit/_edit.mjs +1300 -135
  46. package/api/theme-edit/_how-commands.d.mts +11 -26
  47. package/api/theme-edit/_how-commands.mjs +30 -2
  48. package/api/theme-edit/_how-question.d.mts +7 -0
  49. package/api/theme-edit/_how-question.mjs +1304 -176
  50. package/api/theme-edit/_how.mjs +144 -30
  51. package/api/theme-edit/_overview.mjs +2 -0
  52. package/api/theme-edit/_palette.d.mts +11 -0
  53. package/api/theme-edit/_palette.mjs +194 -65
  54. package/api/theme-edit/_parts.d.mts +33 -0
  55. package/api/theme-edit/_parts.mjs +138 -9
  56. package/api/theme-edit/_png.d.mts +18 -0
  57. package/api/theme-edit/_png.mjs +95 -14
  58. package/api/theme-edit/_preview-app.d.mts +9 -0
  59. package/api/theme-edit/_preview-app.mjs +1191 -71
  60. package/api/theme-edit/_preview.d.mts +16 -3
  61. package/api/theme-edit/_preview.mjs +335 -30
  62. package/api/theme-edit/_project.d.mts +11 -0
  63. package/api/theme-edit/_project.mjs +46 -12
  64. package/api/theme-edit/_settings.d.mts +240 -5
  65. package/api/theme-edit/_settings.mjs +2561 -115
  66. package/api/theme-edit/_tables.d.mts +24 -0
  67. package/api/theme-edit/_tables.mjs +211 -149
  68. package/api/theme-edit/_vet.d.mts +42 -0
  69. package/api/theme-edit/_vet.mjs +144 -0
  70. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  71. package/api/theme-edit/theme-edit.type.mjs +1 -1
  72. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  73. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  74. package/api/upgrade/registry/registry.mjs +6 -1
  75. package/assets/codemods/parse.mjs +2 -2
  76. package/assets/docs/tree/single-component.doc.mjs +11 -2
  77. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  78. package/assets/docs.generated.json +2 -2
  79. package/assets/preview-app/next.config.mjs +7 -1
  80. package/assets/preview-app/package.json +1 -0
  81. package/assets/preview-app/src/app/globals.css +1 -0
  82. package/assets/self-audit.generated.json +1 -1
  83. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  84. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  85. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  86. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  87. package/assets/templates/components.generated.json +1 -1
  88. package/assets/templates/pages/dashboard/page.tsx +1 -1
  89. package/authoring/doctypes/_schema.d.mts +52 -5
  90. package/authoring/doctypes/_schema.mjs +62 -7
  91. package/authoring/doctypes/base/type.ts +10 -0
  92. package/authoring/doctypes/component/component.doc.mjs +1 -1
  93. package/authoring/doctypes/function/function.doc.mjs +6 -0
  94. package/authoring/doctypes/function/type.ts +3 -0
  95. package/authoring/doctypes/legacy.mjs +5 -1
  96. package/authoring/index.d.ts +1 -0
  97. package/authoring/shadcn/source-variants.d.mts +1 -1
  98. package/authoring/shadcn/source-variants.mjs +32 -10
  99. package/clients/cli/build-id.generated.json +1 -1
  100. package/clients/cli/commands/doctor.doc.mjs +2 -2
  101. package/clients/cli/commands/experimental/theme.mjs +237 -45
  102. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  103. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  105. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  106. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  108. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  109. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  110. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  111. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  112. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  113. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  114. package/clients/cli/commands/theme.mjs +190 -46
  115. package/clients/cli/formatters/index.mjs +7 -4
  116. package/clients/cli/lib/cli-error.mjs +9 -3
  117. package/clients/cli/lib/component-format.mjs +27 -9
  118. package/clients/cli/lib/json-shim.mjs +72 -2
  119. package/clients/cli/manifest.generated.json +1 -1
  120. package/clients/cli/run.mjs +49 -0
  121. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  122. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  123. package/foundation/agent-docs/agent-docs.mjs +3 -2
  124. package/foundation/config/config-writer.mjs +2 -2
  125. package/foundation/config/project.mjs +60 -14
  126. package/foundation/discovery/component-discovery.mjs +5 -17
  127. package/foundation/discovery/icon-set-writer.mjs +1 -1
  128. package/foundation/discovery/module-exports.mjs +1 -15
  129. package/foundation/discovery/template-adapter.mjs +44 -19
  130. package/foundation/discovery/template-source-tree.mjs +3 -16
  131. package/foundation/discovery/theme-discovery.d.mts +5 -1
  132. package/foundation/discovery/theme-discovery.mjs +30 -35
  133. package/foundation/fs/exact-codec.d.mts +35 -0
  134. package/foundation/fs/exact-codec.mjs +148 -0
  135. package/foundation/fs/gather-cache.d.mts +15 -5
  136. package/foundation/fs/gather-cache.mjs +123 -30
  137. package/foundation/fs/paths.d.mts +39 -0
  138. package/foundation/fs/paths.mjs +44 -11
  139. package/foundation/fs/read-record.mjs +11 -1
  140. package/foundation/integrations/contribution-fixes.mjs +1 -16
  141. package/foundation/integrations/may-have-integrations.mjs +3 -2
  142. package/foundation/integrations/public-imports.mjs +1 -1
  143. package/foundation/render/embedded-imports.mjs +1 -1
  144. package/foundation/render/host-exit.d.mts +8 -0
  145. package/foundation/render/host-exit.mjs +11 -0
  146. package/foundation/render/page-host.mjs +56 -10
  147. package/foundation/render/page-worker.mjs +14 -0
  148. package/foundation/render/render-page.mjs +37 -2
  149. package/foundation/response/error-codes.d.mts +2 -1
  150. package/foundation/response/error-codes.d.ts +1 -0
  151. package/foundation/response/error-codes.doc.mjs +5 -0
  152. package/foundation/response/error-codes.mjs +3 -0
  153. package/foundation/response/json.d.mts +15 -0
  154. package/foundation/response/json.mjs +52 -1
  155. package/foundation/response/response-types.doc.mjs +1 -1
  156. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  157. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  158. package/foundation/xle/browser.d.mts +2 -2
  159. package/package.json +7 -6
@@ -13,6 +13,7 @@
13
13
  import {parse as parseModule} from '@babel/parser';
14
14
  import * as fs from 'node:fs';
15
15
  import * as path from 'node:path';
16
+ import {createRequire} from 'node:module';
16
17
  import {fileURLToPath} from 'node:url';
17
18
  import {cliVersion} from '../../foundation/release/run-context.mjs';
18
19
  import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
@@ -21,7 +22,7 @@ import {
21
22
  PathSafetyError,
22
23
  } from '../../foundation/fs/path-safety.mjs';
23
24
  import {baseResolved, installLine, openProject} from './_project.mjs';
24
- import {P} from './_tables.mjs';
25
+ import {P, wordTable} from './_tables.mjs';
25
26
  import {
26
27
  buildTheme,
27
28
  editedThemes,
@@ -33,9 +34,11 @@ import {
33
34
  shown,
34
35
  staleBuild,
35
36
  themeFiles,
37
+ usableNewName,
36
38
  windowsReserved,
37
39
  } from './_settings.mjs';
38
40
  import {
41
+ baseFontsCss,
39
42
  colorsPageSource,
40
43
  componentsPageSource,
41
44
  overviewPageSource,
@@ -43,6 +46,7 @@ import {
43
46
  themeImports,
44
47
  } from './_preview.mjs';
45
48
  import {
49
+ isEditorTemp,
46
50
  PALETTE_STAND_IN,
47
51
  paletteFiles,
48
52
  paletteMapping,
@@ -60,7 +64,10 @@ import {
60
64
  import {detectStylingSystem} from '../../foundation/agent-docs/agent-docs.mjs';
61
65
  import {requireProject, context} from './_context.mjs';
62
66
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
63
- import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
67
+ import {
68
+ formatCliCommand,
69
+ quoteCommandArgument,
70
+ } from '../../foundation/env/package-manager.mjs';
64
71
  import {sha256} from '../../foundation/render/source-block.mjs';
65
72
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
66
73
 
@@ -84,7 +91,9 @@ const MAX_WORDS = 40;
84
91
 
85
92
  /**
86
93
  * @typedef {{id: string, label: string, file: string}} PreviewPage
87
- * @typedef {{version: 1, theme: string | null, pages: PreviewPage[], files: string[], hashes?: Record<string, string>}} PreviewData
94
+ * @typedef {{version: 1, theme: string | null, pages: PreviewPage[], files: string[], hashes?: Record<string, string>, parents?: number}} PreviewData
95
+ * `parents`: how many folders over the preview folder its first add made,
96
+ * which remove takes away again when they are empty.
88
97
  * `hashes`: a short hash of each file as the preview wrote it, so a file
89
98
  * changed by hand is never replaced or deleted
90
99
  * @typedef {(path: string | null) => string} Retry the command again, with
@@ -134,6 +143,97 @@ function checkFolderName(where, what, retry) {
134
143
  );
135
144
  }
136
145
 
146
+ /**
147
+ * Whether a stylesheet comes in through the files the root layout imports,
148
+ * followed through relative and `@/` imports (a root `styles/globals.css`,
149
+ * as create-next-app writes it), a few levels deep.
150
+ * @param {string} cwd
151
+ * @param {string} app the routes folder
152
+ * @param {RegExp} sheet
153
+ */
154
+ function layoutImportsSheet(cwd, app, sheet, dir = app) {
155
+ // Every layout over the preview: the routes folder's, and one in a route
156
+ // group or [param] folder on the way.
157
+ /** @type {string[]} */
158
+ const starts = [];
159
+ for (let at = dir; ; at = path.dirname(at)) {
160
+ for (const x of ['tsx', 'ts', 'jsx', 'js'])
161
+ if (fs.existsSync(path.join(at, `layout.${x}`)))
162
+ starts.push(path.join(at, `layout.${x}`));
163
+ if (at === app || !at.startsWith(app + path.sep)) break;
164
+ }
165
+ if (!starts.length) return false;
166
+ const aliases = tsconfigAliases(cwd);
167
+ const seen = new Set();
168
+ /** @param {string} file @param {number} depth @returns {boolean} */
169
+ const reads = (file, depth) => {
170
+ if (seen.has(file) || depth > 4) return false;
171
+ seen.add(file);
172
+ /** @type {string} */
173
+ let text;
174
+ try {
175
+ text = fs.readFileSync(file, 'utf8');
176
+ } catch {
177
+ return false;
178
+ }
179
+ if (sheet.test(text)) return true;
180
+ for (const m of text.matchAll(
181
+ /(?:import|@import)\s*(?:[^'"]*from\s*)?(?:url\()?['"]([^'"]+)['"]/g,
182
+ )) {
183
+ const spec = m[1];
184
+ // An alias the tsconfig sets; else `@/` is the src folder or the
185
+ // project root.
186
+ const alias = aliases.find(a => spec.startsWith(a.prefix));
187
+ const bases = alias
188
+ ? alias.to.map(t => path.join(t, spec.slice(alias.prefix.length)))
189
+ : spec.startsWith('@/')
190
+ ? [
191
+ path.join(cwd, 'src', spec.slice(2)),
192
+ path.join(cwd, spec.slice(2)),
193
+ ]
194
+ : spec.startsWith('.')
195
+ ? [path.resolve(path.dirname(file), spec)]
196
+ : [];
197
+ const hit = bases
198
+ .flatMap(b =>
199
+ ['', '.css', '.scss', '.ts', '.tsx', '.js', '.jsx'].map(x => b + x),
200
+ )
201
+ .find(f => fs.existsSync(f) && fs.statSync(f).isFile());
202
+ if (hit && reads(hit, depth + 1)) return true;
203
+ }
204
+ return false;
205
+ };
206
+ return starts.some(start => reads(start, 0));
207
+ }
208
+
209
+ /**
210
+ * The import aliases the app's tsconfig `paths` set (`~/*`, `#app/*`), each
211
+ * with the folders it stands for.
212
+ * @param {string} cwd
213
+ * @returns {Array<{prefix: string, to: string[]}>}
214
+ */
215
+ function tsconfigAliases(cwd) {
216
+ const o = appCompilerOptions(cwd);
217
+ const paths = o && typeof o.paths === 'object' && o.paths ? o.paths : {};
218
+ const baseUrl = path.resolve(
219
+ cwd,
220
+ typeof o?.baseUrl === 'string' ? o.baseUrl : '.',
221
+ );
222
+ return Object.entries(/** @type {Record<string, unknown>} */ (paths)).flatMap(
223
+ ([key, targets]) =>
224
+ key.endsWith('/*') && Array.isArray(targets)
225
+ ? [
226
+ {
227
+ prefix: key.slice(0, -1),
228
+ to: targets
229
+ .filter(t => typeof t === 'string' && t.endsWith('/*'))
230
+ .map(t => path.resolve(baseUrl, String(t).slice(0, -2))),
231
+ },
232
+ ]
233
+ : [],
234
+ );
235
+ }
236
+
137
237
  /**
138
238
  * A note when the app never imports Core's stylesheet, or null: without
139
239
  * it, components render unstyled, and some show nothing. Read from the
@@ -180,7 +280,8 @@ function coreStylesheetMissing(cwd, at) {
180
280
  const src = path.join(cwd, 'src');
181
281
  if (
182
282
  imports(at.app) ||
183
- (at.app.startsWith(src + path.sep) ? false : imports(src))
283
+ (at.app.startsWith(src + path.sep) ? false : imports(src)) ||
284
+ layoutImportsSheet(cwd, at.app, SHEET, at.dir)
184
285
  )
185
286
  return null;
186
287
  const layout = ['tsx', 'ts', 'jsx', 'js']
@@ -204,11 +305,12 @@ function readNextConfig(cwd) {
204
305
  basePath: undefined,
205
306
  distDir: undefined,
206
307
  };
308
+ // The order Next loads them in; it refuses next.config.cjs.
207
309
  for (const name of [
208
- 'next.config.mjs',
209
310
  'next.config.js',
311
+ 'next.config.mjs',
210
312
  'next.config.ts',
211
- 'next.config.cjs',
313
+ 'next.config.mts',
212
314
  ]) {
213
315
  /** @type {string} */
214
316
  let text;
@@ -270,6 +372,11 @@ function readNextConfig(cwd) {
270
372
  let exported = null;
271
373
  for (const st of body) {
272
374
  if (st.type === 'ExportDefaultDeclaration') exported = st.declaration;
375
+ // export {config as default}
376
+ if (st.type === 'ExportNamedDeclaration' && !st.source)
377
+ for (const sp of st.specifiers ?? [])
378
+ if ((sp.exported?.name ?? sp.exported?.value) === 'default')
379
+ exported = sp.local;
273
380
  if (
274
381
  st.type === 'ExpressionStatement' &&
275
382
  st.expression.type === 'AssignmentExpression' &&
@@ -281,6 +388,66 @@ function readNextConfig(cwd) {
281
388
  }
282
389
  const config = exported && configOf(exported);
283
390
  if (!config) return exported ? unknown : none;
391
+ const wrapped = resolve(exported)?.type === 'CallExpression';
392
+ // Changes to the config after it is made: `config.key = value` sets a
393
+ // key (the last one counts), and anything else (Object.assign, a
394
+ // computed key) makes every key unknown.
395
+ const names = new Set(
396
+ [...consts]
397
+ .filter(([, init]) => resolve(init) === config)
398
+ .map(([n]) => n),
399
+ );
400
+ /** @type {Map<string, any>} */
401
+ const later = new Map();
402
+ let changed = false;
403
+ // Only a statement at the top of the file surely runs: a key set inside
404
+ // an `if` or a function, or deleted, is known only by running it.
405
+ const UNSURE = Symbol('unsure');
406
+ const topLevel = new Set(
407
+ body
408
+ .filter(st => st.type === 'ExpressionStatement')
409
+ .map(st => st.expression),
410
+ );
411
+ /** @param {any} n */
412
+ const visit = n => {
413
+ if (!n || typeof n !== 'object') return;
414
+ if (Array.isArray(n)) return n.forEach(visit);
415
+ if (
416
+ n.type === 'AssignmentExpression' &&
417
+ n.left?.type === 'MemberExpression' &&
418
+ names.has(n.left.object?.name)
419
+ ) {
420
+ if (n.left.computed) changed = true;
421
+ else
422
+ later.set(
423
+ n.left.property.name,
424
+ topLevel.has(n) && n.operator === '=' ? n.right : UNSURE,
425
+ );
426
+ }
427
+ if (
428
+ n.type === 'UnaryExpression' &&
429
+ n.operator === 'delete' &&
430
+ n.argument?.type === 'MemberExpression' &&
431
+ names.has(n.argument.object?.name)
432
+ ) {
433
+ if (n.argument.computed) changed = true;
434
+ else later.set(n.argument.property.name, UNSURE);
435
+ }
436
+ if (
437
+ n.type === 'CallExpression' &&
438
+ n.arguments?.some(
439
+ (/** @type {any} */ a) =>
440
+ a.type === 'Identifier' && names.has(a.name),
441
+ ) &&
442
+ n.callee?.type === 'MemberExpression' &&
443
+ n.callee.object?.name === 'Object'
444
+ )
445
+ changed = true;
446
+ for (const [k, v] of Object.entries(n))
447
+ if (k !== 'loc' && k !== 'start' && k !== 'end') visit(v);
448
+ };
449
+ visit(body);
450
+ if (changed) return unknown;
284
451
  // The config's keys in order, with a spread of a constant object read
285
452
  // in place; a spread of anything else may set any key (`null`).
286
453
  /** @type {Array<{key: string, value: any} | null>} */
@@ -302,8 +469,10 @@ function readNextConfig(cwd) {
302
469
  }
303
470
  };
304
471
  flatten(config, 0);
305
- /** The entry that sets a key last; null when an unreadable spread may; undefined when nothing does. @param {string} key */
472
+ /** The entry that sets a key last: a later assignment, else the last key; null when an unreadable spread may; undefined when nothing does. @param {string} key */
306
473
  const prop = key => {
474
+ if (later.has(key))
475
+ return later.get(key) === UNSURE ? null : {key, value: later.get(key)};
307
476
  for (let i = entries.length - 1; i >= 0; i--) {
308
477
  const e = entries[i];
309
478
  if (e === null) return null;
@@ -332,10 +501,13 @@ function readNextConfig(cwd) {
332
501
  const out = n.elements.map((/** @type {any} */ e) => str(e));
333
502
  return out.every((/** @type {any} */ e) => e != null) ? out : null;
334
503
  }),
335
- basePath: value('basePath', n => {
336
- const v = str(n);
337
- return v == null ? null : v.replace(/\/+$/, '');
338
- }),
504
+ // A wrapper such as withX(config) may add a basePath of its own.
505
+ basePath: wrapped
506
+ ? null
507
+ : value('basePath', n => {
508
+ const v = str(n);
509
+ return v == null ? null : v.replace(/\/+$/, '');
510
+ }),
339
511
  distDir: value('distDir', n => {
340
512
  const v = str(n);
341
513
  return v == null
@@ -407,6 +579,134 @@ function reservedFolder(cwd, dir) {
407
579
  return null;
408
580
  }
409
581
 
582
+ /**
583
+ * The app's tsconfig.json compiler options (comments and trailing commas
584
+ * allowed), or null when there is none.
585
+ * @param {string} cwd
586
+ * @returns {Record<string, unknown> | null}
587
+ */
588
+ function appCompilerOptions(cwd) {
589
+ /** @type {string} */
590
+ let text;
591
+ try {
592
+ text = fs.readFileSync(path.join(cwd, 'tsconfig.json'), 'utf8');
593
+ } catch {
594
+ return null;
595
+ }
596
+ try {
597
+ const json = text
598
+ .replace(
599
+ /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\/|\/\/.*$/gm,
600
+ (m, str) => str ?? '',
601
+ )
602
+ .replace(/,(\s*[}\]])/g, '$1');
603
+ const o = JSON.parse(json)?.compilerOptions;
604
+ return o && typeof o === 'object' ? o : {};
605
+ } catch {
606
+ return {};
607
+ }
608
+ }
609
+
610
+ /**
611
+ * Notes on what the preview's TypeScript files need from the app: an app
612
+ * with no TypeScript gets the install line (Next sets it up on the next
613
+ * build otherwise), and an app whose tsconfig turns on
614
+ * `noUncheckedIndexedAccess` is told which template pages were written as
615
+ * their template ships them, which may not pass it.
616
+ * @param {string} cwd
617
+ * @param {string} dir
618
+ * @param {string[]} added page ids added by this command
619
+ * @returns {string[]}
620
+ */
621
+ function typeScriptNotes(cwd, dir, added) {
622
+ const options = appCompilerOptions(cwd);
623
+ if (!options) {
624
+ const hasTs = (() => {
625
+ try {
626
+ return Boolean(
627
+ createRequire(path.join(cwd, 'package.json')).resolve('typescript'),
628
+ );
629
+ } catch {
630
+ return false;
631
+ }
632
+ })();
633
+ return hasTs
634
+ ? []
635
+ : [
636
+ `the app has no TypeScript, and the preview's files are .tsx, so the next build sets it up; to do it now: ${installLine(cwd, ['typescript', '@types/react', '@types/node']).replace(/ (add|install) /, ' $1 -D ')}`,
637
+ ];
638
+ }
639
+ const templates = added.filter(
640
+ id => !['overview', 'components', COLORS_PAGE.id].includes(id),
641
+ );
642
+ if (options.noUncheckedIndexedAccess !== true || !templates.length) return [];
643
+ const files = templates.map(id =>
644
+ shown(cwd, path.join(dir, PAGES_DIR, `${id}.tsx`)),
645
+ );
646
+ return [
647
+ `the app's tsconfig.json turns on noUncheckedIndexedAccess, and ${files.join(', ')} ${files.length > 1 ? 'are' : 'is'} written as the page template ships, which may not pass it; if the build stops there, fix the reported lines or remove the page with ${PREVIEW} remove ${templates[0]}`,
648
+ ];
649
+ }
650
+
651
+ /**
652
+ * Why a file cannot be read (its error code), or null when it can.
653
+ * @param {string} file
654
+ * @returns {string | null}
655
+ */
656
+ function unreadable(file) {
657
+ try {
658
+ fs.closeSync(fs.openSync(file, 'r'));
659
+ return null;
660
+ } catch (e) {
661
+ const code = /** @type {any} */ (e)?.code;
662
+ return code === 'ENOENT' ? null : (code ?? 'error');
663
+ }
664
+ }
665
+
666
+ /**
667
+ * Whether a folder beside `dir` has its name in another case.
668
+ * @param {string} dir
669
+ */
670
+ function twinBeside(dir) {
671
+ const name = path.basename(dir);
672
+ try {
673
+ return fs
674
+ .readdirSync(path.dirname(dir))
675
+ .some(n => n !== name && n.toLowerCase() === name.toLowerCase());
676
+ } catch {
677
+ return false;
678
+ }
679
+ }
680
+
681
+ /**
682
+ * A folder beside `dir`, or beside one of its parents, whose name differs
683
+ * only in case, or null.
684
+ * @param {string} dir
685
+ * @returns {string | null}
686
+ */
687
+ function sameCaseSibling(dir) {
688
+ for (let at = dir; path.dirname(at) !== at; at = path.dirname(at)) {
689
+ const parent = path.dirname(at);
690
+ const name = path.basename(at);
691
+ /** @type {string[]} */
692
+ let names;
693
+ try {
694
+ names = fs.readdirSync(parent);
695
+ } catch {
696
+ continue;
697
+ }
698
+ const twin = names.find(
699
+ n => n !== name && n.toLowerCase() === name.toLowerCase(),
700
+ );
701
+ if (twin) return path.join(parent, twin);
702
+ if (fs.existsSync(path.join(parent, 'package.json'))) break;
703
+ }
704
+ return null;
705
+ }
706
+
707
+ /** An intercepting route folder: `(.)x`, `(..)x`, `(..)(..)x`, `(...)x`. */
708
+ const INTERCEPT = /^\((\.{1,3})\)/;
709
+
410
710
  /**
411
711
  * Why Next does not serve a folder inside the routes folder at its own
412
712
  * URL, or null: a `_private` folder is never routed, an `@slot` folder is a
@@ -418,7 +718,9 @@ function unroutedSegment(app, dir) {
418
718
  const seg = path
419
719
  .relative(app, dir)
420
720
  .split(path.sep)
421
- .find(x => /^[_@[]/.test(x));
721
+ .find(x => /^[_@[]/.test(x) || INTERCEPT.test(x));
722
+ if (seg && INTERCEPT.test(seg))
723
+ return `Next reads the folder ${seg} as an intercepting route ((.), (..) and (...) folders show another route's page), not a URL of its own, and a page there breaks the app`;
422
724
  return seg
423
725
  ? `Next does not serve the folder ${seg} at a URL of its own (_private folders are never routed, @slot and [param] folders are not plain URL segments)`
424
726
  : null;
@@ -615,6 +917,75 @@ function checkPlacement(cwd, dir, where, retry) {
615
917
  `${where} is no place for the preview: ${why}.`,
616
918
  {run: [fallback]},
617
919
  );
920
+ // A folder name that is not a plain URL segment (a space, an accent,
921
+ // ?, #, %) is not served at the URL it seems to have. The characters a
922
+ // URL path takes as they are (RFC 3986 unreserved and sub-delims, @, ~)
923
+ // are served.
924
+ const PLAIN = /^[A-Za-z0-9._~!$&'()+,;=@-]+$/;
925
+ const segs = app ? path.relative(app, dir).split(path.sep) : [];
926
+ const odd = segs.filter(
927
+ seg => seg && !/^\(.+\)$|^\[.+\]$/.test(seg) && !PLAIN.test(seg),
928
+ );
929
+ if (app && odd.length) {
930
+ const slug = (/** @type {string} */ seg) =>
931
+ seg
932
+ .normalize('NFD')
933
+ .replace(/[\u0300-\u036f]/g, '')
934
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
935
+ .replace(/^-+|-+$/g, '')
936
+ .toLowerCase() || 'theme-preview';
937
+ // Every odd segment slugged, then the first free folder from it.
938
+ const base = path.join(
939
+ app,
940
+ ...segs.map(seg => (odd.includes(seg) ? slug(seg) : seg)),
941
+ );
942
+ let fixed = base;
943
+ for (
944
+ let n = 2;
945
+ fs.existsSync(fixed) || twinBeside(fixed) || sameUrlPage(cwd, app, fixed);
946
+ n++
947
+ )
948
+ fixed = `${base}-${n}`;
949
+ refuse(
950
+ E.ERR_INVALID_ARGUMENT,
951
+ `${where} is no place for the preview: Next does not serve the folder "${odd[0]}" at the URL its name seems to give (a space, a letter outside A-Z, %, # or ? are no plain URL segment).`,
952
+ {run: [retry(shown(cwd, fixed))]},
953
+ );
954
+ }
955
+ // A folder whose name differs from a folder beside it only in case is the
956
+ // same folder on macOS and Windows: one of them is lost in a checkout.
957
+ const twin = sameCaseSibling(dir);
958
+ if (twin) {
959
+ // A twin of a folder on the way: the same path through the folder that
960
+ // is there. A twin of the folder itself: the first free name beside it.
961
+ const base = path.dirname(twin);
962
+ const rel = path.relative(base, dir).split(path.sep);
963
+ // Both spellings are folders already: no path through either is free,
964
+ // so the way on is a new folder beside them.
965
+ const bothThere = rel.length > 1 && fs.existsSync(path.join(base, rel[0]));
966
+ let free = path.join(twin, ...rel.slice(1));
967
+ if (rel.length === 1 || bothThere) {
968
+ const start = rel.length === 1 ? dir : path.join(base, 'theme-preview');
969
+ free = start;
970
+ for (let n = 2; fs.existsSync(free) || twinBeside(free); n++)
971
+ free = `${start}-${n}`;
972
+ }
973
+ const existing = fs.existsSync(path.join(dir, PREVIEW_DATA));
974
+ refuse(
975
+ E.ERR_INVALID_ARGUMENT,
976
+ `${where} is no place for the preview: ${shownDir(cwd, twin)}/ differs from it only in case, and on macOS and Windows they are one folder, so the project could not be checked out there.${existing ? ` The preview already there can still be removed.` : ''}`,
977
+ {
978
+ run: [
979
+ retry(shown(cwd, free)),
980
+ ...(existing
981
+ ? [
982
+ `${PREVIEW} remove --path ${quoteCommandArgument(shownDir(cwd, dir))}`,
983
+ ]
984
+ : []),
985
+ ],
986
+ },
987
+ );
988
+ }
618
989
  if (!app) return;
619
990
  if (served && app !== served)
620
991
  refuse(
@@ -646,18 +1017,19 @@ function checkPlacement(cwd, dir, where, retry) {
646
1017
  );
647
1018
  }
648
1019
  if (
649
- served &&
650
- !rootLayouts.length &&
651
- !fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f))
1020
+ (app && !served) ||
1021
+ (served &&
1022
+ !rootLayouts.length &&
1023
+ !fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f)))
652
1024
  ) {
653
1025
  let free = 'theme-app';
654
1026
  for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
655
1027
  free = `theme-app-${n}`;
656
1028
  refuse(
657
1029
  E.ERR_INVALID_ARGUMENT,
658
- `${shown(cwd, served)}/ has no root layout (no layout.tsx in it or in a route group), so Next cannot build a page in ${where}.`,
1030
+ `${shown(cwd, served ?? app)}/ has no root layout (no layout.tsx in it or in a route group)${served ? '' : ' and is not there yet'}, so Next cannot build a page in ${where}.`,
659
1031
  {
660
- fix: `add a root layout to ${shown(cwd, served)}/ to use the preview in this app`,
1032
+ fix: `add a root layout to ${shown(cwd, served ?? app)}/ to use the preview in this app`,
661
1033
  run: [
662
1034
  `${PREVIEW} app ${free} # a new app with its own root layout and the preview`,
663
1035
  ],
@@ -676,8 +1048,12 @@ function checkPlacement(cwd, dir, where, retry) {
676
1048
  );
677
1049
  const clash = sameUrlPage(cwd, app, dir);
678
1050
  if (clash) {
679
- let free = `${dir}-2`;
680
- for (let n = 3; fs.existsSync(free); n++) free = `${dir}-${n}`;
1051
+ // The first free name from the base name, whose URL no other page
1052
+ // serves either.
1053
+ const base = dir.replace(/-\d+$/, '');
1054
+ let free = `${base}-2`;
1055
+ for (let n = 3; fs.existsSync(free) || sameUrlPage(cwd, app, free); n++)
1056
+ free = `${base}-${n}`;
681
1057
  refuse(
682
1058
  E.ERR_FILE_EXISTS,
683
1059
  `${shown(cwd, clash)} already serves /${urlSegments(app, dir).join('/')} or the URLs under it, so a preview in ${where} would stop the app from building, or take that URL from it.`,
@@ -727,6 +1103,52 @@ function previewDir(cwd, where, opts = {}) {
727
1103
  );
728
1104
  throw e;
729
1105
  }
1106
+ // A file on the way, or a path longer than the system takes, would
1107
+ // fail every command on it with a system error.
1108
+ const blocker = (() => {
1109
+ for (
1110
+ let at = path.dirname(dir);
1111
+ at.startsWith(cwd + path.sep);
1112
+ at = path.dirname(at)
1113
+ )
1114
+ try {
1115
+ if (!fs.statSync(at).isDirectory()) return at;
1116
+ } catch {
1117
+ // Not there yet: made with the folder.
1118
+ }
1119
+ return null;
1120
+ })();
1121
+ if (blocker)
1122
+ refuse(
1123
+ E.ERR_INVALID_ARGUMENT,
1124
+ `--path ${where} goes through ${shown(cwd, blocker)}, which is a file, so no folder can be made there.`,
1125
+ {
1126
+ run: [
1127
+ retry(
1128
+ shown(cwd, path.join(path.dirname(blocker), 'theme-preview')),
1129
+ ),
1130
+ ],
1131
+ },
1132
+ );
1133
+ // A folder name is at most 255 bytes on every common file system; the
1134
+ // whole path, with the preview's own files below it, is kept under
1135
+ // 3,500 bytes.
1136
+ const longName = path
1137
+ .relative(cwd, dir)
1138
+ .split(path.sep)
1139
+ .find(seg => Buffer.byteLength(seg) > 255);
1140
+ if (longName)
1141
+ refuse(
1142
+ E.ERR_INVALID_ARGUMENT,
1143
+ `--path ${where} has a folder name longer than 255 bytes, the most a file system takes for one name.`,
1144
+ {run: [retry(null)]},
1145
+ );
1146
+ if (Buffer.byteLength(dir) > 3500)
1147
+ refuse(
1148
+ E.ERR_INVALID_ARGUMENT,
1149
+ `--path ${where} is longer than 3,500 bytes, with the preview's files in it.`,
1150
+ {run: [retry(null)]},
1151
+ );
730
1152
  if (opts.write) checkPlacement(cwd, dir, `--path ${where}`, retry);
731
1153
  return {dir, app: appOf(dir)};
732
1154
  }
@@ -766,22 +1188,95 @@ function previewDir(cwd, where, opts = {}) {
766
1188
  served && !known ? (nestedRootLayouts(served)[0] ?? null) : null;
767
1189
  const dir = known ?? (served && path.join(nested ?? served, 'theme-preview'));
768
1190
  if (!dir && opts.optional) return /** @type {any} */ (null);
769
- if (!dir)
1191
+ if (!dir) {
1192
+ // A workspace root: the Next apps below it, each with a --path into
1193
+ // its routes folder.
1194
+ const apps = nextAppsUnder(cwd);
770
1195
  refuse(
771
1196
  E.ERR_NOT_FOUND,
772
- 'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
1197
+ apps.length
1198
+ ? `No app routes folder here (app/ or src/app/); the Next ${apps.length > 1 ? 'apps' : 'app'} below ${apps.length > 1 ? 'are' : 'is'} ${apps.map(a => `${shown(cwd, a.root)}/`).join(', ')}.`
1199
+ : 'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
773
1200
  {
774
1201
  run: [
775
- `${PREVIEW} add --path app/theme-preview # an app routes folder beside the app's own`,
1202
+ ...apps
1203
+ .slice(0, 3)
1204
+ .map(
1205
+ a =>
1206
+ `${PREVIEW} add --path ${quoteCommandArgument(shown(cwd, path.join(a.routes, 'theme-preview')))}`,
1207
+ ),
776
1208
  `${PREVIEW} app theme-app # a new starter app with the preview in it`,
777
1209
  ],
778
1210
  },
779
1211
  );
1212
+ }
780
1213
  inProjectOrRefuse(cwd, dir, retry);
781
1214
  if (opts.write) checkPlacement(cwd, dir, `${shownDir(cwd, dir)}/`, retry);
782
1215
  return {dir, app: appOf(dir)};
783
1216
  }
784
1217
 
1218
+ /**
1219
+ * The Next apps in folders below `cwd` (a few levels, node_modules left
1220
+ * out): each folder with a package.json that depends on `next` and a routes
1221
+ * folder with a root layout.
1222
+ * @param {string} cwd
1223
+ * @returns {Array<{root: string, routes: string}>}
1224
+ */
1225
+ function nextAppsUnder(cwd) {
1226
+ /** @type {Array<{root: string, routes: string}>} */
1227
+ const out = [];
1228
+ /** @param {string} dir @param {number} depth */
1229
+ const walk = (dir, depth) => {
1230
+ if (depth > 3 || out.length >= 10) return;
1231
+ /** @type {fs.Dirent[]} */
1232
+ let entries;
1233
+ try {
1234
+ entries = fs.readdirSync(dir, {withFileTypes: true});
1235
+ } catch {
1236
+ return;
1237
+ }
1238
+ for (const e of entries) {
1239
+ if (
1240
+ !e.isDirectory() ||
1241
+ e.name === 'node_modules' ||
1242
+ e.name.startsWith('.')
1243
+ )
1244
+ continue;
1245
+ const sub = path.join(dir, e.name);
1246
+ const routes = nextRoutesOf(sub);
1247
+ if (routes) out.push({root: sub, routes});
1248
+ else walk(sub, depth + 1);
1249
+ }
1250
+ };
1251
+ walk(cwd, 1);
1252
+ return out.sort((a, b) => a.root.localeCompare(b.root));
1253
+ }
1254
+
1255
+ /**
1256
+ * The routes folder of a Next app in `dir` (app/, else src/app/, with a
1257
+ * root layout), when its package.json depends on `next`; else null.
1258
+ * @param {string} dir
1259
+ * @returns {string | null}
1260
+ */
1261
+ function nextRoutesOf(dir) {
1262
+ try {
1263
+ const pkg = JSON.parse(
1264
+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),
1265
+ );
1266
+ if (!['dependencies', 'devDependencies'].some(k => pkg?.[k]?.next))
1267
+ return null;
1268
+ } catch {
1269
+ return null;
1270
+ }
1271
+ return (
1272
+ [path.join(dir, 'app'), path.join(dir, 'src', 'app')].find(
1273
+ r =>
1274
+ fs.existsSync(r) &&
1275
+ fs.readdirSync(r).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f)),
1276
+ ) ?? null
1277
+ );
1278
+ }
1279
+
785
1280
  /**
786
1281
  * Refuse a preview folder that reaches outside the project through a link,
787
1282
  * as `--path` refuses one: every file the preview writes would land there.
@@ -827,9 +1322,11 @@ const STARTER = path.join(CLI_PACKAGE, 'assets', 'preview-app');
827
1322
  * @param {string} file absolute
828
1323
  * @param {string} root absolute
829
1324
  * @param {string} what what the path is, for the refusal
1325
+ * @param {{cwd?: string, pf?: string}} [opts] `cwd`: paths in the refusal
1326
+ * are shown from it; `pf`: the caller's --path flag, for the suggestion
830
1327
  * @returns {string}
831
1328
  */
832
- function confined(file, root, what) {
1329
+ function confined(file, root, what, opts = {}) {
833
1330
  try {
834
1331
  return assertWithin(file, root, {allowAbsolute: true, label: what});
835
1332
  } catch (e) {
@@ -848,12 +1345,14 @@ function confined(file, root, what) {
848
1345
  } catch {
849
1346
  // Not there: look at its folder.
850
1347
  }
1348
+ const at = (/** @type {string} */ f) =>
1349
+ opts.cwd ? shown(opts.cwd, f) || '.' : f;
851
1350
  refuse(
852
1351
  E.ERR_PATH_TRAVERSAL,
853
1352
  link == null
854
- ? `${what} names ${file}, which is outside ${root}.`
855
- : `${link.at} is a link to ${link.to}, outside ${root}; the preview never writes through a link.`,
856
- {run: [`${PREVIEW} list`]},
1353
+ ? `${what} names ${at(file)}, which is outside ${at(root)}.`
1354
+ : `${at(link.at)} is a link to ${link.to}, outside ${at(root)}; the preview never writes through a link.`,
1355
+ {run: [`${PREVIEW} list${opts.pf ?? ''}`]},
857
1356
  );
858
1357
  }
859
1358
  throw e;
@@ -938,7 +1437,11 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
938
1437
  reservedFolder(cwd, root) ??
939
1438
  (routes.some(r => root === r || root.startsWith(r + path.sep))
940
1439
  ? "it is inside this app's routes folder, where Next would serve the new app's files as pages of this one"
941
- : null);
1440
+ : null) ??
1441
+ (t =>
1442
+ t
1443
+ ? `${shownDir(cwd, t)}/ differs from it only in case, and on macOS and Windows they are one folder`
1444
+ : null)(sameCaseSibling(root));
942
1445
  if (why) {
943
1446
  let free = 'theme-app';
944
1447
  for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
@@ -1135,6 +1638,11 @@ function previewProblem(d) {
1135
1638
  return '"theme" is not a theme name or null';
1136
1639
  if (!Array.isArray(d.pages)) return '"pages" is not a list';
1137
1640
  if (!Array.isArray(d.files)) return '"files" is not a list';
1641
+ if (
1642
+ d.parents !== undefined &&
1643
+ !(Number.isInteger(d.parents) && d.parents >= 0 && d.parents <= 20)
1644
+ )
1645
+ return '"parents" is not a small whole number';
1138
1646
  const ids = new Set();
1139
1647
  for (const p of d.pages) {
1140
1648
  if (!p || typeof p !== 'object' || Array.isArray(p))
@@ -1161,6 +1669,8 @@ function previewProblem(d) {
1161
1669
  f.split('/').some(x => x === '' || x === '.')
1162
1670
  )
1163
1671
  return `"files" holds ${JSON.stringify(f)}, which is not a file path relative to the folder`;
1672
+ else if (f.split('/').includes('..'))
1673
+ return `"files" holds ${JSON.stringify(f)}, which leads outside the folder (${OUTSIDE_FIX})`;
1164
1674
  if (
1165
1675
  d.hashes != null &&
1166
1676
  (typeof d.hashes !== 'object' ||
@@ -1213,15 +1723,21 @@ function holdsApp(cwd, dir) {
1213
1723
  );
1214
1724
  }
1215
1725
 
1726
+ /** What a record entry that leads outside the folder takes. */
1727
+ const OUTSIDE_FIX = `${PREVIEW} remove drops it and deletes nothing outside`;
1728
+
1216
1729
  /**
1217
1730
  * The preview's data, null when the folder has none; a refusal when the
1218
1731
  * file is there but unreadable or of the wrong shape.
1219
1732
  * @param {string} cwd
1220
1733
  * @param {string} dir
1221
1734
  * @param {string} [pf] the caller's --path flag, for the refusal
1735
+ * @param {{dropped?: string[]}} [opts] `dropped`: entries of "files" that
1736
+ * lead outside the folder are taken out and collected here, as `remove`
1737
+ * does
1222
1738
  * @returns {PreviewData | null}
1223
1739
  */
1224
- function readPreview(cwd, dir, pf = '') {
1740
+ function readPreview(cwd, dir, pf = '', opts = {}) {
1225
1741
  /** @type {string} */
1226
1742
  let text;
1227
1743
  try {
@@ -1246,6 +1762,14 @@ function readPreview(cwd, dir, pf = '') {
1246
1762
  pf,
1247
1763
  );
1248
1764
  }
1765
+ // `remove` drops an entry that leads outside the folder, and deletes
1766
+ // nothing there.
1767
+ if (opts.dropped && data && Array.isArray(data.files)) {
1768
+ const outside = (/** @type {unknown} */ f) =>
1769
+ typeof f === 'string' && f.split('/').includes('..');
1770
+ for (const f of data.files) if (outside(f)) opts.dropped.push(f);
1771
+ data.files = data.files.filter((/** @type {unknown} */ f) => !outside(f));
1772
+ }
1249
1773
  const problem = previewProblem(data);
1250
1774
  if (problem) damagedPreview(cwd, dir, problem, pf);
1251
1775
  data.files = [...new Set(data.files)];
@@ -1598,7 +2122,7 @@ function checkWrite(cwd, dir, data, w, elsewhere) {
1598
2122
  page
1599
2123
  ? {
1600
2124
  fix: `give ${name} another name if you want to keep it, then run the command again; or add another page`,
1601
- run: ['astryx template --list --type page'],
2125
+ run: [formatCliCommand('template --list --type page', cwd)],
1602
2126
  }
1603
2127
  : {
1604
2128
  fix: `move ${name} out of the folder, then run the command again; or put the preview in another folder`,
@@ -1613,7 +2137,9 @@ function checkWrite(cwd, dir, data, w, elsewhere) {
1613
2137
  E.ERR_FILE_EXISTS,
1614
2138
  `${name} was changed by hand after the preview wrote it, so it is not replaced.`,
1615
2139
  {
1616
- fix: `copy your changes out of ${name}, then give it another name, and run the command again`,
2140
+ // A copy renamed in the folder would still import the preview's
2141
+ // pages and break when they go: it moves out, importing none.
2142
+ fix: `move ${name} out of ${shownDir(cwd, dir)}/ (copy what you changed somewhere else in the app, importing nothing from the preview folder), then run the command again`,
1617
2143
  },
1618
2144
  );
1619
2145
  return 'replace';
@@ -1811,6 +2337,186 @@ function commitStep(step) {
1811
2337
  if (stopAt?.(step)) throw STOPPED;
1812
2338
  }
1813
2339
 
2340
+ /** Folders the importer search never enters: installs and build output. */
2341
+ const NOT_SOURCE = new Set([
2342
+ 'node_modules',
2343
+ 'out',
2344
+ 'dist',
2345
+ 'build',
2346
+ 'coverage',
2347
+ ]);
2348
+
2349
+ /** At most this many source files are read; past it, nothing is deleted. */
2350
+ let IMPORTER_SCAN_MAX = 50000;
2351
+
2352
+ /**
2353
+ * For tests: read at most `n` source files when checking for importers
2354
+ * (null: the default).
2355
+ * @param {number | null} n
2356
+ */
2357
+ export function setImporterScanMax(n) {
2358
+ IMPORTER_SCAN_MAX = n ?? 50000;
2359
+ }
2360
+
2361
+ /**
2362
+ * Files of the project's own that import any of `targets` (preview files
2363
+ * about to be deleted), so deleting them would break the app's build. The
2364
+ * whole project root is read: every .ts/.tsx/.js/.jsx/.mjs/.cjs/.mdx file
2365
+ * outside node_modules, build output and dot folders, the preview's own
2366
+ * files left out. Each file's import and export-from declarations,
2367
+ * import() and require() calls (a string or a template with no
2368
+ * substitution) are read from its syntax tree and resolved: relative,
2369
+ * `@/`, or a tsconfig `paths` alias. `tooBig` when the project holds more
2370
+ * source files than are read, so the caller refuses instead of guessing.
2371
+ * @param {string} cwd
2372
+ * @param {PreviewData} data
2373
+ * @param {string} dir the preview folder
2374
+ * @param {string[]} targets absolute paths, without extension
2375
+ * @returns {{importers: string[], tooBig: boolean}}
2376
+ */
2377
+ function pageImporters(cwd, data, dir, targets) {
2378
+ const wanted = new Set(targets);
2379
+ if (!wanted.size) return {importers: [], tooBig: false};
2380
+ const names = [...new Set(targets.map(t => path.basename(t)))];
2381
+ const own = new Set(data.files.map(f => path.join(dir, f)));
2382
+ const aliases = tsconfigAliases(cwd);
2383
+ /** @type {Set<string>} */
2384
+ const out = new Set();
2385
+ let files = 0;
2386
+ let tooBig = false;
2387
+ /** @param {string} file @param {string} spec */
2388
+ const resolves = (file, spec) => {
2389
+ const alias = aliases.find(x => spec.startsWith(x.prefix));
2390
+ const bases = alias
2391
+ ? alias.to.map(t => path.join(t, spec.slice(alias.prefix.length)))
2392
+ : spec.startsWith('@/')
2393
+ ? [path.join(cwd, 'src', spec.slice(2)), path.join(cwd, spec.slice(2))]
2394
+ : spec.startsWith('.')
2395
+ ? [path.resolve(path.dirname(file), spec)]
2396
+ : [];
2397
+ return bases.some(
2398
+ b =>
2399
+ wanted.has(b.replace(/\.(tsx|ts|jsx|js|mjs|cjs)$/, '')) ||
2400
+ wanted.has(path.join(b, 'index')),
2401
+ );
2402
+ };
2403
+ /** @param {any} node @param {(spec: string) => void} found */
2404
+ const specifiers = (node, found) => {
2405
+ if (!node || typeof node !== 'object') return;
2406
+ if (Array.isArray(node)) {
2407
+ for (const x of node) specifiers(x, found);
2408
+ return;
2409
+ }
2410
+ const text = (/** @type {any} */ n) =>
2411
+ n?.type === 'StringLiteral'
2412
+ ? n.value
2413
+ : n?.type === 'TemplateLiteral' && n.expressions.length === 0
2414
+ ? n.quasis.map((/** @type {any} */ q) => q.value.cooked).join('')
2415
+ : null;
2416
+ if (
2417
+ (node.type === 'ImportDeclaration' ||
2418
+ node.type === 'ExportNamedDeclaration' ||
2419
+ node.type === 'ExportAllDeclaration') &&
2420
+ node.source
2421
+ ) {
2422
+ const t = text(node.source);
2423
+ if (t != null) found(t);
2424
+ } else if (node.type === 'ImportExpression') {
2425
+ const t = text(node.source);
2426
+ if (t != null) found(t);
2427
+ } else if (
2428
+ node.type === 'CallExpression' &&
2429
+ (node.callee?.type === 'Import' ||
2430
+ (node.callee?.type === 'Identifier' && node.callee.name === 'require'))
2431
+ ) {
2432
+ const t = text(node.arguments?.[0]);
2433
+ if (t != null) found(t);
2434
+ } else if (
2435
+ node.type === 'TSImportType' ||
2436
+ node.type === 'TSExternalModuleReference'
2437
+ ) {
2438
+ const t = text(node.argument ?? node.expression);
2439
+ if (t != null) found(t);
2440
+ }
2441
+ for (const [k, v] of Object.entries(node))
2442
+ if (
2443
+ k !== 'loc' &&
2444
+ k !== 'start' &&
2445
+ k !== 'end' &&
2446
+ v &&
2447
+ typeof v === 'object'
2448
+ )
2449
+ specifiers(v, found);
2450
+ };
2451
+ /** @param {string} at */
2452
+ const walk = at => {
2453
+ if (tooBig) return;
2454
+ /** @type {fs.Dirent[]} */
2455
+ let entries;
2456
+ try {
2457
+ entries = fs.readdirSync(at, {withFileTypes: true});
2458
+ } catch {
2459
+ return;
2460
+ }
2461
+ for (const e of entries) {
2462
+ const full = path.join(at, e.name);
2463
+ if (e.isDirectory()) {
2464
+ if (!NOT_SOURCE.has(e.name) && !e.name.startsWith('.')) walk(full);
2465
+ if (tooBig) return;
2466
+ continue;
2467
+ }
2468
+ if (!/\.(tsx|ts|jsx|js|mjs|cjs|mdx)$/.test(e.name) || own.has(full))
2469
+ continue;
2470
+ if (e.name.endsWith('.d.ts')) continue;
2471
+ if (++files > IMPORTER_SCAN_MAX) {
2472
+ tooBig = true;
2473
+ return;
2474
+ }
2475
+ /** @type {string} */
2476
+ let source;
2477
+ try {
2478
+ source = fs.readFileSync(full, 'utf8');
2479
+ } catch {
2480
+ continue;
2481
+ }
2482
+ // Only a file that names a target's file name can import it.
2483
+ if (!names.some(n => source.includes(n))) continue;
2484
+ /** @type {string[]} */
2485
+ const specs = [];
2486
+ try {
2487
+ const ast = parseModule(
2488
+ e.name.endsWith('.mdx')
2489
+ ? source
2490
+ .split('\n')
2491
+ .filter(l => /^\s*(import|export)\b/.test(l))
2492
+ .join('\n')
2493
+ : source,
2494
+ {
2495
+ sourceType: 'unambiguous',
2496
+ errorRecovery: true,
2497
+ plugins: [
2498
+ 'jsx',
2499
+ ...(/\.(ts|tsx|mts|cts)$/.test(e.name)
2500
+ ? [/** @type {const} */ ('typescript')]
2501
+ : []),
2502
+ ],
2503
+ },
2504
+ );
2505
+ specifiers(ast.program, spec => specs.push(spec));
2506
+ } catch {
2507
+ // Not parsed: read its import strings as text.
2508
+ for (const m of source.matchAll(
2509
+ /(?:from\s*|import\s*\(\s*|require\s*\(\s*|import\s+)['"`]([^'"`$]+)['"`]/g,
2510
+ ))
2511
+ specs.push(m[1]);
2512
+ }
2513
+ if (specs.some(sp => resolves(full, sp))) out.add(shown(cwd, full));
2514
+ }
2515
+ };
2516
+ walk(cwd);
2517
+ return {importers: [...out].sort(), tooBig};
2518
+ }
2519
+
1814
2520
  /**
1815
2521
  * Page files in the preview folder that theme-preview.json does not list:
1816
2522
  * a stopped change can leave one behind when its step record is damaged.
@@ -1868,6 +2574,29 @@ function pendingEscapes(dir, p) {
1868
2574
  });
1869
2575
  }
1870
2576
 
2577
+ /**
2578
+ * Delete the temp files a preview command left in a preview folder, found
2579
+ * by the names only the editor makes (`.<file>.astryx-<pid>-<id>.tmp`),
2580
+ * once their process is gone.
2581
+ * @param {string} dir
2582
+ */
2583
+ function sweepTemps(dir) {
2584
+ for (const sub of ['', PAGES_DIR, LEGACY_PAGES_DIR]) {
2585
+ /** @type {string[]} */
2586
+ let names;
2587
+ try {
2588
+ names = fs.readdirSync(path.join(dir, sub));
2589
+ } catch {
2590
+ continue;
2591
+ }
2592
+ for (const name of names) {
2593
+ const m = /^\..+\.astryx-(\d+)-[a-z0-9]+\.tmp$/.exec(name);
2594
+ if (m && (!alive(Number(m[1])) || Number(m[1]) === process.pid))
2595
+ fs.rmSync(path.join(dir, sub, name), {force: true});
2596
+ }
2597
+ }
2598
+ }
2599
+
1871
2600
  /**
1872
2601
  * Finish a preview change that was stopped part way (a kill), from the
1873
2602
  * step record it left: its leftover temp files go; each file it was writing
@@ -1888,22 +2617,7 @@ function recoverPreview(cwd, dir) {
1888
2617
  // Unreadable, or naming a path outside the folder: the change is
1889
2618
  // treated as never started.
1890
2619
  const abandon = () => {
1891
- // Its temp files are found by the names only the editor makes, when
1892
- // their process is gone.
1893
- for (const sub of ['', PAGES_DIR, LEGACY_PAGES_DIR]) {
1894
- /** @type {string[]} */
1895
- let names;
1896
- try {
1897
- names = fs.readdirSync(path.join(dir, sub));
1898
- } catch {
1899
- continue;
1900
- }
1901
- for (const name of names) {
1902
- const m = /^\..+\.astryx-(\d+)-[a-z0-9]+\.tmp$/.exec(name);
1903
- if (m && !alive(Number(m[1])))
1904
- fs.rmSync(path.join(dir, sub, name), {force: true});
1905
- }
1906
- }
2620
+ sweepTemps(dir);
1907
2621
  fs.rmSync(pendingFile, {force: true});
1908
2622
  const strays = unrecordedPages(dir).map(rel =>
1909
2623
  shown(cwd, path.join(dir, rel)),
@@ -1913,7 +2627,12 @@ function recoverPreview(cwd, dir) {
1913
2627
  try {
1914
2628
  p = JSON.parse(fs.readFileSync(pendingFile, 'utf8'));
1915
2629
  } catch (e) {
1916
- if (/** @type {any} */ (e)?.code === 'ENOENT') return null;
2630
+ // No step record: temp files a stopped command left (one killed before
2631
+ // it wrote the record) go, once their process is gone.
2632
+ if (/** @type {any} */ (e)?.code === 'ENOENT') {
2633
+ sweepTemps(dir);
2634
+ return null;
2635
+ }
1917
2636
  return abandon();
1918
2637
  }
1919
2638
  if (pendingEscapes(dir, p)) return abandon();
@@ -2202,11 +2921,11 @@ async function buildWorn(cwd, theme, options, notes) {
2202
2921
  }
2203
2922
 
2204
2923
  /** The Colors page: its id and file, relative to the route folder. */
2205
- const COLORS_PAGE = {
2924
+ const COLORS_PAGE = wordTable({
2206
2925
  id: 'colors',
2207
2926
  label: 'Colors',
2208
2927
  file: `${PAGES_DIR}/colors`,
2209
- };
2928
+ });
2210
2929
 
2211
2930
  /**
2212
2931
  * The Colors page source of a theme, and whether the theme has generated
@@ -2276,6 +2995,38 @@ async function colorsPage(cwd, dir, slug) {
2276
2995
  };
2277
2996
  }
2278
2997
 
2998
+ /**
2999
+ * When the theme a preview wore is gone, its Colors page goes too: it shows
3000
+ * that theme's colors and tells you to set them. The file is deleted when it
3001
+ * is as the preview wrote it; a page changed by hand is kept, out of the nav.
3002
+ * @param {string} cwd
3003
+ * @param {string} dir
3004
+ * @param {PreviewData} data
3005
+ * @param {{writes: Array<{rel: string}>, deletes: string[]}} move
3006
+ * @param {string} gone
3007
+ * @param {string[]} notes
3008
+ */
3009
+ function dropGoneColors(cwd, dir, data, move, gone, notes) {
3010
+ const page = data.pages.find(p => p.id === COLORS_PAGE.id);
3011
+ if (!page) return;
3012
+ const rel = `${page.file}.tsx`;
3013
+ const ids = new Set(data.pages.map(p => p.id));
3014
+ const owned =
3015
+ fs.existsSync(path.join(dir, rel)) &&
3016
+ ownedUnchanged(dir, data, rel, ids) === 'delete';
3017
+ data.pages = data.pages.filter(p => p !== page);
3018
+ data.files = data.files.filter(f => f !== rel);
3019
+ move.writes = move.writes.filter(
3020
+ w => w.rel !== rel && w.rel !== `${PAGES_DIR}/${COLORS_PAGE.id}.tsx`,
3021
+ );
3022
+ if (owned) move.deletes.push(rel);
3023
+ notes.push(
3024
+ owned
3025
+ ? `removed the Colors page: it showed the colors of ${gone}, which is gone`
3026
+ : `left the Colors page out of the nav: it showed the colors of ${gone}, which is gone, and was changed by hand, so ${shown(cwd, path.join(dir, rel))} is kept`,
3027
+ );
3028
+ }
3029
+
2279
3030
  /**
2280
3031
  * The route file and, when the preview has one, the Colors page as the
2281
3032
  * page list and the theme say now. With `gone`, the theme the preview wore
@@ -2332,6 +3083,19 @@ function paletteStandIn(cwd, slug) {
2332
3083
  return shown(cwd, file);
2333
3084
  }
2334
3085
 
3086
+ /**
3087
+ * The --path a preview command needs for a preview folder: none for the
3088
+ * default one.
3089
+ * @param {string} cwd
3090
+ * @param {string} dir
3091
+ */
3092
+ function dirFlag(cwd, dir) {
3093
+ const fallback = previewDir(cwd, undefined, {optional: true})?.dir;
3094
+ return fallback === dir
3095
+ ? ''
3096
+ : ` --path ${quoteCommandArgument(shownDir(cwd, dir))}`;
3097
+ }
3098
+
2335
3099
  /**
2336
3100
  * Rewrite the in-app preview routes of a theme when their imports changed, so
2337
3101
  * a font package installed after `set` loads on the next change or `show`,
@@ -2392,6 +3156,15 @@ export async function refreshPreviewRoute(cwd, slug) {
2392
3156
  }
2393
3157
  return true;
2394
3158
  });
3159
+ // A theme that has generated colors now, under a preview with no
3160
+ // Colors page: the next add adds it.
3161
+ if (
3162
+ !data.pages.some(p => p.id === COLORS_PAGE.id) &&
3163
+ (await colorsPage(cwd, dir, slug)).colors
3164
+ )
3165
+ stale.push(
3166
+ `${shownDir(cwd, dir)}/ (${slug} has generated colors now; ${PREVIEW} add${dirFlag(cwd, dir)} adds its Colors page)`,
3167
+ );
2395
3168
  if (!writes.length) continue;
2396
3169
  commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
2397
3170
  changed = true;
@@ -2536,7 +3309,61 @@ async function rankedPages(words, cwd, notes, flags) {
2536
3309
  String(r.reason ?? '').replace(/^matches \d+\/\d+ terms: /, ''),
2537
3310
  ]),
2538
3311
  );
3312
+ // A description that is a template's id or display name names it.
3313
+ const plain = (/** @type {string} */ x) =>
3314
+ x
3315
+ .toLowerCase()
3316
+ .replace(/[^a-z0-9]+/g, ' ')
3317
+ .trim();
3318
+ const exact = listed.find(
3319
+ t => plain(t.id) === plain(words) || plain(t.name ?? '') === plain(words),
3320
+ )?.id;
3321
+ if (exact && frames.has(exact))
3322
+ refuse(
3323
+ E.ERR_INVALID_ARGUMENT,
3324
+ `${exact} is an app frame, not a page, so a description does not add it; name it with --template to add it as a page anyway.`,
3325
+ {run: [`${PREVIEW} add --template ${exact}${flags}`]},
3326
+ );
3327
+ // Build's page ranking, when build picked no page itself (it fell back to
3328
+ // a frame): its pages the description names (by name, keyword or docs,
3329
+ // or a word of it in the page's id), best score first; on a tie, a page whose id holds a word of the
3330
+ // description goes first.
3331
+ const said = plain(words)
3332
+ .split(' ')
3333
+ .filter(w => w.length > 2);
3334
+ const byId = (/** @type {string} */ id) =>
3335
+ said.some(w => id.split('-').includes(w)) ? 1 : 0;
3336
+ const fellBack =
3337
+ !start || (start.basis === 'fallback' && frames.has(start.name));
3338
+ const ranked = (fellBack ? [...(kit.data.pages ?? [])] : [])
3339
+ .map((r, i) => ({
3340
+ name: r.name,
3341
+ score: Number(r.score) || 0,
3342
+ reason: String(r.reason ?? ''),
3343
+ i,
3344
+ }))
3345
+ .filter(
3346
+ r =>
3347
+ listed.some(t => t.id === r.name) &&
3348
+ (/^(exact name|name|keyword|docs mention|description mentions)\b/.test(
3349
+ r.reason,
3350
+ ) ||
3351
+ r.score >= 100 ||
3352
+ byId(r.name)),
3353
+ )
3354
+ .sort(
3355
+ (a, b) => b.score - a.score || byId(b.name) - byId(a.name) || a.i - b.i,
3356
+ )
3357
+ .map(r => r.name);
3358
+ for (const r of kit.data.pages ?? [])
3359
+ if (!matchedWords.has(r.name))
3360
+ matchedWords.set(
3361
+ r.name,
3362
+ String(r.reason ?? '').replace(/^matches \d+\/\d+ terms: /, ''),
3363
+ );
2539
3364
  const names = [
3365
+ ...(exact ? [exact] : []),
3366
+ ...ranked,
2540
3367
  ...(start ? [start.name, ...start.alternatives.map(a => a.name)] : []),
2541
3368
  ...found.map((/** @type {any} */ r) => r.name),
2542
3369
  ].filter((n, i, a) => a.indexOf(n) === i);
@@ -2553,7 +3380,7 @@ async function rankedPages(words, cwd, notes, flags) {
2553
3380
  listed.some(t => t.id === id),
2554
3381
  ),
2555
3382
  ),
2556
- 'astryx template --list --type page',
3383
+ formatCliCommand('template --list --type page', cwd),
2557
3384
  ];
2558
3385
  // No page relates when the ranking fell back to a frame with no direct
2559
3386
  // match, and no page the search found matches three words of the request
@@ -2569,6 +3396,8 @@ async function rankedPages(words, cwd, notes, flags) {
2569
3396
  const named = APP_PAGES.some(([re]) => re.test(words.toLowerCase()));
2570
3397
  const unrelated =
2571
3398
  !named &&
3399
+ !exact &&
3400
+ !ranked.some(n => !frames.has(n)) &&
2572
3401
  (!pages.length ||
2573
3402
  (start &&
2574
3403
  start.basis === 'fallback' &&
@@ -2583,7 +3412,10 @@ async function rankedPages(words, cwd, notes, flags) {
2583
3412
  `No page template relates to "${words}". Name a page to add it anyway.`,
2584
3413
  {
2585
3414
  run: pages.length
2586
- ? [...suggest(pages), 'astryx template --list --type page']
3415
+ ? [
3416
+ ...suggest(pages),
3417
+ formatCliCommand('template --list --type page', cwd),
3418
+ ]
2587
3419
  : fallback,
2588
3420
  },
2589
3421
  );
@@ -2654,7 +3486,7 @@ async function rankedPages(words, cwd, notes, flags) {
2654
3486
  displayName: label(name),
2655
3487
  why: reason
2656
3488
  ? `${reason}${words ? `; it covers ${words}` : ''}. ${shape}`
2657
- : i === 0 && closest
3489
+ : i === 0 && closest && name !== exact
2658
3490
  ? `the closest page, not exactly the one described${words ? `: it covers ${words}` : ''}; the rest of the description is not on it. ${shape}`
2659
3491
  : `${i === 0 ? 'the best match' : 'the next match'}${words ? `: it covers ${words}` : ''}. ${shape}`,
2660
3492
  };
@@ -2722,6 +3554,17 @@ function installed(cwd, pkg) {
2722
3554
  return findNodeModulesPackage(cwd, pkg) != null;
2723
3555
  }
2724
3556
 
3557
+ /**
3558
+ * The folder of the nearest package.json over `dir`, up to `cwd`.
3559
+ * @param {string} cwd
3560
+ * @param {string} dir
3561
+ */
3562
+ function appRootOf(cwd, dir) {
3563
+ for (let at = dir; at.startsWith(cwd + path.sep); at = path.dirname(at))
3564
+ if (fs.existsSync(path.join(at, 'package.json'))) return at;
3565
+ return cwd;
3566
+ }
3567
+
2725
3568
  /**
2726
3569
  * What a template page needs that the app lacks, from its real imports:
2727
3570
  * packages the app's package.json does not name (with the command that
@@ -2820,7 +3663,7 @@ function wornTheme(cwd, slug, again, without) {
2820
3663
  `${installLine(cwd, [`@astryxdesign/theme-${name}`])} # then a theme of your own can start from it`,
2821
3664
  ]
2822
3665
  : []),
2823
- `${EDITOR} new my-${name} --like ${name} # a theme of your own that starts from it`,
3666
+ `${EDITOR} new ${usableNewName(cwd, `my-${name}`)} --like ${name} # a theme of your own that starts from it`,
2824
3667
  ],
2825
3668
  },
2826
3669
  );
@@ -2905,7 +3748,7 @@ async function namedTemplate(cwd, id, flags) {
2905
3748
  {
2906
3749
  run: [
2907
3750
  ...near.map(n => `${PREVIEW} add --template ${n}${flags}`),
2908
- 'astryx template --list --type page',
3751
+ formatCliCommand('template --list --type page', cwd),
2909
3752
  ],
2910
3753
  },
2911
3754
  );
@@ -3008,6 +3851,25 @@ async function addPreview(description, options, box) {
3008
3851
  options.theme != null
3009
3852
  ? ` --theme ${quoteCommandArgument(options.theme)}`
3010
3853
  : '';
3854
+ // A default page's id (overview, components, colors), as `remove` takes
3855
+ // it, adds exactly that page back (or is refused, saying why).
3856
+ const DEFAULT_IDS = ['overview', 'components', COLORS_PAGE.id];
3857
+ const isDefault = (/** @type {unknown} */ v) =>
3858
+ typeof v === 'string' && DEFAULT_IDS.includes(v.trim().toLowerCase());
3859
+ // Beside another page asked for, it is refused below (drop one).
3860
+ const blank = (/** @type {unknown} */ v) => v == null || !String(v).trim();
3861
+ const askedId = [description, options.template]
3862
+ .find(isDefault)
3863
+ ?.trim()
3864
+ .toLowerCase();
3865
+ const again =
3866
+ askedId != null &&
3867
+ (blank(description) || isDefault(description)) &&
3868
+ (blank(options.template) || isDefault(options.template));
3869
+ if (again) {
3870
+ description = undefined;
3871
+ options = {...options, template: undefined};
3872
+ }
3011
3873
  const said = (description ?? '').trim();
3012
3874
  const named =
3013
3875
  options.template == null ? null : String(options.template).trim();
@@ -3015,7 +3877,7 @@ async function addPreview(description, options, box) {
3015
3877
  refuse(E.ERR_INVALID_ARGUMENT, '--template needs a page template id.', {
3016
3878
  run: [
3017
3879
  `${PREVIEW} add --template dashboard${tf}${pf}`,
3018
- 'astryx template --list --type page',
3880
+ formatCliCommand('template --list --type page', cwd),
3019
3881
  ],
3020
3882
  });
3021
3883
  if (said && named != null)
@@ -3085,10 +3947,31 @@ async function addPreview(description, options, box) {
3085
3947
  const existing = readPreview(cwd, at.dir, pf);
3086
3948
  /** @type {PreviewData} */
3087
3949
  const data = existing ?? {version: 1, theme: null, pages: [], files: []};
3950
+ // The folders over a new preview folder that are not there yet: the first
3951
+ // add makes them, and remove takes them away again when they are empty.
3952
+ if (!existing) {
3953
+ let made = 0;
3954
+ for (
3955
+ let up = path.dirname(at.dir);
3956
+ up.startsWith((at.app ?? cwd) + path.sep) && !fs.existsSync(up);
3957
+ up = path.dirname(up)
3958
+ )
3959
+ made++;
3960
+ if (made) data.parents = made;
3961
+ }
3088
3962
  const wore = data.theme;
3089
3963
  const againWith = (/** @type {string | null} */ t) =>
3090
3964
  `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${t == null ? '' : ` --theme ${t}`}${pf}`;
3091
- const without = "leave out --theme and the pages wear the app's own theme";
3965
+ // What leaving out --theme does here, exactly: the theme the preview
3966
+ // wears keeps, else the one editor theme there is, else the app's own.
3967
+ const without = (() => {
3968
+ if (data.theme && fs.existsSync(themeFiles(cwd, data.theme).dir))
3969
+ return `leave out --theme and the preview keeps wearing ${data.theme}`;
3970
+ const themes = editedThemes(cwd);
3971
+ return themes.length === 1
3972
+ ? `leave out --theme and the pages wear ${themes[0]}, the one theme under themes/`
3973
+ : "leave out --theme and the pages wear the app's own theme";
3974
+ })();
3092
3975
  if (options.theme != null) {
3093
3976
  wornTheme(cwd, options.theme, againWith, without);
3094
3977
  data.theme = options.theme;
@@ -3117,13 +4000,22 @@ async function addPreview(description, options, box) {
3117
4000
  `the preview now wears ${data.theme ?? "the app's own theme"} (was ${wore ?? "the app's own theme"}), so its pages are written again`,
3118
4001
  );
3119
4002
  const project = await openProject(cwd);
4003
+ // Whether the preview has, or gets with a bare add, a Colors page.
4004
+ const hasColors = async () =>
4005
+ data.pages.some(p => p.id === COLORS_PAGE.id) ||
4006
+ (data.theme != null &&
4007
+ fs.existsSync(themeFiles(cwd, data.theme).dir) &&
4008
+ (await colorsPage(cwd, at.dir, data.theme)).colors);
3120
4009
  /** @param {string} id */
3121
4010
  const defaultPage = async id =>
3122
4011
  id === 'overview'
3123
4012
  ? {
3124
4013
  id,
3125
4014
  label: 'Overview',
3126
- text: overviewPageSource(project, {theme: data.theme}),
4015
+ text: overviewPageSource(project, {
4016
+ theme: data.theme,
4017
+ colors: await hasColors(),
4018
+ }),
3127
4019
  }
3128
4020
  : {
3129
4021
  id,
@@ -3155,6 +4047,33 @@ async function addPreview(description, options, box) {
3155
4047
  text: colors.source,
3156
4048
  });
3157
4049
  }
4050
+ // A default page named on its own adds exactly that page, when it is
4051
+ // not there yet.
4052
+ if (askedId != null) {
4053
+ const there = data.pages.find(p => p.id === askedId);
4054
+ if (there && fs.existsSync(path.join(at.dir, `${there.file}.tsx`)))
4055
+ refuse(
4056
+ E.ERR_FILE_EXISTS,
4057
+ `The ${askedId} page is already in the preview; it is kept up to date as the theme changes.`,
4058
+ {run: [`${PREVIEW} list${pf}`]},
4059
+ );
4060
+ if (!add.some(a => a.id === askedId))
4061
+ refuse(
4062
+ E.ERR_NOT_FOUND,
4063
+ askedId === COLORS_PAGE.id
4064
+ ? `There is no Colors page to add: ${data.theme ? `${data.theme} has no generated colors yet` : "the preview wears the app's own theme, and the page shows an editor theme's colors"}.`
4065
+ : `The ${askedId} page cannot be added here.`,
4066
+ {
4067
+ run:
4068
+ askedId === COLORS_PAGE.id && data.theme
4069
+ ? [
4070
+ `${EDITOR} set ${data.theme} accent "#7c3aed" # then add it again`,
4071
+ ]
4072
+ : [`${PREVIEW} list${pf}`],
4073
+ },
4074
+ );
4075
+ add.splice(0, add.length, ...add.filter(a => a.id === askedId));
4076
+ }
3158
4077
  } else {
3159
4078
  const flags = `${tf}${pf}`;
3160
4079
  const picks = explicit
@@ -3167,7 +4086,9 @@ async function addPreview(description, options, box) {
3167
4086
  await template(pick.name, {cwd, type: 'page'})
3168
4087
  );
3169
4088
  const source = shownTemplate.data.source;
3170
- const needs = pageNeeds(cwd, source);
4089
+ // Packages are the app's: the nearest package.json over the preview
4090
+ // (in a workspace, the app's own, not the root's).
4091
+ const needs = pageNeeds(appRootOf(cwd, at.dir), source);
3171
4092
  // A StyleX page calls stylex.create when its module loads, so without
3172
4093
  // a StyleX compiler it breaks the whole route.
3173
4094
  const needsCompiler = needs.stylexCompiler;
@@ -3229,6 +4150,7 @@ async function addPreview(description, options, box) {
3229
4150
  })();
3230
4151
  const elsewhere = retry(free);
3231
4152
  const move = movedPages(cwd, at.dir, data);
4153
+ if (gone) dropGoneColors(cwd, at.dir, data, move, gone, notes);
3232
4154
  /** @type {Map<string, {rel: string, text: string, keepHash?: boolean}>} */
3233
4155
  const writes = new Map(move.writes.map(w => [w.rel, w]));
3234
4156
  /** @type {string[]} */
@@ -3243,7 +4165,13 @@ async function addPreview(description, options, box) {
3243
4165
  writes.set(rel, w);
3244
4166
  if (!data.files.includes(rel)) data.files.push(rel);
3245
4167
  const had = data.pages.find(x => x.id === page.id);
3246
- if (!had) {
4168
+ // A recorded page whose file is gone is added back, not refreshed.
4169
+ if (!had || !fs.existsSync(path.join(at.dir, rel))) {
4170
+ if (had) {
4171
+ had.label = page.label;
4172
+ added.push(page.id);
4173
+ continue;
4174
+ }
3247
4175
  data.pages.push({
3248
4176
  id: page.id,
3249
4177
  label: page.label,
@@ -3305,6 +4233,19 @@ async function addPreview(description, options, box) {
3305
4233
  writes.set(w.rel, w);
3306
4234
  if (!data.files.includes(w.rel)) data.files.push(w.rel);
3307
4235
  }
4236
+ // Every recorded page this command writes again is named, the Colors page
4237
+ // the route writes included.
4238
+ for (const p of data.pages)
4239
+ if (
4240
+ writes.has(`${p.file}.tsx`) &&
4241
+ !added.includes(p.id) &&
4242
+ !refreshed.includes(p.id) &&
4243
+ !rewrote.includes(p.id) &&
4244
+ fs.existsSync(path.join(at.dir, `${p.file}.tsx`)) &&
4245
+ fs.readFileSync(path.join(at.dir, `${p.file}.tsx`), 'utf8') !==
4246
+ writes.get(`${p.file}.tsx`)?.text
4247
+ )
4248
+ refreshed.push(p.id);
3308
4249
  await buildWorn(cwd, theme, options, notes);
3309
4250
  commitPreview(
3310
4251
  cwd,
@@ -3328,6 +4269,33 @@ async function addPreview(description, options, box) {
3328
4269
  const worn = data.theme;
3329
4270
  if (worn)
3330
4271
  await themeLocked(options, worn, () => recordPreview(cwd, worn, at.dir));
4272
+ // A font the theme names whose package the app lacks shows as the next
4273
+ // font in the stack.
4274
+ if (data.theme && fs.existsSync(themeFiles(cwd, data.theme).dir))
4275
+ try {
4276
+ const ctx = await context(cwd);
4277
+ for (const f of fontPackages(ctx, loadTheme(cwd, data.theme)))
4278
+ if (!f.installed)
4279
+ notes.push(
4280
+ `${f.family} is not installed, so the preview shows the next font in the stack in its place; install it: ${installLine(cwd, [f.pkg])}`,
4281
+ );
4282
+ } catch {
4283
+ // A theme that does not load is reported where it is used.
4284
+ }
4285
+ if (again)
4286
+ notes.push(
4287
+ `a default page's id brings back the default pages that are missing, as ${PREVIEW} add does`,
4288
+ );
4289
+ notes.push(...typeScriptNotes(cwd, at.dir, added));
4290
+ if (
4291
+ askedId === COLORS_PAGE.id &&
4292
+ !data.pages.some(p => p.id === COLORS_PAGE.id)
4293
+ )
4294
+ notes.push(
4295
+ data.theme
4296
+ ? `the Colors page shows a theme's generated colors, and ${data.theme} has none yet; it appears once it does: ${EDITOR} set ${data.theme} accent <color>`
4297
+ : `the Colors page shows a theme's generated colors, and the preview wears the app's own theme; it appears with an editor theme that has colors: ${PREVIEW} add --theme <theme>`,
4298
+ );
3331
4299
  return {
3332
4300
  type: 'themeEdit.previewAdd',
3333
4301
  data: {
@@ -3434,7 +4402,12 @@ export async function themeEditPreviewApp(dir, options = {}) {
3434
4402
  })) {
3435
4403
  const sub = path.join(rel, entry.name);
3436
4404
  if (entry.isDirectory()) copyDir(sub);
3437
- else if (entry.isFile() && !(rel === '' && skip.has(entry.name)))
4405
+ else if (
4406
+ entry.isFile() &&
4407
+ !(rel === '' && skip.has(entry.name)) &&
4408
+ // A temp file a stopped command left is no part of the theme.
4409
+ !isEditorTemp(entry.name)
4410
+ )
3438
4411
  themeCopy.push({
3439
4412
  rel: path.join(to.dir, sub),
3440
4413
  text: fs.readFileSync(path.join(from.dir, sub)),
@@ -3458,7 +4431,11 @@ export async function themeEditPreviewApp(dir, options = {}) {
3458
4431
  routeTheme = {
3459
4432
  name: slug,
3460
4433
  module: fromRoute(to.js),
3461
- css: [fromRoute(to.css), ...fonts.map(x => `${x.pkg}/index.css`)],
4434
+ css: [
4435
+ fromRoute(to.css),
4436
+ ...baseFontsCss(ctx, theme),
4437
+ ...fonts.map(x => `${x.pkg}/index.css`),
4438
+ ],
3462
4439
  mode: themeImports(ctx, slug, theme, path.join(cwd, routeDir)).mode,
3463
4440
  };
3464
4441
  // The app's theme folder sits where this project's does, so the Colors
@@ -3472,7 +4449,14 @@ export async function themeEditPreviewApp(dir, options = {}) {
3472
4449
  const preview = [];
3473
4450
  /** @type {Array<[string, string, string]>} */
3474
4451
  const pages = [
3475
- ['overview', 'Overview', overviewPageSource(project, {theme: slug})],
4452
+ [
4453
+ 'overview',
4454
+ 'Overview',
4455
+ overviewPageSource(project, {
4456
+ theme: slug,
4457
+ colors: colorsSource != null,
4458
+ }),
4459
+ ],
3476
4460
  [
3477
4461
  'components',
3478
4462
  'Components',
@@ -3611,6 +4595,37 @@ export async function themeEditPreviewList(options = {}) {
3611
4595
  const themeMissing = Boolean(
3612
4596
  data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
3613
4597
  );
4598
+ if (at && fs.existsSync(path.join(at.dir, PENDING)))
4599
+ notes.push(
4600
+ `a preview change was stopped part way, so this list may be out of date; ${PREVIEW} add${pf} finishes it`,
4601
+ );
4602
+ // A page whose file is gone breaks the route, which still imports it.
4603
+ const missing = new Set(
4604
+ (data?.pages ?? [])
4605
+ .filter(p => at && !fs.existsSync(path.join(at.dir, `${p.file}.tsx`)))
4606
+ .map(p => p.id),
4607
+ );
4608
+ if (at && missing.size)
4609
+ notes.push(
4610
+ `${[...missing].join(', ')} ${missing.size > 1 ? 'are' : 'is'} listed, but ${missing.size > 1 ? 'their files are' : 'its file is'} gone, so the route does not build; ${PREVIEW} add${pf} writes ${missing.size > 1 ? 'them' : 'it'} again`,
4611
+ );
4612
+ // No preview yet: say so when `add` would refuse the folder, with its
4613
+ // reason and the way on, rather than suggest it.
4614
+ if (!data) {
4615
+ try {
4616
+ previewDir(cwd, options.path, {
4617
+ write: true,
4618
+ retry: p =>
4619
+ `${PREVIEW} add${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`,
4620
+ });
4621
+ } catch (e) {
4622
+ if (typeof (/** @type {any} */ (e)?.code) !== 'string') throw e;
4623
+ const way = /** @type {any} */ (e).suggestions?.[0]?.name;
4624
+ notes.push(
4625
+ `${PREVIEW} add${pf} refuses this folder: ${String(/** @type {any} */ (e).message).replace(/ Nothing was (written|changed)\.$/, '')}${way ? ` Instead: ${way}` : ''}`,
4626
+ );
4627
+ }
4628
+ }
3614
4629
  if (data?.theme && themeMissing) {
3615
4630
  const themes = editedThemes(cwd);
3616
4631
  notes.push(
@@ -3623,7 +4638,11 @@ export async function themeEditPreviewList(options = {}) {
3623
4638
  folder: at && data ? shownDir(cwd, at.dir) : null,
3624
4639
  theme: data?.theme ?? null,
3625
4640
  themeMissing,
3626
- pages: (data?.pages ?? []).map(x => ({id: x.id, label: x.label})),
4641
+ pages: (data?.pages ?? []).map(x => ({
4642
+ id: x.id,
4643
+ label: x.label,
4644
+ ...(missing.has(x.id) ? {missing: true} : {}),
4645
+ })),
3627
4646
  notes,
3628
4647
  },
3629
4648
  };
@@ -3658,9 +4677,29 @@ async function removePreview(page, options, box) {
3658
4677
  const retry = (/** @type {string | null} */ p) =>
3659
4678
  `${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
3660
4679
  const at = previewDir(cwd, options.path, {retry});
4680
+ // The pages a stopped change was removing, read before it is finished.
4681
+ /** @type {string[]} */
4682
+ let removing = [];
4683
+ try {
4684
+ const pend = JSON.parse(
4685
+ fs.readFileSync(path.join(at.dir, PENDING), 'utf8'),
4686
+ );
4687
+ const ids = (/** @type {any} */ r) =>
4688
+ Array.isArray(r?.pages)
4689
+ ? r.pages.map((/** @type {any} */ x) => String(x?.id))
4690
+ : [];
4691
+ const after = ids(pend?.record);
4692
+ removing = ids(pend?.old).filter(
4693
+ (/** @type {string} */ id) => !after.includes(id),
4694
+ );
4695
+ } catch {
4696
+ // No stopped change, or a damaged one.
4697
+ }
3661
4698
  const recovered = recoverPreview(cwd, at.dir);
3662
4699
  box.note = recovered;
3663
- const data = readPreview(cwd, at.dir, pf);
4700
+ /** @type {string[]} */
4701
+ const dropped = [];
4702
+ const data = readPreview(cwd, at.dir, pf, {dropped});
3664
4703
  if (!data) {
3665
4704
  // A folder that holds the app takes no preview: the way on is the
3666
4705
  // preview elsewhere, or a new one in its own folder.
@@ -3692,11 +4731,15 @@ async function removePreview(page, options, box) {
3692
4731
  // theme-preview.json is a file anyone can edit: every path in it must
3693
4732
  // stay in the route folder before anything is removed.
3694
4733
  const inside = (/** @type {string} */ rel) =>
3695
- confined(path.join(at.dir, rel), at.dir, `${PREVIEW_DATA} names`);
4734
+ confined(path.join(at.dir, rel), at.dir, PREVIEW_DATA, {cwd, pf});
3696
4735
  for (const rel of data.files) inside(rel);
3697
4736
  for (const p of data.pages) inside(`${p.file}.tsx`);
3698
4737
  /** @type {string[]} */
3699
4738
  const notes = recovered ? [recovered] : [];
4739
+ if (dropped.length)
4740
+ notes.push(
4741
+ `dropped ${dropped.map(f => JSON.stringify(f)).join(', ')} from ${PREVIEW_DATA}: ${dropped.length > 1 ? 'they lead' : 'it leads'} outside the folder, so nothing there was deleted`,
4742
+ );
3700
4743
  /** @type {string[]} */
3701
4744
  const kept = [];
3702
4745
  /** @type {string[]} */
@@ -3709,6 +4752,28 @@ async function removePreview(page, options, box) {
3709
4752
  one =
3710
4753
  data.pages.find(x => x.id === key) ??
3711
4754
  data.pages.find(x => x.id.toLowerCase() === key.toLowerCase());
4755
+ // The same remove run again after it was stopped: the change just
4756
+ // finished removed the page.
4757
+ if (
4758
+ !one &&
4759
+ recovered &&
4760
+ removing.some(id => id.toLowerCase() === key.toLowerCase())
4761
+ )
4762
+ return {
4763
+ type: 'themeEdit.previewRemove',
4764
+ data: {
4765
+ folder,
4766
+ removed: [],
4767
+ kept: [],
4768
+ missing: [],
4769
+ rewritten: [],
4770
+ notes: [
4771
+ ...notes,
4772
+ `${key} is no longer in the preview: the change that was stopped removed it`,
4773
+ ],
4774
+ pages: data.pages.map(x => x.id),
4775
+ },
4776
+ };
3712
4777
  if (!one)
3713
4778
  refuse(E.ERR_NOT_FOUND, `The preview has no page "${page}".`, {
3714
4779
  didYouMean: nearest(
@@ -3719,6 +4784,40 @@ async function removePreview(page, options, box) {
3719
4784
  });
3720
4785
  }
3721
4786
 
4787
+ // A file of the app's own that imports a page about to go would break:
4788
+ // the page stays, and the file is named. One guard for a page and for the
4789
+ // whole preview.
4790
+ {
4791
+ const going = one && data.pages.length > 1 ? [one] : data.pages;
4792
+ // The whole preview takes its route and layout too, which other files
4793
+ // may import (a re-export at another URL).
4794
+ const targets = [
4795
+ ...going.map(p => path.join(at.dir, p.file)),
4796
+ ...(going === data.pages
4797
+ ? data.files
4798
+ .filter(f => /^(page|layout)\.(tsx|ts|jsx|js)$/.test(f))
4799
+ .map(f => path.join(at.dir, f.replace(/\.[a-z]+$/, '')))
4800
+ : []),
4801
+ ];
4802
+ const {importers, tooBig} = pageImporters(cwd, data, at.dir, targets);
4803
+ if (tooBig)
4804
+ refuse(
4805
+ E.ERR_INVALID_ARGUMENT,
4806
+ `This project holds more than ${IMPORTER_SCAN_MAX} source files, too many to check that none of them imports ${going.length > 1 ? 'the preview pages' : 'the page'}, so nothing was removed.`,
4807
+ {
4808
+ fix: `delete ${folder}/ by hand once nothing imports from it`,
4809
+ },
4810
+ );
4811
+ if (importers.length)
4812
+ refuse(
4813
+ E.ERR_FILE_EXISTS,
4814
+ `${importers.slice(0, 3).join(', ')}${importers.length > 3 ? ` and ${importers.length - 3} more` : ''} ${importers.length > 1 ? 'import' : 'imports'} ${going.length > 1 ? 'the preview pages' : `the ${going[0]?.id} page`}, and the preview did not write ${importers.length > 1 ? 'them' : 'it'}, so removing ${going.length > 1 ? 'them' : 'it'} would break the app's build.`,
4815
+ {
4816
+ fix: `stop ${importers.length > 1 ? 'those files' : importers[0]} importing from ${folder}/ (copy what ${importers.length > 1 ? 'they need' : 'it needs'} out of it first), then run ${PREVIEW} remove${one ? ` ${one.id}` : ''}${pf} again`,
4817
+ },
4818
+ );
4819
+ }
4820
+
3722
4821
  if (one && data.pages.length > 1) {
3723
4822
  const target = one;
3724
4823
  const rel = `${target.file}.tsx`;
@@ -3733,12 +4832,19 @@ async function removePreview(page, options, box) {
3733
4832
  `${name} was not written by the preview, so it is kept; only its nav item is gone`,
3734
4833
  );
3735
4834
  } else if (!fs.existsSync(inside(rel))) missing.push(name);
3736
- else if (verdict !== 'delete') {
4835
+ else if (unreadable(inside(rel))) {
4836
+ kept.push(name);
4837
+ notes.push(
4838
+ `${name} could not be read (${unreadable(inside(rel))}), so it is left in place and stays in ${PREVIEW_DATA}; fix its permissions, then run ${PREVIEW} remove${pf} again`,
4839
+ );
4840
+ } else if (verdict !== 'delete') {
3737
4841
  kept.push(name);
3738
4842
  notes.push(keptNote(name, verdict));
3739
4843
  } else deletes.push(rel);
3740
4844
  data.pages = data.pages.filter(x => x !== target);
3741
- data.files = data.files.filter(f => f !== rel);
4845
+ // A file left in place because it could not be read stays recorded.
4846
+ if (!unreadable(inside(rel)))
4847
+ data.files = data.files.filter(f => f !== rel);
3742
4848
  const wore = data.theme;
3743
4849
  /** @type {string | null} */
3744
4850
  let gone = null;
@@ -3750,6 +4856,7 @@ async function removePreview(page, options, box) {
3750
4856
  );
3751
4857
  }
3752
4858
  const move = movedPages(cwd, at.dir, data);
4859
+ if (gone) dropGoneColors(cwd, at.dir, data, move, gone, notes);
3753
4860
  // A page whose file is gone leaves the nav, so the route never imports
3754
4861
  // a missing file.
3755
4862
  const moving = new Set(move.writes.map(w => w.rel));
@@ -3844,7 +4951,7 @@ async function removePreview(page, options, box) {
3844
4951
  E.ERR_FILE_EXISTS,
3845
4952
  `${shown(cwd, path.join(at.dir, 'page.tsx'))} was changed by hand after the preview wrote it. It imports the preview pages, so removing them would leave a route that does not build.`,
3846
4953
  {
3847
- fix: `copy your changes out of ${shown(cwd, path.join(at.dir, 'page.tsx'))}, give it another name, then run ${PREVIEW} remove${pf} again`,
4954
+ fix: `move ${shown(cwd, path.join(at.dir, 'page.tsx'))} out of ${folder}/ (copy what you changed somewhere else in the app), then run ${PREVIEW} remove${pf} again`,
3848
4955
  },
3849
4956
  );
3850
4957
  const ids = new Set(data.pages.map(p => p.id));
@@ -3885,6 +4992,14 @@ async function removePreview(page, options, box) {
3885
4992
  );
3886
4993
  continue;
3887
4994
  }
4995
+ const cannot = unreadable(file);
4996
+ if (cannot) {
4997
+ kept.push(shown(cwd, file));
4998
+ notes.push(
4999
+ `${shown(cwd, file)} could not be read (${cannot}), so it is left in place; fix its permissions, then run ${PREVIEW} remove${pf} again`,
5000
+ );
5001
+ continue;
5002
+ }
3888
5003
  plan.push({file, before: fs.readFileSync(file)});
3889
5004
  }
3890
5005
  // theme-preview.json goes last, so an interrupted remove can run again.
@@ -3912,6 +5027,7 @@ async function removePreview(page, options, box) {
3912
5027
  {run: [`${retry(options.path ?? null)} # once the cause is fixed`]},
3913
5028
  );
3914
5029
  }
5030
+ sweepTemps(at.dir);
3915
5031
  tidyPageFolders(at.dir);
3916
5032
  // Files the record does not list stay: the preview never deletes what it
3917
5033
  // has no record of writing. Each is named, so the folder left is no
@@ -3926,11 +5042,15 @@ async function removePreview(page, options, box) {
3926
5042
  }
3927
5043
  try {
3928
5044
  fs.rmdirSync(at.dir);
3929
- // Route group folders, such as (tools)/, that only held the preview.
5045
+ // The folders the first add made over it, and route group folders,
5046
+ // such as (tools)/, that only held the preview; never one with
5047
+ // anything else in it.
5048
+ let made = data.parents ?? 0;
3930
5049
  for (
3931
5050
  let up = path.dirname(at.dir);
3932
- /^\(.+\)$/.test(path.basename(up)) && at.app && up.startsWith(at.app);
3933
- up = path.dirname(up)
5051
+ (made > 0 || (at.app != null && /^\(.+\)$/.test(path.basename(up)))) &&
5052
+ up.startsWith((at.app ?? cwd) + path.sep);
5053
+ up = path.dirname(up), made--
3934
5054
  )
3935
5055
  fs.rmdirSync(up);
3936
5056
  } catch {