@astryxdesign/cli 0.7.14-canary.gfb823d9 → 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 (135) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/component/_adapter.d.mts +15 -0
  3. package/api/component/_adapter.mjs +76 -0
  4. package/api/component/component.mjs +8 -1
  5. package/api/search/_named-keywords.d.mts +31 -0
  6. package/api/search/_named-keywords.mjs +177 -0
  7. package/api/search/search-index.mjs +8 -1
  8. package/api/search/search.d.mts +6 -1
  9. package/api/search/search.mjs +49 -8
  10. package/api/theme/_adapter.d.mts +33 -0
  11. package/api/theme/_adapter.mjs +352 -16
  12. package/api/theme/build/build.mjs +261 -10
  13. package/api/theme/eject/eject.mjs +13 -1
  14. package/api/theme/list/list.mjs +11 -2
  15. package/api/theme/palette/generate/color.d.mts +2 -0
  16. package/api/theme/palette/generate/color.mjs +1 -1
  17. package/api/theme/template/template.mjs +139 -6
  18. package/api/theme/theme.type.d.mts +15 -1
  19. package/api/theme/theme.type.mjs +9 -3
  20. package/api/theme/themeAdd.doc.mjs +1 -1
  21. package/api/theme/themeBuild.doc.mjs +10 -2
  22. package/api/theme/themeEject.doc.mjs +2 -2
  23. package/api/theme/themeListAvailable.doc.mjs +1 -1
  24. package/api/theme/themeRemove.doc.mjs +1 -1
  25. package/api/theme/themeTemplate.doc.mjs +8 -0
  26. package/api/theme/themeUse.doc.mjs +1 -1
  27. package/api/theme-edit/_adapter.d.mts +36 -2
  28. package/api/theme-edit/_adapter.mjs +340 -12
  29. package/api/theme-edit/_check.d.mts +28 -25
  30. package/api/theme-edit/_check.mjs +876 -308
  31. package/api/theme-edit/_color.d.mts +53 -4
  32. package/api/theme-edit/_color.mjs +406 -79
  33. package/api/theme-edit/_compiler.d.mts +14 -6
  34. package/api/theme-edit/_compiler.mjs +89 -59
  35. package/api/theme-edit/_context.d.mts +28 -8
  36. package/api/theme-edit/_context.mjs +142 -19
  37. package/api/theme-edit/_edit.d.mts +3 -1
  38. package/api/theme-edit/_edit.mjs +746 -76
  39. package/api/theme-edit/_how-commands.d.mts +91 -0
  40. package/api/theme-edit/_how-commands.mjs +269 -0
  41. package/api/theme-edit/_how-question.d.mts +57 -0
  42. package/api/theme-edit/_how-question.mjs +2574 -0
  43. package/api/theme-edit/_how.d.mts +27 -8
  44. package/api/theme-edit/_how.mjs +776 -175
  45. package/api/theme-edit/_overview.d.mts +9 -0
  46. package/api/theme-edit/_overview.mjs +296 -0
  47. package/api/theme-edit/_palette.d.mts +155 -15
  48. package/api/theme-edit/_palette.mjs +1446 -262
  49. package/api/theme-edit/_parts.mjs +61 -5
  50. package/api/theme-edit/_png.d.mts +18 -6
  51. package/api/theme-edit/_png.mjs +135 -25
  52. package/api/theme-edit/_preview-app.d.mts +32 -11
  53. package/api/theme-edit/_preview-app.mjs +1976 -285
  54. package/api/theme-edit/_preview.d.mts +39 -8
  55. package/api/theme-edit/_preview.mjs +367 -41
  56. package/api/theme-edit/_settings.d.mts +147 -11
  57. package/api/theme-edit/_settings.mjs +908 -99
  58. package/api/theme-edit/_tables.d.mts +4 -16
  59. package/api/theme-edit/_tables.mjs +51 -117
  60. package/api/theme-edit/theme-edit.type.d.mts +102 -66
  61. package/api/theme-edit/theme-edit.type.mjs +58 -40
  62. package/api/theme-edit/themeEditHow.doc.mjs +17 -6
  63. package/api/theme-edit/themeEditNew.doc.mjs +21 -5
  64. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +18 -5
  65. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -9
  66. package/api/theme-edit/themeEditPreviewList.doc.mjs +11 -2
  67. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +29 -3
  68. package/api/theme-edit/themeEditSet.doc.mjs +14 -8
  69. package/api/theme-edit/themeEditShow.doc.mjs +10 -5
  70. package/api/theme-edit/themeEditUndo.doc.mjs +9 -4
  71. package/assets/discover/official-packages.json +4 -0
  72. package/assets/docs/tree/icon-sets.doc.mjs +3 -3
  73. package/assets/docs.generated.json +1 -0
  74. package/assets/icons/definitions/bookmarkAdd.doc.mjs +9 -0
  75. package/assets/icons/definitions/documentSearch.doc.mjs +9 -0
  76. package/assets/icons/definitions/keyboard.doc.mjs +9 -0
  77. package/assets/icons/definitions/paintBrush.doc.mjs +9 -0
  78. package/assets/icons/definitions/wallet.doc.mjs +9 -0
  79. package/assets/preview-app/gitignore +3 -0
  80. package/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs +1 -1
  81. package/assets/templates/blocks/components/Lightbox/LightboxGallery.tsx +1 -1
  82. package/assets/templates/components.generated.json +1 -0
  83. package/assets/templates/pages/gallery-hero/page.tsx +8 -2
  84. package/assets/templates/pages/settings-dialog/template.doc.mjs +3 -3
  85. package/assets/templates/pages/side-gallery/page.tsx +1 -1
  86. package/assets/templates/pages/table-filter/template.doc.mjs +2 -2
  87. package/assets/templates/pages/theme-showcase/template.doc.mjs +1 -1
  88. package/clients/cli/bin/astryx.mjs +37 -5
  89. package/clients/cli/commands/experimental/theme.mjs +422 -57
  90. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +22 -9
  91. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +103 -4
  92. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +13 -8
  93. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +5 -5
  94. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +5 -5
  95. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  96. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  97. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -8
  98. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  99. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  100. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  101. package/clients/cli/commands/experimental-theme.doc.mjs +3 -4
  102. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  103. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  104. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  105. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  106. package/clients/cli/commands/theme.mjs +145 -46
  107. package/clients/cli/commands.generated.json +1 -0
  108. package/clients/cli/index.mjs +96 -5
  109. package/clients/cli/lib/json-shim.mjs +29 -1
  110. package/foundation/config/project.d.mts +16 -2
  111. package/foundation/config/project.mjs +40 -6
  112. package/foundation/config/theme-state.d.mts +9 -0
  113. package/foundation/config/theme-state.mjs +20 -1
  114. package/foundation/discovery/template-adapter.d.mts +12 -1
  115. package/foundation/discovery/template-adapter.mjs +29 -4
  116. package/foundation/discovery/template-icons.d.mts +13 -0
  117. package/foundation/discovery/template-icons.mjs +76 -0
  118. package/foundation/discovery/template-needs.d.mts +7 -0
  119. package/foundation/discovery/template-needs.mjs +117 -8
  120. package/foundation/discovery/template-source-tree.d.mts +5 -1
  121. package/foundation/discovery/template-source-tree.mjs +6 -4
  122. package/foundation/discovery/theme-discovery.d.mts +14 -3
  123. package/foundation/discovery/theme-discovery.mjs +45 -12
  124. package/foundation/doc-compiler/import.mjs +68 -3
  125. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  126. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  127. package/foundation/fs/fs-error.d.mts +17 -0
  128. package/foundation/fs/fs-error.mjs +34 -0
  129. package/foundation/response/error-codes.d.mts +3 -1
  130. package/foundation/response/error-codes.doc.mjs +13 -1
  131. package/foundation/response/error-codes.mjs +11 -1
  132. package/foundation/response/response-types.doc.mjs +6 -6
  133. package/package.json +6 -7
  134. package/clients/cli/commands/experimental-theme-palette-generate.doc.mjs +0 -73
  135. package/clients/cli/commands/experimental-theme-palette.doc.mjs +0 -37
@@ -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';
@@ -19,7 +20,7 @@ import {
19
20
  assertWithin,
20
21
  PathSafetyError,
21
22
  } from '../../foundation/fs/path-safety.mjs';
22
- import {openProject} from './_project.mjs';
23
+ import {baseResolved, openProject} from './_project.mjs';
23
24
  import {
24
25
  loadTheme,
25
26
  nearest,
@@ -30,15 +31,25 @@ import {
30
31
  fontPackages,
31
32
  } from './_settings.mjs';
32
33
  import {
34
+ colorsPageSource,
33
35
  componentsPageSource,
34
36
  overviewPageSource,
35
37
  previewRouteSource,
36
38
  themeImports,
37
39
  } from './_preview.mjs';
40
+ import {
41
+ paletteFiles,
42
+ paletteMapping,
43
+ tempFor,
44
+ writeWhole,
45
+ } from './_palette.mjs';
38
46
  import {build} from '../build/build.mjs';
47
+ import {search} from '../search/search.mjs';
39
48
  import {template} from '../template/template.mjs';
40
- import {analyzeTemplateNeeds} from '../../foundation/discovery/template-needs.mjs';
41
- import {createFileProtectionResolver} from '../../foundation/fs/file-protection.mjs';
49
+ import {
50
+ analyzeTemplateNeeds,
51
+ extractImportedPackages,
52
+ } from '../../foundation/discovery/template-needs.mjs';
42
53
  import {detectStylingSystem} from '../../foundation/agent-docs/agent-docs.mjs';
43
54
  import {requireProject, context} from './_context.mjs';
44
55
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
@@ -48,46 +59,235 @@ const E = ERROR_CODES;
48
59
  /** The preview's data file: the pages it shows and the files it wrote. */
49
60
  const PREVIEW_DATA = 'theme-preview.json';
50
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;
51
74
 
52
75
  /**
53
76
  * @typedef {{id: string, label: string, file: string}} PreviewPage
54
- * @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
55
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
+ }
56
172
 
57
173
  /**
58
174
  * Where the preview route lives. `--path` names it (inside the project);
59
- * else an existing preview in the app's routes folder; else the routes
60
- * folder of a Next app router (`app/` or `src/app/`); else
61
- * `./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/`).
62
178
  * @param {string} cwd
63
179
  * @param {string | undefined} where
64
- * @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
65
184
  * @returns {{dir: string, app: string | null}} `app`: the routes folder, when the route is in one
66
185
  */
67
186
  function previewDir(cwd, where, opts = {}) {
187
+ const retry =
188
+ opts.retry ??
189
+ (p => `${PREVIEW} list${p == null ? '' : ` --path ${shq(p)}`}`);
68
190
  const routes = ['app', path.join('src', 'app')]
69
191
  .map(r => path.join(cwd, r))
70
192
  .filter(r => fs.existsSync(r) && fs.statSync(r).isDirectory());
71
193
  const appOf = (/** @type {string} */ dir) =>
72
194
  routes.find(r => dir.startsWith(r + path.sep)) ?? null;
73
195
  if (where != null) {
196
+ checkFolderName(where, '--path', retry);
197
+ /** @type {string} */
198
+ let dir;
74
199
  try {
75
- const dir = assertWithin(path.resolve(cwd, where), cwd, {
200
+ dir = assertWithin(path.resolve(cwd, where), cwd, {
76
201
  allowAbsolute: true,
77
202
  label: '--path',
78
203
  });
79
- return {dir, app: appOf(dir)};
80
204
  } catch (e) {
81
205
  if (e instanceof PathSafetyError)
82
206
  refuse(
83
207
  E.ERR_PATH_TRAVERSAL,
84
208
  `--path ${where} is outside the project; put the preview inside the folder you run the command from.`,
209
+ {run: [retry(null)]},
85
210
  );
86
211
  throw e;
87
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)};
88
259
  }
89
260
  const candidates = routes.map(r => path.join(r, 'theme-preview'));
90
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
+ }
91
291
  const dir = known ?? candidates[0];
92
292
  if (!dir && opts.optional) return /** @type {any} */ (null);
93
293
  if (!dir)
@@ -96,8 +296,8 @@ function previewDir(cwd, where, opts = {}) {
96
296
  'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
97
297
  {
98
298
  run: [
99
- `${PREVIEW} add --path <dir> (a folder inside your app's routes)`,
100
- `${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`,
101
301
  ],
102
302
  },
103
303
  );
@@ -109,13 +309,6 @@ const CLI_PACKAGE = path.resolve(
109
309
  '../..',
110
310
  );
111
311
  const STARTER = path.join(CLI_PACKAGE, 'assets', 'preview-app');
112
- /** Starter files a folder may already have: they are the app's own, so never replaced. */
113
- const STARTER_KEEP = new Set(['package.json', '.gitignore']);
114
- /** What the starter's own package.json depends on. */
115
- const STARTER_DEPENDENCIES = Object.keys(
116
- JSON.parse(fs.readFileSync(path.join(STARTER, 'package.json'), 'utf8'))
117
- .dependencies,
118
- );
119
312
 
120
313
  /**
121
314
  * `file` when it is inside `root`, also through links; else a refusal.
@@ -128,29 +321,70 @@ function confined(file, root, what) {
128
321
  try {
129
322
  return assertWithin(file, root, {allowAbsolute: true, label: what});
130
323
  } catch (e) {
131
- 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
+ }
132
332
  refuse(
133
333
  E.ERR_PATH_TRAVERSAL,
134
- `${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}.`,
135
337
  );
338
+ }
136
339
  throw e;
137
340
  }
138
341
  }
139
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
+
140
371
  /**
141
372
  * The files a new starter app (Next.js app router, Core and the neutral
142
373
  * theme) writes into `where`, with `extra` files beside them, checked before
143
- * anything is written: every file stays inside the folder, also through
144
- * links; with `overwrite`, a protected file there is refused and the app's
145
- * own package.json and .gitignore are kept.
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.
146
377
  * @param {string} cwd
147
378
  * @param {string} where
148
- * @param {boolean} overwrite
149
- * @param {(root: string) => Array<{rel: string, text: string}>} extra files relative to the app folder
379
+ * @param {(root: string) => Array<{rel: string, text: string | Buffer}>} extra files relative to the app folder
150
380
  * @param {Record<string, string>} dependencies added to the starter's package.json
151
- * @returns {{root: string, writes: Array<{file: string, text: string}>, kept: string[]}}
381
+ * @param {string | null} [slug] the theme, repeated in suggestions
382
+ * @returns {{root: string, writes: Array<{file: string, text: string | Buffer}>}}
152
383
  */
153
- function planStarterApp(cwd, where, overwrite, 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);
154
388
  /** @type {string} */
155
389
  let root;
156
390
  try {
@@ -163,18 +397,71 @@ function planStarterApp(cwd, where, overwrite, extra, dependencies) {
163
397
  refuse(
164
398
  E.ERR_PATH_TRAVERSAL,
165
399
  `${where} is outside the current folder; make the app inside the folder you run the command from.`,
400
+ {run: [again(null)]},
166
401
  );
167
402
  throw e;
168
403
  }
169
- if (fs.existsSync(root) && fs.readdirSync(root).length && !overwrite)
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}`;
426
+ refuse(
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
+ },
435
+ );
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
+ )
170
458
  refuse(
171
459
  E.ERR_FILE_EXISTS,
172
- `${shown(cwd, root) || '.'} exists and is not empty; a starter app goes into a new or empty folder (--overwrite replaces its files).`,
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))]},
173
462
  );
174
- /** @type {Array<{file: string, text: string}>} */
463
+ /** @type {Array<{file: string, text: string | Buffer}>} */
175
464
  const writes = [];
176
- /** @type {string[]} */
177
- const kept = [];
178
465
  /** @param {string} from */
179
466
  const walk = from => {
180
467
  for (const entry of fs.readdirSync(from, {withFileTypes: true})) {
@@ -182,23 +469,24 @@ function planStarterApp(cwd, where, overwrite, 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
- if (STARTER_KEEP.has(name) && fs.existsSync(file)) {
192
- kept.push(shown(cwd, file));
193
- continue;
194
- }
195
478
  const text = fs.readFileSync(src, 'utf8');
479
+ const key = rel.split(path.sep).join('/');
196
480
  writes.push({
197
481
  file,
198
482
  text:
199
- rel === 'package.json'
483
+ key === 'package.json'
200
484
  ? starterPackageJson(text, dependencies)
201
- : text,
485
+ : key === 'src/app/page.tsx'
486
+ ? STARTER_HOME
487
+ : key === 'src/app/layout.tsx'
488
+ ? starterLayout(text)
489
+ : text,
202
490
  });
203
491
  }
204
492
  }
@@ -209,29 +497,20 @@ function planStarterApp(cwd, where, overwrite, extra, dependencies) {
209
497
  file: confined(path.join(root, x.rel), root, 'an app file'),
210
498
  text: x.text,
211
499
  });
212
- const existing = writes.map(w => w.file).filter(f => fs.existsSync(f));
213
- if (existing.length) {
214
- /** @type {ReturnType<typeof createFileProtectionResolver>} */
215
- let resolver;
216
- try {
217
- resolver = createFileProtectionResolver(cwd);
218
- } catch (e) {
219
- refuse(
220
- E.ERR_FILE_EXISTS,
221
- `Could not read this project's file protection (${e instanceof Error ? e.message : String(e)}), so no existing file is replaced; nothing was written.`,
222
- );
223
- }
224
- const blocked = existing.flatMap(f => {
225
- const protection = resolver.classify(f)[0];
226
- return protection ? [`${shown(cwd, f)} (${protection.declaration})`] : [];
227
- });
228
- if (blocked.length)
229
- refuse(
230
- E.ERR_FILE_EXISTS,
231
- `${blocked.join(', ')} ${blocked.length === 1 ? 'is' : 'are'} protected, so never replaced, even with --overwrite; nothing was written. Choose another app folder.`,
232
- );
233
- }
234
- return {root, writes, kept: kept.sort()};
500
+ return {root, writes};
501
+ }
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
+ );
235
514
  }
236
515
 
237
516
  /**
@@ -253,62 +532,456 @@ function starterPackageJson(text, dependencies) {
253
532
  }
254
533
 
255
534
  /**
256
- * 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.
257
538
  * @param {string} cwd
258
- * @param {{writes: Array<{file: string, text: string}>}} plan
539
+ * @param {{root: string, writes: Array<{file: string, text: string | Buffer}>}} plan
540
+ * @param {(dir: string) => string} again the command with this folder
259
541
  * @returns {string[]} the files written
260
542
  */
261
- function writeStarterApp(cwd, plan) {
262
- for (const w of plan.writes) {
263
- fs.mkdirSync(path.dirname(w.file), {recursive: true});
264
- 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
+ );
265
597
  }
266
598
  return plan.writes.map(w => shown(cwd, w.file)).sort();
267
599
  }
268
600
 
269
- /** @param {string} dir @returns {PreviewData | null} */
270
- 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;
271
738
  try {
272
- 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;
273
742
  } catch {
274
- return null;
743
+ return false;
275
744
  }
276
745
  }
277
746
 
278
747
  /**
279
- * A preview file, checked: inside the route folder, also through links, and
280
- * 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.
281
752
  * @param {string} cwd
282
753
  * @param {string} dir
283
754
  * @param {PreviewData} data
284
- * @param {string} rel relative to dir
285
- * @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'}
286
758
  */
287
- function previewFile(cwd, dir, data, rel) {
288
- const file = confined(path.join(dir, rel), dir, 'a preview file');
289
- const key = rel.split(path.sep).join('/');
290
- 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))
291
792
  refuse(
292
793
  E.ERR_FILE_EXISTS,
293
- `${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
+ },
294
798
  );
295
- return file;
799
+ return 'replace';
296
800
  }
297
801
 
298
802
  /**
299
- * 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.
300
807
  * @param {string} cwd
301
808
  * @param {string} dir
302
809
  * @param {PreviewData} data
303
- * @param {string} rel relative to dir
304
- * @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
814
+ */
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[]}}
305
925
  */
306
- function writePreviewFile(cwd, dir, data, rel, text) {
307
- const file = previewFile(cwd, dir, data, rel);
308
- fs.mkdirSync(path.dirname(file), {recursive: true});
309
- fs.writeFileSync(file, text);
310
- const key = rel.split(path.sep).join('/');
311
- if (!data.files.includes(key)) data.files.push(key);
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
+ }
312
985
  }
313
986
 
314
987
  /** The themes this command made, by name. @param {string} cwd */
@@ -329,7 +1002,7 @@ function editedThemes(cwd) {
329
1002
  * @param {string} cwd
330
1003
  * @param {string} dir
331
1004
  * @param {PreviewData} data
332
- * @returns {Promise<{name: string, module: string, css: string[]} | null>}
1005
+ * @returns {Promise<{name: string, module: string, css: string[], mode: 'system' | 'light' | 'dark'} | null>}
333
1006
  */
334
1007
  async function routeTheme(cwd, dir, data) {
335
1008
  if (!data.theme) return null;
@@ -338,55 +1011,222 @@ async function routeTheme(cwd, dir, data) {
338
1011
  if (!fs.existsSync(themeFiles(cwd, data.theme).js))
339
1012
  await buildTheme(ctx, data.theme, t);
340
1013
  const ti = themeImports(ctx, data.theme, t, dir);
341
- return {name: data.theme, module: ti.module, css: ti.css};
1014
+ return {name: data.theme, module: ti.module, css: ti.css, mode: ti.mode};
342
1015
  }
343
1016
 
1017
+ /** The Colors page: its id and file, relative to the route folder. */
1018
+ const COLORS_PAGE = {
1019
+ id: 'colors',
1020
+ label: 'Colors',
1021
+ file: `${PAGES_DIR}/colors`,
1022
+ };
1023
+
344
1024
  /**
345
- * Write the route and the data file from the page list.
1025
+ * The Colors page source of a theme, and whether the theme has generated
1026
+ * colors. The page imports the generated color module, so it follows every
1027
+ * change; the tokens that use each shade are written into it.
346
1028
  * @param {string} cwd
347
- * @param {string} dir
348
- * @param {PreviewData} data
349
- * @param {{name: string, module: string, css: string[]} | null} [theme] from {@link routeTheme}
1029
+ * @param {string} dir the route folder
1030
+ * @param {string} slug
1031
+ * @returns {Promise<{source: string, colors: boolean}>}
350
1032
  */
351
- async function writeRoute(cwd, dir, data, theme) {
352
- if (theme === undefined) theme = await routeTheme(cwd, dir, data);
353
- writePreviewFile(
1033
+ async function colorsPage(cwd, dir, slug) {
1034
+ const data = loadTheme(cwd, slug);
1035
+ const ctx = await context(cwd);
1036
+ const pal = paletteMapping(
354
1037
  cwd,
355
- dir,
1038
+ slug,
356
1039
  data,
357
- 'page.tsx',
358
- previewRouteSource({pages: data.pages, theme}),
1040
+ await baseResolved(ctx.project, data.like),
1041
+ ctx.project.core.tokenDefaults,
359
1042
  );
360
- if (!data.files.includes(PREVIEW_DATA)) data.files.push(PREVIEW_DATA);
361
- fs.writeFileSync(
362
- path.join(dir, PREVIEW_DATA),
363
- `${JSON.stringify(data, null, 2)}\n`,
1043
+ const file = path.join(cwd, paletteFiles(slug).palette);
1044
+ if (!pal || !fs.existsSync(file))
1045
+ return {
1046
+ source: colorsPageSource({slug, module: null, seeds: {}, uses: {}}),
1047
+ colors: false,
1048
+ };
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
+ );
1060
+ /** @type {Record<string, Record<'light' | 'dark', Record<string, string[]>>>} */
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']
364
1070
  );
1071
+ for (const [token, v] of Object.entries(pal.tokens)) {
1072
+ for (const m of modes) {
1073
+ if (exact(token, m)) continue;
1074
+ const r = v[m];
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})` : ''}`,
1079
+ );
1080
+ }
1081
+ }
1082
+ const pageDir = path.join(dir, path.dirname(COLORS_PAGE.file));
1083
+ const rel = path
1084
+ .relative(pageDir, file.replace(/\.ts$/, ''))
1085
+ .split(path.sep)
1086
+ .join('/');
1087
+ return {
1088
+ source: colorsPageSource({
1089
+ slug,
1090
+ module: rel.startsWith('.') ? rel : `./${rel}`,
1091
+ seeds: Object.fromEntries(pal.families.map(f => [f.id, f.seed])),
1092
+ uses,
1093
+ }),
1094
+ colors: true,
1095
+ };
365
1096
  }
366
1097
 
367
1098
  /**
368
- * Rewrite the in-app preview route of a theme when its imports changed, so
369
- * a font package installed after `set` loads on the next change or `show`.
370
- * Only the preview in the usual place (app/ or src/app/theme-preview) is
371
- * kept this way; a preview elsewhere follows on its next `preview add`.
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.
1102
+ * @param {string} cwd
1103
+ * @param {string} dir
1104
+ * @param {PreviewData} data
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}>>}
1108
+ */
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;
1133
+ }
1134
+
1135
+ /**
1136
+ * Rewrite the in-app preview routes of a theme when their imports changed, so
1137
+ * a font package installed after `set` loads on the next change or `show`,
1138
+ * and its Colors page, so it names the shades the tokens use now.
1139
+ * The preview in the usual place (app/ or src/app/theme-preview) and every
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.
372
1142
  * @param {string} cwd
373
1143
  * @param {string} slug
374
- * @returns {Promise<boolean>} whether the route 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
375
1147
  */
376
1148
  export async function refreshPreviewRoute(cwd, slug) {
377
1149
  const at = previewDir(cwd, undefined, {optional: true});
378
- const data = at && readPreview(at.dir);
379
- if (!data || data.theme !== slug || !data.files.includes('page.tsx'))
380
- return false;
381
- const file = previewFile(cwd, at.dir, data, 'page.tsx');
382
- const text = previewRouteSource({
383
- pages: data.pages,
384
- theme: await routeTheme(cwd, at.dir, data),
385
- });
386
- if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === text)
387
- return false;
388
- fs.writeFileSync(file, text);
389
- return true;
1150
+ const dirs = [
1151
+ ...new Set([...(at ? [at.dir] : []), ...recordedPreviews(cwd, slug)]),
1152
+ ];
1153
+ let changed = false;
1154
+ /** @type {string[]} */
1155
+ const stale = [];
1156
+ for (const dir of dirs) {
1157
+ /** @type {PreviewData | null} */
1158
+ let data;
1159
+ try {
1160
+ data = readPreview(cwd, dir);
1161
+ } catch {
1162
+ continue;
1163
+ }
1164
+ if (!data || data.theme !== slug || !data.files.includes('page.tsx'))
1165
+ continue;
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;
1178
+ });
1179
+ if (!writes.length) continue;
1180
+ commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
1181
+ changed = true;
1182
+ }
1183
+ return {changed, stale};
1184
+ }
1185
+
1186
+ /**
1187
+ * Where a theme's previews are, so a preview added with --path is kept in
1188
+ * step too: themes/<theme>/previews.json, project-relative folders.
1189
+ * @param {string} cwd
1190
+ * @param {string} slug
1191
+ */
1192
+ const previewsFile = (cwd, slug) =>
1193
+ path.join(themeFiles(cwd, slug).dir, 'previews.json');
1194
+
1195
+ /**
1196
+ * The preview folders recorded for a theme that are still inside the
1197
+ * project.
1198
+ * @param {string} cwd
1199
+ * @param {string} slug
1200
+ * @returns {string[]}
1201
+ */
1202
+ function recordedPreviews(cwd, slug) {
1203
+ try {
1204
+ const list = JSON.parse(fs.readFileSync(previewsFile(cwd, slug), 'utf8'));
1205
+ return (Array.isArray(list) ? list : [])
1206
+ .map(rel => path.resolve(cwd, String(rel)))
1207
+ .filter(dir => !path.relative(cwd, dir).startsWith('..'));
1208
+ } catch {
1209
+ return [];
1210
+ }
1211
+ }
1212
+
1213
+ /**
1214
+ * Record a preview folder for a theme, or with `keep` false forget it.
1215
+ * @param {string} cwd
1216
+ * @param {string} slug
1217
+ * @param {string} dir
1218
+ * @param {boolean} [keep]
1219
+ */
1220
+ function recordPreview(cwd, slug, dir, keep = true) {
1221
+ if (!fs.existsSync(themeFiles(cwd, slug).dir)) return;
1222
+ const rel = path.relative(cwd, dir).split(path.sep).join('/');
1223
+ const list = recordedPreviews(cwd, slug)
1224
+ .map(d => path.relative(cwd, d).split(path.sep).join('/'))
1225
+ .filter(x => x !== rel);
1226
+ if (keep) list.push(rel);
1227
+ const file = previewsFile(cwd, slug);
1228
+ if (list.length) writeWhole(file, `${JSON.stringify(list, null, 2)}\n`);
1229
+ else fs.rmSync(file, {force: true});
390
1230
  }
391
1231
 
392
1232
  /**
@@ -395,22 +1235,41 @@ export async function refreshPreviewRoute(cwd, slug) {
395
1235
  * @param {{dir: string, app: string | null}} at
396
1236
  */
397
1237
  function openLine(cwd, at) {
398
- if (at.app)
399
- return `open /${path.relative(at.app, at.dir).split(path.sep).join('/')} in the running app`;
400
- 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`;
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
+ }
1249
+ const routes = ['app', path.join('src', 'app')].filter(r =>
1250
+ fs.existsSync(path.join(cwd, r)),
1251
+ );
1252
+ if (routes.length)
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>`;
401
1255
  }
402
1256
 
403
1257
  const STYLEX_IMPORT = /from\s+['"]@stylexjs\/stylex['"]/;
404
1258
 
405
1259
  /**
406
1260
  * Why a template page was skipped.
407
- * @param {{missingPackages: string[], stylexCompiler: boolean}} s
1261
+ * @param {{missingPackages: string[], notInstalled: string[], stylexCompiler: boolean}} s
408
1262
  */
409
1263
  function skipReason(s) {
410
1264
  return [
411
1265
  ...(s.missingPackages.length
412
1266
  ? [`needs ${s.missingPackages.join(', ')}`]
413
1267
  : []),
1268
+ ...(s.notInstalled.length
1269
+ ? [
1270
+ `needs ${s.notInstalled.join(', ')}, which the app's package.json names but is not installed`,
1271
+ ]
1272
+ : []),
414
1273
  ...(s.stylexCompiler
415
1274
  ? [
416
1275
  'uses StyleX, and this app has no StyleX compiler (astryx docs styling-overview)',
@@ -419,162 +1278,744 @@ function skipReason(s) {
419
1278
  ].join(' and ');
420
1279
  }
421
1280
 
1281
+ /**
1282
+ * The page templates for a description, best first, each with why: the
1283
+ * build ranking's picks, then the template search's, so a page the app
1284
+ * cannot show has a next match. App frames (the Shell templates) are left
1285
+ * out: the preview is an app shell already, and `--template` can still name
1286
+ * one. The closest page is added even when it is not exactly the page asked
1287
+ * for, with a note; only a description no page relates to is refused, with
1288
+ * the closest pages to name instead, and nothing is written.
1289
+ * @param {string} words
1290
+ * @param {string} cwd
1291
+ * @param {string[]} notes notes for the result
1292
+ * @param {string} flags the caller's other flags, for the suggestions
1293
+ * @returns {Promise<Array<{name: string, displayName: string, why: string}>>}
1294
+ */
1295
+ async function rankedPages(words, cwd, notes, flags) {
1296
+ const kit =
1297
+ /** @type {import('../build/build.type.mjs').BuildKitResponse} */ (
1298
+ await build(words, {cwd})
1299
+ );
1300
+ const start = kit.data.start;
1301
+ const listed = await pageTemplates(cwd);
1302
+ const frames = new Set(
1303
+ listed.filter(t => /^Shell\b/.test(t.category ?? '')).map(t => t.id),
1304
+ );
1305
+ const found = /** @type {any} */ (
1306
+ await search(words, {cwd, type: 'template', limit: 20})
1307
+ ).data.results.filter((/** @type {any} */ r) => r.kind === 'page');
1308
+ /** @type {Map<string, string>} */
1309
+ const matchedWords = new Map(
1310
+ found.map((/** @type {any} */ r) => [
1311
+ r.name,
1312
+ String(r.reason ?? '').replace(/^matches \d+\/\d+ terms: /, ''),
1313
+ ]),
1314
+ );
1315
+ const names = [
1316
+ ...(start ? [start.name, ...start.alternatives.map(a => a.name)] : []),
1317
+ ...found.map((/** @type {any} */ r) => r.name),
1318
+ ].filter((n, i, a) => a.indexOf(n) === i);
1319
+ const skippedFrames = names.filter(n => frames.has(n));
1320
+ const pages = names.filter(n => !frames.has(n));
1321
+ /** @param {string} name */
1322
+ const label = name => listed.find(t => t.id === name)?.name ?? name;
1323
+ const suggest = (/** @type {string[]} */ list) =>
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
+ ];
1334
+ // No page relates when the ranking fell back to a frame with no direct
1335
+ // match, and no page the search found matches three words of the request
1336
+ // or two fifths of them.
1337
+ const termsMatched = (/** @type {any} */ r) => {
1338
+ const m = /^matches (\d+)\/(\d+)/.exec(String(r.reason ?? ''));
1339
+ if (!m) return 0;
1340
+ const [hit, of] = [Number(m[1]), Number(m[2])];
1341
+ return hit >= 3 || hit / of >= 0.4 ? hit : 0;
1342
+ };
1343
+ // A page the description names in a phrase (a blog post, an issue
1344
+ // tracker) always relates.
1345
+ const named = APP_PAGES.some(([re]) => re.test(words.toLowerCase()));
1346
+ const unrelated =
1347
+ !named &&
1348
+ (!pages.length ||
1349
+ (start &&
1350
+ start.basis === 'fallback' &&
1351
+ frames.has(start.name) &&
1352
+ !kit.data.directMatch &&
1353
+ !found.some(
1354
+ (/** @type {any} */ r) => !frames.has(r.name) && termsMatched(r) >= 2,
1355
+ )));
1356
+ if (unrelated)
1357
+ refuse(
1358
+ E.ERR_NOT_FOUND,
1359
+ `No page template relates to "${words}". Name a page to add it anyway.`,
1360
+ {
1361
+ run: pages.length
1362
+ ? [...suggest(pages), 'astryx template --list --type page']
1363
+ : fallback,
1364
+ },
1365
+ );
1366
+ if (skippedFrames.length)
1367
+ notes.push(
1368
+ `left out ${skippedFrames.join(', ')}: app frames, not pages (add one with --template <id>)`,
1369
+ );
1370
+ const closest = start && start.basis === 'closest';
1371
+ const text = words.toLowerCase();
1372
+ // An app the description names (an app screenshot, an issue tracker, a
1373
+ // board) shows its theme better than a hero, so a page for it goes first.
1374
+ const exists = (/** @type {string} */ id) =>
1375
+ listed.some(t => t.id === id) && !frames.has(id);
1376
+ const app = APP_PAGES.find(([re, ids]) => re.test(text) && ids.some(exists));
1377
+ // A hero described as left-aligned or split takes the side layout.
1378
+ const side =
1379
+ /\bleft[- ]aligned\b|\bsplit\b|\bside[- ]by[- ]side\b|\basymmetric/.test(
1380
+ text,
1381
+ ) &&
1382
+ pages[0] !== 'side-gallery' &&
1383
+ /hero|landing/.test(text);
1384
+ /** @type {Map<string, string>} */
1385
+ const reasons = new Map();
1386
+ if (app) {
1387
+ // The ranked page stays first when it already serves the app named;
1388
+ // the app's pages come next, in order, so the next one is taken when
1389
+ // one cannot be shown here.
1390
+ const named = /** @type {RegExpExecArray} */ (app[0].exec(text))[0];
1391
+ const keep = app[1].includes(pages[0]) ? pages[0] : null;
1392
+ const ids = app[1].filter(id => exists(id) && id !== keep);
1393
+ for (const id of [...ids].reverse()) {
1394
+ if (pages.includes(id)) pages.splice(pages.indexOf(id), 1);
1395
+ pages.splice(keep ? 1 : 0, 0, id);
1396
+ }
1397
+ if (keep)
1398
+ reasons.set(
1399
+ keep,
1400
+ `the description names ${named}, and this page is that app`,
1401
+ );
1402
+ ids.forEach((id, k) =>
1403
+ reasons.set(
1404
+ id,
1405
+ k === 0 && !keep
1406
+ ? `the description names ${named}, and this page is made for that`
1407
+ : `the next page for ${named}`,
1408
+ ),
1409
+ );
1410
+ } else if (side && listed.some(t => t.id === 'side-gallery')) {
1411
+ if (pages.includes('side-gallery'))
1412
+ pages.splice(pages.indexOf('side-gallery'), 1);
1413
+ pages.unshift('side-gallery');
1414
+ reasons.set(
1415
+ 'side-gallery',
1416
+ 'the description asks for a left-aligned or split hero, and this hero puts the copy beside the picture',
1417
+ );
1418
+ }
1419
+ if (/\btop[- ]?nav|\bnav ?bar|\bnavigation bar|\bheader nav/.test(text))
1420
+ notes.push(
1421
+ 'no page has a top nav of its own: the preview frame has one, and your app keeps its own',
1422
+ );
1423
+ return pages.map((name, i) => {
1424
+ const words = matchedWords.get(name);
1425
+ const doc = listed.find(t => t.id === name)?.description ?? '';
1426
+ const shape = doc.split(/(?<=\.)\s/)[0];
1427
+ const reason = reasons.get(name);
1428
+ return {
1429
+ name,
1430
+ displayName: label(name),
1431
+ why: reason
1432
+ ? `${reason}${words ? `; it covers ${words}` : ''}. ${shape}`
1433
+ : i === 0 && closest
1434
+ ? `the closest page, not exactly the one described${words ? `: it covers ${words}` : ''}; the rest of the description is not on it. ${shape}`
1435
+ : `${i === 0 ? 'the best match' : 'the next match'}${words ? `: it covers ${words}` : ''}. ${shape}`,
1436
+ };
1437
+ });
1438
+ }
1439
+
1440
+ /**
1441
+ * App pages for the apps a description names, best first. Each is matched
1442
+ * by a phrase, never one loose word, so "buy tickets" is not an issue
1443
+ * tracker and "an AI tool" is not a chat. A detail view comes before its
1444
+ * list.
1445
+ * @type {Array<[RegExp, string[]]>}
1446
+ */
1447
+ const APP_PAGES = [
1448
+ [
1449
+ /\b(issue|ticket|bug|task|work[- ]item) (detail|details|view|page)\b/,
1450
+ ['work-item-detail', 'detail-page'],
1451
+ ],
1452
+ [
1453
+ /\b(issue[- ]?tracker|bug[- ]tracker|issue (list|table|queue|board)|ticket(ing)? (system|queue|tracker)|backlog)\b/,
1454
+ ['table-grouped', 'table'],
1455
+ ],
1456
+ [/\b(kanban|task board|project board)\b/, ['kanban-board']],
1457
+ [/\b(analytics )?dashboard\b|\banalytics (app|page|view)\b/, ['dashboard']],
1458
+ [
1459
+ /\b(email|mail) (inbox|client|app)\b|\binbox (app|view|page)\b/,
1460
+ ['table-inbox'],
1461
+ ],
1462
+ [
1463
+ /\b(chat (app|interface|ui|window|screen|view)|chatbot|ai (chat|assistant) (app|interface|ui))\b/,
1464
+ ['ai-chat'],
1465
+ ],
1466
+ [/\b(settings|preferences) (page|screen|panel|view)\b/, ['settings']],
1467
+ [/\b(docs|documentation) (site|page|portal)\b/, ['documentation']],
1468
+ [/\b(data ?table|spreadsheet|data grid)\b/, ['table']],
1469
+ [
1470
+ /\b(blog( post)?|article|news (story|article|page)|essay|long[- ]read)\b/,
1471
+ ['documentation-design', 'course-detail'],
1472
+ ],
1473
+ [
1474
+ /\b(app|product) (screenshot|window|preview|ui)\b/,
1475
+ ['table-grouped', 'dashboard', 'table'],
1476
+ ],
1477
+ ];
1478
+
1479
+ /**
1480
+ * The page templates this project has, with their display names.
1481
+ * @param {string} cwd
1482
+ * @returns {Promise<Array<{id: string, name: string, category?: string, description?: string}>>}
1483
+ */
1484
+ async function pageTemplates(cwd) {
1485
+ return /** @type {any} */ (
1486
+ (await template(undefined, {list: true, type: 'page', cwd})).data
1487
+ );
1488
+ }
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
+
422
1677
  /**
423
1678
  * Add pages to the in-app theme preview, and write the preview route the
424
1679
  * first time. With a description, the build ranking picks the template
425
1680
  * pages that fit it best (`top` of them); `template` names one instead.
426
- * With neither, the default pages: the sample app page and every component.
427
- * Every check runs before the first write, so a refusal changes nothing.
1681
+ * With neither, the default pages: the sample app page, every component,
1682
+ * and the theme's generated colors when it has any.
1683
+ * Every check runs before the first write, so a refusal changes nothing;
1684
+ * the files are staged and renamed into place together.
428
1685
  * @experimental
429
1686
  * @param {string} [description]
430
1687
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewAddOptions} [options]
431
1688
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewAddResponse>}
432
1689
  */
433
1690
  export async function themeEditPreviewAdd(description, options = {}) {
434
- const {cwd = process.cwd(), top = 1} = options;
1691
+ const {cwd = process.cwd()} = options;
435
1692
  if (isOutsideProject(cwd))
436
1693
  refuse(
437
1694
  E.ERR_PROJECT_REQUIRED,
438
1695
  'No package.json here, so there is no app to put the preview in.',
439
1696
  {
440
1697
  run: [
441
- `${PREVIEW} add --path <dir> (run in your app: a folder inside its routes)`,
442
- `${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`,
443
1700
  ],
444
1701
  },
445
1702
  );
446
- const words = (description ?? '').trim();
447
- 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)
448
1716
  refuse(
449
1717
  E.ERR_INVALID_ARGUMENT,
450
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
+ },
451
1750
  );
452
- if (!Number.isInteger(top) || top < 1 || top > 3)
453
- refuse(E.ERR_INVALID_ARGUMENT, `--top takes 1, 2 or 3, not "${top}".`);
454
- const at = previewDir(cwd, options.path);
455
- const data = readPreview(at.dir) ?? {
456
- version: 1,
457
- theme: null,
458
- pages: [],
459
- files: [],
460
- };
461
1751
  /** @type {string[]} */
462
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";
463
1780
  if (options.theme != null) {
464
- loadTheme(cwd, options.theme);
1781
+ wornTheme(cwd, options.theme, againWith, without);
465
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
+ );
466
1789
  } else if (!data.theme) {
467
1790
  const themes = editedThemes(cwd);
468
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
+ );
469
1796
  }
470
- 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
+ );
471
1807
  const project = await openProject(cwd);
472
- /** @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}>} */
473
1825
  const add = [];
474
- /** @type {Array<{page: string, missingPackages: string[], installCommand: string | null, stylexCompiler: boolean}>} */
1826
+ /** @type {Array<{page: string, reason: string, installCommand: string | null}>} */
475
1827
  const skipped = [];
476
- if (!words && options.template == null) {
477
- add.push(
478
- {id: 'overview', label: 'Overview', source: overviewPageSource(project)},
479
- {
480
- id: 'components',
481
- label: 'Components',
482
- source: componentsPageSource(project).source,
483
- },
484
- );
485
- } else {
486
- /** @type {Array<{name: string, displayName: string}>} */
487
- let picks;
488
- if (options.template != null)
489
- picks = [{name: options.template, displayName: options.template}];
490
- else {
491
- const kit =
492
- /** @type {import('../build/build.type.mjs').BuildKitResponse} */ (
493
- await build(words, {cwd})
494
- );
495
- const start = kit.data.start;
496
- picks = start ? [start, ...start.alternatives].slice(0, top) : [];
497
- if (!picks.length)
498
- refuse(
499
- E.ERR_NOT_FOUND,
500
- `No page template to show for "${words}": this project has none.`,
501
- {run: [`${PREVIEW} add`]},
502
- );
1828
+ /** @type {Array<{page: string, why: string}>} */
1829
+ const matched = [];
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'));
1837
+ if (data.theme) {
1838
+ const colors = await colorsPage(cwd, at.dir, data.theme);
1839
+ if (colors.colors)
1840
+ add.push({
1841
+ id: COLORS_PAGE.id,
1842
+ label: COLORS_PAGE.label,
1843
+ text: colors.source,
1844
+ });
503
1845
  }
504
- for (const pick of picks) {
1846
+ } else {
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()) {
1852
+ if (add.length >= (explicit ? 1 : top)) break;
505
1853
  const shownTemplate =
506
1854
  /** @type {import('../template/template.type.mjs').TemplateShowResponse} */ (
507
1855
  await template(pick.name, {cwd, type: 'page'})
508
1856
  );
509
- 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);
510
1860
  // A StyleX page calls stylex.create when its module loads, so without
511
1861
  // a StyleX compiler it breaks the whole route.
512
1862
  const needsCompiler =
513
- STYLEX_IMPORT.test(shownTemplate.data.source) &&
514
- detectStylingSystem(cwd) !== 'stylex';
515
- 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);
516
1868
  skipped.push({
517
1869
  page: pick.name,
518
- missingPackages: needs.missingPackages,
519
- installCommand: needs.installCommand,
520
- stylexCompiler: needsCompiler,
1870
+ reason: `${skipReason({
1871
+ missingPackages: needs.missingPackages,
1872
+ notInstalled: absent,
1873
+ stylexCompiler: needsCompiler,
1874
+ })}${needs.missingPackages.length && !needs.installCommand ? ' (the app has more than one lockfile, so install it with the package manager you use)' : ''}`,
1875
+ installCommand,
521
1876
  });
1877
+ if (installCommand) runs.push(installCommand);
1878
+ if (needsCompiler) stylexSkipped = true;
1879
+ if (i === 0) firstSkipped = true;
522
1880
  continue;
523
1881
  }
524
- add.push({id: pick.name, label: pick.displayName, template: pick.name});
1882
+ add.push({id: pick.name, label: pick.displayName, text: source});
1883
+ matched.push({page: pick.name, why: pick.why});
525
1884
  }
526
1885
  }
527
1886
  for (const s of skipped)
528
1887
  notes.push(
529
- `the ${s.page} page was not added: ${skipReason(s)}${s.installCommand ? `; ${s.installCommand}, then add it again` : ''}`,
1888
+ `the ${s.page} page was not added: it ${s.reason}${s.installCommand ? `; ${s.installCommand}, then add it again` : ''}`,
530
1889
  );
1890
+ if (firstSkipped && add.length && !explicit)
1891
+ notes.push(`added ${add.map(a => a.id).join(', ')} in its place`);
531
1892
  if (!add.length)
532
1893
  refuse(
533
1894
  E.ERR_DEP_MISSING,
534
- `No page was added: ${skipped.map(s => `the ${s.page} page ${skipReason(s)}`).join('; ')}. Nothing was written.`,
1895
+ `No page was added: ${skipped.map(s => `the ${s.page} page ${s.reason}`).join('; ')}.`,
535
1896
  {
536
- 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
+ ],
537
1904
  },
538
1905
  );
539
- for (const page of add)
540
- previewFile(cwd, at.dir, data, `pages/${page.id}.tsx`);
541
- previewFile(cwd, at.dir, data, 'page.tsx');
542
- previewFile(cwd, at.dir, data, PREVIEW_DATA);
543
- 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));
544
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]));
545
1922
  /** @type {string[]} */
546
1923
  const added = [];
1924
+ /** Pages that were there already and are written again. @type {string[]} */
1925
+ const refreshed = [];
547
1926
  for (const page of add) {
548
- const file = `pages/${page.id}`;
549
- if (page.template != null) {
550
- const target = previewFile(cwd, at.dir, data, `${file}.tsx`);
551
- await template(page.template, {
552
- cwd,
553
- type: 'page',
554
- targetPath: path.relative(cwd, target),
555
- overwrite: true,
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);
1933
+ const had = data.pages.find(x => x.id === page.id);
1934
+ if (!had) {
1935
+ data.pages.push({
1936
+ id: page.id,
1937
+ label: page.label,
1938
+ file: `${PAGES_DIR}/${page.id}`,
556
1939
  });
557
- if (!data.files.includes(`${file}.tsx`)) data.files.push(`${file}.tsx`);
558
- } else
559
- writePreviewFile(
560
- cwd,
561
- at.dir,
562
- data,
563
- `${file}.tsx`,
564
- /** @type {string} */ (page.source),
565
- );
566
- if (!data.pages.some(x => x.id === page.id)) {
567
- data.pages.push({id: page.id, label: page.label, file});
568
1940
  added.push(page.id);
1941
+ } else {
1942
+ had.label = page.label;
1943
+ refreshed.push(page.id);
1944
+ }
1945
+ }
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);
569
1978
  }
570
1979
  }
571
- await writeRoute(cwd, at.dir, data, theme);
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);
2010
+ if (data.theme) recordPreview(cwd, data.theme, at.dir);
572
2011
  return {
573
2012
  type: 'themeEdit.previewAdd',
574
2013
  data: {
575
- folder: shown(cwd, at.dir),
2014
+ folder: shownDir(cwd, at.dir),
576
2015
  theme: data.theme,
577
2016
  added,
2017
+ refreshed,
2018
+ matched,
578
2019
  skipped,
579
2020
  notes,
580
2021
  pages: data.pages.map(x => x.id),
@@ -596,49 +2037,86 @@ export async function themeEditPreviewAdd(description, options = {}) {
596
2037
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewAppResponse>}
597
2038
  */
598
2039
  export async function themeEditPreviewApp(dir, options = {}) {
599
- const {cwd = process.cwd(), overwrite = false} = options;
2040
+ const {cwd = process.cwd()} = options;
600
2041
  if (typeof dir !== 'string' || !dir.trim())
601
2042
  refuse(
602
2043
  E.ERR_INVALID_ARGUMENT,
603
2044
  'Name the folder for the new app: a new or empty folder inside the current one.',
604
- {run: [`${PREVIEW} app <dir>`]},
2045
+ {run: [`${PREVIEW} app theme-app`]},
605
2046
  );
606
2047
  const slug = options.theme ?? null;
607
- 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
+ );
608
2057
  // A new app has no Core installed yet: its pages come from this CLI's own
609
2058
  // Core when the current folder has none.
610
2059
  const project = await openProject(cwd).catch(() => openProject(CLI_PACKAGE));
611
2060
  /** @type {Record<string, string>} */
612
2061
  const dependencies = {};
613
- /** @type {Array<{rel: string, text: string}>} */
2062
+ /** @type {Array<{rel: string, text: string | Buffer}>} */
614
2063
  const themeCopy = [];
615
- /** @type {{name: string, module: string, css: string[]} | null} */
2064
+ /** @type {{name: string, module: string, css: string[], mode: 'system' | 'light' | 'dark'} | null} */
616
2065
  let routeTheme = null;
2066
+ /** @type {string[]} */
2067
+ const notes = [];
617
2068
  const routeDir = path.join('src', 'app', 'theme-preview');
618
2069
  // The folder checks come before the theme build, so a refusal writes nothing.
619
- planStarterApp(cwd, dir, overwrite, () => [], {});
2070
+ planStarterApp(cwd, dir, () => [], {}, slug);
2071
+ /** @type {string | null} */
2072
+ let colorsSource = null;
620
2073
  if (slug != null && theme) {
621
2074
  const from = themeFiles(cwd, slug);
622
- if (!fs.existsSync(from.js) || !fs.existsSync(from.css))
623
- 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
+ }
624
2090
  const to = themeFiles('', slug);
625
2091
  // The theme and its build, with the type declarations the build writes;
626
2092
  // not its history, preview pages or pictures.
627
2093
  const skip = new Set(
628
2094
  [
629
2095
  from.history,
2096
+ previewsFile(cwd, slug),
630
2097
  from.preview,
631
2098
  from.sheet,
632
2099
  from.previewPng,
633
2100
  from.sheetPng,
634
2101
  ].map(f => path.basename(f)),
635
2102
  );
636
- for (const entry of fs.readdirSync(from.dir, {withFileTypes: true}))
637
- if (entry.isFile() && !skip.has(entry.name))
638
- themeCopy.push({
639
- rel: path.join(to.dir, entry.name),
640
- text: fs.readFileSync(path.join(from.dir, entry.name), 'utf8'),
641
- });
2103
+ // The whole folder, tokens/ included, as bytes: a font or a picture
2104
+ // there must arrive as it is.
2105
+ /** @param {string} rel */
2106
+ const copyDir = rel => {
2107
+ for (const entry of fs.readdirSync(path.join(from.dir, rel), {
2108
+ withFileTypes: true,
2109
+ })) {
2110
+ const sub = path.join(rel, entry.name);
2111
+ if (entry.isDirectory()) copyDir(sub);
2112
+ else if (entry.isFile() && !(rel === '' && skip.has(entry.name)))
2113
+ themeCopy.push({
2114
+ rel: path.join(to.dir, sub),
2115
+ text: fs.readFileSync(path.join(from.dir, sub)),
2116
+ });
2117
+ }
2118
+ };
2119
+ copyDir('');
642
2120
  if (theme.like && theme.like !== 'neutral')
643
2121
  dependencies[`@astryxdesign/theme-${theme.like}`] = cliVersion();
644
2122
  /** @param {string} rel */
@@ -646,51 +2124,87 @@ export async function themeEditPreviewApp(dir, options = {}) {
646
2124
  const r = path.relative(routeDir, rel).split(path.sep).join('/');
647
2125
  return r.startsWith('.') ? r : `./${r}`;
648
2126
  };
649
- const fonts = fontPackages(await context(cwd), theme).filter(
650
- x => x.installed,
651
- );
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);
652
2130
  for (const font of fonts)
653
- dependencies[font.pkg] = readVersion(project, font.pkg) ?? 'latest';
2131
+ dependencies[font.pkg] =
2132
+ readVersion(project, font.pkg) ?? OPEN_FONT_RANGE;
654
2133
  routeTheme = {
655
2134
  name: slug,
656
2135
  module: fromRoute(to.js),
657
2136
  css: [fromRoute(to.css), ...fonts.map(x => `${x.pkg}/index.css`)],
2137
+ mode: themeImports(ctx, slug, theme, path.join(cwd, routeDir)).mode,
658
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;
659
2143
  }
660
2144
  /** @type {PreviewData} */
661
- const data = {version: 1, theme: slug, pages: [], files: []};
2145
+ const data = {version: 1, theme: slug, pages: [], files: [], hashes: {}};
662
2146
  /** @type {Array<{rel: string, text: string}>} */
663
2147
  const preview = [];
664
- for (const [id, label, source] of /** @type {const} */ ([
665
- ['overview', 'Overview', overviewPageSource(project)],
666
- ['components', 'Components', componentsPageSource(project).source],
667
- ])) {
668
- data.pages.push({id, label, file: `pages/${id}`});
669
- preview.push({rel: `pages/${id}.tsx`, text: source});
2148
+ /** @type {Array<[string, string, string]>} */
2149
+ const pages = [
2150
+ ['overview', 'Overview', overviewPageSource(project, {theme: slug})],
2151
+ [
2152
+ 'components',
2153
+ 'Components',
2154
+ componentsPageSource(project, {theme: slug}).source,
2155
+ ],
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});
670
2169
  }
671
2170
  preview.push({
672
2171
  rel: 'page.tsx',
673
- text: previewRouteSource({pages: data.pages, theme: routeTheme}),
2172
+ text: previewRouteSource({
2173
+ pages: data.pages,
2174
+ theme: routeTheme,
2175
+ by: `${PREVIEW} app`,
2176
+ }),
674
2177
  });
675
2178
  data.files = [...preview.map(x => x.rel), PREVIEW_DATA];
676
- 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)]));
677
2180
  const plan = planStarterApp(
678
2181
  cwd,
679
2182
  dir,
680
- overwrite,
681
2183
  () => [
682
2184
  ...themeCopy,
683
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
+ },
684
2190
  ],
685
2191
  dependencies,
2192
+ slug,
686
2193
  );
687
- const files = writeStarterApp(cwd, plan);
688
- const folder = shown(cwd, plan.root) || '.';
689
- /** @type {string[]} */
690
- const notes = [];
691
- if (plan.kept.length)
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
+ )
692
2206
  notes.push(
693
- `kept the app's own ${plan.kept.join(', ')}: the starter needs ${[...STARTER_DEPENDENCIES, ...Object.keys(dependencies)].join(', ')} in package.json`,
2207
+ `add "${folder}" to "exclude" in this project's tsconfig.json, so its own type check leaves the new app out`,
694
2208
  );
695
2209
  return {
696
2210
  type: 'themeEdit.previewApp',
@@ -700,11 +2214,14 @@ export async function themeEditPreviewApp(dir, options = {}) {
700
2214
  pages: data.pages.map(x => x.id),
701
2215
  files,
702
2216
  notes,
703
- 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`,
704
2218
  },
705
2219
  };
706
2220
  }
707
2221
 
2222
+ /** The version range of an open font package the host project lacks. */
2223
+ const OPEN_FONT_RANGE = '^5.0.0';
2224
+
708
2225
  /**
709
2226
  * The installed version of a package, as the project resolves it.
710
2227
  * @param {import('./_project.mjs').ThemeProject} project
@@ -723,7 +2240,8 @@ function readVersion(project, pkg) {
723
2240
 
724
2241
  /**
725
2242
  * The pages of the in-app theme preview. With no preview, and with no
726
- * 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.
727
2245
  * @experimental
728
2246
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewListOptions} [options]
729
2247
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewListResponse>}
@@ -731,12 +2249,16 @@ function readVersion(project, pkg) {
731
2249
  export async function themeEditPreviewList(options = {}) {
732
2250
  const {cwd = process.cwd()} = options;
733
2251
  requireProject(cwd);
734
- const at = previewDir(cwd, options.path, {optional: true});
735
- 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);
736
2258
  return {
737
2259
  type: 'themeEdit.previewList',
738
2260
  data: {
739
- folder: at && data ? shown(cwd, at.dir) : null,
2261
+ folder: at && data ? shownDir(cwd, at.dir) : null,
740
2262
  theme: data?.theme ?? null,
741
2263
  pages: (data?.pages ?? []).map(x => ({id: x.id, label: x.label})),
742
2264
  },
@@ -745,8 +2267,9 @@ export async function themeEditPreviewList(options = {}) {
745
2267
 
746
2268
  /**
747
2269
  * Remove one page from the in-app theme preview, or with no page the whole
748
- * preview: only the files it wrote are deleted, and only inside the route
749
- * 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.
750
2273
  * @experimental
751
2274
  * @param {string} [page]
752
2275
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewListOptions} [options]
@@ -755,63 +2278,231 @@ export async function themeEditPreviewList(options = {}) {
755
2278
  export async function themeEditPreviewRemove(page, options = {}) {
756
2279
  const {cwd = process.cwd()} = options;
757
2280
  requireProject(cwd);
758
- const at = previewDir(cwd, options.path);
759
- 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);
760
2286
  if (!data)
761
2287
  refuse(
762
2288
  E.ERR_NOT_FOUND,
763
- `There is no theme preview in ${shown(cwd, at.dir)}/ (no ${PREVIEW_DATA}).`,
764
- {run: [`${PREVIEW} add`]},
2289
+ `There is no theme preview in ${shownDir(cwd, at.dir)}/ (no ${PREVIEW_DATA}).`,
2290
+ {run: [`${PREVIEW} add${pf}`]},
765
2291
  );
2292
+ const folder = shownDir(cwd, at.dir);
766
2293
  // theme-preview.json is a file anyone can edit: every path in it must
767
2294
  // stay in the route folder before anything is removed.
768
2295
  const inside = (/** @type {string} */ rel) =>
769
2296
  confined(path.join(at.dir, rel), at.dir, `${PREVIEW_DATA} names`);
770
2297
  for (const rel of data.files) inside(rel);
771
2298
  for (const p of data.pages) inside(`${p.file}.tsx`);
772
- /** @param {string} rel */
773
- const drop = rel => {
774
- const file = inside(rel);
775
- fs.rmSync(file, {force: true});
776
- return shown(cwd, file);
777
- };
778
- if (page != null && data.pages.length > 1) {
779
- 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());
780
2313
  if (!one)
781
2314
  refuse(E.ERR_NOT_FOUND, `The preview has no page "${page}".`, {
782
2315
  didYouMean: nearest(
783
- page,
2316
+ key.toLowerCase(),
784
2317
  data.pages.map(x => x.id),
785
2318
  ),
786
- run: [`${PREVIEW} list`],
2319
+ run: [`${PREVIEW} list${pf}`],
787
2320
  });
788
- data.pages = data.pages.filter(x => x !== one);
789
- 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);
790
2342
  data.files = data.files.filter(f => f !== rel);
791
- const removed = [drop(rel)];
792
- 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);
793
2419
  return {
794
2420
  type: 'themeEdit.previewRemove',
795
2421
  data: {
796
- folder: shown(cwd, at.dir),
797
- removed,
2422
+ folder,
2423
+ removed: deletes.map(r => shown(cwd, path.join(at.dir, r))),
2424
+ kept,
2425
+ missing,
2426
+ rewritten,
2427
+ notes,
798
2428
  pages: data.pages.map(x => x.id),
799
2429
  },
800
2430
  };
801
2431
  }
802
- if (page != null && !data.pages.some(x => x.id === page))
803
- refuse(E.ERR_NOT_FOUND, `The preview has no page "${page}".`, {
804
- run: [`${PREVIEW} list`],
805
- });
806
- const removed = data.files.map(drop);
807
- 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;
808
2450
  try {
809
- fs.rmdirSync(sub);
2451
+ st = fs.lstatSync(file);
810
2452
  } catch {
811
- // Not empty: something there is not the preview's.
2453
+ missing.push(shown(cwd, file));
2454
+ continue;
812
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
+ }
2503
+ if (data.theme) recordPreview(cwd, data.theme, at.dir, false);
813
2504
  return {
814
2505
  type: 'themeEdit.previewRemove',
815
- data: {folder: shown(cwd, at.dir), removed, pages: []},
2506
+ data: {folder, removed, kept, missing, rewritten: [], notes, pages: []},
816
2507
  };
817
2508
  }