@astryxdesign/cli 0.7.14-canary.gfdb9213 → 0.7.14

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 (95) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/theme/_adapter.d.mts +33 -0
  3. package/api/theme/_adapter.mjs +352 -16
  4. package/api/theme/build/build.mjs +261 -10
  5. package/api/theme/eject/eject.mjs +13 -1
  6. package/api/theme/list/list.mjs +11 -2
  7. package/api/theme/template/template.mjs +139 -6
  8. package/api/theme/theme.type.d.mts +15 -1
  9. package/api/theme/theme.type.mjs +9 -3
  10. package/api/theme/themeAdd.doc.mjs +1 -1
  11. package/api/theme/themeBuild.doc.mjs +10 -2
  12. package/api/theme/themeEject.doc.mjs +2 -2
  13. package/api/theme/themeListAvailable.doc.mjs +1 -1
  14. package/api/theme/themeRemove.doc.mjs +1 -1
  15. package/api/theme/themeTemplate.doc.mjs +8 -0
  16. package/api/theme/themeUse.doc.mjs +1 -1
  17. package/api/theme-edit/_adapter.d.mts +10 -2
  18. package/api/theme-edit/_adapter.mjs +52 -31
  19. package/api/theme-edit/_check.d.mts +28 -25
  20. package/api/theme-edit/_check.mjs +586 -548
  21. package/api/theme-edit/_color.d.mts +28 -2
  22. package/api/theme-edit/_color.mjs +306 -68
  23. package/api/theme-edit/_compiler.d.mts +8 -4
  24. package/api/theme-edit/_compiler.mjs +30 -27
  25. package/api/theme-edit/_context.d.mts +10 -4
  26. package/api/theme-edit/_context.mjs +21 -4
  27. package/api/theme-edit/_edit.mjs +300 -43
  28. package/api/theme-edit/_how-commands.d.mts +91 -0
  29. package/api/theme-edit/_how-commands.mjs +269 -0
  30. package/api/theme-edit/_how-question.d.mts +57 -0
  31. package/api/theme-edit/_how-question.mjs +2574 -0
  32. package/api/theme-edit/_how.d.mts +25 -17
  33. package/api/theme-edit/_how.mjs +727 -305
  34. package/api/theme-edit/_palette.d.mts +127 -19
  35. package/api/theme-edit/_palette.mjs +1313 -399
  36. package/api/theme-edit/_parts.mjs +36 -3
  37. package/api/theme-edit/_png.d.mts +18 -6
  38. package/api/theme-edit/_png.mjs +135 -25
  39. package/api/theme-edit/_preview-app.d.mts +26 -7
  40. package/api/theme-edit/_preview-app.mjs +1611 -280
  41. package/api/theme-edit/_preview.d.mts +4 -2
  42. package/api/theme-edit/_preview.mjs +18 -7
  43. package/api/theme-edit/_settings.d.mts +56 -5
  44. package/api/theme-edit/_settings.mjs +197 -49
  45. package/api/theme-edit/_tables.d.mts +0 -12
  46. package/api/theme-edit/_tables.mjs +24 -97
  47. package/api/theme-edit/theme-edit.type.d.mts +22 -5
  48. package/api/theme-edit/theme-edit.type.mjs +17 -6
  49. package/api/theme-edit/themeEditHow.doc.mjs +13 -3
  50. package/api/theme-edit/themeEditNew.doc.mjs +2 -1
  51. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +16 -4
  52. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -4
  53. package/api/theme-edit/themeEditPreviewList.doc.mjs +9 -1
  54. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +27 -2
  55. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  56. package/assets/docs.generated.json +1 -0
  57. package/assets/preview-app/gitignore +3 -0
  58. package/assets/templates/components.generated.json +1 -0
  59. package/clients/cli/bin/astryx.mjs +37 -5
  60. package/clients/cli/commands/experimental/theme.mjs +231 -31
  61. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +14 -5
  62. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -1
  63. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  64. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  65. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  66. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  67. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  68. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  69. package/clients/cli/commands/experimental-theme.doc.mjs +2 -2
  70. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  71. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  72. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  73. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  74. package/clients/cli/commands/theme.mjs +104 -40
  75. package/clients/cli/commands.generated.json +1 -0
  76. package/clients/cli/index.mjs +96 -4
  77. package/clients/cli/lib/json-shim.mjs +29 -1
  78. package/foundation/config/project.d.mts +16 -2
  79. package/foundation/config/project.mjs +40 -6
  80. package/foundation/config/theme-state.d.mts +9 -0
  81. package/foundation/config/theme-state.mjs +20 -1
  82. package/foundation/discovery/template-adapter.d.mts +12 -1
  83. package/foundation/discovery/template-adapter.mjs +24 -1
  84. package/foundation/discovery/template-needs.d.mts +7 -0
  85. package/foundation/discovery/template-needs.mjs +117 -8
  86. package/foundation/discovery/template-source-tree.d.mts +5 -1
  87. package/foundation/discovery/template-source-tree.mjs +6 -4
  88. package/foundation/discovery/theme-discovery.d.mts +14 -3
  89. package/foundation/discovery/theme-discovery.mjs +45 -12
  90. package/foundation/doc-compiler/import.mjs +68 -3
  91. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  92. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  93. package/foundation/fs/fs-error.d.mts +17 -0
  94. package/foundation/fs/fs-error.mjs +34 -0
  95. package/package.json +6 -6
@@ -10,6 +10,7 @@
10
10
  * @position api/theme-edit — imported only by _adapter.mjs
11
11
  */
12
12
 
13
+ import {createHash} from 'node:crypto';
13
14
  import * as fs from 'node:fs';
14
15
  import * as path from 'node:path';
15
16
  import {fileURLToPath} from 'node:url';
@@ -23,7 +24,6 @@ import {baseResolved, openProject} from './_project.mjs';
23
24
  import {
24
25
  loadTheme,
25
26
  nearest,
26
- q,
27
27
  refuse,
28
28
  shown,
29
29
  themeFiles,
@@ -37,11 +37,19 @@ import {
37
37
  previewRouteSource,
38
38
  themeImports,
39
39
  } from './_preview.mjs';
40
- import {paletteFiles, paletteMapping} from './_palette.mjs';
40
+ import {
41
+ paletteFiles,
42
+ paletteMapping,
43
+ tempFor,
44
+ writeWhole,
45
+ } from './_palette.mjs';
41
46
  import {build} from '../build/build.mjs';
42
47
  import {search} from '../search/search.mjs';
43
48
  import {template} from '../template/template.mjs';
44
- import {analyzeTemplateNeeds} from '../../foundation/discovery/template-needs.mjs';
49
+ import {
50
+ analyzeTemplateNeeds,
51
+ extractImportedPackages,
52
+ } from '../../foundation/discovery/template-needs.mjs';
45
53
  import {detectStylingSystem} from '../../foundation/agent-docs/agent-docs.mjs';
46
54
  import {requireProject, context} from './_context.mjs';
47
55
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
@@ -51,46 +59,235 @@ const E = ERROR_CODES;
51
59
  /** The preview's data file: the pages it shows and the files it wrote. */
52
60
  const PREVIEW_DATA = 'theme-preview.json';
53
61
  const PREVIEW = 'astryx experimental theme preview';
62
+ const EDITOR = 'astryx experimental theme editor';
63
+ /**
64
+ * The folder of the preview pages, beside the route. Next never routes a
65
+ * folder whose name starts with `_`; a `pages/` folder at the project root or
66
+ * in `src/` is Next's Pages Router.
67
+ */
68
+ const PAGES_DIR = '_pages';
69
+ /** Where older releases put the pages; a preview found there is moved. */
70
+ const LEGACY_PAGES_DIR = 'pages';
71
+ const PAGE_ID = /^[a-z0-9][a-z0-9-]*$/;
72
+ /** At most this many words of a description go to the ranking. */
73
+ const MAX_WORDS = 40;
54
74
 
55
75
  /**
56
76
  * @typedef {{id: string, label: string, file: string}} PreviewPage
57
- * @typedef {{version: 1, theme: string | null, pages: PreviewPage[], files: string[]}} PreviewData
77
+ * @typedef {{version: 1, theme: string | null, pages: PreviewPage[], files: string[], hashes?: Record<string, string>}} PreviewData
78
+ * `hashes`: a short hash of each file as the preview wrote it, so a file
79
+ * changed by hand is never replaced or deleted
80
+ * @typedef {(path: string | null) => string} Retry the command again, with
81
+ * this --path (null: none)
82
+ */
83
+
84
+ /** A project-relative folder for messages: `.` for the project root. */
85
+ const shownDir = (/** @type {string} */ cwd, /** @type {string} */ dir) =>
86
+ shown(cwd, dir) || '.';
87
+
88
+ /**
89
+ * A value as one shell word: single quotes whenever a character could mean
90
+ * something to a shell, so a suggested command is safe to paste.
91
+ * @param {unknown} v
92
+ */
93
+ const shq = v =>
94
+ /^[\w./@:=+-]+$/.test(String(v))
95
+ ? String(v)
96
+ : `'${String(v).replace(/'/g, `'\\''`)}'`;
97
+
98
+ /**
99
+ * Refuse a folder name that this platform would take literally in a way the
100
+ * caller did not mean: Windows separators or a drive letter on POSIX, a `~`
101
+ * the shell did not expand, white space at either end, or a name too long
102
+ * for the file system.
103
+ * @param {string} where
104
+ * @param {string} what the flag or argument, for the message
105
+ * @param {Retry} retry
106
+ */
107
+ function checkFolderName(where, what, retry) {
108
+ const posix = path.sep === '/';
109
+ if (posix && (where.includes('\\') || /^[A-Za-z]:/.test(where))) {
110
+ const fixed = where.replace(/\\/g, '/');
111
+ refuse(
112
+ E.ERR_INVALID_ARGUMENT,
113
+ `${what} ${where} uses Windows path syntax; folders here are separated by "/".`,
114
+ {run: [retry(/^[A-Za-z]:/.test(where) ? null : fixed)]},
115
+ );
116
+ }
117
+ if (where.startsWith('~'))
118
+ refuse(
119
+ E.ERR_INVALID_ARGUMENT,
120
+ `${what} ${where} starts with "~", which is not your home folder here; name the folder from the project.`,
121
+ {run: [retry(null)]},
122
+ );
123
+ if (where !== where.trim())
124
+ refuse(
125
+ E.ERR_INVALID_ARGUMENT,
126
+ `${what} "${where}" starts or ends with white space.`,
127
+ {run: [retry(where.trim() || null)]},
128
+ );
129
+ if (where.split(/[\\/]/).some(seg => Buffer.byteLength(seg) > 255))
130
+ refuse(
131
+ E.ERR_INVALID_ARGUMENT,
132
+ `${what} has a folder name longer than 255 bytes, which the file system does not allow.`,
133
+ {run: [retry(null)]},
134
+ );
135
+ }
136
+
137
+ /**
138
+ * Why a folder is no place for files this command writes, or null: themes
139
+ * live in themes/ (and a preview app's whole tree would ship with the
140
+ * theme), packages in node_modules/, and Next serves every file under a
141
+ * Pages Router folder (`pages/` or `src/pages/`) as a page.
142
+ * @param {string} cwd
143
+ * @param {string} dir
144
+ */
145
+ function reservedFolder(cwd, dir) {
146
+ const segs = shown(cwd, dir).split('/').filter(Boolean);
147
+ if (segs[0] === 'themes')
148
+ return 'themes/ holds the themes, and everything in a theme folder is copied with the theme';
149
+ if (segs.includes('node_modules'))
150
+ return 'node_modules/ belongs to the package manager, which replaces it';
151
+ if (segs[0] === 'pages' || (segs[0] === 'src' && segs[1] === 'pages'))
152
+ return 'Next serves every file under the Pages Router folder (pages/ or src/pages/) as a public page; this preview needs the App Router (app/ or src/app/)';
153
+ return null;
154
+ }
155
+
156
+ /**
157
+ * Why Next does not serve a folder inside the routes folder at its own
158
+ * URL, or null: a `_private` folder is never routed, an `@slot` folder is a
159
+ * parallel route slot, and a `[param]` folder is a dynamic segment.
160
+ * @param {string} app the routes folder
161
+ * @param {string} dir
58
162
  */
163
+ function unroutedSegment(app, dir) {
164
+ const seg = path
165
+ .relative(app, dir)
166
+ .split(path.sep)
167
+ .find(x => /^[_@[]/.test(x));
168
+ return seg
169
+ ? `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)`
170
+ : null;
171
+ }
59
172
 
60
173
  /**
61
174
  * Where the preview route lives. `--path` names it (inside the project);
62
- * else an existing preview in the app's routes folder; else the routes
63
- * folder of a Next app router (`app/` or `src/app/`); else
64
- * `./theme-preview/` at the project root, with no app around it.
175
+ * else an existing preview in the app's routes folder; else the one preview
176
+ * a theme recorded elsewhere (`retry` given); else the routes folder of a
177
+ * Next app router (`app/` or `src/app/`).
65
178
  * @param {string} cwd
66
179
  * @param {string | undefined} where
67
- * @param {{optional?: boolean}} [opts] `optional`: null instead of a refusal when there is no routes folder
180
+ * @param {{optional?: boolean, write?: boolean, retry?: Retry}} [opts]
181
+ * `optional`: null instead of a refusal when there is no routes folder;
182
+ * `write`: the folder is checked as a place to write; `retry`: the
183
+ * command again with another --path, for refusals
68
184
  * @returns {{dir: string, app: string | null}} `app`: the routes folder, when the route is in one
69
185
  */
70
186
  function previewDir(cwd, where, opts = {}) {
187
+ const retry =
188
+ opts.retry ??
189
+ (p => `${PREVIEW} list${p == null ? '' : ` --path ${shq(p)}`}`);
71
190
  const routes = ['app', path.join('src', 'app')]
72
191
  .map(r => path.join(cwd, r))
73
192
  .filter(r => fs.existsSync(r) && fs.statSync(r).isDirectory());
74
193
  const appOf = (/** @type {string} */ dir) =>
75
194
  routes.find(r => dir.startsWith(r + path.sep)) ?? null;
76
195
  if (where != null) {
196
+ checkFolderName(where, '--path', retry);
197
+ /** @type {string} */
198
+ let dir;
77
199
  try {
78
- const dir = assertWithin(path.resolve(cwd, where), cwd, {
200
+ dir = assertWithin(path.resolve(cwd, where), cwd, {
79
201
  allowAbsolute: true,
80
202
  label: '--path',
81
203
  });
82
- return {dir, app: appOf(dir)};
83
204
  } catch (e) {
84
205
  if (e instanceof PathSafetyError)
85
206
  refuse(
86
207
  E.ERR_PATH_TRAVERSAL,
87
208
  `--path ${where} is outside the project; put the preview inside the folder you run the command from.`,
209
+ {run: [retry(null)]},
88
210
  );
89
211
  throw e;
90
212
  }
213
+ if (opts.write) {
214
+ if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory())
215
+ refuse(
216
+ E.ERR_INVALID_ARGUMENT,
217
+ `--path ${where} is a file; the preview goes in a folder of its own.`,
218
+ {run: [retry(null)]},
219
+ );
220
+ // The project root, src/ and the routes folder hold the app itself;
221
+ // nothing the preview writes there is served.
222
+ if (dir === cwd || dir === path.join(cwd, 'src') || routes.includes(dir))
223
+ refuse(
224
+ E.ERR_INVALID_ARGUMENT,
225
+ fs.existsSync(path.join(dir, PREVIEW_DATA))
226
+ ? `--path ${where} holds an older theme preview, in a folder that holds the app itself; remove it, then add the preview in its own folder.`
227
+ : `--path ${where} is no place for the preview: the folder holds the app itself, and the app does not serve a preview there.`,
228
+ {
229
+ run: fs.existsSync(path.join(dir, PREVIEW_DATA))
230
+ ? [`${PREVIEW} remove --path ${shq(shownDir(cwd, dir))}`]
231
+ : [
232
+ retry(
233
+ routes.length
234
+ ? shown(cwd, path.join(routes[0], 'theme-preview'))
235
+ : 'theme-preview',
236
+ ),
237
+ ],
238
+ },
239
+ );
240
+ const app = appOf(dir);
241
+ const why =
242
+ reservedFolder(cwd, dir) ?? (app && unroutedSegment(app, dir));
243
+ if (why)
244
+ refuse(
245
+ E.ERR_INVALID_ARGUMENT,
246
+ `--path ${where} is no place for the preview: ${why}.`,
247
+ {
248
+ run: [
249
+ retry(
250
+ routes.length
251
+ ? shown(cwd, path.join(routes[0], 'theme-preview'))
252
+ : null,
253
+ ),
254
+ ],
255
+ },
256
+ );
257
+ }
258
+ return {dir, app: appOf(dir)};
91
259
  }
92
260
  const candidates = routes.map(r => path.join(r, 'theme-preview'));
93
261
  const known = candidates.find(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
262
+ if (!known && opts.retry) {
263
+ // A preview added with --path is recorded with its theme, so a later
264
+ // command finds it without the flag instead of starting a second one.
265
+ const recorded = [
266
+ ...new Set(editedThemes(cwd).flatMap(t => recordedPreviews(cwd, t))),
267
+ ].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
268
+ if (recorded.length === 1)
269
+ return {dir: recorded[0], app: appOf(recorded[0])};
270
+ if (recorded.length > 1)
271
+ refuse(
272
+ E.ERR_INVALID_ARGUMENT,
273
+ `There are ${recorded.length} theme previews here (${recorded.map(d => `${shownDir(cwd, d)}/`).join(', ')}) and none in the default place; name one with --path.`,
274
+ {run: recorded.map(d => retry(shownDir(cwd, d)))},
275
+ );
276
+ // An older release could put a preview at the project root or in src/,
277
+ // where its pages/ folder is the Pages Router: every page is public.
278
+ const older = [cwd, path.join(cwd, 'src')].find(d =>
279
+ fs.existsSync(path.join(d, PREVIEW_DATA)),
280
+ );
281
+ if (older && !recorded.length) {
282
+ if (opts.write)
283
+ refuse(
284
+ E.ERR_INVALID_ARGUMENT,
285
+ `An older theme preview is in ${shownDir(cwd, older)}/, a folder that holds the app itself (its pages/ may be public routes of the app); remove it, then add the preview again.`,
286
+ {run: [`${PREVIEW} remove --path ${shq(shownDir(cwd, older))}`]},
287
+ );
288
+ return {dir: older, app: null};
289
+ }
290
+ }
94
291
  const dir = known ?? candidates[0];
95
292
  if (!dir && opts.optional) return /** @type {any} */ (null);
96
293
  if (!dir)
@@ -99,8 +296,8 @@ function previewDir(cwd, where, opts = {}) {
99
296
  'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
100
297
  {
101
298
  run: [
102
- `${PREVIEW} add --path <dir> (a folder inside your app's routes)`,
103
- `${PREVIEW} app <dir> (a new starter app with the preview in it)`,
299
+ `${PREVIEW} add --path <dir> # a folder inside your app's routes`,
300
+ `${PREVIEW} app <dir> # a new starter app with the preview in it`,
104
301
  ],
105
302
  },
106
303
  );
@@ -124,27 +321,70 @@ function confined(file, root, what) {
124
321
  try {
125
322
  return assertWithin(file, root, {allowAbsolute: true, label: what});
126
323
  } catch (e) {
127
- if (e instanceof PathSafetyError)
324
+ if (e instanceof PathSafetyError) {
325
+ /** @type {string | null} */
326
+ let link = null;
327
+ try {
328
+ if (fs.lstatSync(file).isSymbolicLink()) link = fs.readlinkSync(file);
329
+ } catch {
330
+ // Not there: the path itself leads out.
331
+ }
128
332
  refuse(
129
333
  E.ERR_PATH_TRAVERSAL,
130
- `${what} ${file} is outside ${root}; nothing was written or removed.`,
334
+ link == null
335
+ ? `${what} ${file} is outside ${root}.`
336
+ : `${what} ${file}, which is a link to ${link}, outside ${root}.`,
131
337
  );
338
+ }
132
339
  throw e;
133
340
  }
134
341
  }
135
342
 
343
+ /** Files a fresh folder may hold and still count as empty. */
344
+ const IGNORABLE = new Set(['.git', '.DS_Store', 'Thumbs.db']);
345
+
346
+ /**
347
+ * The home page of a new starter app: it points to the preview.
348
+ * The starter's own home page is the repository example's.
349
+ */
350
+ const STARTER_HOME = `'use client';
351
+
352
+ import {VStack} from '@astryxdesign/core/Layout';
353
+ import {Heading, Text} from '@astryxdesign/core/Text';
354
+ import {Link} from '@astryxdesign/core/Link';
355
+
356
+ export default function Home() {
357
+ return (
358
+ <main style={{display: 'flex', justifyContent: 'center', padding: '4rem 2rem'}}>
359
+ <VStack gap={3}>
360
+ <Heading level={1}>Theme preview app</Heading>
361
+ <Text type="body" color="secondary">
362
+ Made by astryx experimental theme preview app. The preview pages wear the theme.
363
+ </Text>
364
+ <Link href="/theme-preview">Open the theme preview</Link>
365
+ </VStack>
366
+ </main>
367
+ );
368
+ }
369
+ `;
370
+
136
371
  /**
137
372
  * The files a new starter app (Next.js app router, Core and the neutral
138
373
  * theme) writes into `where`, with `extra` files beside them, checked before
139
- * anything is written: the folder is new or empty, and every file stays
140
- * inside it, also through links.
374
+ * anything is written: the folder is new or empty, it is not inside the
375
+ * project's routes, themes or packages, and every file stays inside it,
376
+ * also through links.
141
377
  * @param {string} cwd
142
378
  * @param {string} where
143
379
  * @param {(root: string) => Array<{rel: string, text: string | Buffer}>} extra files relative to the app folder
144
380
  * @param {Record<string, string>} dependencies added to the starter's package.json
381
+ * @param {string | null} [slug] the theme, repeated in suggestions
145
382
  * @returns {{root: string, writes: Array<{file: string, text: string | Buffer}>}}
146
383
  */
147
- function planStarterApp(cwd, where, extra, dependencies) {
384
+ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
385
+ const again = (/** @type {string | null} */ p) =>
386
+ `${PREVIEW} app ${shq(p ?? 'theme-app')}${slug == null ? '' : ` --theme ${shq(slug)}`}`;
387
+ checkFolderName(where, 'The app folder', again);
148
388
  /** @type {string} */
149
389
  let root;
150
390
  try {
@@ -157,22 +397,69 @@ function planStarterApp(cwd, where, extra, dependencies) {
157
397
  refuse(
158
398
  E.ERR_PATH_TRAVERSAL,
159
399
  `${where} is outside the current folder; make the app inside the folder you run the command from.`,
400
+ {run: [again(null)]},
160
401
  );
161
402
  throw e;
162
403
  }
163
- if (fs.existsSync(root) && fs.readdirSync(root).length) {
164
- const name = shown(cwd, root) || '.';
165
- const base = path.basename(root) || 'theme-preview';
166
- let free = `${base}-preview`;
167
- for (let n = 2; fs.existsSync(path.join(path.dirname(root), free)); n++)
168
- free = `${base}-preview-${n}`;
169
- const next = shown(cwd, path.join(path.dirname(root), free));
404
+ /** A free folder name inside the current folder, near `dir`. @param {string} dir */
405
+ const freeNear = dir => {
406
+ const parent = dir === cwd ? cwd : path.dirname(dir);
407
+ const base = dir === cwd ? 'theme-app' : `${path.basename(dir)}-preview`;
408
+ let free = base;
409
+ for (let n = 2; fs.existsSync(path.join(parent, free)); n++)
410
+ free = `${base}-${n}`;
411
+ return shown(cwd, path.join(parent, free));
412
+ };
413
+ const name = shownDir(cwd, root);
414
+ const routes = ['app', path.join('src', 'app')]
415
+ .map(r => path.join(cwd, r))
416
+ .filter(r => fs.existsSync(r) && fs.statSync(r).isDirectory());
417
+ const why =
418
+ reservedFolder(cwd, root) ??
419
+ (routes.some(r => root === r || root.startsWith(r + path.sep))
420
+ ? "it is inside this app's routes folder, where Next would serve the new app's files as pages of this one"
421
+ : null);
422
+ if (why) {
423
+ let free = 'theme-app';
424
+ for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
425
+ free = `theme-app-${n}`;
170
426
  refuse(
171
- E.ERR_FILE_EXISTS,
172
- `${name} exists and is not empty; a starter app goes only into a new or empty folder.`,
173
- {run: [`${PREVIEW} app ${q(next)}`]},
427
+ E.ERR_INVALID_ARGUMENT,
428
+ `${name} is no place for a new app: ${why}.`,
429
+ {
430
+ run: [
431
+ again(free),
432
+ `${PREVIEW} add # the preview inside this app instead`,
433
+ ],
434
+ },
174
435
  );
175
436
  }
437
+ /** @type {fs.Stats | null} */
438
+ let st = null;
439
+ try {
440
+ st = fs.lstatSync(root);
441
+ } catch {
442
+ // A new folder.
443
+ }
444
+ if (st?.isSymbolicLink() && !fs.existsSync(root))
445
+ refuse(
446
+ E.ERR_FILE_EXISTS,
447
+ `${name} is a link to ${fs.readlinkSync(root)}, which does not exist.`,
448
+ {run: [again(freeNear(root))]},
449
+ );
450
+ if (st && fs.existsSync(root) && !fs.statSync(root).isDirectory())
451
+ refuse(E.ERR_FILE_EXISTS, `${name} is a file; the app goes in a folder.`, {
452
+ run: [again(freeNear(root))],
453
+ });
454
+ if (
455
+ fs.existsSync(root) &&
456
+ fs.readdirSync(root).some(entry => !IGNORABLE.has(entry))
457
+ )
458
+ refuse(
459
+ E.ERR_FILE_EXISTS,
460
+ `${name} exists and is not empty; a starter app goes only into a new or empty folder. Choose another name, or empty the folder.`,
461
+ {run: [again(freeNear(root))]},
462
+ );
176
463
  /** @type {Array<{file: string, text: string | Buffer}>} */
177
464
  const writes = [];
178
465
  /** @param {string} from */
@@ -182,19 +469,24 @@ function planStarterApp(cwd, where, extra, dependencies) {
182
469
  if (entry.isDirectory()) walk(src);
183
470
  else if (entry.name !== 'README.md') {
184
471
  const rel = path.relative(STARTER, src);
185
- const name = rel === 'gitignore' ? '.gitignore' : rel;
472
+ const target = rel === 'gitignore' ? '.gitignore' : rel;
186
473
  const file = confined(
187
- path.join(root, name),
474
+ path.join(root, target),
188
475
  root,
189
476
  'a starter app file',
190
477
  );
191
478
  const text = fs.readFileSync(src, 'utf8');
479
+ const key = rel.split(path.sep).join('/');
192
480
  writes.push({
193
481
  file,
194
482
  text:
195
- rel === 'package.json'
483
+ key === 'package.json'
196
484
  ? starterPackageJson(text, dependencies)
197
- : text,
485
+ : key === 'src/app/page.tsx'
486
+ ? STARTER_HOME
487
+ : key === 'src/app/layout.tsx'
488
+ ? starterLayout(text)
489
+ : text,
198
490
  });
199
491
  }
200
492
  }
@@ -208,6 +500,19 @@ function planStarterApp(cwd, where, extra, dependencies) {
208
500
  return {root, writes};
209
501
  }
210
502
 
503
+ /**
504
+ * The starter's root layout, with a title and description of its own.
505
+ * @param {string} text
506
+ */
507
+ function starterLayout(text) {
508
+ return text
509
+ .replace(/title: '[^']*'/, "title: 'Theme preview'")
510
+ .replace(
511
+ /description:\s*'[^']*'/,
512
+ "description: 'An Astryx app made to preview a theme'",
513
+ );
514
+ }
515
+
211
516
  /**
212
517
  * The starter's package.json with the Astryx packages pinned to this CLI's
213
518
  * release, and `dependencies` added.
@@ -227,62 +532,456 @@ function starterPackageJson(text, dependencies) {
227
532
  }
228
533
 
229
534
  /**
230
- * Write a planned starter app. No install runs here.
535
+ * Write a planned starter app: into a temp folder beside it first, then
536
+ * renamed into place (or moved into the empty folder), so a failure leaves
537
+ * nothing behind. No install runs here.
231
538
  * @param {string} cwd
232
- * @param {{writes: Array<{file: string, text: string | Buffer}>}} plan
539
+ * @param {{root: string, writes: Array<{file: string, text: string | Buffer}>}} plan
540
+ * @param {(dir: string) => string} again the command with this folder
233
541
  * @returns {string[]} the files written
234
542
  */
235
- function writeStarterApp(cwd, plan) {
236
- for (const w of plan.writes) {
237
- fs.mkdirSync(path.dirname(w.file), {recursive: true});
238
- fs.writeFileSync(w.file, w.text);
543
+ function writeStarterApp(cwd, plan, again) {
544
+ const {root} = plan;
545
+ const parent = path.dirname(root);
546
+ /** The folders on the way to the app that this call makes. @type {string[]} */
547
+ const made = [];
548
+ for (let d = parent; !fs.existsSync(d); d = path.dirname(d)) made.push(d);
549
+ /** @type {string | null} */
550
+ let tmp = null;
551
+ /** @type {string[]} */
552
+ const movedIn = [];
553
+ try {
554
+ fs.mkdirSync(parent, {recursive: true});
555
+ tmp = fs.mkdtempSync(path.join(parent, '.astryx-app-'));
556
+ for (const w of plan.writes) {
557
+ const file = path.join(tmp, path.relative(root, w.file));
558
+ fs.mkdirSync(path.dirname(file), {recursive: true});
559
+ fs.writeFileSync(file, w.text);
560
+ }
561
+ if (!fs.existsSync(root)) {
562
+ fs.renameSync(tmp, root);
563
+ tmp = null;
564
+ } else {
565
+ for (const entry of fs.readdirSync(tmp)) {
566
+ const to = path.join(root, entry);
567
+ if (fs.existsSync(to))
568
+ throw Object.assign(new Error(`${to} exists`), {code: 'EEXIST'});
569
+ fs.renameSync(path.join(tmp, entry), to);
570
+ movedIn.push(to);
571
+ }
572
+ fs.rmdirSync(tmp);
573
+ tmp = null;
574
+ }
575
+ } catch (e) {
576
+ for (const m of movedIn) fs.rmSync(m, {recursive: true, force: true});
577
+ if (tmp) fs.rmSync(tmp, {recursive: true, force: true});
578
+ for (const d of made)
579
+ try {
580
+ fs.rmdirSync(d);
581
+ } catch {
582
+ // Not empty: something else is in it now.
583
+ }
584
+ const code = /** @type {any} */ (e)?.code;
585
+ if (code === undefined) throw e;
586
+ if (code === 'EEXIST' || code === 'ENOTEMPTY')
587
+ refuse(
588
+ E.ERR_FILE_EXISTS,
589
+ `${shownDir(cwd, root)} was filled by something else while the app was written, so the app was not put there.`,
590
+ {run: [again(`${shownDir(cwd, root)}-2`)]},
591
+ );
592
+ refuse(
593
+ E.ERR_WRITE_FAILED,
594
+ `The app could not be written (${code}); nothing of it was left in ${shownDir(cwd, root)}.`,
595
+ {run: [`${again(shownDir(cwd, root))} # once the cause is fixed`]},
596
+ );
239
597
  }
240
598
  return plan.writes.map(w => shown(cwd, w.file)).sort();
241
599
  }
242
600
 
243
- /** @param {string} dir @returns {PreviewData | null} */
244
- function readPreview(dir) {
601
+ /**
602
+ * Why a theme-preview.json is not the preview's data, or null. It is a file
603
+ * anyone can edit, so its shape is checked before it decides any write or
604
+ * delete. A path that leads out of the folder is refused later, by
605
+ * {@link confined}.
606
+ * @param {any} d
607
+ * @returns {string | null}
608
+ */
609
+ function previewProblem(d) {
610
+ if (!d || typeof d !== 'object' || Array.isArray(d))
611
+ return 'it is not a JSON object';
612
+ if (d.version !== 1)
613
+ return `"version" is ${JSON.stringify(d.version)}, not 1`;
614
+ if (d.theme != null && typeof d.theme !== 'string')
615
+ return '"theme" is not a theme name or null';
616
+ if (!Array.isArray(d.pages)) return '"pages" is not a list';
617
+ if (!Array.isArray(d.files)) return '"files" is not a list';
618
+ const ids = new Set();
619
+ for (const p of d.pages) {
620
+ if (!p || typeof p !== 'object' || Array.isArray(p))
621
+ return '"pages" holds an entry that is not an object';
622
+ if (typeof p.id !== 'string' || !PAGE_ID.test(p.id))
623
+ return `the page id ${JSON.stringify(p.id)} is not lowercase letters, digits and dashes`;
624
+ if (typeof p.label !== 'string')
625
+ return `the page ${p.id} has no text label`;
626
+ if (
627
+ p.file !== `${PAGES_DIR}/${p.id}` &&
628
+ p.file !== `${LEGACY_PAGES_DIR}/${p.id}`
629
+ )
630
+ return `the page ${p.id} names the file ${JSON.stringify(p.file)}, not ${PAGES_DIR}/${p.id}`;
631
+ if (ids.has(p.id)) return `the page ${p.id} is listed twice`;
632
+ ids.add(p.id);
633
+ }
634
+ for (const f of d.files)
635
+ if (
636
+ typeof f !== 'string' ||
637
+ !f ||
638
+ f.includes('\\') ||
639
+ path.posix.isAbsolute(f) ||
640
+ /^[A-Za-z]:/.test(f) ||
641
+ f.split('/').some(x => x === '' || x === '.')
642
+ )
643
+ return `"files" holds ${JSON.stringify(f)}, which is not a file path relative to the folder`;
644
+ if (
645
+ d.hashes != null &&
646
+ (typeof d.hashes !== 'object' ||
647
+ Array.isArray(d.hashes) ||
648
+ Object.values(d.hashes).some(h => typeof h !== 'string'))
649
+ )
650
+ return '"hashes" is not a map of file to hash';
651
+ return null;
652
+ }
653
+
654
+ /**
655
+ * Refuse a damaged theme-preview.json: it decides which files the preview
656
+ * may replace or delete, so no preview command changes the folder until it
657
+ * is fixed.
658
+ * @param {string} cwd
659
+ * @param {string} dir
660
+ * @param {string} why
661
+ * @param {string} pf the caller's --path flag, for the suggestion
662
+ * @returns {never}
663
+ */
664
+ function damagedPreview(cwd, dir, why, pf) {
665
+ const folder = shownDir(cwd, dir);
666
+ refuse(
667
+ E.ERR_THEME_INVALID,
668
+ `${folder}/${PREVIEW_DATA} is damaged: ${why}. It lists the preview's pages and the files it wrote, so the preview commands leave the folder alone until it is fixed.`,
669
+ {
670
+ fix: `fix ${folder}/${PREVIEW_DATA} by hand; or give the folder a new name that starts with _ (Next does not serve such a folder, and nothing in it is lost), then run ${PREVIEW} add${pf} again`,
671
+ },
672
+ );
673
+ }
674
+
675
+ /**
676
+ * The preview's data, null when the folder has none; a refusal when the
677
+ * file is there but unreadable or of the wrong shape.
678
+ * @param {string} cwd
679
+ * @param {string} dir
680
+ * @param {string} [pf] the caller's --path flag, for the refusal
681
+ * @returns {PreviewData | null}
682
+ */
683
+ function readPreview(cwd, dir, pf = '') {
684
+ /** @type {string} */
685
+ let text;
686
+ try {
687
+ text = fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8');
688
+ } catch (e) {
689
+ const code = /** @type {any} */ (e)?.code;
690
+ if (code === 'ENOENT' || code === 'ENOTDIR') return null;
691
+ damagedPreview(cwd, dir, `it cannot be read (${code})`, pf);
692
+ }
693
+ /** @type {any} */
694
+ let data;
695
+ try {
696
+ data = JSON.parse(text);
697
+ } catch (e) {
698
+ damagedPreview(
699
+ cwd,
700
+ dir,
701
+ `it is not valid JSON (${/** @type {Error} */ (e).message})`,
702
+ pf,
703
+ );
704
+ }
705
+ const problem = previewProblem(data);
706
+ if (problem) damagedPreview(cwd, dir, problem, pf);
707
+ data.files = [...new Set(data.files)];
708
+ return data;
709
+ }
710
+
711
+ /** A short hash of a file's text. @param {string | Buffer} text */
712
+ const digest = text =>
713
+ createHash('sha256').update(text).digest('hex').slice(0, 16);
714
+
715
+ /**
716
+ * The hash recorded for a file the preview writes: of its text without
717
+ * white space, semicolons, commas and quote styles, so a formatter run
718
+ * (prettier, eslint --fix) does not count as a change by hand.
719
+ * @param {string | Buffer} text
720
+ */
721
+ const contentHash = text =>
722
+ digest(
723
+ String(text)
724
+ .replace(/["'`]/g, "'")
725
+ .replace(/[\s;,]+/g, ''),
726
+ );
727
+
728
+ /**
729
+ * Whether a file the preview wrote was changed since, by its recorded hash.
730
+ * A file with no hash (written by an older release) counts as unchanged.
731
+ * @param {string} dir
732
+ * @param {PreviewData} data
733
+ * @param {string} rel
734
+ */
735
+ function editedByHand(dir, data, rel) {
736
+ const was = data.hashes?.[rel];
737
+ if (!was) return false;
245
738
  try {
246
- return JSON.parse(fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8'));
739
+ const text = fs.readFileSync(path.join(dir, rel));
740
+ // Older records hold the hash of the exact text.
741
+ return contentHash(text) !== was && digest(text) !== was;
247
742
  } catch {
248
- return null;
743
+ return false;
249
744
  }
250
745
  }
251
746
 
252
747
  /**
253
- * A preview file, checked: inside the route folder, also through links, and
254
- * not a file there that the preview did not write, which is never replaced.
748
+ * Check one planned write before anything is written. A file the preview
749
+ * did not write is never replaced, unless it already holds exactly the
750
+ * planned text (a page an interrupted run left behind is adopted). A file
751
+ * the preview wrote and someone changed since is not replaced either.
255
752
  * @param {string} cwd
256
753
  * @param {string} dir
257
754
  * @param {PreviewData} data
258
- * @param {string} rel relative to dir
259
- * @returns {string} the absolute file
755
+ * @param {{rel: string, text: string}} w
756
+ * @param {string} elsewhere a command that puts the preview in a free folder
757
+ * @returns {'new' | 'same' | 'replace'}
260
758
  */
261
- function previewFile(cwd, dir, data, rel) {
262
- const file = confined(path.join(dir, rel), dir, 'a preview file');
263
- const key = rel.split(path.sep).join('/');
264
- if (fs.existsSync(file) && !data.files.includes(key))
759
+ function checkWrite(cwd, dir, data, w, elsewhere) {
760
+ const file = confined(path.join(dir, w.rel), dir, 'a preview file');
761
+ /** @type {fs.Stats} */
762
+ let st;
763
+ try {
764
+ st = fs.lstatSync(file);
765
+ } catch {
766
+ return 'new';
767
+ }
768
+ const name = shown(cwd, file);
769
+ if (!st.isFile())
770
+ refuse(
771
+ E.ERR_FILE_EXISTS,
772
+ `${name} is ${st.isDirectory() ? 'a folder' : 'not a plain file'}, where the preview writes a file; it is never replaced.`,
773
+ {run: [elsewhere]},
774
+ );
775
+ if (fs.readFileSync(file, 'utf8') === w.text) return 'same';
776
+ const page = /^_?pages\/([^/]+)\.tsx$/.exec(w.rel)?.[1];
777
+ if (!data.files.includes(w.rel))
778
+ refuse(
779
+ E.ERR_FILE_EXISTS,
780
+ `${name} exists and the preview did not write it; it is never replaced.`,
781
+ page
782
+ ? {
783
+ fix: `give ${name} another name if you want to keep it, then run the command again; or add another page`,
784
+ run: ['astryx template --list --type page'],
785
+ }
786
+ : {
787
+ fix: `move ${name} out of the folder, then run the command again; or put the preview in another folder`,
788
+ run: [elsewhere],
789
+ },
790
+ );
791
+ if (editedByHand(dir, data, w.rel))
265
792
  refuse(
266
793
  E.ERR_FILE_EXISTS,
267
- `${shown(cwd, file)} exists and the preview did not write it; it is never replaced. Move it, or put the preview elsewhere with --path.`,
794
+ `${name} was changed by hand after the preview wrote it, so it is not replaced.`,
795
+ {
796
+ fix: `copy your changes out of ${name}, then delete it or give it another name, and run the command again`,
797
+ },
268
798
  );
269
- return file;
799
+ return 'replace';
270
800
  }
271
801
 
272
802
  /**
273
- * Write one file of the preview, checked as {@link previewFile} checks it.
803
+ * Apply a checked plan to the preview folder: every write goes to a temp
804
+ * file first, then all are renamed into place, then the deletes run, then
805
+ * theme-preview.json is written with the new hashes. When any step fails,
806
+ * every file is put back as it was, and the refusal says so.
274
807
  * @param {string} cwd
275
808
  * @param {string} dir
276
809
  * @param {PreviewData} data
277
- * @param {string} rel relative to dir
278
- * @param {string} text
810
+ * @param {Array<{rel: string, text: string, keepHash?: boolean}>} writes
811
+ * `keepHash`: a file moved as it is keeps its recorded hash
812
+ * @param {string[]} deletes relative to dir
813
+ * @param {string} again the command, to run again once the cause is fixed
279
814
  */
280
- function writePreviewFile(cwd, dir, data, rel, text) {
281
- const file = previewFile(cwd, dir, data, rel);
282
- fs.mkdirSync(path.dirname(file), {recursive: true});
283
- fs.writeFileSync(file, text);
284
- const key = rel.split(path.sep).join('/');
285
- if (!data.files.includes(key)) data.files.push(key);
815
+ function commitPreview(cwd, dir, data, writes, deletes, again) {
816
+ /** The temp file of each target. @type {Map<string, string>} */
817
+ const temps = new Map();
818
+ const tmp = (/** @type {string} */ file) => {
819
+ if (!temps.has(file)) temps.set(file, tempFor(file));
820
+ return /** @type {string} */ (temps.get(file));
821
+ };
822
+ /** @type {string[]} */
823
+ const staged = [];
824
+ /** Folders this call made. @type {string[]} */
825
+ const made = [];
826
+ /** @type {Array<{file: string, before: Buffer | null}>} */
827
+ const touched = [];
828
+ const before = (/** @type {string} */ file) => {
829
+ try {
830
+ return fs.readFileSync(file);
831
+ } catch {
832
+ return null;
833
+ }
834
+ };
835
+ /** @param {string} folder */
836
+ const mkdir = folder => {
837
+ /** @type {string[]} */
838
+ const missing = [];
839
+ for (let d = folder; !fs.existsSync(d); d = path.dirname(d))
840
+ missing.unshift(d);
841
+ fs.mkdirSync(folder, {recursive: true});
842
+ made.push(...missing);
843
+ };
844
+ /** @param {string} file @param {string} text */
845
+ const stage = (file, text) => {
846
+ // Recorded before the write, so a write that fails halfway (a full
847
+ // disk) leaves no temp file behind.
848
+ staged.push(tmp(file));
849
+ fs.writeFileSync(tmp(file), text);
850
+ try {
851
+ // A file someone made read-only keeps its mode.
852
+ fs.chmodSync(tmp(file), fs.statSync(file).mode & 0o777);
853
+ } catch {
854
+ // A new file.
855
+ }
856
+ };
857
+ let current = dir;
858
+ let step = 'written';
859
+ try {
860
+ for (const w of writes) {
861
+ current = confined(path.join(dir, w.rel), dir, 'a preview file');
862
+ mkdir(path.dirname(current));
863
+ stage(current, w.text);
864
+ }
865
+ for (const w of writes) {
866
+ current = path.join(dir, w.rel);
867
+ touched.push({file: current, before: before(current)});
868
+ fs.renameSync(tmp(current), current);
869
+ }
870
+ staged.length = 0;
871
+ step = 'removed';
872
+ for (const rel of deletes) {
873
+ current = confined(path.join(dir, rel), dir, 'a preview file');
874
+ const was = before(current);
875
+ if (was == null) continue;
876
+ touched.push({file: current, before: was});
877
+ fs.rmSync(current);
878
+ }
879
+ step = 'written';
880
+ const hashes = {...data.hashes};
881
+ for (const w of writes)
882
+ if (!w.keepHash || !hashes[w.rel]) hashes[w.rel] = contentHash(w.text);
883
+ for (const rel of deletes) delete hashes[rel];
884
+ for (const rel of Object.keys(hashes))
885
+ if (!data.files.includes(rel)) delete hashes[rel];
886
+ data.hashes = hashes;
887
+ if (!data.files.includes(PREVIEW_DATA)) data.files.push(PREVIEW_DATA);
888
+ current = path.join(dir, PREVIEW_DATA);
889
+ touched.push({file: current, before: before(current)});
890
+ stage(current, `${JSON.stringify(data, null, 2)}\n`);
891
+ fs.renameSync(tmp(current), current);
892
+ } catch (e) {
893
+ for (const t of staged) fs.rmSync(t, {force: true});
894
+ for (const t of touched.reverse())
895
+ try {
896
+ if (t.before == null) fs.rmSync(t.file, {force: true});
897
+ else fs.writeFileSync(t.file, t.before);
898
+ } catch {
899
+ // Best effort: the refusal below names the file.
900
+ }
901
+ for (const d of made.reverse())
902
+ try {
903
+ fs.rmdirSync(d);
904
+ } catch {
905
+ // Not empty: something else is in it now.
906
+ }
907
+ if (/** @type {any} */ (e)?.code === undefined) throw e;
908
+ refuse(
909
+ E.ERR_WRITE_FAILED,
910
+ `${shown(cwd, current)} could not be ${step} (${/** @type {any} */ (e).code}), so every file of the preview was put back as it was.`,
911
+ {run: [`${again} # once the cause is fixed`]},
912
+ );
913
+ }
914
+ }
915
+
916
+ /**
917
+ * Move the pages an older release wrote into pages/ to {@link PAGES_DIR}/,
918
+ * in the plan and in `data`: a pages/ folder at the project root or in
919
+ * src/ is Next's Pages Router. A page the preview did not write keeps its
920
+ * place.
921
+ * @param {string} cwd
922
+ * @param {string} dir
923
+ * @param {PreviewData} data
924
+ * @returns {{writes: Array<{rel: string, text: string, keepHash: boolean}>, deletes: string[], moved: string[]}}
925
+ */
926
+ function movedPages(cwd, dir, data) {
927
+ /** @type {Array<{rel: string, text: string, keepHash: boolean}>} */
928
+ const writes = [];
929
+ /** @type {string[]} */
930
+ const deletes = [];
931
+ /** @type {string[]} */
932
+ const moved = [];
933
+ for (const p of data.pages) {
934
+ const from = `${p.file}.tsx`;
935
+ if (
936
+ !p.file.startsWith(`${LEGACY_PAGES_DIR}/`) ||
937
+ !data.files.includes(from)
938
+ )
939
+ continue;
940
+ const to = `${PAGES_DIR}/${p.id}.tsx`;
941
+ const target = confined(path.join(dir, to), dir, 'a preview file');
942
+ /** @type {string | null} */
943
+ let text = null;
944
+ try {
945
+ text = fs.readFileSync(
946
+ confined(path.join(dir, from), dir, 'a preview file'),
947
+ 'utf8',
948
+ );
949
+ } catch {
950
+ // Gone already: only the record moves.
951
+ }
952
+ if (
953
+ fs.existsSync(target) &&
954
+ (text == null || fs.readFileSync(target, 'utf8') !== text)
955
+ )
956
+ refuse(
957
+ E.ERR_FILE_EXISTS,
958
+ `${shown(cwd, target)} exists and the preview did not write it; the preview moves its pages there.`,
959
+ {
960
+ fix: `give ${shown(cwd, target)} another name if you want to keep it, then run the command again`,
961
+ },
962
+ );
963
+ p.file = `${PAGES_DIR}/${p.id}`;
964
+ data.files = data.files.map(f => (f === from ? to : f));
965
+ if (data.hashes?.[from]) {
966
+ data.hashes[to] = data.hashes[from];
967
+ delete data.hashes[from];
968
+ }
969
+ if (text == null) continue;
970
+ writes.push({rel: to, text, keepHash: true});
971
+ deletes.push(from);
972
+ moved.push(p.id);
973
+ }
974
+ return {writes, deletes, moved};
975
+ }
976
+
977
+ /** Remove the page folders when nothing is left in them. @param {string} dir */
978
+ function tidyPageFolders(dir) {
979
+ for (const sub of [PAGES_DIR, LEGACY_PAGES_DIR])
980
+ try {
981
+ fs.rmdirSync(path.join(dir, sub));
982
+ } catch {
983
+ // Not there, or not empty: something there is not the preview's.
984
+ }
286
985
  }
287
986
 
288
987
  /** The themes this command made, by name. @param {string} cwd */
@@ -316,7 +1015,11 @@ async function routeTheme(cwd, dir, data) {
316
1015
  }
317
1016
 
318
1017
  /** The Colors page: its id and file, relative to the route folder. */
319
- const COLORS_PAGE = {id: 'colors', label: 'Colors', file: 'pages/colors'};
1018
+ const COLORS_PAGE = {
1019
+ id: 'colors',
1020
+ label: 'Colors',
1021
+ file: `${PAGES_DIR}/colors`,
1022
+ };
320
1023
 
321
1024
  /**
322
1025
  * The Colors page source of a theme, and whether the theme has generated
@@ -343,21 +1046,36 @@ async function colorsPage(cwd, dir, slug) {
343
1046
  source: colorsPageSource({slug, module: null, seeds: {}, uses: {}}),
344
1047
  colors: false,
345
1048
  };
346
- const exact = new Set(
347
- data.settings.filter(s => s.source === 'token' && !s.on).map(s => s.thing),
348
- );
1049
+ /** Whether the theme sets a token exactly, as a whole-theme value, in a mode. @param {string} token @param {'light' | 'dark'} m */
1050
+ const exact = (token, m) =>
1051
+ data.settings.some(
1052
+ s =>
1053
+ s.source === 'token' &&
1054
+ s.thing === token &&
1055
+ !s.on &&
1056
+ !s.when &&
1057
+ !s.state &&
1058
+ (!s.mode || s.mode === m),
1059
+ );
349
1060
  /** @type {Record<string, Record<'light' | 'dark', Record<string, string[]>>>} */
350
1061
  const uses = {};
1062
+ // Only the theme's own modes have shades; text on a fill is marked on
1063
+ // the neutral shade it uses, and pure black or white on no shade.
1064
+ const modes = /** @type {Array<'light' | 'dark'>} */ (
1065
+ data.mode === 'light-only'
1066
+ ? ['light']
1067
+ : data.mode === 'dark-only'
1068
+ ? ['dark']
1069
+ : ['light', 'dark']
1070
+ );
351
1071
  for (const [token, v] of Object.entries(pal.tokens)) {
352
- if (exact.has(token)) continue;
353
- const byMode = (uses[v.family] ??= {light: {}, dark: {}});
354
- for (const m of /** @type {const} */ (['light', 'dark'])) {
1072
+ for (const m of modes) {
1073
+ if (exact(token, m)) continue;
355
1074
  const r = v[m];
356
- // A dark fill that keeps the exact color uses the light ramp's shade:
357
- // it is marked there, for dark mode.
358
- const ramp = r.from ?? m;
359
- (byMode[ramp][r.stop] ??= []).push(
360
- `${token}${r.alpha ? ` (opacity ${r.alpha})` : ''}${ramp !== m ? ` (${m} mode too)` : ''}`,
1075
+ if (r.family === 'black' || r.family === 'white') continue;
1076
+ const byMode = (uses[r.family ?? v.family] ??= {light: {}, dark: {}});
1077
+ (byMode[m][r.stop] ??= []).push(
1078
+ `${token}${r.alpha ? ` (opacity ${r.alpha})` : ''}`,
361
1079
  );
362
1080
  }
363
1081
  }
@@ -378,46 +1096,40 @@ async function colorsPage(cwd, dir, slug) {
378
1096
  }
379
1097
 
380
1098
  /**
381
- * Rewrite the Colors page when the preview has one, so it names the shades
382
- * the theme's tokens use now, or says the theme has no color left.
383
- * @param {string} cwd
384
- * @param {string} dir
385
- * @param {PreviewData} data
386
- * @returns {Promise<boolean>} whether it was rewritten
387
- */
388
- async function refreshColorsPage(cwd, dir, data) {
389
- const rel = `${COLORS_PAGE.file}.tsx`;
390
- if (!data.theme || !data.files.includes(rel)) return false;
391
- const file = previewFile(cwd, dir, data, rel);
392
- const {source} = await colorsPage(cwd, dir, data.theme);
393
- if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === source)
394
- return false;
395
- fs.writeFileSync(file, source);
396
- return true;
397
- }
398
-
399
- /**
400
- * Write the route and the data file from the page list.
1099
+ * The route file and, when the preview has one, the Colors page as the
1100
+ * page list and the theme say now. With `gone`, the theme the preview wore
1101
+ * was deleted: its Colors page says the preview has no theme colors.
401
1102
  * @param {string} cwd
402
1103
  * @param {string} dir
403
1104
  * @param {PreviewData} data
404
- * @param {{name: string, module: string, css: string[]} | null} [theme] from {@link routeTheme}
1105
+ * @param {{name: string, module: string, css: string[], mode?: 'system' | 'light' | 'dark'} | null} theme from {@link routeTheme}
1106
+ * @param {{gone?: string | null, by?: string}} [opts] `by`: the command named in the route's header
1107
+ * @returns {Promise<Array<{rel: string, text: string}>>}
405
1108
  */
406
- async function writeRoute(cwd, dir, data, theme) {
407
- if (theme === undefined) theme = await routeTheme(cwd, dir, data);
408
- await refreshColorsPage(cwd, dir, data);
409
- writePreviewFile(
410
- cwd,
411
- dir,
412
- data,
413
- 'page.tsx',
414
- previewRouteSource({pages: data.pages, theme}),
415
- );
416
- if (!data.files.includes(PREVIEW_DATA)) data.files.push(PREVIEW_DATA);
417
- fs.writeFileSync(
418
- path.join(dir, PREVIEW_DATA),
419
- `${JSON.stringify(data, null, 2)}\n`,
420
- );
1109
+ async function routeWrites(cwd, dir, data, theme, opts = {}) {
1110
+ /** @type {Array<{rel: string, text: string}>} */
1111
+ const out = [];
1112
+ const colors = data.pages.find(p => p.id === COLORS_PAGE.id);
1113
+ const rel = colors && `${colors.file}.tsx`;
1114
+ if (rel && data.files.includes(rel)) {
1115
+ if (data.theme)
1116
+ out.push({rel, text: (await colorsPage(cwd, dir, data.theme)).source});
1117
+ else if (opts.gone)
1118
+ out.push({
1119
+ rel,
1120
+ text: colorsPageSource({
1121
+ slug: opts.gone,
1122
+ module: null,
1123
+ seeds: {},
1124
+ uses: {},
1125
+ }),
1126
+ });
1127
+ }
1128
+ out.push({
1129
+ rel: 'page.tsx',
1130
+ text: previewRouteSource({pages: data.pages, theme, by: opts.by}),
1131
+ });
1132
+ return out;
421
1133
  }
422
1134
 
423
1135
  /**
@@ -425,10 +1137,13 @@ async function writeRoute(cwd, dir, data, theme) {
425
1137
  * a font package installed after `set` loads on the next change or `show`,
426
1138
  * and its Colors page, so it names the shades the tokens use now.
427
1139
  * The preview in the usual place (app/ or src/app/theme-preview) and every
428
- * preview added with --path for the theme are kept this way.
1140
+ * preview added with --path for the theme are kept this way. A damaged
1141
+ * preview, and a file changed by hand, are left as they are.
429
1142
  * @param {string} cwd
430
1143
  * @param {string} slug
431
- * @returns {Promise<boolean>} whether the route or the Colors page was rewritten
1144
+ * @returns {Promise<{changed: boolean, stale: string[]}>} `changed`: the
1145
+ * route or the Colors page was rewritten; `stale`: preview files changed by
1146
+ * hand, which keep showing the theme as it was
432
1147
  */
433
1148
  export async function refreshPreviewRoute(cwd, slug) {
434
1149
  const at = previewDir(cwd, undefined, {optional: true});
@@ -436,21 +1151,36 @@ export async function refreshPreviewRoute(cwd, slug) {
436
1151
  ...new Set([...(at ? [at.dir] : []), ...recordedPreviews(cwd, slug)]),
437
1152
  ];
438
1153
  let changed = false;
1154
+ /** @type {string[]} */
1155
+ const stale = [];
439
1156
  for (const dir of dirs) {
440
- const data = readPreview(dir);
1157
+ /** @type {PreviewData | null} */
1158
+ let data;
1159
+ try {
1160
+ data = readPreview(cwd, dir);
1161
+ } catch {
1162
+ continue;
1163
+ }
441
1164
  if (!data || data.theme !== slug || !data.files.includes('page.tsx'))
442
1165
  continue;
443
- if (await refreshColorsPage(cwd, dir, data)) changed = true;
444
- const file = previewFile(cwd, dir, data, 'page.tsx');
445
- const text = previewRouteSource({
446
- pages: data.pages,
447
- theme: await routeTheme(cwd, dir, data),
1166
+ const writes = (
1167
+ await routeWrites(cwd, dir, data, await routeTheme(cwd, dir, data))
1168
+ ).filter(w => {
1169
+ const file = confined(path.join(dir, w.rel), dir, 'a preview file');
1170
+ if (!data.files.includes(w.rel)) return false;
1171
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === w.text)
1172
+ return false;
1173
+ if (editedByHand(dir, data, w.rel)) {
1174
+ stale.push(shown(cwd, file));
1175
+ return false;
1176
+ }
1177
+ return true;
448
1178
  });
449
- if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === text) continue;
450
- fs.writeFileSync(file, text);
1179
+ if (!writes.length) continue;
1180
+ commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
451
1181
  changed = true;
452
1182
  }
453
- return changed;
1183
+ return {changed, stale};
454
1184
  }
455
1185
 
456
1186
  /**
@@ -495,7 +1225,7 @@ function recordPreview(cwd, slug, dir, keep = true) {
495
1225
  .filter(x => x !== rel);
496
1226
  if (keep) list.push(rel);
497
1227
  const file = previewsFile(cwd, slug);
498
- if (list.length) fs.writeFileSync(file, `${JSON.stringify(list, null, 2)}\n`);
1228
+ if (list.length) writeWhole(file, `${JSON.stringify(list, null, 2)}\n`);
499
1229
  else fs.rmSync(file, {force: true});
500
1230
  }
501
1231
 
@@ -505,27 +1235,41 @@ function recordPreview(cwd, slug, dir, keep = true) {
505
1235
  * @param {{dir: string, app: string | null}} at
506
1236
  */
507
1237
  function openLine(cwd, at) {
508
- if (at.app)
509
- return `open /${path.relative(at.app, at.dir).split(path.sep).join('/')} in the running app`;
1238
+ if (at.app) {
1239
+ // A (group) folder is not part of the URL; each other folder is one
1240
+ // URL segment, encoded.
1241
+ const url = path
1242
+ .relative(at.app, at.dir)
1243
+ .split(path.sep)
1244
+ .filter(seg => !/^\(.*\)$/.test(seg))
1245
+ .map(seg => encodeURIComponent(seg))
1246
+ .join('/');
1247
+ return `open /${url} in the running app`;
1248
+ }
510
1249
  const routes = ['app', path.join('src', 'app')].filter(r =>
511
1250
  fs.existsSync(path.join(cwd, r)),
512
1251
  );
513
1252
  if (routes.length)
514
- return `the preview is in ${shown(cwd, at.dir)}/, outside the app's routes folder (${routes[0]}/), so the app does not serve it: put it there with --path ${routes[0]}/${path.basename(at.dir)}`;
515
- return `no app routes folder (app/ or src/app/) was found, so the preview is in ${shown(cwd, at.dir)}/; a starter app around it is not set up yet: serve page.tsx from a route of your app, or move it there with --path`;
1253
+ return `the preview is in ${shownDir(cwd, at.dir)}/, outside the app's routes folder (${routes[0].split(path.sep).join('/')}/), so the app does not serve it: put it there with --path ${routes[0].split(path.sep).join('/')}/theme-preview`;
1254
+ return `no app routes folder (app/ or src/app/) was found, so the preview is in ${shownDir(cwd, at.dir)}/; serve page.tsx from a route of your app, or make a starter app around a preview with ${PREVIEW} app <dir>`;
516
1255
  }
517
1256
 
518
1257
  const STYLEX_IMPORT = /from\s+['"]@stylexjs\/stylex['"]/;
519
1258
 
520
1259
  /**
521
1260
  * Why a template page was skipped.
522
- * @param {{missingPackages: string[], stylexCompiler: boolean}} s
1261
+ * @param {{missingPackages: string[], notInstalled: string[], stylexCompiler: boolean}} s
523
1262
  */
524
1263
  function skipReason(s) {
525
1264
  return [
526
1265
  ...(s.missingPackages.length
527
1266
  ? [`needs ${s.missingPackages.join(', ')}`]
528
1267
  : []),
1268
+ ...(s.notInstalled.length
1269
+ ? [
1270
+ `needs ${s.notInstalled.join(', ')}, which the app's package.json names but is not installed`,
1271
+ ]
1272
+ : []),
529
1273
  ...(s.stylexCompiler
530
1274
  ? [
531
1275
  'uses StyleX, and this app has no StyleX compiler (astryx docs styling-overview)',
@@ -578,6 +1322,15 @@ async function rankedPages(words, cwd, notes, flags) {
578
1322
  const label = name => listed.find(t => t.id === name)?.name ?? name;
579
1323
  const suggest = (/** @type {string[]} */ list) =>
580
1324
  list.slice(0, 3).map(n => `${PREVIEW} add --template ${n}${flags}`);
1325
+ // With no page close, a few pages that need nothing more, and the list.
1326
+ const fallback = [
1327
+ ...suggest(
1328
+ ['dashboard', 'settings', 'login'].filter(id =>
1329
+ listed.some(t => t.id === id),
1330
+ ),
1331
+ ),
1332
+ 'astryx template --list --type page',
1333
+ ];
581
1334
  // No page relates when the ranking fell back to a frame with no direct
582
1335
  // match, and no page the search found matches three words of the request
583
1336
  // or two fifths of them.
@@ -604,7 +1357,11 @@ async function rankedPages(words, cwd, notes, flags) {
604
1357
  refuse(
605
1358
  E.ERR_NOT_FOUND,
606
1359
  `No page template relates to "${words}". Name a page to add it anyway.`,
607
- {run: suggest(pages.length ? pages : skippedFrames)},
1360
+ {
1361
+ run: pages.length
1362
+ ? [...suggest(pages), 'astryx template --list --type page']
1363
+ : fallback,
1364
+ },
608
1365
  );
609
1366
  if (skippedFrames.length)
610
1367
  notes.push(
@@ -730,195 +1487,531 @@ async function pageTemplates(cwd) {
730
1487
  );
731
1488
  }
732
1489
 
1490
+ /**
1491
+ * Whether a package is installed for the project: its folder is in a
1492
+ * node_modules/ of the project or above it. A package the package.json
1493
+ * names but nobody installed does not count.
1494
+ * @param {string} cwd
1495
+ * @param {string} pkg
1496
+ */
1497
+ function installed(cwd, pkg) {
1498
+ for (let dir = cwd; ; dir = path.dirname(dir)) {
1499
+ if (fs.existsSync(path.join(dir, 'node_modules', pkg, 'package.json')))
1500
+ return true;
1501
+ if (path.dirname(dir) === dir) return false;
1502
+ }
1503
+ }
1504
+
1505
+ /**
1506
+ * The packages a template source imports that the app's package.json names
1507
+ * but that are not installed. React, Next and the Astryx packages are left
1508
+ * out: the app runs on them.
1509
+ * @param {string} cwd
1510
+ * @param {string} source
1511
+ * @param {string[]} missing packages already reported as missing
1512
+ */
1513
+ function notInstalled(cwd, source, missing) {
1514
+ return [...extractImportedPackages(source)].filter(
1515
+ pkg =>
1516
+ !missing.includes(pkg) &&
1517
+ !/^(react|react-dom|next)$/.test(pkg) &&
1518
+ !pkg.startsWith('@astryxdesign/') &&
1519
+ !installed(cwd, pkg),
1520
+ );
1521
+ }
1522
+
1523
+ /** The command that installs what the package.json names. @param {string} cwd */
1524
+ function installCommandOf(cwd) {
1525
+ for (const [lock, pm] of /** @type {const} */ ([
1526
+ ['pnpm-lock.yaml', 'pnpm'],
1527
+ ['yarn.lock', 'yarn'],
1528
+ ['bun.lockb', 'bun'],
1529
+ ['bun.lock', 'bun'],
1530
+ ]))
1531
+ if (fs.existsSync(path.join(cwd, lock))) return `${pm} install`;
1532
+ return 'npm install';
1533
+ }
1534
+
1535
+ /**
1536
+ * The settings of the theme a preview wears, or a refusal that names the
1537
+ * themes there are: the closest editor theme by name, or for a package
1538
+ * theme (the base themes) what to do instead.
1539
+ * @param {string} cwd
1540
+ * @param {string} slug
1541
+ * @param {(theme: string | null) => string} again the command with this --theme (null: none)
1542
+ * @param {string} without what leaving --theme out does
1543
+ */
1544
+ function wornTheme(cwd, slug, again, without) {
1545
+ try {
1546
+ return loadTheme(cwd, slug);
1547
+ } catch (e) {
1548
+ const code = /** @type {any} */ (e)?.code;
1549
+ if (code !== E.ERR_UNKNOWN_THEME && code !== E.ERR_INVALID_ARGUMENT)
1550
+ throw e;
1551
+ const name = String(slug)
1552
+ .trim()
1553
+ .toLowerCase()
1554
+ .replace(/^@astryxdesign\/theme-/, '');
1555
+ const themes = editedThemes(cwd);
1556
+ if (!themes.includes(name) && isPackageTheme(cwd, name))
1557
+ refuse(
1558
+ E.ERR_UNKNOWN_THEME,
1559
+ `${slug} is a package theme, not a theme made by ${EDITOR}; ${without}.`,
1560
+ {
1561
+ run: [
1562
+ again(null),
1563
+ `${EDITOR} new my-theme --like ${name} # a theme of your own that starts from it`,
1564
+ ],
1565
+ },
1566
+ );
1567
+ const near = themes.includes(name) ? [name] : nearest(name, themes);
1568
+ if (near.length)
1569
+ refuse(
1570
+ E.ERR_UNKNOWN_THEME,
1571
+ `There is no theme "${slug}" under themes/.`,
1572
+ {run: near.map(n => again(n))},
1573
+ );
1574
+ throw e;
1575
+ }
1576
+ }
1577
+
1578
+ /**
1579
+ * Whether a name is a theme package: the neutral base, or an installed
1580
+ * `@astryxdesign/theme-<name>`.
1581
+ * @param {string} cwd
1582
+ * @param {string} name
1583
+ */
1584
+ function isPackageTheme(cwd, name) {
1585
+ return (
1586
+ name === 'neutral' ||
1587
+ (/^[a-z][a-z0-9-]*$/.test(name) &&
1588
+ installed(cwd, `@astryxdesign/theme-${name}`))
1589
+ );
1590
+ }
1591
+
1592
+ /**
1593
+ * The page template `--template` names, or a refusal: a block or component
1594
+ * example is not a page, and the suggestions are page templates only, as
1595
+ * commands.
1596
+ * @param {string} cwd
1597
+ * @param {string} id
1598
+ * @param {string} flags the caller's other flags
1599
+ * @returns {Promise<{name: string, displayName: string, why: string}>}
1600
+ */
1601
+ async function namedTemplate(cwd, id, flags) {
1602
+ const pages = await pageTemplates(cwd);
1603
+ const hit = pages.find(t => t.id === id);
1604
+ if (hit)
1605
+ return {
1606
+ name: id,
1607
+ displayName: hit.name ?? id,
1608
+ why: 'named with --template',
1609
+ };
1610
+ try {
1611
+ const shownTemplate =
1612
+ /** @type {import('../template/template.type.mjs').TemplateShowResponse} */ (
1613
+ await template(id, {cwd, type: 'page'})
1614
+ );
1615
+ const name = shownTemplate.data.template;
1616
+ return {
1617
+ name,
1618
+ displayName: pages.find(t => t.id === name)?.name ?? name,
1619
+ why: 'named with --template',
1620
+ };
1621
+ } catch (e) {
1622
+ if (/** @type {any} */ (e)?.code !== E.ERR_UNKNOWN_TEMPLATE) throw e;
1623
+ }
1624
+ const all = /** @type {Array<{id: string, type: string}>} */ (
1625
+ /** @type {any} */ (await template(undefined, {list: true, cwd})).data
1626
+ );
1627
+ const other = all.find(t => t.id === id);
1628
+ const near = nearest(
1629
+ id.toLowerCase(),
1630
+ pages.map(t => t.id),
1631
+ 5,
1632
+ );
1633
+ refuse(
1634
+ E.ERR_UNKNOWN_TEMPLATE,
1635
+ other
1636
+ ? `${id} is a ${other.type} template, not a page; preview add takes page templates.`
1637
+ : `There is no page template "${id}".`,
1638
+ {
1639
+ run: [
1640
+ ...near.map(n => `${PREVIEW} add --template ${n}${flags}`),
1641
+ 'astryx template --list --type page',
1642
+ ],
1643
+ },
1644
+ );
1645
+ }
1646
+
1647
+ /**
1648
+ * The text of a recorded page written again: a default page, or the page
1649
+ * template its id names when the app can show it; else null.
1650
+ * @param {string} cwd
1651
+ * @param {string} id
1652
+ * @param {(id: string) => Promise<{text: string}>} defaultPage
1653
+ * @returns {Promise<string | null>}
1654
+ */
1655
+ async function pageAgain(cwd, id, defaultPage) {
1656
+ if (id === 'overview' || id === 'components')
1657
+ return (await defaultPage(id)).text;
1658
+ try {
1659
+ const shownTemplate =
1660
+ /** @type {import('../template/template.type.mjs').TemplateShowResponse} */ (
1661
+ await template(id, {cwd, type: 'page'})
1662
+ );
1663
+ const source = shownTemplate.data.source;
1664
+ const needs = analyzeTemplateNeeds(source, cwd);
1665
+ if (
1666
+ needs.missingPackages.length ||
1667
+ notInstalled(cwd, source, []).length ||
1668
+ (STYLEX_IMPORT.test(source) && detectStylingSystem(cwd) !== 'stylex')
1669
+ )
1670
+ return null;
1671
+ return source;
1672
+ } catch {
1673
+ return null;
1674
+ }
1675
+ }
1676
+
733
1677
  /**
734
1678
  * Add pages to the in-app theme preview, and write the preview route the
735
1679
  * first time. With a description, the build ranking picks the template
736
1680
  * pages that fit it best (`top` of them); `template` names one instead.
737
1681
  * With neither, the default pages: the sample app page, every component,
738
1682
  * and the theme's generated colors when it has any.
739
- * Every check runs before the first write, so a refusal changes nothing.
1683
+ * Every check runs before the first write, so a refusal changes nothing;
1684
+ * the files are staged and renamed into place together.
740
1685
  * @experimental
741
1686
  * @param {string} [description]
742
1687
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewAddOptions} [options]
743
1688
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewAddResponse>}
744
1689
  */
745
1690
  export async function themeEditPreviewAdd(description, options = {}) {
746
- const {cwd = process.cwd(), top = 1} = options;
1691
+ const {cwd = process.cwd()} = options;
747
1692
  if (isOutsideProject(cwd))
748
1693
  refuse(
749
1694
  E.ERR_PROJECT_REQUIRED,
750
1695
  'No package.json here, so there is no app to put the preview in.',
751
1696
  {
752
1697
  run: [
753
- `${PREVIEW} add --path <dir> (run in your app: a folder inside its routes)`,
754
- `${PREVIEW} app <dir> (a new starter app with the preview in it)`,
1698
+ `${PREVIEW} add # run in your app`,
1699
+ `${PREVIEW} app <dir> # a new starter app with the preview in it`,
755
1700
  ],
756
1701
  },
757
1702
  );
758
- const words = (description ?? '').trim();
759
- if (words && options.template != null)
1703
+ const pf = options.path != null ? ` --path ${shq(options.path)}` : '';
1704
+ const tf = options.theme != null ? ` --theme ${shq(options.theme)}` : '';
1705
+ const said = (description ?? '').trim();
1706
+ const named =
1707
+ options.template == null ? null : String(options.template).trim();
1708
+ if (named === '')
1709
+ refuse(E.ERR_INVALID_ARGUMENT, '--template needs a page template id.', {
1710
+ run: [
1711
+ `${PREVIEW} add --template dashboard${tf}${pf}`,
1712
+ 'astryx template --list --type page',
1713
+ ],
1714
+ });
1715
+ if (said && named != null)
760
1716
  refuse(
761
1717
  E.ERR_INVALID_ARGUMENT,
762
1718
  '--template names the page; a description asks the ranking to pick one, so drop one of them.',
1719
+ {
1720
+ run: [
1721
+ `${PREVIEW} add --template ${shq(named)}${tf}${pf}`,
1722
+ `${PREVIEW} add ${shq(said)}${tf}${pf}`,
1723
+ ],
1724
+ },
1725
+ );
1726
+ const top = options.top == null ? 1 : Number(String(options.top));
1727
+ if (options.top != null && !/^[1-3]$/.test(String(options.top)))
1728
+ refuse(
1729
+ E.ERR_INVALID_ARGUMENT,
1730
+ `--top takes 1, 2 or 3, not "${String(options.top)}".`,
1731
+ {
1732
+ run: [
1733
+ `${PREVIEW} add ${shq(said || 'a sales dashboard')} --top 2${tf}${pf}`,
1734
+ ],
1735
+ },
1736
+ );
1737
+ if (options.top != null && !said)
1738
+ refuse(
1739
+ E.ERR_INVALID_ARGUMENT,
1740
+ named != null
1741
+ ? '--top says how many ranked pages to add; --template names one page, so drop --top.'
1742
+ : '--top says how many pages to add for a description, and there is none.',
1743
+ {
1744
+ run: [
1745
+ named != null
1746
+ ? `${PREVIEW} add --template ${shq(named)}${tf}${pf}`
1747
+ : `${PREVIEW} add 'a sales dashboard' --top ${String(options.top)}${tf}${pf}`,
1748
+ ],
1749
+ },
763
1750
  );
764
- if (!Number.isInteger(top) || top < 1 || top > 3)
765
- refuse(E.ERR_INVALID_ARGUMENT, `--top takes 1, 2 or 3, not "${top}".`);
766
- const at = previewDir(cwd, options.path);
767
- const data = readPreview(at.dir) ?? {
768
- version: 1,
769
- theme: null,
770
- pages: [],
771
- files: [],
772
- };
773
1751
  /** @type {string[]} */
774
1752
  const notes = [];
1753
+ let words = said;
1754
+ const allWords = said ? said.split(/\s+/) : [];
1755
+ if (allWords.length > MAX_WORDS) {
1756
+ const seen = new Set();
1757
+ words = allWords
1758
+ .filter(w => {
1759
+ const k = w.toLowerCase();
1760
+ if (seen.has(k)) return false;
1761
+ seen.add(k);
1762
+ return true;
1763
+ })
1764
+ .slice(0, MAX_WORDS)
1765
+ .join(' ');
1766
+ notes.push(
1767
+ `the description has ${allWords.length} words; the first ${MAX_WORDS} different ones picked the page`,
1768
+ );
1769
+ }
1770
+ const retry = (/** @type {string | null} */ p) =>
1771
+ `${PREVIEW} add${said ? ` ${shq(said)}` : ''}${named != null ? ` --template ${shq(named)}` : ''}${tf}${p == null ? '' : ` --path ${shq(p)}`}`;
1772
+ const at = previewDir(cwd, options.path, {write: true, retry});
1773
+ const existing = readPreview(cwd, at.dir, pf);
1774
+ /** @type {PreviewData} */
1775
+ const data = existing ?? {version: 1, theme: null, pages: [], files: []};
1776
+ const wore = data.theme;
1777
+ const againWith = (/** @type {string | null} */ t) =>
1778
+ `${PREVIEW} add${said ? ` ${shq(said)}` : ''}${named != null ? ` --template ${shq(named)}` : ''}${t == null ? '' : ` --theme ${t}`}${pf}`;
1779
+ const without = "leave out --theme and the pages wear the app's own theme";
775
1780
  if (options.theme != null) {
776
- loadTheme(cwd, options.theme);
1781
+ wornTheme(cwd, options.theme, againWith, without);
777
1782
  data.theme = options.theme;
1783
+ } else if (data.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir)) {
1784
+ const themes = editedThemes(cwd);
1785
+ data.theme = themes.length === 1 ? themes[0] : null;
1786
+ notes.push(
1787
+ `the preview wore ${wore}, which is gone; it now wears ${data.theme ?? "the app's own theme"}`,
1788
+ );
778
1789
  } else if (!data.theme) {
779
1790
  const themes = editedThemes(cwd);
780
1791
  data.theme = themes.length === 1 ? themes[0] : null;
1792
+ if (themes.length > 1)
1793
+ notes.push(
1794
+ `${themes.length} themes under themes/ (${themes.join(', ')}): the pages wear the app's own theme; pass --theme ${themes[0]} to wear one`,
1795
+ );
781
1796
  }
782
- if (data.theme) loadTheme(cwd, data.theme);
1797
+ if (data.theme) wornTheme(cwd, data.theme, againWith, without);
1798
+ const switched = existing != null && wore !== data.theme;
1799
+ const gone =
1800
+ wore && !data.theme && !fs.existsSync(themeFiles(cwd, wore).dir)
1801
+ ? wore
1802
+ : null;
1803
+ if (switched && !gone)
1804
+ notes.push(
1805
+ `the preview now wears ${data.theme ?? "the app's own theme"} (was ${wore ?? "the app's own theme"}), so its pages are written again`,
1806
+ );
783
1807
  const project = await openProject(cwd);
784
- /** @type {Array<{id: string, label: string, source?: string, template?: string}>} */
1808
+ /** @param {string} id */
1809
+ const defaultPage = async id =>
1810
+ id === 'overview'
1811
+ ? {
1812
+ id,
1813
+ label: 'Overview',
1814
+ text: overviewPageSource(project, {theme: data.theme}),
1815
+ }
1816
+ : {
1817
+ id,
1818
+ label: 'Components',
1819
+ text: componentsPageSource(project, {
1820
+ theme: data.theme,
1821
+ C: (await context(cwd)).C,
1822
+ }).source,
1823
+ };
1824
+ /** @type {Array<{id: string, label: string, text: string}>} */
785
1825
  const add = [];
786
1826
  /** @type {Array<{page: string, reason: string, installCommand: string | null}>} */
787
1827
  const skipped = [];
788
1828
  /** @type {Array<{page: string, why: string}>} */
789
1829
  const matched = [];
790
- if (!words && options.template == null) {
791
- add.push(
792
- {
793
- id: 'overview',
794
- label: 'Overview',
795
- source: overviewPageSource(project, {theme: data.theme}),
796
- },
797
- {
798
- id: 'components',
799
- label: 'Components',
800
- source: componentsPageSource(project, {
801
- theme: data.theme,
802
- C: (await context(cwd)).C,
803
- }).source,
804
- },
805
- );
1830
+ /** @type {string[]} */
1831
+ const runs = [];
1832
+ let stylexSkipped = false;
1833
+ let firstSkipped = false;
1834
+ const explicit = named != null;
1835
+ if (!words && !explicit) {
1836
+ add.push(await defaultPage('overview'), await defaultPage('components'));
806
1837
  if (data.theme) {
807
1838
  const colors = await colorsPage(cwd, at.dir, data.theme);
808
1839
  if (colors.colors)
809
1840
  add.push({
810
1841
  id: COLORS_PAGE.id,
811
1842
  label: COLORS_PAGE.label,
812
- source: colors.source,
1843
+ text: colors.source,
813
1844
  });
814
1845
  }
815
1846
  } else {
816
- /** @type {Array<{name: string, displayName: string, why: string}>} */
817
- let picks;
818
- const explicit = options.template != null;
819
- if (explicit) {
820
- const name = /** @type {string} */ (options.template);
821
- picks = [
822
- {
823
- name,
824
- displayName:
825
- (await pageTemplates(cwd)).find(t => t.id === name)?.name ?? name,
826
- why: 'named with --template',
827
- },
828
- ];
829
- } else
830
- picks = await rankedPages(
831
- words,
832
- cwd,
833
- notes,
834
- [
835
- ...(options.theme != null ? [` --theme ${q(options.theme)}`] : []),
836
- ...(options.path != null ? [` --path ${q(options.path)}`] : []),
837
- ].join(''),
838
- );
839
- for (const pick of picks) {
1847
+ const flags = `${tf}${pf}`;
1848
+ const picks = explicit
1849
+ ? [await namedTemplate(cwd, /** @type {string} */ (named), flags)]
1850
+ : await rankedPages(words, cwd, notes, flags);
1851
+ for (const [i, pick] of picks.entries()) {
840
1852
  if (add.length >= (explicit ? 1 : top)) break;
841
1853
  const shownTemplate =
842
1854
  /** @type {import('../template/template.type.mjs').TemplateShowResponse} */ (
843
1855
  await template(pick.name, {cwd, type: 'page'})
844
1856
  );
845
- const needs = analyzeTemplateNeeds(shownTemplate.data.source, cwd);
1857
+ const source = shownTemplate.data.source;
1858
+ const needs = analyzeTemplateNeeds(source, cwd);
1859
+ const absent = notInstalled(cwd, source, needs.missingPackages);
846
1860
  // A StyleX page calls stylex.create when its module loads, so without
847
1861
  // a StyleX compiler it breaks the whole route.
848
1862
  const needsCompiler =
849
- STYLEX_IMPORT.test(shownTemplate.data.source) &&
850
- detectStylingSystem(cwd) !== 'stylex';
851
- if (needs.missingPackages.length || needsCompiler) {
1863
+ STYLEX_IMPORT.test(source) && detectStylingSystem(cwd) !== 'stylex';
1864
+ if (needs.missingPackages.length || absent.length || needsCompiler) {
1865
+ const installCommand =
1866
+ needs.installCommand ??
1867
+ (absent.length ? installCommandOf(cwd) : null);
852
1868
  skipped.push({
853
1869
  page: pick.name,
854
- reason: skipReason({
1870
+ reason: `${skipReason({
855
1871
  missingPackages: needs.missingPackages,
1872
+ notInstalled: absent,
856
1873
  stylexCompiler: needsCompiler,
857
- }),
858
- installCommand: needs.installCommand,
1874
+ })}${needs.missingPackages.length && !needs.installCommand ? ' (the app has more than one lockfile, so install it with the package manager you use)' : ''}`,
1875
+ installCommand,
859
1876
  });
1877
+ if (installCommand) runs.push(installCommand);
1878
+ if (needsCompiler) stylexSkipped = true;
1879
+ if (i === 0) firstSkipped = true;
860
1880
  continue;
861
1881
  }
862
- add.push({id: pick.name, label: pick.displayName, template: pick.name});
1882
+ add.push({id: pick.name, label: pick.displayName, text: source});
863
1883
  matched.push({page: pick.name, why: pick.why});
864
1884
  }
865
1885
  }
866
1886
  for (const s of skipped)
867
1887
  notes.push(
868
- `the ${s.page} page was not added: it ${s.reason}${s.installCommand ? `; ${s.installCommand}, then add it again` : ''}${add.length ? `; added ${add.map(a => a.id).join(', ')} instead` : ''}`,
1888
+ `the ${s.page} page was not added: it ${s.reason}${s.installCommand ? `; ${s.installCommand}, then add it again` : ''}`,
869
1889
  );
1890
+ if (firstSkipped && add.length && !explicit)
1891
+ notes.push(`added ${add.map(a => a.id).join(', ')} in its place`);
870
1892
  if (!add.length)
871
1893
  refuse(
872
1894
  E.ERR_DEP_MISSING,
873
- `No page was added: ${skipped.map(s => `the ${s.page} page ${s.reason}`).join('; ')}. Nothing was written.`,
1895
+ `No page was added: ${skipped.map(s => `the ${s.page} page ${s.reason}`).join('; ')}.`,
874
1896
  {
875
- run: skipped.flatMap(s => (s.installCommand ? [s.installCommand] : [])),
1897
+ run: [
1898
+ ...new Set(runs),
1899
+ ...(stylexSkipped
1900
+ ? ['astryx docs styling-overview # how to add a StyleX compiler']
1901
+ : []),
1902
+ `${PREVIEW} add${tf}${pf} # the default pages, which need nothing more`,
1903
+ ],
876
1904
  },
877
1905
  );
878
- for (const page of add)
879
- previewFile(cwd, at.dir, data, `pages/${page.id}.tsx`);
880
- previewFile(cwd, at.dir, data, 'page.tsx');
881
- previewFile(cwd, at.dir, data, PREVIEW_DATA);
882
- const theme = await routeTheme(cwd, at.dir, data);
1906
+ if (switched)
1907
+ for (const id of ['overview', 'components'])
1908
+ if (data.pages.some(p => p.id === id) && !add.some(a => a.id === id))
1909
+ add.push(await defaultPage(id));
883
1910
 
1911
+ // The plan: every check below runs before the first write.
1912
+ const free = (() => {
1913
+ const base = path.basename(at.dir) || 'theme-preview';
1914
+ let n = 2;
1915
+ while (fs.existsSync(path.join(path.dirname(at.dir), `${base}-${n}`))) n++;
1916
+ return shown(cwd, path.join(path.dirname(at.dir), `${base}-${n}`));
1917
+ })();
1918
+ const elsewhere = retry(free);
1919
+ const move = movedPages(cwd, at.dir, data);
1920
+ /** @type {Map<string, {rel: string, text: string, keepHash?: boolean}>} */
1921
+ const writes = new Map(move.writes.map(w => [w.rel, w]));
884
1922
  /** @type {string[]} */
885
1923
  const added = [];
886
1924
  /** Pages that were there already and are written again. @type {string[]} */
887
1925
  const refreshed = [];
888
1926
  for (const page of add) {
889
- const file = `pages/${page.id}`;
890
- if (page.template != null) {
891
- const target = previewFile(cwd, at.dir, data, `${file}.tsx`);
892
- await template(page.template, {
893
- cwd,
894
- type: 'page',
895
- targetPath: path.relative(cwd, target),
896
- overwrite: true,
897
- });
898
- if (!data.files.includes(`${file}.tsx`)) data.files.push(`${file}.tsx`);
899
- } else
900
- writePreviewFile(
901
- cwd,
902
- at.dir,
903
- data,
904
- `${file}.tsx`,
905
- /** @type {string} */ (page.source),
906
- );
1927
+ const rel = `${PAGES_DIR}/${page.id}.tsx`;
1928
+ const w = {rel, text: page.text};
1929
+ if (!move.moved.includes(page.id))
1930
+ checkWrite(cwd, at.dir, data, w, elsewhere);
1931
+ writes.set(rel, w);
1932
+ if (!data.files.includes(rel)) data.files.push(rel);
907
1933
  const had = data.pages.find(x => x.id === page.id);
908
1934
  if (!had) {
909
- data.pages.push({id: page.id, label: page.label, file});
1935
+ data.pages.push({
1936
+ id: page.id,
1937
+ label: page.label,
1938
+ file: `${PAGES_DIR}/${page.id}`,
1939
+ });
910
1940
  added.push(page.id);
911
1941
  } else {
912
1942
  had.label = page.label;
913
1943
  refreshed.push(page.id);
914
1944
  }
915
1945
  }
916
- await writeRoute(cwd, at.dir, data, theme);
1946
+ // A recorded page whose file is gone is written again (a default page,
1947
+ // or the template its id names), or else left out of the nav, so the
1948
+ // route never imports a missing file.
1949
+ /** @type {string[]} */
1950
+ const rewrote = [];
1951
+ /** @type {string[]} */
1952
+ const dropped = [];
1953
+ for (const p of [...data.pages]) {
1954
+ const rel = `${p.file}.tsx`;
1955
+ if (writes.has(rel) || fs.existsSync(path.join(at.dir, rel))) continue;
1956
+ if (
1957
+ p.id === COLORS_PAGE.id &&
1958
+ data.files.includes(rel) &&
1959
+ (data.theme || gone)
1960
+ )
1961
+ continue;
1962
+ const text = data.files.includes(rel)
1963
+ ? await pageAgain(cwd, p.id, defaultPage)
1964
+ : null;
1965
+ if (text != null) {
1966
+ const to = `${PAGES_DIR}/${p.id}.tsx`;
1967
+ const w = {rel: to, text};
1968
+ checkWrite(cwd, at.dir, data, w, elsewhere);
1969
+ writes.set(to, w);
1970
+ data.files = data.files.filter(f => f !== rel);
1971
+ if (!data.files.includes(to)) data.files.push(to);
1972
+ p.file = `${PAGES_DIR}/${p.id}`;
1973
+ rewrote.push(p.id);
1974
+ } else {
1975
+ data.pages = data.pages.filter(x => x !== p);
1976
+ data.files = data.files.filter(f => f !== rel);
1977
+ dropped.push(p.id);
1978
+ }
1979
+ }
1980
+ if (rewrote.length)
1981
+ notes.push(
1982
+ `wrote ${rewrote.join(', ')} again: ${rewrote.length > 1 ? 'their files were' : 'its file was'} gone`,
1983
+ );
1984
+ if (dropped.length)
1985
+ notes.push(
1986
+ `left ${dropped.join(', ')} out of the nav: ${dropped.length > 1 ? 'their files were' : 'its file was'} gone, and the preview cannot write ${dropped.length > 1 ? 'them' : 'it'} again`,
1987
+ );
1988
+ if (!data.files.includes('page.tsx'))
1989
+ checkWrite(cwd, at.dir, data, {rel: 'page.tsx', text: '\0'}, elsewhere);
1990
+ const theme = await routeTheme(cwd, at.dir, data);
1991
+ for (const w of await routeWrites(cwd, at.dir, data, theme, {gone})) {
1992
+ if (!writes.has(w.rel)) checkWrite(cwd, at.dir, data, w, elsewhere);
1993
+ writes.set(w.rel, w);
1994
+ if (!data.files.includes(w.rel)) data.files.push(w.rel);
1995
+ }
1996
+ commitPreview(
1997
+ cwd,
1998
+ at.dir,
1999
+ data,
2000
+ [...writes.values()],
2001
+ move.deletes,
2002
+ retry(options.path ?? null),
2003
+ );
2004
+ tidyPageFolders(at.dir);
2005
+ if (move.moved.length)
2006
+ notes.push(
2007
+ `moved ${move.moved.join(', ')} from ${LEGACY_PAGES_DIR}/ to ${PAGES_DIR}/, a folder Next never serves as a route`,
2008
+ );
2009
+ if (wore && wore !== data.theme) recordPreview(cwd, wore, at.dir, false);
917
2010
  if (data.theme) recordPreview(cwd, data.theme, at.dir);
918
2011
  return {
919
2012
  type: 'themeEdit.previewAdd',
920
2013
  data: {
921
- folder: shown(cwd, at.dir),
2014
+ folder: shownDir(cwd, at.dir),
922
2015
  theme: data.theme,
923
2016
  added,
924
2017
  refreshed,
@@ -949,10 +2042,18 @@ export async function themeEditPreviewApp(dir, options = {}) {
949
2042
  refuse(
950
2043
  E.ERR_INVALID_ARGUMENT,
951
2044
  'Name the folder for the new app: a new or empty folder inside the current one.',
952
- {run: [`${PREVIEW} app <dir>`]},
2045
+ {run: [`${PREVIEW} app theme-app`]},
953
2046
  );
954
2047
  const slug = options.theme ?? null;
955
- const theme = slug == null ? null : loadTheme(cwd, slug);
2048
+ const theme =
2049
+ slug == null
2050
+ ? null
2051
+ : wornTheme(
2052
+ cwd,
2053
+ slug,
2054
+ t => `${PREVIEW} app ${shq(dir)}${t == null ? '' : ` --theme ${t}`}`,
2055
+ 'leave out --theme and the app wears the neutral theme',
2056
+ );
956
2057
  // A new app has no Core installed yet: its pages come from this CLI's own
957
2058
  // Core when the current folder has none.
958
2059
  const project = await openProject(cwd).catch(() => openProject(CLI_PACKAGE));
@@ -960,15 +2061,32 @@ export async function themeEditPreviewApp(dir, options = {}) {
960
2061
  const dependencies = {};
961
2062
  /** @type {Array<{rel: string, text: string | Buffer}>} */
962
2063
  const themeCopy = [];
963
- /** @type {{name: string, module: string, css: string[]} | null} */
2064
+ /** @type {{name: string, module: string, css: string[], mode: 'system' | 'light' | 'dark'} | null} */
964
2065
  let routeTheme = null;
2066
+ /** @type {string[]} */
2067
+ const notes = [];
965
2068
  const routeDir = path.join('src', 'app', 'theme-preview');
966
2069
  // The folder checks come before the theme build, so a refusal writes nothing.
967
- planStarterApp(cwd, dir, () => [], {});
2070
+ planStarterApp(cwd, dir, () => [], {}, slug);
2071
+ /** @type {string | null} */
2072
+ let colorsSource = null;
968
2073
  if (slug != null && theme) {
969
2074
  const from = themeFiles(cwd, slug);
970
- if (!fs.existsSync(from.js) || !fs.existsSync(from.css))
971
- await buildTheme(await context(cwd), slug, theme);
2075
+ const ctx = await context(cwd);
2076
+ const mtime = (/** @type {string} */ f) => {
2077
+ try {
2078
+ return fs.statSync(f).mtimeMs;
2079
+ } catch {
2080
+ return -1;
2081
+ }
2082
+ };
2083
+ const built = Math.min(mtime(from.js), mtime(from.css));
2084
+ if (built < 0 || mtime(from.settings) > built) {
2085
+ await buildTheme(ctx, slug, theme);
2086
+ notes.push(
2087
+ `built ${shown(cwd, from.dir)}/ first: its build was ${built < 0 ? 'missing' : 'older than its settings'}, and the app gets a current copy`,
2088
+ );
2089
+ }
972
2090
  const to = themeFiles('', slug);
973
2091
  // The theme and its build, with the type declarations the build writes;
974
2092
  // not its history, preview pages or pictures.
@@ -1006,51 +2124,88 @@ export async function themeEditPreviewApp(dir, options = {}) {
1006
2124
  const r = path.relative(routeDir, rel).split(path.sep).join('/');
1007
2125
  return r.startsWith('.') ? r : `./${r}`;
1008
2126
  };
1009
- const fonts = fontPackages(await context(cwd), theme).filter(
1010
- x => x.installed,
1011
- );
2127
+ // The new app installs its own packages, so every open font the theme
2128
+ // names is added, at the version this project has, else a known one.
2129
+ const fonts = fontPackages(ctx, theme);
1012
2130
  for (const font of fonts)
1013
- dependencies[font.pkg] = readVersion(project, font.pkg) ?? 'latest';
2131
+ dependencies[font.pkg] =
2132
+ readVersion(project, font.pkg) ?? OPEN_FONT_RANGE;
1014
2133
  routeTheme = {
1015
2134
  name: slug,
1016
2135
  module: fromRoute(to.js),
1017
2136
  css: [fromRoute(to.css), ...fonts.map(x => `${x.pkg}/index.css`)],
2137
+ mode: themeImports(ctx, slug, theme, path.join(cwd, routeDir)).mode,
1018
2138
  };
2139
+ // The app's theme folder sits where this project's does, so the Colors
2140
+ // page imports the copied colors by the same relative path.
2141
+ const colors = await colorsPage(cwd, path.join(cwd, routeDir), slug);
2142
+ if (colors.colors) colorsSource = colors.source;
1019
2143
  }
1020
2144
  /** @type {PreviewData} */
1021
- const data = {version: 1, theme: slug, pages: [], files: []};
1022
- /** @type {Array<{rel: string, text: string | Buffer}>} */
2145
+ const data = {version: 1, theme: slug, pages: [], files: [], hashes: {}};
2146
+ /** @type {Array<{rel: string, text: string}>} */
1023
2147
  const preview = [];
1024
- for (const [id, label, source] of /** @type {const} */ ([
2148
+ /** @type {Array<[string, string, string]>} */
2149
+ const pages = [
1025
2150
  ['overview', 'Overview', overviewPageSource(project, {theme: slug})],
1026
2151
  [
1027
2152
  'components',
1028
2153
  'Components',
1029
2154
  componentsPageSource(project, {theme: slug}).source,
1030
2155
  ],
1031
- ])) {
1032
- data.pages.push({id, label, file: `pages/${id}`});
1033
- preview.push({rel: `pages/${id}.tsx`, text: source});
2156
+ ...(colorsSource == null
2157
+ ? []
2158
+ : [
2159
+ /** @type {[string, string, string]} */ ([
2160
+ COLORS_PAGE.id,
2161
+ COLORS_PAGE.label,
2162
+ colorsSource,
2163
+ ]),
2164
+ ]),
2165
+ ];
2166
+ for (const [id, label, source] of pages) {
2167
+ data.pages.push({id, label, file: `${PAGES_DIR}/${id}`});
2168
+ preview.push({rel: `${PAGES_DIR}/${id}.tsx`, text: source});
1034
2169
  }
1035
2170
  preview.push({
1036
2171
  rel: 'page.tsx',
1037
- text: previewRouteSource({pages: data.pages, theme: routeTheme}),
2172
+ text: previewRouteSource({
2173
+ pages: data.pages,
2174
+ theme: routeTheme,
2175
+ by: `${PREVIEW} app`,
2176
+ }),
1038
2177
  });
1039
2178
  data.files = [...preview.map(x => x.rel), PREVIEW_DATA];
1040
- preview.push({rel: PREVIEW_DATA, text: `${JSON.stringify(data, null, 2)}\n`});
2179
+ data.hashes = Object.fromEntries(preview.map(x => [x.rel, digest(x.text)]));
1041
2180
  const plan = planStarterApp(
1042
2181
  cwd,
1043
2182
  dir,
1044
2183
  () => [
1045
2184
  ...themeCopy,
1046
2185
  ...preview.map(x => ({rel: path.join(routeDir, x.rel), text: x.text})),
2186
+ {
2187
+ rel: path.join(routeDir, PREVIEW_DATA),
2188
+ text: `${JSON.stringify(data, null, 2)}\n`,
2189
+ },
1047
2190
  ],
1048
2191
  dependencies,
2192
+ slug,
1049
2193
  );
1050
- const files = writeStarterApp(cwd, plan);
1051
- const folder = shown(cwd, plan.root) || '.';
1052
- /** @type {string[]} */
1053
- const notes = [];
2194
+ const files = writeStarterApp(
2195
+ cwd,
2196
+ plan,
2197
+ d =>
2198
+ `${PREVIEW} app ${shq(d)}${slug == null ? '' : ` --theme ${shq(slug)}`}`,
2199
+ );
2200
+ const folder = shownDir(cwd, plan.root);
2201
+ if (
2202
+ plan.root !== cwd &&
2203
+ !isOutsideProject(cwd) &&
2204
+ fs.existsSync(path.join(cwd, 'tsconfig.json'))
2205
+ )
2206
+ notes.push(
2207
+ `add "${folder}" to "exclude" in this project's tsconfig.json, so its own type check leaves the new app out`,
2208
+ );
1054
2209
  return {
1055
2210
  type: 'themeEdit.previewApp',
1056
2211
  data: {
@@ -1059,11 +2214,14 @@ export async function themeEditPreviewApp(dir, options = {}) {
1059
2214
  pages: data.pages.map(x => x.id),
1060
2215
  files,
1061
2216
  notes,
1062
- open: `cd ${folder} && npm install && npm run dev, then open /theme-preview`,
2217
+ open: `cd ${shq(folder)} && npm install && npm run dev, then open /theme-preview`,
1063
2218
  },
1064
2219
  };
1065
2220
  }
1066
2221
 
2222
+ /** The version range of an open font package the host project lacks. */
2223
+ const OPEN_FONT_RANGE = '^5.0.0';
2224
+
1067
2225
  /**
1068
2226
  * The installed version of a package, as the project resolves it.
1069
2227
  * @param {import('./_project.mjs').ThemeProject} project
@@ -1082,7 +2240,8 @@ function readVersion(project, pkg) {
1082
2240
 
1083
2241
  /**
1084
2242
  * The pages of the in-app theme preview. With no preview, and with no
1085
- * routes folder for one, the list is empty.
2243
+ * routes folder for one, the list is empty; a damaged theme-preview.json is
2244
+ * refused, naming the file.
1086
2245
  * @experimental
1087
2246
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewListOptions} [options]
1088
2247
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewListResponse>}
@@ -1090,12 +2249,16 @@ function readVersion(project, pkg) {
1090
2249
  export async function themeEditPreviewList(options = {}) {
1091
2250
  const {cwd = process.cwd()} = options;
1092
2251
  requireProject(cwd);
1093
- const at = previewDir(cwd, options.path, {optional: true});
1094
- const data = at && readPreview(at.dir);
2252
+ const pf = options.path != null ? ` --path ${shq(options.path)}` : '';
2253
+ const at = previewDir(cwd, options.path, {
2254
+ optional: true,
2255
+ retry: p => `${PREVIEW} list${p == null ? '' : ` --path ${shq(p)}`}`,
2256
+ });
2257
+ const data = at && readPreview(cwd, at.dir, pf);
1095
2258
  return {
1096
2259
  type: 'themeEdit.previewList',
1097
2260
  data: {
1098
- folder: at && data ? shown(cwd, at.dir) : null,
2261
+ folder: at && data ? shownDir(cwd, at.dir) : null,
1099
2262
  theme: data?.theme ?? null,
1100
2263
  pages: (data?.pages ?? []).map(x => ({id: x.id, label: x.label})),
1101
2264
  },
@@ -1104,8 +2267,9 @@ export async function themeEditPreviewList(options = {}) {
1104
2267
 
1105
2268
  /**
1106
2269
  * Remove one page from the in-app theme preview, or with no page the whole
1107
- * preview: only the files it wrote are deleted, and only inside the route
1108
- * folder.
2270
+ * preview. Only files the preview wrote are deleted, only inside the route
2271
+ * folder, and never one changed by hand since: those are kept and named.
2272
+ * Every check, the theme included, runs before the first delete.
1109
2273
  * @experimental
1110
2274
  * @param {string} [page]
1111
2275
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewListOptions} [options]
@@ -1114,64 +2278,231 @@ export async function themeEditPreviewList(options = {}) {
1114
2278
  export async function themeEditPreviewRemove(page, options = {}) {
1115
2279
  const {cwd = process.cwd()} = options;
1116
2280
  requireProject(cwd);
1117
- const at = previewDir(cwd, options.path);
1118
- const data = readPreview(at.dir);
2281
+ const pf = options.path != null ? ` --path ${shq(options.path)}` : '';
2282
+ const retry = (/** @type {string | null} */ p) =>
2283
+ `${PREVIEW} remove${page != null ? ` ${shq(page)}` : ''}${p == null ? '' : ` --path ${shq(p)}`}`;
2284
+ const at = previewDir(cwd, options.path, {retry});
2285
+ const data = readPreview(cwd, at.dir, pf);
1119
2286
  if (!data)
1120
2287
  refuse(
1121
2288
  E.ERR_NOT_FOUND,
1122
- `There is no theme preview in ${shown(cwd, at.dir)}/ (no ${PREVIEW_DATA}).`,
1123
- {run: [`${PREVIEW} add`]},
2289
+ `There is no theme preview in ${shownDir(cwd, at.dir)}/ (no ${PREVIEW_DATA}).`,
2290
+ {run: [`${PREVIEW} add${pf}`]},
1124
2291
  );
2292
+ const folder = shownDir(cwd, at.dir);
1125
2293
  // theme-preview.json is a file anyone can edit: every path in it must
1126
2294
  // stay in the route folder before anything is removed.
1127
2295
  const inside = (/** @type {string} */ rel) =>
1128
2296
  confined(path.join(at.dir, rel), at.dir, `${PREVIEW_DATA} names`);
1129
2297
  for (const rel of data.files) inside(rel);
1130
2298
  for (const p of data.pages) inside(`${p.file}.tsx`);
1131
- /** @param {string} rel */
1132
- const drop = rel => {
1133
- const file = inside(rel);
1134
- fs.rmSync(file, {force: true});
1135
- return shown(cwd, file);
1136
- };
1137
- if (page != null && data.pages.length > 1) {
1138
- const one = data.pages.find(x => x.id === page);
2299
+ /** @type {string[]} */
2300
+ const notes = [];
2301
+ /** @type {string[]} */
2302
+ const kept = [];
2303
+ /** @type {string[]} */
2304
+ const missing = [];
2305
+
2306
+ /** @type {PreviewPage | undefined} */
2307
+ let one;
2308
+ if (page != null) {
2309
+ const key = String(page).trim();
2310
+ one =
2311
+ data.pages.find(x => x.id === key) ??
2312
+ data.pages.find(x => x.id.toLowerCase() === key.toLowerCase());
1139
2313
  if (!one)
1140
2314
  refuse(E.ERR_NOT_FOUND, `The preview has no page "${page}".`, {
1141
2315
  didYouMean: nearest(
1142
- page,
2316
+ key.toLowerCase(),
1143
2317
  data.pages.map(x => x.id),
1144
2318
  ),
1145
- run: [`${PREVIEW} list`],
2319
+ run: [`${PREVIEW} list${pf}`],
1146
2320
  });
1147
- data.pages = data.pages.filter(x => x !== one);
1148
- const rel = `${one.file}.tsx`;
2321
+ }
2322
+
2323
+ if (one && data.pages.length > 1) {
2324
+ const target = one;
2325
+ const rel = `${target.file}.tsx`;
2326
+ const name = shown(cwd, inside(rel));
2327
+ /** @type {string[]} */
2328
+ const deletes = [];
2329
+ if (!data.files.includes(rel)) {
2330
+ kept.push(name);
2331
+ notes.push(
2332
+ `${name} was not written by the preview, so it is kept; only its nav item is gone`,
2333
+ );
2334
+ } else if (!fs.existsSync(inside(rel))) missing.push(name);
2335
+ else if (editedByHand(at.dir, data, rel)) {
2336
+ kept.push(name);
2337
+ notes.push(
2338
+ `${name} was changed by hand after the preview wrote it, so it is kept`,
2339
+ );
2340
+ } else deletes.push(rel);
2341
+ data.pages = data.pages.filter(x => x !== target);
1149
2342
  data.files = data.files.filter(f => f !== rel);
1150
- const removed = [drop(rel)];
1151
- await writeRoute(cwd, at.dir, data);
2343
+ const wore = data.theme;
2344
+ /** @type {string | null} */
2345
+ let gone = null;
2346
+ if (wore && !fs.existsSync(themeFiles(cwd, wore).dir)) {
2347
+ gone = wore;
2348
+ data.theme = null;
2349
+ notes.push(
2350
+ `the preview wore ${wore}, which is gone; it now wears the app's own theme`,
2351
+ );
2352
+ }
2353
+ const move = movedPages(cwd, at.dir, data);
2354
+ // A page whose file is gone leaves the nav, so the route never imports
2355
+ // a missing file.
2356
+ const moving = new Set(move.writes.map(w => w.rel));
2357
+ const lost = data.pages.filter(p => {
2358
+ const rel = `${p.file}.tsx`;
2359
+ if (moving.has(rel) || fs.existsSync(path.join(at.dir, rel)))
2360
+ return false;
2361
+ return !(
2362
+ p.id === COLORS_PAGE.id &&
2363
+ data.files.includes(rel) &&
2364
+ (data.theme || gone)
2365
+ );
2366
+ });
2367
+ if (lost.length) {
2368
+ data.pages = data.pages.filter(p => !lost.includes(p));
2369
+ data.files = data.files.filter(
2370
+ f => !lost.some(p => f === `${p.file}.tsx`),
2371
+ );
2372
+ notes.push(
2373
+ `left ${lost.map(p => p.id).join(', ')} out of the nav: ${lost.length > 1 ? 'their files were' : 'its file was'} gone`,
2374
+ );
2375
+ }
2376
+ /** @type {Array<{rel: string, text: string}>} */
2377
+ let planned;
2378
+ try {
2379
+ const theme = await routeTheme(cwd, at.dir, data);
2380
+ planned = await routeWrites(cwd, at.dir, data, theme, {gone});
2381
+ } catch (e) {
2382
+ const err = /** @type {any} */ (e);
2383
+ if (
2384
+ [E.ERR_THEME_INVALID, E.ERR_UNKNOWN_THEME, E.ERR_THEME_LOAD].includes(
2385
+ err?.code,
2386
+ )
2387
+ )
2388
+ err.suggestions = [
2389
+ {
2390
+ name: `${PREVIEW} remove${pf}`,
2391
+ reason:
2392
+ 'do this instead: removes the whole preview, which needs no theme',
2393
+ },
2394
+ ...(err.suggestions ?? []),
2395
+ ];
2396
+ throw e;
2397
+ }
2398
+ const elsewhere = `${PREVIEW} remove${pf}`;
2399
+ /** @type {Map<string, {rel: string, text: string, keepHash?: boolean}>} */
2400
+ const writes = new Map(move.writes.map(w => [w.rel, w]));
2401
+ /** @type {string[]} */
2402
+ const rewritten = [];
2403
+ for (const w of planned) {
2404
+ const was = checkWrite(cwd, at.dir, data, w, elsewhere);
2405
+ writes.set(w.rel, w);
2406
+ if (!data.files.includes(w.rel)) data.files.push(w.rel);
2407
+ if (was !== 'same') rewritten.push(shown(cwd, path.join(at.dir, w.rel)));
2408
+ }
2409
+ commitPreview(
2410
+ cwd,
2411
+ at.dir,
2412
+ data,
2413
+ [...writes.values()],
2414
+ [...deletes, ...move.deletes],
2415
+ retry(options.path ?? null),
2416
+ );
2417
+ tidyPageFolders(at.dir);
2418
+ if (gone) recordPreview(cwd, gone, at.dir, false);
1152
2419
  return {
1153
2420
  type: 'themeEdit.previewRemove',
1154
2421
  data: {
1155
- folder: shown(cwd, at.dir),
1156
- removed,
2422
+ folder,
2423
+ removed: deletes.map(r => shown(cwd, path.join(at.dir, r))),
2424
+ kept,
2425
+ missing,
2426
+ rewritten,
2427
+ notes,
1157
2428
  pages: data.pages.map(x => x.id),
1158
2429
  },
1159
2430
  };
1160
2431
  }
1161
- if (page != null && !data.pages.some(x => x.id === page))
1162
- refuse(E.ERR_NOT_FOUND, `The preview has no page "${page}".`, {
1163
- run: [`${PREVIEW} list`],
1164
- });
1165
- const removed = data.files.map(drop);
1166
- for (const sub of [path.join(at.dir, 'pages'), at.dir])
2432
+
2433
+ // The whole preview: every entry is checked before the first delete. A
2434
+ // route changed by hand would be kept and still import the pages, so it
2435
+ // stops the remove instead.
2436
+ if (data.files.includes('page.tsx') && editedByHand(at.dir, data, 'page.tsx'))
2437
+ refuse(
2438
+ E.ERR_FILE_EXISTS,
2439
+ `${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.`,
2440
+ {
2441
+ fix: `copy your changes out of ${shown(cwd, path.join(at.dir, 'page.tsx'))}, delete it or give it another name, then run ${PREVIEW} remove${pf} again`,
2442
+ },
2443
+ );
2444
+ /** @type {Array<{file: string, before: Buffer}>} */
2445
+ const plan = [];
2446
+ for (const rel of data.files) {
2447
+ const file = inside(rel);
2448
+ /** @type {fs.Stats} */
2449
+ let st;
1167
2450
  try {
1168
- fs.rmdirSync(sub);
2451
+ st = fs.lstatSync(file);
1169
2452
  } catch {
1170
- // Not empty: something there is not the preview's.
2453
+ missing.push(shown(cwd, file));
2454
+ continue;
1171
2455
  }
2456
+ if (st.isDirectory())
2457
+ damagedPreview(
2458
+ cwd,
2459
+ at.dir,
2460
+ `"files" holds ${rel}, which is a folder; the preview writes only files`,
2461
+ pf,
2462
+ );
2463
+ if (rel !== PREVIEW_DATA && editedByHand(at.dir, data, rel)) {
2464
+ kept.push(shown(cwd, file));
2465
+ notes.push(
2466
+ `${shown(cwd, file)} was changed by hand after the preview wrote it, so it is kept`,
2467
+ );
2468
+ continue;
2469
+ }
2470
+ plan.push({file, before: fs.readFileSync(file)});
2471
+ }
2472
+ // theme-preview.json goes last, so an interrupted remove can run again.
2473
+ plan.sort(
2474
+ (a, b) =>
2475
+ Number(path.basename(a.file) === PREVIEW_DATA) -
2476
+ Number(path.basename(b.file) === PREVIEW_DATA),
2477
+ );
2478
+ /** @type {string[]} */
2479
+ const removed = [];
2480
+ for (const [i, p] of plan.entries())
2481
+ try {
2482
+ fs.rmSync(p.file);
2483
+ removed.push(shown(cwd, p.file));
2484
+ } catch (e) {
2485
+ for (const back of plan.slice(0, i))
2486
+ try {
2487
+ fs.writeFileSync(back.file, back.before);
2488
+ } catch {
2489
+ // Best effort: the refusal below names the file.
2490
+ }
2491
+ refuse(
2492
+ E.ERR_WRITE_FAILED,
2493
+ `${shown(cwd, p.file)} could not be removed (${/** @type {any} */ (e)?.code ?? 'error'}), so the preview's files were put back.`,
2494
+ {run: [`${retry(options.path ?? null)} # once the cause is fixed`]},
2495
+ );
2496
+ }
2497
+ tidyPageFolders(at.dir);
2498
+ try {
2499
+ fs.rmdirSync(at.dir);
2500
+ } catch {
2501
+ // Not empty: something there is not the preview's.
2502
+ }
1172
2503
  if (data.theme) recordPreview(cwd, data.theme, at.dir, false);
1173
2504
  return {
1174
2505
  type: 'themeEdit.previewRemove',
1175
- data: {folder: shown(cwd, at.dir), removed, pages: []},
2506
+ data: {folder, removed, kept, missing, rewritten: [], notes, pages: []},
1176
2507
  };
1177
2508
  }