@astryxdesign/cli 0.7.14 → 0.7.15-canary.g06b7e61
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.
- package/CHANGELOG.md +3 -3
- package/README.md +63 -63
- package/api/build/_adapter.d.mts +4 -0
- package/api/build/_adapter.mjs +28 -2
- package/api/build/blocks/blocks.d.mts +10 -1
- package/api/build/blocks/blocks.mjs +84 -7
- package/api/build/build.mjs +6 -1
- package/api/build/tree.d.mts +4 -0
- package/api/build/tree.mjs +9 -2
- package/api/doctor/_adapter.d.mts +3 -1
- package/api/doctor/_adapter.mjs +14 -1
- package/api/doctor/_authoring-audit.d.mts +42 -0
- package/api/doctor/_authoring-audit.mjs +106 -0
- package/api/doctor/doctor.d.mts +7 -0
- package/api/doctor/doctor.mjs +24 -39
- package/api/doctor/theme-checks.mjs +56 -21
- package/api/integration/add-helpers.mjs +5 -0
- package/api/integration/add-theme.mjs +15 -110
- package/api/integration/validate-integration.mjs +17 -3
- package/api/integration/validateIntegration.doc.mjs +1 -1
- package/api/search/_adapter.mjs +124 -3
- package/api/search/_candidate-score.mjs +63 -9
- package/api/search/_entries.d.mts +10 -0
- package/api/search/_entries.mjs +68 -1
- package/api/search/_gather-templates.d.mts +11 -0
- package/api/search/_gather-templates.mjs +22 -2
- package/api/search/_words.mjs +26 -6
- package/api/swizzle/copy/copy.mjs +1 -1
- package/api/theme/_adapter.d.mts +37 -5
- package/api/theme/_adapter.mjs +381 -57
- package/api/theme/_fork.d.mts +90 -0
- package/api/theme/_fork.mjs +246 -0
- package/api/theme/build/build.d.mts +40 -2
- package/api/theme/build/build.mjs +477 -66
- package/api/theme/eject/eject.mjs +36 -15
- package/api/theme/list/list.mjs +3 -6
- package/api/theme/palette/generate/generator.d.mts +13 -0
- package/api/theme/palette/generate/generator.mjs +32 -2
- package/api/theme/targets/targets.d.mts +8 -0
- package/api/theme/targets/targets.mjs +24 -4
- package/api/theme/template/template.mjs +48 -2
- package/api/theme/theme.type.d.mts +8 -0
- package/api/theme/theme.type.mjs +5 -1
- package/api/theme/themeBuild.doc.mjs +7 -4
- package/api/theme/themeEject.doc.mjs +3 -3
- package/api/theme/themeRemove.doc.mjs +5 -2
- package/api/theme/themeTargets.doc.mjs +1 -1
- package/api/theme/themeTemplate.doc.mjs +2 -2
- package/api/theme/themeUse.doc.mjs +8 -2
- package/api/theme-edit/_adapter.d.mts +46 -3
- package/api/theme-edit/_adapter.mjs +496 -112
- package/api/theme-edit/_catalog.d.mts +1 -6
- package/api/theme-edit/_catalog.mjs +5 -268
- package/api/theme-edit/_check.d.mts +9 -4
- package/api/theme-edit/_check.mjs +1232 -229
- package/api/theme-edit/_color.d.mts +19 -0
- package/api/theme-edit/_color.mjs +280 -34
- package/api/theme-edit/_compiler.d.mts +3 -1
- package/api/theme-edit/_compiler.mjs +52 -13
- package/api/theme-edit/_context.d.mts +4 -1
- package/api/theme-edit/_context.mjs +126 -13
- package/api/theme-edit/_css.d.mts +84 -0
- package/api/theme-edit/_css.mjs +700 -0
- package/api/theme-edit/_edit.d.mts +9 -3
- package/api/theme-edit/_edit.mjs +806 -103
- package/api/theme-edit/_how-commands.d.mts +38 -7
- package/api/theme-edit/_how-commands.mjs +64 -45
- package/api/theme-edit/_how-question.d.mts +33 -0
- package/api/theme-edit/_how-question.mjs +2553 -381
- package/api/theme-edit/_how.mjs +402 -31
- package/api/theme-edit/_overview.mjs +2 -7
- package/api/theme-edit/_palette.d.mts +60 -13
- package/api/theme-edit/_palette.mjs +826 -295
- package/api/theme-edit/_parts.d.mts +42 -10
- package/api/theme-edit/_parts.mjs +280 -69
- package/api/theme-edit/_png.d.mts +4 -4
- package/api/theme-edit/_png.mjs +4 -2
- package/api/theme-edit/_preview-app.d.mts +14 -0
- package/api/theme-edit/_preview-app.mjs +1675 -235
- package/api/theme-edit/_preview.d.mts +7 -16
- package/api/theme-edit/_preview.mjs +79 -86
- package/api/theme-edit/_project.d.mts +32 -2
- package/api/theme-edit/_project.mjs +80 -19
- package/api/theme-edit/_settings.d.mts +199 -52
- package/api/theme-edit/_settings.mjs +1422 -217
- package/api/theme-edit/_tables.d.mts +19 -6
- package/api/theme-edit/_tables.mjs +150 -92
- package/api/theme-edit/theme-edit.type.d.mts +20 -1
- package/api/theme-edit/theme-edit.type.mjs +6 -3
- package/api/theme-edit/themeEditHow.doc.mjs +6 -0
- package/api/theme-edit/themeEditNew.doc.mjs +1 -1
- package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
- package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
- package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
- package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
- package/api/theme-edit/themeEditSet.doc.mjs +1 -1
- package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
- package/api/upgrade/_adapter.d.mts +1 -0
- package/assets/codemods/run-codemod.mjs +61 -0
- package/assets/codemods/runner.mjs +5 -4
- package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
- package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
- package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
- package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
- package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
- package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
- package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
- package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
- package/assets/docs/tree/calendars.doc.mjs +1 -3
- package/assets/docs/tree/checks.doc.mjs +22 -1
- package/assets/docs/tree/publishing.doc.mjs +1 -0
- package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
- package/assets/docs.generated.json +2 -1
- package/assets/preview-app/next.config.mjs +7 -1
- package/assets/self-audit.generated.json +1 -0
- package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
- package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
- package/assets/templates/components.generated.json +1 -1
- package/authoring/integration/integration.doc.mjs +8 -0
- package/authoring/integration/schema.d.mts +8 -0
- package/authoring/integration/schema.mjs +1 -0
- package/authoring/integration/type.ts +9 -0
- package/clients/cli/bin/astryx.mjs +19 -15
- package/clients/cli/build-id.generated.json +1 -0
- package/clients/cli/commands/ensure-core-built.mjs +12 -5
- package/clients/cli/commands/experimental/index.mjs +10 -10
- package/clients/cli/commands/experimental/theme.mjs +200 -81
- package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
- package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
- package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
- package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
- package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
- package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
- package/clients/cli/commands/integration.mjs +8 -0
- package/clients/cli/commands/manifest.mjs +5 -2
- package/clients/cli/commands/theme-build.doc.mjs +2 -2
- package/clients/cli/commands/theme-list.doc.mjs +1 -1
- package/clients/cli/commands/theme-template.doc.mjs +1 -1
- package/clients/cli/commands/theme.mjs +439 -66
- package/clients/cli/index.mjs +27 -6
- package/clients/cli/lib/cli-error.mjs +118 -3
- package/clients/cli/lib/manifest.mjs +37 -0
- package/clients/cli/lib/resolve-theme.mjs +2 -1
- package/clients/cli/manifest.generated.json +1 -0
- package/foundation/config/project.mjs +34 -8
- package/foundation/config/theme-state.d.mts +16 -0
- package/foundation/config/theme-state.mjs +84 -13
- package/foundation/discovery/module-exports.mjs +16 -2
- package/foundation/discovery/stored-self-audit.d.mts +31 -0
- package/foundation/discovery/stored-self-audit.mjs +119 -0
- package/foundation/discovery/template-adapter.d.mts +48 -2
- package/foundation/discovery/template-adapter.mjs +51 -19
- package/foundation/discovery/template-needs.d.mts +19 -0
- package/foundation/discovery/template-needs.mjs +50 -16
- package/foundation/discovery/template-source-tree.d.mts +7 -0
- package/foundation/discovery/template-source-tree.mjs +15 -0
- package/foundation/discovery/theme-discovery.d.mts +2 -1
- package/foundation/discovery/theme-discovery.mjs +16 -10
- package/foundation/discovery/theme-imports.d.mts +16 -0
- package/foundation/discovery/theme-imports.mjs +30 -2
- package/foundation/discovery/theme-module-extensions.d.mts +18 -0
- package/foundation/discovery/theme-module-extensions.mjs +30 -0
- package/foundation/doc-compiler/import.mjs +22 -15
- package/foundation/doc-compiler/stored-docs.d.mts +18 -12
- package/foundation/doc-compiler/stored-docs.mjs +52 -19
- package/foundation/env/private-dir.d.mts +17 -0
- package/foundation/env/private-dir.mjs +42 -0
- package/foundation/fs/gather-cache.d.mts +108 -0
- package/foundation/fs/gather-cache.mjs +783 -0
- package/foundation/fs/jiti-cache.d.mts +21 -0
- package/foundation/fs/jiti-cache.mjs +66 -0
- package/foundation/fs/module-loader.mjs +14 -3
- package/foundation/fs/read-record.d.mts +31 -1
- package/foundation/fs/read-record.mjs +100 -7
- package/foundation/integrations/autolink.d.mts +1 -24
- package/foundation/integrations/autolink.mjs +7 -60
- package/foundation/integrations/declared-dependencies.d.mts +27 -0
- package/foundation/integrations/declared-dependencies.mjs +73 -0
- package/foundation/integrations/integrations.d.mts +8 -0
- package/foundation/integrations/integrations.mjs +4 -0
- package/foundation/integrations/may-have-integrations.d.mts +8 -0
- package/foundation/integrations/may-have-integrations.mjs +47 -0
- package/foundation/integrations/validate-contributions.d.mts +62 -1
- package/foundation/integrations/validate-contributions.mjs +476 -40
- package/foundation/release/cache.d.mts +32 -4
- package/foundation/release/cache.mjs +105 -16
- package/foundation/release/folder-lock.d.mts +28 -0
- package/foundation/release/folder-lock.mjs +205 -0
- package/foundation/release/lock-lease.d.mts +2 -1
- package/foundation/release/lock-lease.mjs +7 -2
- package/foundation/response/error-codes.doc.mjs +1 -1
- package/foundation/response/response-types.doc.mjs +5 -5
- package/package.json +8 -6
- package/api/theme-edit/_css-properties.d.mts +0 -10
- package/api/theme-edit/_css-properties.mjs +0 -556
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* @position api/theme-edit — imported only by _adapter.mjs
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import {
|
|
13
|
+
import {parse as parseModule} from '@babel/parser';
|
|
14
14
|
import * as fs from 'node:fs';
|
|
15
15
|
import * as path from 'node:path';
|
|
16
16
|
import {fileURLToPath} from 'node:url';
|
|
@@ -20,15 +20,20 @@ import {
|
|
|
20
20
|
assertWithin,
|
|
21
21
|
PathSafetyError,
|
|
22
22
|
} from '../../foundation/fs/path-safety.mjs';
|
|
23
|
-
import {baseResolved, openProject} from './_project.mjs';
|
|
23
|
+
import {baseResolved, installLine, openProject} from './_project.mjs';
|
|
24
|
+
import {P} from './_tables.mjs';
|
|
24
25
|
import {
|
|
26
|
+
buildTheme,
|
|
27
|
+
editedThemes,
|
|
28
|
+
fontPackages,
|
|
25
29
|
loadTheme,
|
|
30
|
+
modesOf,
|
|
26
31
|
nearest,
|
|
27
32
|
refuse,
|
|
28
33
|
shown,
|
|
34
|
+
staleBuild,
|
|
29
35
|
themeFiles,
|
|
30
|
-
|
|
31
|
-
fontPackages,
|
|
36
|
+
windowsReserved,
|
|
32
37
|
} from './_settings.mjs';
|
|
33
38
|
import {
|
|
34
39
|
colorsPageSource,
|
|
@@ -38,10 +43,12 @@ import {
|
|
|
38
43
|
themeImports,
|
|
39
44
|
} from './_preview.mjs';
|
|
40
45
|
import {
|
|
46
|
+
PALETTE_STAND_IN,
|
|
41
47
|
paletteFiles,
|
|
42
48
|
paletteMapping,
|
|
43
49
|
tempFor,
|
|
44
50
|
writeWhole,
|
|
51
|
+
refuseIfLockLost,
|
|
45
52
|
} from './_palette.mjs';
|
|
46
53
|
import {build} from '../build/build.mjs';
|
|
47
54
|
import {search} from '../search/search.mjs';
|
|
@@ -53,6 +60,9 @@ import {
|
|
|
53
60
|
import {detectStylingSystem} from '../../foundation/agent-docs/agent-docs.mjs';
|
|
54
61
|
import {requireProject, context} from './_context.mjs';
|
|
55
62
|
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
|
|
63
|
+
import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
|
|
64
|
+
import {sha256} from '../../foundation/render/source-block.mjs';
|
|
65
|
+
import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
|
|
56
66
|
|
|
57
67
|
const E = ERROR_CODES;
|
|
58
68
|
|
|
@@ -85,16 +95,6 @@ const MAX_WORDS = 40;
|
|
|
85
95
|
const shownDir = (/** @type {string} */ cwd, /** @type {string} */ dir) =>
|
|
86
96
|
shown(cwd, dir) || '.';
|
|
87
97
|
|
|
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
98
|
/**
|
|
99
99
|
* Refuse a folder name that this platform would take literally in a way the
|
|
100
100
|
* caller did not mean: Windows separators or a drive letter on POSIX, a `~`
|
|
@@ -134,11 +134,255 @@ function checkFolderName(where, what, retry) {
|
|
|
134
134
|
);
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
/**
|
|
138
|
+
* A note when the app never imports Core's stylesheet, or null: without
|
|
139
|
+
* it, components render unstyled, and some show nothing. Read from the
|
|
140
|
+
* files of the routes folder and src/ (best effort).
|
|
141
|
+
* @param {string} cwd
|
|
142
|
+
* @param {{dir: string, app: string | null}} at
|
|
143
|
+
* @returns {string | null}
|
|
144
|
+
*/
|
|
145
|
+
function coreStylesheetMissing(cwd, at) {
|
|
146
|
+
if (!at.app) return null;
|
|
147
|
+
const SHEET = /@astryxdesign\/core\/astryx\.css/;
|
|
148
|
+
let seen = 0;
|
|
149
|
+
/** @param {string} folder @returns {boolean} */
|
|
150
|
+
const imports = folder => {
|
|
151
|
+
/** @type {fs.Dirent[]} */
|
|
152
|
+
let entries;
|
|
153
|
+
try {
|
|
154
|
+
entries = fs.readdirSync(folder, {withFileTypes: true});
|
|
155
|
+
} catch {
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
for (const e of entries) {
|
|
159
|
+
const full = path.join(folder, e.name);
|
|
160
|
+
if (e.isDirectory()) {
|
|
161
|
+
if (
|
|
162
|
+
e.name === 'node_modules' ||
|
|
163
|
+
e.name.startsWith('.') ||
|
|
164
|
+
full === at.dir
|
|
165
|
+
)
|
|
166
|
+
continue;
|
|
167
|
+
if (imports(full)) return true;
|
|
168
|
+
} else if (
|
|
169
|
+
/\.(tsx|ts|jsx|js|mjs|css|scss)$/.test(e.name) &&
|
|
170
|
+
++seen < 2000
|
|
171
|
+
)
|
|
172
|
+
try {
|
|
173
|
+
if (SHEET.test(fs.readFileSync(full, 'utf8'))) return true;
|
|
174
|
+
} catch {
|
|
175
|
+
// Unreadable: skip it.
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return false;
|
|
179
|
+
};
|
|
180
|
+
const src = path.join(cwd, 'src');
|
|
181
|
+
if (
|
|
182
|
+
imports(at.app) ||
|
|
183
|
+
(at.app.startsWith(src + path.sep) ? false : imports(src))
|
|
184
|
+
)
|
|
185
|
+
return null;
|
|
186
|
+
const layout = ['tsx', 'ts', 'jsx', 'js']
|
|
187
|
+
.map(x => path.join(at.app ?? '', `layout.${x}`))
|
|
188
|
+
.find(f => fs.existsSync(f));
|
|
189
|
+
return `the app does not import Core's stylesheet, so the preview's components render unstyled and some show nothing; add import '@astryxdesign/core/astryx.css'; to ${layout ? shown(cwd, layout) : "the app's root layout"}`;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* What next.config sets, read from its syntax tree: `pageExtensions`,
|
|
194
|
+
* `basePath` and `distDir`, each a literal value, `undefined` when it is
|
|
195
|
+
* not set, or `null` when it is set in a way only running the config tells
|
|
196
|
+
* (a spread, a function config, a value from code). Comments say nothing.
|
|
197
|
+
* @param {string} cwd
|
|
198
|
+
* @returns {{file: string | null, pageExtensions: string[] | null | undefined, basePath: string | null | undefined, distDir: string | null | undefined}}
|
|
199
|
+
*/
|
|
200
|
+
function readNextConfig(cwd) {
|
|
201
|
+
const none = {
|
|
202
|
+
file: null,
|
|
203
|
+
pageExtensions: undefined,
|
|
204
|
+
basePath: undefined,
|
|
205
|
+
distDir: undefined,
|
|
206
|
+
};
|
|
207
|
+
for (const name of [
|
|
208
|
+
'next.config.mjs',
|
|
209
|
+
'next.config.js',
|
|
210
|
+
'next.config.ts',
|
|
211
|
+
'next.config.cjs',
|
|
212
|
+
]) {
|
|
213
|
+
/** @type {string} */
|
|
214
|
+
let text;
|
|
215
|
+
try {
|
|
216
|
+
text = fs.readFileSync(path.join(cwd, name), 'utf8');
|
|
217
|
+
} catch {
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
const unknown = {
|
|
221
|
+
file: name,
|
|
222
|
+
pageExtensions: null,
|
|
223
|
+
basePath: null,
|
|
224
|
+
distDir: null,
|
|
225
|
+
};
|
|
226
|
+
/** @type {any} */
|
|
227
|
+
let file;
|
|
228
|
+
try {
|
|
229
|
+
file = parseModule(text, {
|
|
230
|
+
sourceType: 'unambiguous',
|
|
231
|
+
plugins: ['typescript'],
|
|
232
|
+
errorRecovery: true,
|
|
233
|
+
});
|
|
234
|
+
} catch {
|
|
235
|
+
return unknown;
|
|
236
|
+
}
|
|
237
|
+
const body = /** @type {any[]} */ (file.program.body);
|
|
238
|
+
/** Top-level constants, by name. @type {Map<string, any>} */
|
|
239
|
+
const consts = new Map();
|
|
240
|
+
for (const st of body)
|
|
241
|
+
if (st.type === 'VariableDeclaration' && st.kind === 'const')
|
|
242
|
+
for (const d of st.declarations)
|
|
243
|
+
if (d.id?.type === 'Identifier' && d.init)
|
|
244
|
+
consts.set(d.id.name, d.init);
|
|
245
|
+
/** @param {any} n @param {number} depth @returns {any} */
|
|
246
|
+
const resolve = (n, depth = 0) => {
|
|
247
|
+
while (
|
|
248
|
+
n &&
|
|
249
|
+
/^TS(As|Satisfies|NonNull)Expression$|^ParenthesizedExpression$/.test(
|
|
250
|
+
n.type,
|
|
251
|
+
)
|
|
252
|
+
)
|
|
253
|
+
n = n.expression;
|
|
254
|
+
if (n?.type === 'Identifier' && depth < 4 && consts.has(n.name))
|
|
255
|
+
return resolve(consts.get(n.name), depth + 1);
|
|
256
|
+
return n;
|
|
257
|
+
};
|
|
258
|
+
/** The config object: exported, or passed to a wrapper such as withX(config). @param {any} n @returns {any} */
|
|
259
|
+
const configOf = n => {
|
|
260
|
+
n = resolve(n);
|
|
261
|
+
if (n?.type === 'ObjectExpression') return n;
|
|
262
|
+
if (n?.type === 'CallExpression')
|
|
263
|
+
for (const a of n.arguments) {
|
|
264
|
+
const o = configOf(a);
|
|
265
|
+
if (o) return o;
|
|
266
|
+
}
|
|
267
|
+
return null;
|
|
268
|
+
};
|
|
269
|
+
/** @type {any} */
|
|
270
|
+
let exported = null;
|
|
271
|
+
for (const st of body) {
|
|
272
|
+
if (st.type === 'ExportDefaultDeclaration') exported = st.declaration;
|
|
273
|
+
if (
|
|
274
|
+
st.type === 'ExpressionStatement' &&
|
|
275
|
+
st.expression.type === 'AssignmentExpression' &&
|
|
276
|
+
st.expression.left.type === 'MemberExpression' &&
|
|
277
|
+
st.expression.left.object?.name === 'module' &&
|
|
278
|
+
st.expression.left.property?.name === 'exports'
|
|
279
|
+
)
|
|
280
|
+
exported = st.expression.right;
|
|
281
|
+
}
|
|
282
|
+
const config = exported && configOf(exported);
|
|
283
|
+
if (!config) return exported ? unknown : none;
|
|
284
|
+
// The config's keys in order, with a spread of a constant object read
|
|
285
|
+
// in place; a spread of anything else may set any key (`null`).
|
|
286
|
+
/** @type {Array<{key: string, value: any} | null>} */
|
|
287
|
+
const entries = [];
|
|
288
|
+
/** @param {any} obj @param {number} depth */
|
|
289
|
+
const flatten = (obj, depth) => {
|
|
290
|
+
for (const x of obj.properties) {
|
|
291
|
+
if (x.type === 'SpreadElement') {
|
|
292
|
+
const inner = resolve(x.argument);
|
|
293
|
+
if (inner?.type === 'ObjectExpression' && depth < 4)
|
|
294
|
+
flatten(inner, depth + 1);
|
|
295
|
+
else entries.push(null);
|
|
296
|
+
} else if (
|
|
297
|
+
(x.type === 'ObjectProperty' || x.type === 'ObjectMethod') &&
|
|
298
|
+
!x.computed
|
|
299
|
+
)
|
|
300
|
+
entries.push({key: x.key.name ?? x.key.value, value: x.value});
|
|
301
|
+
else entries.push(null);
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
flatten(config, 0);
|
|
305
|
+
/** The entry that sets a key last; null when an unreadable spread may; undefined when nothing does. @param {string} key */
|
|
306
|
+
const prop = key => {
|
|
307
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
308
|
+
const e = entries[i];
|
|
309
|
+
if (e === null) return null;
|
|
310
|
+
if (e.key === key) return e;
|
|
311
|
+
}
|
|
312
|
+
return undefined;
|
|
313
|
+
};
|
|
314
|
+
/** @param {any} n @returns {string | null} */
|
|
315
|
+
const str = n => {
|
|
316
|
+
n = resolve(n);
|
|
317
|
+
if (n?.type === 'StringLiteral') return n.value;
|
|
318
|
+
if (n?.type === 'TemplateLiteral' && !n.expressions.length)
|
|
319
|
+
return n.quasis[0].value.cooked;
|
|
320
|
+
return null;
|
|
321
|
+
};
|
|
322
|
+
/** @param {string} key @param {(n: any) => any} read */
|
|
323
|
+
const value = (key, read) => {
|
|
324
|
+
const p = prop(key);
|
|
325
|
+
return p ? read(p.value) : p;
|
|
326
|
+
};
|
|
327
|
+
return {
|
|
328
|
+
file: name,
|
|
329
|
+
pageExtensions: value('pageExtensions', n => {
|
|
330
|
+
n = resolve(n);
|
|
331
|
+
if (n?.type !== 'ArrayExpression') return null;
|
|
332
|
+
const out = n.elements.map((/** @type {any} */ e) => str(e));
|
|
333
|
+
return out.every((/** @type {any} */ e) => e != null) ? out : null;
|
|
334
|
+
}),
|
|
335
|
+
basePath: value('basePath', n => {
|
|
336
|
+
const v = str(n);
|
|
337
|
+
return v == null ? null : v.replace(/\/+$/, '');
|
|
338
|
+
}),
|
|
339
|
+
distDir: value('distDir', n => {
|
|
340
|
+
const v = str(n);
|
|
341
|
+
return v == null
|
|
342
|
+
? null
|
|
343
|
+
: (v.replace(/^\.?\//, '').split('/')[0] ?? null);
|
|
344
|
+
}),
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
return none;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The `basePath` next.config sets: '' when it sets none, null when only
|
|
352
|
+
* running the config tells. Every URL of the app starts with it.
|
|
353
|
+
* @param {string} cwd
|
|
354
|
+
* @returns {string | null}
|
|
355
|
+
*/
|
|
356
|
+
function nextBasePath(cwd) {
|
|
357
|
+
const v = readNextConfig(cwd).basePath;
|
|
358
|
+
return v === undefined ? '' : v;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Notes on next.config values the preview depends on that only running
|
|
363
|
+
* the config tells: the page extensions (the route is page.tsx) and the
|
|
364
|
+
* base path of its URL.
|
|
365
|
+
* @param {string} cwd
|
|
366
|
+
* @returns {string[]}
|
|
367
|
+
*/
|
|
368
|
+
function nextConfigNotes(cwd) {
|
|
369
|
+
const c = readNextConfig(cwd);
|
|
370
|
+
/** @type {string[]} */
|
|
371
|
+
const notes = [];
|
|
372
|
+
if (c.pageExtensions === null)
|
|
373
|
+
notes.push(
|
|
374
|
+
`${c.file} sets pageExtensions in a way only running it tells; the preview's route is page.tsx, so "tsx" must be in it`,
|
|
375
|
+
);
|
|
376
|
+
return notes;
|
|
377
|
+
}
|
|
378
|
+
|
|
137
379
|
/**
|
|
138
380
|
* Why a folder is no place for files this command writes, or null: themes
|
|
139
381
|
* live in themes/ (and a preview app's whole tree would ship with the
|
|
140
|
-
* theme), packages in node_modules/,
|
|
141
|
-
*
|
|
382
|
+
* theme), packages in node_modules/, Next empties its build folder
|
|
383
|
+
* (`.next/`, `out/` or the `distDir` next.config names) on every build,
|
|
384
|
+
* and Next serves every file under a Pages Router folder (`pages/` or
|
|
385
|
+
* `src/pages/`) as a page.
|
|
142
386
|
* @param {string} cwd
|
|
143
387
|
* @param {string} dir
|
|
144
388
|
*/
|
|
@@ -148,6 +392,16 @@ function reservedFolder(cwd, dir) {
|
|
|
148
392
|
return 'themes/ holds the themes, and everything in a theme folder is copied with the theme';
|
|
149
393
|
if (segs.includes('node_modules'))
|
|
150
394
|
return 'node_modules/ belongs to the package manager, which replaces it';
|
|
395
|
+
if (segs[0] === 'public')
|
|
396
|
+
return 'Next serves every file in public/ as it is, at the site root, so anyone could download it';
|
|
397
|
+
const built = [
|
|
398
|
+
...new Set(['.next', 'out', readNextConfig(cwd).distDir]),
|
|
399
|
+
].find(d => d && segs[0] === d);
|
|
400
|
+
if (built)
|
|
401
|
+
return `${built}/ is where Next writes its build, and the next build empties it`;
|
|
402
|
+
const odd = segs.find(seg => windowsReserved(seg) || /^\.+$/.test(seg));
|
|
403
|
+
if (odd)
|
|
404
|
+
return `${odd} is a name Windows does not allow for a folder, so the project could not be checked out there`;
|
|
151
405
|
if (segs[0] === 'pages' || (segs[0] === 'src' && segs[1] === 'pages'))
|
|
152
406
|
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
407
|
return null;
|
|
@@ -170,11 +424,273 @@ function unroutedSegment(app, dir) {
|
|
|
170
424
|
: null;
|
|
171
425
|
}
|
|
172
426
|
|
|
427
|
+
/**
|
|
428
|
+
* The URL a folder of the routes folder is served at, with route groups
|
|
429
|
+
* dropped, as path segments.
|
|
430
|
+
* @param {string} app
|
|
431
|
+
* @param {string} dir
|
|
432
|
+
*/
|
|
433
|
+
const urlSegments = (app, dir) =>
|
|
434
|
+
path
|
|
435
|
+
.relative(app, dir)
|
|
436
|
+
.split(path.sep)
|
|
437
|
+
.filter(seg => seg && !/^\(.*\)$/.test(seg));
|
|
438
|
+
|
|
439
|
+
/** An optional catch-all route folder, `[[...slug]]`: it also serves its parent folder's URL (a required `[...slug]` does not). */
|
|
440
|
+
const CATCH_ALL = /^\[\[\.\.\.[^\]]+\]\]$/;
|
|
441
|
+
|
|
442
|
+
/** A file Next serves a URL from: a page or a route handler. */
|
|
443
|
+
const ROUTE_FILE = /^(page\.(tsx|ts|jsx|js|mdx)|route\.(tsx|ts|jsx|js))$/;
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* A page or route handler of the app that Next serves at the same URL as
|
|
447
|
+
* `dir`, or null: beside the preview, Next refuses to build (a route and a
|
|
448
|
+
* page), or the preview takes that URL from it.
|
|
449
|
+
* @param {string} cwd
|
|
450
|
+
* @param {string} app the routes folder
|
|
451
|
+
* @param {string} dir
|
|
452
|
+
*/
|
|
453
|
+
function sameUrlPage(cwd, app, dir) {
|
|
454
|
+
const url = urlSegments(app, dir).join('/');
|
|
455
|
+
/** @param {string} folder @returns {string | null} */
|
|
456
|
+
const walk = folder => {
|
|
457
|
+
/** @type {fs.Dirent[]} */
|
|
458
|
+
let entries;
|
|
459
|
+
try {
|
|
460
|
+
entries = fs.readdirSync(folder, {withFileTypes: true});
|
|
461
|
+
} catch {
|
|
462
|
+
return null;
|
|
463
|
+
}
|
|
464
|
+
for (const e of entries) {
|
|
465
|
+
const full = path.join(folder, e.name);
|
|
466
|
+
if (e.isDirectory()) {
|
|
467
|
+
if (/^[_@]/.test(e.name) || e.name === 'node_modules' || full === dir)
|
|
468
|
+
continue;
|
|
469
|
+
const hit = walk(full);
|
|
470
|
+
if (hit) return hit;
|
|
471
|
+
} else if (ROUTE_FILE.test(e.name) && servesUrl(folder)) return full;
|
|
472
|
+
}
|
|
473
|
+
return null;
|
|
474
|
+
};
|
|
475
|
+
/** A folder served at the URL, or at the URLs under it through a catch-all. @param {string} folder */
|
|
476
|
+
const servesUrl = folder => {
|
|
477
|
+
const segs = urlSegments(app, folder);
|
|
478
|
+
return (
|
|
479
|
+
segs.join('/') === url ||
|
|
480
|
+
(CATCH_ALL.test(segs.at(-1) ?? '') && segs.slice(0, -1).join('/') === url)
|
|
481
|
+
);
|
|
482
|
+
};
|
|
483
|
+
// The preview's own folder: a route handler, a page other than the
|
|
484
|
+
// page.tsx the preview writes, or a catch-all route in it.
|
|
485
|
+
try {
|
|
486
|
+
for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
|
|
487
|
+
if (!e.isDirectory()) {
|
|
488
|
+
if (ROUTE_FILE.test(e.name) && e.name !== 'page.tsx')
|
|
489
|
+
return path.join(dir, e.name);
|
|
490
|
+
} else if (CATCH_ALL.test(e.name))
|
|
491
|
+
for (const name of fs.readdirSync(path.join(dir, e.name)))
|
|
492
|
+
if (ROUTE_FILE.test(name)) return path.join(dir, e.name, name);
|
|
493
|
+
}
|
|
494
|
+
} catch {
|
|
495
|
+
// No folder yet.
|
|
496
|
+
}
|
|
497
|
+
const inApp = walk(app);
|
|
498
|
+
if (inApp) return inApp;
|
|
499
|
+
for (const pages of [path.join(cwd, 'pages'), path.join(cwd, 'src', 'pages')])
|
|
500
|
+
for (const ext of ['tsx', 'ts', 'jsx', 'js']) {
|
|
501
|
+
for (const f of [`${url}.${ext}`, `${url}/index.${ext}`]) {
|
|
502
|
+
const full = path.join(pages, f);
|
|
503
|
+
if (url && fs.existsSync(full)) return full;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* The folders that hold a root layout when the routes folder has none of
|
|
511
|
+
* its own: each route group with a layout (`(shop)/`, `(marketing)/`), or
|
|
512
|
+
* a `[locale]/` in an app with the locale in every URL. Empty when the
|
|
513
|
+
* routes folder has its own root layout.
|
|
514
|
+
* @param {string} app
|
|
515
|
+
* @returns {string[]}
|
|
516
|
+
*/
|
|
517
|
+
function nestedRootLayouts(app) {
|
|
518
|
+
const LAYOUT = /^layout\.(tsx|ts|jsx|js)$/;
|
|
519
|
+
if (fs.readdirSync(app).some(f => LAYOUT.test(f))) return [];
|
|
520
|
+
/** @type {string[]} */
|
|
521
|
+
const out = [];
|
|
522
|
+
/** A folder with a layout counts; a route group without one is looked into. @param {string} dir @param {boolean} top */
|
|
523
|
+
const look = (dir, top) => {
|
|
524
|
+
for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
|
|
525
|
+
if (!e.isDirectory()) continue;
|
|
526
|
+
const sub = path.join(dir, e.name);
|
|
527
|
+
const group = /^\(.+\)$/.test(e.name);
|
|
528
|
+
if (!top && !group) continue;
|
|
529
|
+
if (fs.readdirSync(sub).some(f => LAYOUT.test(f))) out.push(sub);
|
|
530
|
+
else if (group) look(sub, false);
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
look(app, true);
|
|
534
|
+
return out.sort();
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Refuse a folder where the preview would not be served as reported, or
|
|
539
|
+
* would break the app: one that holds the app itself, a reserved or
|
|
540
|
+
* unrouted folder, src/app/ while app/ is what Next serves, an app whose
|
|
541
|
+
* next.config names other page extensions, a folder outside the folder of
|
|
542
|
+
* the app's root layout, and a URL another page already has.
|
|
543
|
+
* @param {string} cwd
|
|
544
|
+
* @param {string} dir
|
|
545
|
+
* @param {string} where how the folder was given, for messages
|
|
546
|
+
* @param {Retry} retry
|
|
547
|
+
*/
|
|
548
|
+
function checkPlacement(cwd, dir, where, retry) {
|
|
549
|
+
const served = [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(
|
|
550
|
+
r => fs.existsSync(r) && fs.statSync(r).isDirectory(),
|
|
551
|
+
);
|
|
552
|
+
const fallback = retry(
|
|
553
|
+
served
|
|
554
|
+
? shown(cwd, path.join(served, 'theme-preview'))
|
|
555
|
+
: 'app/theme-preview',
|
|
556
|
+
);
|
|
557
|
+
if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory())
|
|
558
|
+
refuse(
|
|
559
|
+
E.ERR_INVALID_ARGUMENT,
|
|
560
|
+
`${where} is a file; the preview goes in a folder of its own.`,
|
|
561
|
+
{run: [retry(null)]},
|
|
562
|
+
);
|
|
563
|
+
if (holdsApp(cwd, dir)) {
|
|
564
|
+
const record = path.join(dir, PREVIEW_DATA);
|
|
565
|
+
/** @type {string | null} */
|
|
566
|
+
let damaged = null;
|
|
567
|
+
if (fs.existsSync(record))
|
|
568
|
+
try {
|
|
569
|
+
readPreview(cwd, dir);
|
|
570
|
+
} catch {
|
|
571
|
+
damaged = shown(cwd, record);
|
|
572
|
+
}
|
|
573
|
+
refuse(
|
|
574
|
+
E.ERR_INVALID_ARGUMENT,
|
|
575
|
+
damaged
|
|
576
|
+
? `${where} holds the app itself, and an older, damaged ${PREVIEW_DATA}.`
|
|
577
|
+
: fs.existsSync(record)
|
|
578
|
+
? `${where} holds an older theme preview, in a folder that holds the app itself; move its files into a folder of their own, then add the preview there.`
|
|
579
|
+
: `${where} is no place for the preview: the folder holds the app itself (its root, src/, a routes folder or a package.json), and the app does not serve a preview there.`,
|
|
580
|
+
damaged
|
|
581
|
+
? {
|
|
582
|
+
fix: `give ${damaged} another name (for example ${PREVIEW_DATA}.broken), then run ${PREVIEW} add`,
|
|
583
|
+
}
|
|
584
|
+
: {
|
|
585
|
+
run: fs.existsSync(record)
|
|
586
|
+
? [
|
|
587
|
+
`${PREVIEW} remove --path ${quoteCommandArgument(shownDir(cwd, dir))}`,
|
|
588
|
+
]
|
|
589
|
+
: [fallback],
|
|
590
|
+
},
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
const app = [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(r =>
|
|
594
|
+
dir.startsWith(r + path.sep),
|
|
595
|
+
);
|
|
596
|
+
const rootLayouts = served ? nestedRootLayouts(served) : [];
|
|
597
|
+
// The root layout above the folder, when the app has several (one per
|
|
598
|
+
// route group) or one in [locale]/.
|
|
599
|
+
const rootLayout =
|
|
600
|
+
rootLayouts.find(r => dir.startsWith(r + path.sep)) ?? null;
|
|
601
|
+
// A [param] folder that holds the root layout (an app with the locale in
|
|
602
|
+
// every URL) is where its pages go.
|
|
603
|
+
const unrouted =
|
|
604
|
+
app &&
|
|
605
|
+
unroutedSegment(
|
|
606
|
+
app,
|
|
607
|
+
rootLayout && dir.startsWith(rootLayout + path.sep)
|
|
608
|
+
? path.join(app, path.relative(rootLayout, dir))
|
|
609
|
+
: dir,
|
|
610
|
+
);
|
|
611
|
+
const why = reservedFolder(cwd, dir) ?? unrouted;
|
|
612
|
+
if (why)
|
|
613
|
+
refuse(
|
|
614
|
+
E.ERR_INVALID_ARGUMENT,
|
|
615
|
+
`${where} is no place for the preview: ${why}.`,
|
|
616
|
+
{run: [fallback]},
|
|
617
|
+
);
|
|
618
|
+
if (!app) return;
|
|
619
|
+
if (served && app !== served)
|
|
620
|
+
refuse(
|
|
621
|
+
E.ERR_INVALID_ARGUMENT,
|
|
622
|
+
`${where} is in ${shown(cwd, app)}/, and Next serves ${shown(cwd, served)}/ instead when both are there.`,
|
|
623
|
+
{
|
|
624
|
+
run: fs.existsSync(path.join(dir, PREVIEW_DATA))
|
|
625
|
+
? [
|
|
626
|
+
`${PREVIEW} remove --path ${quoteCommandArgument(shownDir(cwd, dir))}`,
|
|
627
|
+
]
|
|
628
|
+
: [fallback],
|
|
629
|
+
},
|
|
630
|
+
);
|
|
631
|
+
const exts = readNextConfig(cwd).pageExtensions;
|
|
632
|
+
if (exts && !exts.includes('tsx')) {
|
|
633
|
+
let free = 'theme-app';
|
|
634
|
+
for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
|
|
635
|
+
free = `theme-app-${n}`;
|
|
636
|
+
refuse(
|
|
637
|
+
E.ERR_INVALID_ARGUMENT,
|
|
638
|
+
`next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx, the route file the preview writes.`,
|
|
639
|
+
{
|
|
640
|
+
fix: 'add "tsx" to pageExtensions to use the preview in this app',
|
|
641
|
+
run: [
|
|
642
|
+
`${retry(shown(cwd, dir))} # once "tsx" is in pageExtensions`,
|
|
643
|
+
`${PREVIEW} app ${free} # or a new app of its own, with the preview`,
|
|
644
|
+
],
|
|
645
|
+
},
|
|
646
|
+
);
|
|
647
|
+
}
|
|
648
|
+
if (
|
|
649
|
+
served &&
|
|
650
|
+
!rootLayouts.length &&
|
|
651
|
+
!fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f))
|
|
652
|
+
) {
|
|
653
|
+
let free = 'theme-app';
|
|
654
|
+
for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
|
|
655
|
+
free = `theme-app-${n}`;
|
|
656
|
+
refuse(
|
|
657
|
+
E.ERR_INVALID_ARGUMENT,
|
|
658
|
+
`${shown(cwd, served)}/ has no root layout (no layout.tsx in it or in a route group), so Next cannot build a page in ${where}.`,
|
|
659
|
+
{
|
|
660
|
+
fix: `add a root layout to ${shown(cwd, served)}/ to use the preview in this app`,
|
|
661
|
+
run: [
|
|
662
|
+
`${PREVIEW} app ${free} # a new app with its own root layout and the preview`,
|
|
663
|
+
],
|
|
664
|
+
},
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
if (rootLayouts.length && !rootLayout)
|
|
668
|
+
refuse(
|
|
669
|
+
E.ERR_INVALID_ARGUMENT,
|
|
670
|
+
`${where} has no root layout above it: the app's root ${rootLayouts.length > 1 ? 'layouts are' : 'layout is'} in ${rootLayouts.map(r => `${shown(cwd, r)}/`).join(', ')}, so a page there would have no html, global CSS or providers.`,
|
|
671
|
+
{
|
|
672
|
+
run: rootLayouts.map(r =>
|
|
673
|
+
retry(shown(cwd, path.join(r, 'theme-preview'))),
|
|
674
|
+
),
|
|
675
|
+
},
|
|
676
|
+
);
|
|
677
|
+
const clash = sameUrlPage(cwd, app, dir);
|
|
678
|
+
if (clash) {
|
|
679
|
+
let free = `${dir}-2`;
|
|
680
|
+
for (let n = 3; fs.existsSync(free); n++) free = `${dir}-${n}`;
|
|
681
|
+
refuse(
|
|
682
|
+
E.ERR_FILE_EXISTS,
|
|
683
|
+
`${shown(cwd, clash)} already serves /${urlSegments(app, dir).join('/')} or the URLs under it, so a preview in ${where} would stop the app from building, or take that URL from it.`,
|
|
684
|
+
{run: [retry(shown(cwd, free))]},
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
173
689
|
/**
|
|
174
690
|
* Where the preview route lives. `--path` names it (inside the project);
|
|
175
691
|
* 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
|
|
177
|
-
*
|
|
692
|
+
* a theme recorded elsewhere (`retry` given); else the routes folder Next
|
|
693
|
+
* serves (`app/`, else `src/app/`).
|
|
178
694
|
* @param {string} cwd
|
|
179
695
|
* @param {string | undefined} where
|
|
180
696
|
* @param {{optional?: boolean, write?: boolean, retry?: Retry}} [opts]
|
|
@@ -186,7 +702,8 @@ function unroutedSegment(app, dir) {
|
|
|
186
702
|
function previewDir(cwd, where, opts = {}) {
|
|
187
703
|
const retry =
|
|
188
704
|
opts.retry ??
|
|
189
|
-
(p =>
|
|
705
|
+
(p =>
|
|
706
|
+
`${PREVIEW} list${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`);
|
|
190
707
|
const routes = ['app', path.join('src', 'app')]
|
|
191
708
|
.map(r => path.join(cwd, r))
|
|
192
709
|
.filter(r => fs.existsSync(r) && fs.statSync(r).isDirectory());
|
|
@@ -210,51 +727,7 @@ function previewDir(cwd, where, opts = {}) {
|
|
|
210
727
|
);
|
|
211
728
|
throw e;
|
|
212
729
|
}
|
|
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
|
-
}
|
|
730
|
+
if (opts.write) checkPlacement(cwd, dir, `--path ${where}`, retry);
|
|
258
731
|
return {dir, app: appOf(dir)};
|
|
259
732
|
}
|
|
260
733
|
const candidates = routes.map(r => path.join(r, 'theme-preview'));
|
|
@@ -265,8 +738,12 @@ function previewDir(cwd, where, opts = {}) {
|
|
|
265
738
|
const recorded = [
|
|
266
739
|
...new Set(editedThemes(cwd).flatMap(t => recordedPreviews(cwd, t))),
|
|
267
740
|
].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
|
|
268
|
-
if (recorded.length === 1)
|
|
741
|
+
if (recorded.length === 1) {
|
|
742
|
+
inProjectOrRefuse(cwd, recorded[0], retry);
|
|
743
|
+
if (opts.write)
|
|
744
|
+
checkPlacement(cwd, recorded[0], shownDir(cwd, recorded[0]), retry);
|
|
269
745
|
return {dir: recorded[0], app: appOf(recorded[0])};
|
|
746
|
+
}
|
|
270
747
|
if (recorded.length > 1)
|
|
271
748
|
refuse(
|
|
272
749
|
E.ERR_INVALID_ARGUMENT,
|
|
@@ -278,17 +755,16 @@ function previewDir(cwd, where, opts = {}) {
|
|
|
278
755
|
const older = [cwd, path.join(cwd, 'src')].find(d =>
|
|
279
756
|
fs.existsSync(path.join(d, PREVIEW_DATA)),
|
|
280
757
|
);
|
|
281
|
-
if (older
|
|
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
|
-
);
|
|
758
|
+
if (older) {
|
|
759
|
+
if (opts.write) checkPlacement(cwd, older, shownDir(cwd, older), retry);
|
|
288
760
|
return {dir: older, app: null};
|
|
289
761
|
}
|
|
290
762
|
}
|
|
291
|
-
|
|
763
|
+
// The routes folder Next serves: app/ when both app/ and src/app/ are there.
|
|
764
|
+
const served = routes[0];
|
|
765
|
+
const nested =
|
|
766
|
+
served && !known ? (nestedRootLayouts(served)[0] ?? null) : null;
|
|
767
|
+
const dir = known ?? (served && path.join(nested ?? served, 'theme-preview'));
|
|
292
768
|
if (!dir && opts.optional) return /** @type {any} */ (null);
|
|
293
769
|
if (!dir)
|
|
294
770
|
refuse(
|
|
@@ -296,14 +772,50 @@ function previewDir(cwd, where, opts = {}) {
|
|
|
296
772
|
'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
|
|
297
773
|
{
|
|
298
774
|
run: [
|
|
299
|
-
`${PREVIEW} add --path
|
|
300
|
-
`${PREVIEW} app
|
|
775
|
+
`${PREVIEW} add --path app/theme-preview # an app routes folder beside the app's own`,
|
|
776
|
+
`${PREVIEW} app theme-app # a new starter app with the preview in it`,
|
|
301
777
|
],
|
|
302
778
|
},
|
|
303
779
|
);
|
|
780
|
+
inProjectOrRefuse(cwd, dir, retry);
|
|
781
|
+
if (opts.write) checkPlacement(cwd, dir, `${shownDir(cwd, dir)}/`, retry);
|
|
304
782
|
return {dir, app: appOf(dir)};
|
|
305
783
|
}
|
|
306
784
|
|
|
785
|
+
/**
|
|
786
|
+
* Refuse a preview folder that reaches outside the project through a link,
|
|
787
|
+
* as `--path` refuses one: every file the preview writes would land there.
|
|
788
|
+
* @param {string} cwd
|
|
789
|
+
* @param {string} dir
|
|
790
|
+
* @param {Retry} retry
|
|
791
|
+
*/
|
|
792
|
+
function inProjectOrRefuse(cwd, dir, retry) {
|
|
793
|
+
/** @param {string} d */
|
|
794
|
+
const within = d => {
|
|
795
|
+
try {
|
|
796
|
+
assertWithin(d, cwd, {allowAbsolute: true, label: 'the preview folder'});
|
|
797
|
+
return true;
|
|
798
|
+
} catch (e) {
|
|
799
|
+
if (e instanceof PathSafetyError) return false;
|
|
800
|
+
throw e;
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
if (within(dir)) return;
|
|
804
|
+
let free = `${dir}-2`;
|
|
805
|
+
for (let n = 3; fs.existsSync(free); n++) free = `${dir}-${n}`;
|
|
806
|
+
refuse(
|
|
807
|
+
E.ERR_PATH_TRAVERSAL,
|
|
808
|
+
`${shownDir(cwd, dir)}/ leads outside the project through a link; the preview stays inside the folder you run the command from.`,
|
|
809
|
+
{
|
|
810
|
+
run: [
|
|
811
|
+
within(path.dirname(dir))
|
|
812
|
+
? retry(shown(cwd, free))
|
|
813
|
+
: `${PREVIEW} app theme-app # a new app of its own, inside this folder`,
|
|
814
|
+
],
|
|
815
|
+
},
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
|
|
307
819
|
const CLI_PACKAGE = path.resolve(
|
|
308
820
|
path.dirname(fileURLToPath(import.meta.url)),
|
|
309
821
|
'../..',
|
|
@@ -322,18 +834,26 @@ function confined(file, root, what) {
|
|
|
322
834
|
return assertWithin(file, root, {allowAbsolute: true, label: what});
|
|
323
835
|
} catch (e) {
|
|
324
836
|
if (e instanceof PathSafetyError) {
|
|
325
|
-
|
|
837
|
+
// The link that leads out: the file itself, or a folder on its way.
|
|
838
|
+
/** @type {{at: string, to: string} | null} */
|
|
326
839
|
let link = null;
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
840
|
+
for (
|
|
841
|
+
let at = file;
|
|
842
|
+
at.startsWith(root + path.sep) && !link;
|
|
843
|
+
at = path.dirname(at)
|
|
844
|
+
)
|
|
845
|
+
try {
|
|
846
|
+
if (fs.lstatSync(at).isSymbolicLink())
|
|
847
|
+
link = {at, to: fs.readlinkSync(at)};
|
|
848
|
+
} catch {
|
|
849
|
+
// Not there: look at its folder.
|
|
850
|
+
}
|
|
332
851
|
refuse(
|
|
333
852
|
E.ERR_PATH_TRAVERSAL,
|
|
334
853
|
link == null
|
|
335
|
-
? `${what} ${file} is outside ${root}.`
|
|
336
|
-
: `${
|
|
854
|
+
? `${what} names ${file}, which is outside ${root}.`
|
|
855
|
+
: `${link.at} is a link to ${link.to}, outside ${root}; the preview never writes through a link.`,
|
|
856
|
+
{run: [`${PREVIEW} list`]},
|
|
337
857
|
);
|
|
338
858
|
}
|
|
339
859
|
throw e;
|
|
@@ -383,7 +903,7 @@ export default function Home() {
|
|
|
383
903
|
*/
|
|
384
904
|
function planStarterApp(cwd, where, extra, dependencies, slug = null) {
|
|
385
905
|
const again = (/** @type {string | null} */ p) =>
|
|
386
|
-
`${PREVIEW} app ${
|
|
906
|
+
`${PREVIEW} app ${quoteCommandArgument(p ?? 'theme-app')}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`;
|
|
387
907
|
checkFolderName(where, 'The app folder', again);
|
|
388
908
|
/** @type {string} */
|
|
389
909
|
let root;
|
|
@@ -663,15 +1183,36 @@ function previewProblem(d) {
|
|
|
663
1183
|
*/
|
|
664
1184
|
function damagedPreview(cwd, dir, why, pf) {
|
|
665
1185
|
const folder = shownDir(cwd, dir);
|
|
1186
|
+
const record = `${folder}/${PREVIEW_DATA}`;
|
|
666
1187
|
refuse(
|
|
667
1188
|
E.ERR_THEME_INVALID,
|
|
668
|
-
`${
|
|
1189
|
+
`${record} 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
1190
|
{
|
|
670
|
-
fix:
|
|
1191
|
+
fix: holdsApp(cwd, dir)
|
|
1192
|
+
? `fix ${record} by hand, or give it another name (for example ${PREVIEW_DATA}.broken): the folder holds your app, so keep the folder as it is; then add the preview in its own folder with ${PREVIEW} add`
|
|
1193
|
+
: `fix ${record} 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
1194
|
},
|
|
672
1195
|
);
|
|
673
1196
|
}
|
|
674
1197
|
|
|
1198
|
+
/**
|
|
1199
|
+
* Whether a folder holds the app itself: the project root, src/, a routes
|
|
1200
|
+
* folder (app/ or src/app/), or any folder with a package.json. Nothing
|
|
1201
|
+
* the preview writes goes there, and nothing there is deleted on a record's
|
|
1202
|
+
* word alone.
|
|
1203
|
+
* @param {string} cwd
|
|
1204
|
+
* @param {string} dir
|
|
1205
|
+
*/
|
|
1206
|
+
function holdsApp(cwd, dir) {
|
|
1207
|
+
return (
|
|
1208
|
+
dir === cwd ||
|
|
1209
|
+
dir === path.join(cwd, 'src') ||
|
|
1210
|
+
dir === path.join(cwd, 'app') ||
|
|
1211
|
+
dir === path.join(cwd, 'src', 'app') ||
|
|
1212
|
+
fs.existsSync(path.join(dir, 'package.json'))
|
|
1213
|
+
);
|
|
1214
|
+
}
|
|
1215
|
+
|
|
675
1216
|
/**
|
|
676
1217
|
* The preview's data, null when the folder has none; a refusal when the
|
|
677
1218
|
* file is there but unreadable or of the wrong shape.
|
|
@@ -684,7 +1225,10 @@ function readPreview(cwd, dir, pf = '') {
|
|
|
684
1225
|
/** @type {string} */
|
|
685
1226
|
let text;
|
|
686
1227
|
try {
|
|
687
|
-
|
|
1228
|
+
// A byte-order mark (Notepad, PowerShell) is not part of the JSON.
|
|
1229
|
+
text = fs
|
|
1230
|
+
.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8')
|
|
1231
|
+
.replace(/^\uFEFF/, '');
|
|
688
1232
|
} catch (e) {
|
|
689
1233
|
const code = /** @type {any} */ (e)?.code;
|
|
690
1234
|
if (code === 'ENOENT' || code === 'ENOTDIR') return null;
|
|
@@ -709,16 +1253,254 @@ function readPreview(cwd, dir, pf = '') {
|
|
|
709
1253
|
}
|
|
710
1254
|
|
|
711
1255
|
/** A short hash of a file's text. @param {string | Buffer} text */
|
|
712
|
-
const digest = text =>
|
|
713
|
-
|
|
1256
|
+
const digest = text => sha256(Buffer.from(text)).slice(0, 16);
|
|
1257
|
+
|
|
1258
|
+
/**
|
|
1259
|
+
* A file's text as a formatter could have left it: white space outside
|
|
1260
|
+
* strings collapsed (and dropped next to punctuation), statement
|
|
1261
|
+
* semicolons and trailing commas dropped, and every string written with one
|
|
1262
|
+
* quote kind. The text inside strings, comments, template literals and
|
|
1263
|
+
* JSX text is kept, so a hand edit there always shows.
|
|
1264
|
+
* @param {string} text
|
|
1265
|
+
*/
|
|
1266
|
+
function formatterNeutral(text) {
|
|
1267
|
+
const PUNCT = /[{}()[\],;:<>=/.?!&|+*%^~-]/;
|
|
1268
|
+
// A quote starts a string after an operator, an opening bracket or one
|
|
1269
|
+
// of these words; elsewhere (JSX text such as "don't") it is plain text.
|
|
1270
|
+
const STRING_AFTER =
|
|
1271
|
+
/(?:^|[=({[,:;!&|?+<]|\b(?:from|import|return|case|in|of|typeof|export|default))$/;
|
|
1272
|
+
let out = '';
|
|
1273
|
+
let space = false;
|
|
1274
|
+
/** @param {string} t */
|
|
1275
|
+
const put = t => {
|
|
1276
|
+
if (space && out && !PUNCT.test(out.at(-1) ?? '') && !PUNCT.test(t[0]))
|
|
1277
|
+
out += ' ';
|
|
1278
|
+
space = false;
|
|
1279
|
+
out += t;
|
|
1280
|
+
};
|
|
1281
|
+
let i = 0;
|
|
1282
|
+
while (i < text.length) {
|
|
1283
|
+
const c = text[i];
|
|
1284
|
+
if (/\s/.test(c)) {
|
|
1285
|
+
space = true;
|
|
1286
|
+
i++;
|
|
1287
|
+
continue;
|
|
1288
|
+
}
|
|
1289
|
+
if (c === '/' && (text[i + 1] === '/' || text[i + 1] === '*')) {
|
|
1290
|
+
const end =
|
|
1291
|
+
text[i + 1] === '/'
|
|
1292
|
+
? text.indexOf('\n', i) === -1
|
|
1293
|
+
? text.length
|
|
1294
|
+
: text.indexOf('\n', i)
|
|
1295
|
+
: text.indexOf('*/', i + 2) === -1
|
|
1296
|
+
? text.length
|
|
1297
|
+
: text.indexOf('*/', i + 2) + 2;
|
|
1298
|
+
put(text.slice(i, end).replace(/\s+/g, ' ').trim());
|
|
1299
|
+
space = true;
|
|
1300
|
+
i = end;
|
|
1301
|
+
continue;
|
|
1302
|
+
}
|
|
1303
|
+
if ((c === '"' || c === "'") && STRING_AFTER.test(out.trimEnd())) {
|
|
1304
|
+
let j = i + 1;
|
|
1305
|
+
let body = '';
|
|
1306
|
+
while (j < text.length && text[j] !== c && text[j] !== '\n') {
|
|
1307
|
+
if (text[j] === '\\' && j + 1 < text.length) {
|
|
1308
|
+
const n = text[j + 1];
|
|
1309
|
+
body += n === '"' || n === "'" ? n : text.slice(j, j + 2);
|
|
1310
|
+
j += 2;
|
|
1311
|
+
} else body += text[j++];
|
|
1312
|
+
}
|
|
1313
|
+
if (text[j] === c) {
|
|
1314
|
+
put(`'${body.replace(/'/g, "\\'")}'`);
|
|
1315
|
+
i = j + 1;
|
|
1316
|
+
continue;
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
if (c === '`') {
|
|
1320
|
+
let j = i + 1;
|
|
1321
|
+
let depth = 0;
|
|
1322
|
+
while (j < text.length && !(text[j] === '`' && depth === 0)) {
|
|
1323
|
+
if (text[j] === '\\') j++;
|
|
1324
|
+
else if (text[j] === '$' && text[j + 1] === '{') depth++;
|
|
1325
|
+
else if (text[j] === '}' && depth > 0) depth--;
|
|
1326
|
+
j++;
|
|
1327
|
+
}
|
|
1328
|
+
put(text.slice(i, j + 1));
|
|
1329
|
+
i = j + 1;
|
|
1330
|
+
continue;
|
|
1331
|
+
}
|
|
1332
|
+
if (c === ';') {
|
|
1333
|
+
space = true;
|
|
1334
|
+
i++;
|
|
1335
|
+
continue;
|
|
1336
|
+
}
|
|
1337
|
+
if (c === ',') {
|
|
1338
|
+
let j = i + 1;
|
|
1339
|
+
while (j < text.length && /\s/.test(text[j])) j++;
|
|
1340
|
+
if (/[}\])]/.test(text[j] ?? '')) {
|
|
1341
|
+
i++;
|
|
1342
|
+
continue;
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
put(c);
|
|
1346
|
+
i++;
|
|
1347
|
+
}
|
|
1348
|
+
return out;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
/**
|
|
1352
|
+
* The hash recorded for a file the preview writes, of its formatter-neutral
|
|
1353
|
+
* text, so a formatter run (prettier, eslint --fix) does not count as a
|
|
1354
|
+
* change by hand while an edit inside a string does.
|
|
1355
|
+
* @param {string | Buffer} text
|
|
1356
|
+
*/
|
|
1357
|
+
const formatterHash = text => `v2:${digest(formatterNeutral(String(text)))}`;
|
|
1358
|
+
|
|
1359
|
+
/** Fields of a syntax tree node that say where or how it was written. */
|
|
1360
|
+
const LAYOUT = new Set([
|
|
1361
|
+
'start',
|
|
1362
|
+
'end',
|
|
1363
|
+
'loc',
|
|
1364
|
+
'range',
|
|
1365
|
+
'extra',
|
|
1366
|
+
'leadingComments',
|
|
1367
|
+
'trailingComments',
|
|
1368
|
+
'innerComments',
|
|
1369
|
+
'comments',
|
|
1370
|
+
'tokens',
|
|
1371
|
+
'errors',
|
|
1372
|
+
]);
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* The text a run of JSX text renders, as JSX reads it: lines trimmed where
|
|
1376
|
+
* they meet a line break, blank lines dropped, the rest joined by a space.
|
|
1377
|
+
* @param {string} value
|
|
1378
|
+
*/
|
|
1379
|
+
function jsxText(value) {
|
|
1380
|
+
const lines = value.split(/\r\n|\n|\r/);
|
|
1381
|
+
let last = 0;
|
|
1382
|
+
lines.forEach((l, i) => {
|
|
1383
|
+
if (/[^ \t]/.test(l)) last = i;
|
|
1384
|
+
});
|
|
1385
|
+
let out = '';
|
|
1386
|
+
lines.forEach((line, i) => {
|
|
1387
|
+
let t = line.replace(/\t/g, ' ');
|
|
1388
|
+
if (i !== 0) t = t.replace(/^ +/, '');
|
|
1389
|
+
if (i !== lines.length - 1) t = t.replace(/ +$/, '');
|
|
1390
|
+
if (t) out += i === last ? t : `${t} `;
|
|
1391
|
+
});
|
|
1392
|
+
return out;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/**
|
|
1396
|
+
* JSX children as they render: text and string expressions (`{" "}`) are
|
|
1397
|
+
* one run of text, and runs that render nothing are dropped, so a
|
|
1398
|
+
* formatter's line breaks and `{" "}` change nothing.
|
|
1399
|
+
* @param {any[]} children
|
|
1400
|
+
* @param {(node: any) => any} walk
|
|
1401
|
+
*/
|
|
1402
|
+
function jsxChildren(children, walk) {
|
|
1403
|
+
/** @type {any[]} */
|
|
1404
|
+
const out = [];
|
|
1405
|
+
for (const c of children ?? []) {
|
|
1406
|
+
const text =
|
|
1407
|
+
c.type === 'JSXText'
|
|
1408
|
+
? jsxText(c.value)
|
|
1409
|
+
: c.type === 'JSXExpressionContainer' &&
|
|
1410
|
+
c.expression?.type === 'StringLiteral'
|
|
1411
|
+
? c.expression.value
|
|
1412
|
+
: null;
|
|
1413
|
+
if (text == null) out.push(walk(c));
|
|
1414
|
+
else if (out.at(-1)?.type === 'Text') out.at(-1).value += text;
|
|
1415
|
+
else out.push({type: 'Text', value: text});
|
|
1416
|
+
}
|
|
1417
|
+
return out.filter(c => !(c.type === 'Text' && c.value === ''));
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
/**
|
|
1421
|
+
* A file's code in a form no formatter changes: its syntax tree, without
|
|
1422
|
+
* positions, parentheses, quote kinds, trailing commas or semicolons, with
|
|
1423
|
+
* object keys written the same quoted or bare, white space in JSX text
|
|
1424
|
+
* collapsed, and its comments by text. Null when it does not parse.
|
|
1425
|
+
* @param {string} text
|
|
1426
|
+
* @returns {string | null}
|
|
1427
|
+
*/
|
|
1428
|
+
function canonicalCode(text) {
|
|
1429
|
+
/** @type {any} */
|
|
1430
|
+
let file;
|
|
1431
|
+
try {
|
|
1432
|
+
file = parseModule(text, {
|
|
1433
|
+
sourceType: 'module',
|
|
1434
|
+
plugins: ['jsx', 'typescript'],
|
|
1435
|
+
errorRecovery: false,
|
|
1436
|
+
});
|
|
1437
|
+
} catch {
|
|
1438
|
+
return null;
|
|
1439
|
+
}
|
|
1440
|
+
/** @param {any} node @returns {any} */
|
|
1441
|
+
const walk = node => {
|
|
1442
|
+
if (Array.isArray(node)) return node.map(walk);
|
|
1443
|
+
if (!node || typeof node !== 'object') return node;
|
|
1444
|
+
/** @type {Record<string, any>} */
|
|
1445
|
+
const out = {};
|
|
1446
|
+
for (const [k, v] of Object.entries(node)) {
|
|
1447
|
+
if (LAYOUT.has(k)) continue;
|
|
1448
|
+
out[k] = walk(v);
|
|
1449
|
+
}
|
|
1450
|
+
// A key written "a" or a is the same key.
|
|
1451
|
+
if (
|
|
1452
|
+
(node.type === 'ObjectProperty' ||
|
|
1453
|
+
node.type === 'ObjectMethod' ||
|
|
1454
|
+
node.type === 'TSPropertySignature' ||
|
|
1455
|
+
node.type === 'ClassProperty') &&
|
|
1456
|
+
!node.computed &&
|
|
1457
|
+
node.key?.type === 'StringLiteral' &&
|
|
1458
|
+
/^[A-Za-z_$][\w$]*$/.test(node.key.value)
|
|
1459
|
+
)
|
|
1460
|
+
out.key = {type: 'Identifier', name: node.key.value};
|
|
1461
|
+
if (node.type === 'JSXElement' || node.type === 'JSXFragment')
|
|
1462
|
+
out.children = jsxChildren(node.children, walk);
|
|
1463
|
+
return out;
|
|
1464
|
+
};
|
|
1465
|
+
const comments = (file.comments ?? []).map((/** @type {any} */ c) =>
|
|
1466
|
+
c.value.replace(/\s+/g, ' ').trim(),
|
|
1467
|
+
);
|
|
1468
|
+
return JSON.stringify([walk(file.program), comments]);
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
/**
|
|
1472
|
+
* The hash recorded for a file the preview writes, of its code in a form no
|
|
1473
|
+
* formatter changes ({@link canonicalCode}), so prettier or eslint --fix
|
|
1474
|
+
* with any options does not count as a change by hand, while an edit to
|
|
1475
|
+
* code, a string or a comment does. A file that does not parse falls back
|
|
1476
|
+
* to the text form ({@link formatterNeutral}).
|
|
1477
|
+
* @param {string | Buffer} text
|
|
1478
|
+
*/
|
|
1479
|
+
const contentHash = text => {
|
|
1480
|
+
const code = canonicalCode(String(text));
|
|
1481
|
+
return code == null ? formatterHash(text) : `v3:${digest(code)}`;
|
|
1482
|
+
};
|
|
1483
|
+
|
|
1484
|
+
/**
|
|
1485
|
+
* Whether a file's text matches a recorded hash of any kind a release
|
|
1486
|
+
* wrote: v3 (syntax tree), v2 (text outside strings), or older.
|
|
1487
|
+
* @param {string | Buffer} text
|
|
1488
|
+
* @param {string} h
|
|
1489
|
+
*/
|
|
1490
|
+
const sameAsRecorded = (text, h) =>
|
|
1491
|
+
h.startsWith('v3:')
|
|
1492
|
+
? contentHash(text) === h
|
|
1493
|
+
: h.startsWith('v2:')
|
|
1494
|
+
? formatterHash(text) === h
|
|
1495
|
+
: oldContentHash(text) === h || digest(text) === h;
|
|
714
1496
|
|
|
715
1497
|
/**
|
|
716
|
-
* The hash
|
|
717
|
-
*
|
|
718
|
-
*
|
|
1498
|
+
* The normalized hash of an earlier release (white space, semicolons,
|
|
1499
|
+
* commas and quote kinds dropped everywhere). Read only for records that
|
|
1500
|
+
* hold it; the next write records {@link contentHash}.
|
|
719
1501
|
* @param {string | Buffer} text
|
|
720
1502
|
*/
|
|
721
|
-
const
|
|
1503
|
+
const oldContentHash = text =>
|
|
722
1504
|
digest(
|
|
723
1505
|
String(text)
|
|
724
1506
|
.replace(/["'`]/g, "'")
|
|
@@ -727,7 +1509,8 @@ const contentHash = text =>
|
|
|
727
1509
|
|
|
728
1510
|
/**
|
|
729
1511
|
* Whether a file the preview wrote was changed since, by its recorded hash.
|
|
730
|
-
* A file with no hash
|
|
1512
|
+
* A file with no hash counts as unchanged here; {@link ownedUnchanged}
|
|
1513
|
+
* decides deletes, and never deletes a file with no hash.
|
|
731
1514
|
* @param {string} dir
|
|
732
1515
|
* @param {PreviewData} data
|
|
733
1516
|
* @param {string} rel
|
|
@@ -737,13 +1520,47 @@ function editedByHand(dir, data, rel) {
|
|
|
737
1520
|
if (!was) return false;
|
|
738
1521
|
try {
|
|
739
1522
|
const text = fs.readFileSync(path.join(dir, rel));
|
|
740
|
-
|
|
741
|
-
|
|
1523
|
+
if (was.startsWith('v2:') || was.startsWith('v3:'))
|
|
1524
|
+
return !sameAsRecorded(text, was);
|
|
1525
|
+
// Older records hold the exact or the earlier normalized hash.
|
|
1526
|
+
return oldContentHash(text) !== was && digest(text) !== was;
|
|
742
1527
|
} catch {
|
|
743
1528
|
return false;
|
|
744
1529
|
}
|
|
745
1530
|
}
|
|
746
1531
|
|
|
1532
|
+
/**
|
|
1533
|
+
* Whether the preview may delete a file its record lists: only its own
|
|
1534
|
+
* route file, its record, and the page file of a recorded page (in
|
|
1535
|
+
* _pages/, or pages/ for an older release), and only when a recorded hash
|
|
1536
|
+
* shows the file is as the preview wrote it. Anything else the record names
|
|
1537
|
+
* is kept: a record can be copied, merged or edited by hand.
|
|
1538
|
+
* @param {string} dir
|
|
1539
|
+
* @param {PreviewData} data
|
|
1540
|
+
* @param {string} rel
|
|
1541
|
+
* @param {Set<string>} ids the recorded page ids
|
|
1542
|
+
* @returns {'delete' | 'not-preview' | 'no-hash' | 'edited'}
|
|
1543
|
+
*/
|
|
1544
|
+
function ownedUnchanged(dir, data, rel, ids) {
|
|
1545
|
+
if (rel === PREVIEW_DATA) return 'delete';
|
|
1546
|
+
const page = /^(?:_pages|pages)\/([a-z0-9][a-z0-9-]*)\.tsx$/.exec(rel);
|
|
1547
|
+
if (rel !== 'page.tsx' && !(page && ids.has(page[1]))) return 'not-preview';
|
|
1548
|
+
if (!data.hashes?.[rel]) return 'no-hash';
|
|
1549
|
+
return editedByHand(dir, data, rel) ? 'edited' : 'delete';
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
/**
|
|
1553
|
+
* Why a file the preview listed is kept, for the result notes.
|
|
1554
|
+
* @param {string} name
|
|
1555
|
+
* @param {'not-preview' | 'no-hash' | 'edited'} why
|
|
1556
|
+
*/
|
|
1557
|
+
const keptNote = (name, why) =>
|
|
1558
|
+
why === 'not-preview'
|
|
1559
|
+
? `${name} is kept: theme-preview.json lists it, but the preview only writes page.tsx and page files in ${PAGES_DIR}/`
|
|
1560
|
+
: why === 'no-hash'
|
|
1561
|
+
? `${name} is kept: theme-preview.json has no record of how the preview wrote it, so it may hold your changes; it stays until you remove it yourself`
|
|
1562
|
+
: `${name} was changed by hand after the preview wrote it, so it is kept`;
|
|
1563
|
+
|
|
747
1564
|
/**
|
|
748
1565
|
* Check one planned write before anything is written. A file the preview
|
|
749
1566
|
* did not write is never replaced, unless it already holds exactly the
|
|
@@ -788,12 +1605,15 @@ function checkWrite(cwd, dir, data, w, elsewhere) {
|
|
|
788
1605
|
run: [elsewhere],
|
|
789
1606
|
},
|
|
790
1607
|
);
|
|
1608
|
+
// A file another command wrote while this one was stopped is not a hand
|
|
1609
|
+
// edit: say the lock was taken.
|
|
1610
|
+
refuseIfLockLost();
|
|
791
1611
|
if (editedByHand(dir, data, w.rel))
|
|
792
1612
|
refuse(
|
|
793
1613
|
E.ERR_FILE_EXISTS,
|
|
794
1614
|
`${name} was changed by hand after the preview wrote it, so it is not replaced.`,
|
|
795
1615
|
{
|
|
796
|
-
fix: `copy your changes out of ${name}, then
|
|
1616
|
+
fix: `copy your changes out of ${name}, then give it another name, and run the command again`,
|
|
797
1617
|
},
|
|
798
1618
|
);
|
|
799
1619
|
return 'replace';
|
|
@@ -856,16 +1676,63 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
|
|
|
856
1676
|
};
|
|
857
1677
|
let current = dir;
|
|
858
1678
|
let step = 'written';
|
|
1679
|
+
const pendingFile = path.join(dir, PENDING);
|
|
1680
|
+
/** The record as it is before this call. @type {any} */
|
|
1681
|
+
let old;
|
|
1682
|
+
try {
|
|
1683
|
+
old = JSON.parse(String(before(path.join(dir, PREVIEW_DATA)) ?? 'null'));
|
|
1684
|
+
} catch {
|
|
1685
|
+
old = null;
|
|
1686
|
+
}
|
|
859
1687
|
try {
|
|
1688
|
+
const hashes = {...data.hashes};
|
|
1689
|
+
for (const w of writes)
|
|
1690
|
+
if (!w.keepHash || !hashes[w.rel]) hashes[w.rel] = contentHash(w.text);
|
|
1691
|
+
for (const rel of deletes) delete hashes[rel];
|
|
1692
|
+
for (const rel of Object.keys(hashes))
|
|
1693
|
+
if (!data.files.includes(rel)) delete hashes[rel];
|
|
1694
|
+
data.hashes = hashes;
|
|
1695
|
+
if (!data.files.includes(PREVIEW_DATA)) data.files.push(PREVIEW_DATA);
|
|
860
1696
|
for (const w of writes) {
|
|
861
1697
|
current = confined(path.join(dir, w.rel), dir, 'a preview file');
|
|
862
1698
|
mkdir(path.dirname(current));
|
|
863
1699
|
stage(current, w.text);
|
|
864
1700
|
}
|
|
1701
|
+
// The record this call ends with, the one it starts from and the temp
|
|
1702
|
+
// files and deletes between them, written before the first rename: a
|
|
1703
|
+
// command stopped part way (a kill) leaves it, and the next preview
|
|
1704
|
+
// command finishes the step from it ({@link recoverPreview}).
|
|
1705
|
+
current = pendingFile;
|
|
1706
|
+
writeWhole(
|
|
1707
|
+
pendingFile,
|
|
1708
|
+
`${JSON.stringify(
|
|
1709
|
+
{
|
|
1710
|
+
version: 1,
|
|
1711
|
+
record: data,
|
|
1712
|
+
old,
|
|
1713
|
+
temps: [...temps.values()].map(t => path.relative(dir, t)),
|
|
1714
|
+
deletes,
|
|
1715
|
+
// What each file to delete holds now: after a stop, it goes only
|
|
1716
|
+
// when it still holds that.
|
|
1717
|
+
deleteHashes: Object.fromEntries(
|
|
1718
|
+
deletes.flatMap(rel => {
|
|
1719
|
+
const text = before(
|
|
1720
|
+
confined(path.join(dir, rel), dir, 'a preview file'),
|
|
1721
|
+
);
|
|
1722
|
+
return text ? [[rel, contentHash(text)]] : [];
|
|
1723
|
+
}),
|
|
1724
|
+
),
|
|
1725
|
+
},
|
|
1726
|
+
null,
|
|
1727
|
+
2,
|
|
1728
|
+
)}\n`,
|
|
1729
|
+
);
|
|
1730
|
+
commitStep('pending');
|
|
865
1731
|
for (const w of writes) {
|
|
866
1732
|
current = path.join(dir, w.rel);
|
|
867
1733
|
touched.push({file: current, before: before(current)});
|
|
868
1734
|
fs.renameSync(tmp(current), current);
|
|
1735
|
+
commitStep('rename');
|
|
869
1736
|
}
|
|
870
1737
|
staged.length = 0;
|
|
871
1738
|
step = 'removed';
|
|
@@ -875,21 +1742,18 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
|
|
|
875
1742
|
if (was == null) continue;
|
|
876
1743
|
touched.push({file: current, before: was});
|
|
877
1744
|
fs.rmSync(current);
|
|
1745
|
+
commitStep('delete');
|
|
878
1746
|
}
|
|
879
1747
|
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
1748
|
current = path.join(dir, PREVIEW_DATA);
|
|
889
1749
|
touched.push({file: current, before: before(current)});
|
|
890
1750
|
stage(current, `${JSON.stringify(data, null, 2)}\n`);
|
|
891
1751
|
fs.renameSync(tmp(current), current);
|
|
1752
|
+
fs.rmSync(pendingFile, {force: true});
|
|
892
1753
|
} catch (e) {
|
|
1754
|
+
// A stop injected by a test stands for a kill: nothing is put back.
|
|
1755
|
+
if (e === STOPPED) throw e;
|
|
1756
|
+
fs.rmSync(pendingFile, {force: true});
|
|
893
1757
|
for (const t of staged) fs.rmSync(t, {force: true});
|
|
894
1758
|
for (const t of touched.reverse())
|
|
895
1759
|
try {
|
|
@@ -913,6 +1777,294 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
|
|
|
913
1777
|
}
|
|
914
1778
|
}
|
|
915
1779
|
|
|
1780
|
+
/** The step record a preview change leaves while it runs. */
|
|
1781
|
+
const PENDING = '.theme-preview.pending.json';
|
|
1782
|
+
|
|
1783
|
+
/** What a test throws to stop a change part way, as a kill would. */
|
|
1784
|
+
const STOPPED = Symbol('stopped');
|
|
1785
|
+
|
|
1786
|
+
/** @type {((step: string) => boolean) | null} */
|
|
1787
|
+
let stopAt = null;
|
|
1788
|
+
|
|
1789
|
+
/**
|
|
1790
|
+
* For tests: stop the next preview changes at the step where `when`
|
|
1791
|
+
* returns true, as a kill would, with nothing put back. Null clears it.
|
|
1792
|
+
* @param {((step: string) => boolean) | null} when
|
|
1793
|
+
*/
|
|
1794
|
+
export function stopPreviewCommitAt(when) {
|
|
1795
|
+
stopAt = when;
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
/** Whether a process is running here. @param {number} pid */
|
|
1799
|
+
function alive(pid) {
|
|
1800
|
+
if (pid === process.pid) return true;
|
|
1801
|
+
try {
|
|
1802
|
+
process.kill(pid, 0);
|
|
1803
|
+
return true;
|
|
1804
|
+
} catch (e) {
|
|
1805
|
+
return /** @type {any} */ (e)?.code === 'EPERM';
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
/** @param {string} step */
|
|
1810
|
+
function commitStep(step) {
|
|
1811
|
+
if (stopAt?.(step)) throw STOPPED;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
/**
|
|
1815
|
+
* Page files in the preview folder that theme-preview.json does not list:
|
|
1816
|
+
* a stopped change can leave one behind when its step record is damaged.
|
|
1817
|
+
* @param {string} dir
|
|
1818
|
+
* @returns {string[]} paths relative to the preview folder
|
|
1819
|
+
*/
|
|
1820
|
+
function unrecordedPages(dir) {
|
|
1821
|
+
/** @type {string[]} */
|
|
1822
|
+
let listed = [];
|
|
1823
|
+
try {
|
|
1824
|
+
const files = JSON.parse(
|
|
1825
|
+
fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8'),
|
|
1826
|
+
)?.files;
|
|
1827
|
+
if (Array.isArray(files)) listed = files.map(String);
|
|
1828
|
+
} catch {
|
|
1829
|
+
// No record, or a damaged one: every page file is unrecorded.
|
|
1830
|
+
}
|
|
1831
|
+
/** @type {string[]} */
|
|
1832
|
+
const out = [];
|
|
1833
|
+
for (const sub of [PAGES_DIR, LEGACY_PAGES_DIR]) {
|
|
1834
|
+
/** @type {string[]} */
|
|
1835
|
+
let names;
|
|
1836
|
+
try {
|
|
1837
|
+
names = fs.readdirSync(path.join(dir, sub));
|
|
1838
|
+
} catch {
|
|
1839
|
+
continue;
|
|
1840
|
+
}
|
|
1841
|
+
for (const name of names.sort()) {
|
|
1842
|
+
const rel = `${sub}/${name}`;
|
|
1843
|
+
if (name.endsWith('.tsx') && !listed.includes(rel)) out.push(rel);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
return out;
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1849
|
+
/**
|
|
1850
|
+
* Whether a step record names a path that leads out of the preview folder
|
|
1851
|
+
* (a hand edit, a damaged file): such a record is not followed.
|
|
1852
|
+
* @param {string} dir
|
|
1853
|
+
* @param {any} p
|
|
1854
|
+
*/
|
|
1855
|
+
function pendingEscapes(dir, p) {
|
|
1856
|
+
const rels = [
|
|
1857
|
+
...(Array.isArray(p?.temps) ? p.temps : []),
|
|
1858
|
+
...(Array.isArray(p?.record?.files) ? p.record.files : []),
|
|
1859
|
+
...(Array.isArray(p?.old?.files) ? p.old.files : []),
|
|
1860
|
+
].filter(x => typeof x === 'string');
|
|
1861
|
+
return rels.some(rel => {
|
|
1862
|
+
try {
|
|
1863
|
+
assertWithin(path.join(dir, rel), dir, {allowAbsolute: true});
|
|
1864
|
+
return false;
|
|
1865
|
+
} catch {
|
|
1866
|
+
return true;
|
|
1867
|
+
}
|
|
1868
|
+
});
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
/**
|
|
1872
|
+
* Finish a preview change that was stopped part way (a kill), from the
|
|
1873
|
+
* step record it left: its leftover temp files go; each file it was writing
|
|
1874
|
+
* keeps the hash of what is on disk when that is the new or the old text,
|
|
1875
|
+
* and no hash otherwise (so it is never deleted on the record's word); a
|
|
1876
|
+
* page whose new file never landed keeps its old file; an old file it was
|
|
1877
|
+
* removing goes only when the preview wrote it and its new file is there.
|
|
1878
|
+
* The record is then written and the step record removed. Nothing happens
|
|
1879
|
+
* when there is no step record.
|
|
1880
|
+
* @param {string} cwd
|
|
1881
|
+
* @param {string} dir
|
|
1882
|
+
* @returns {string | null} a note for the result, when a change was finished
|
|
1883
|
+
*/
|
|
1884
|
+
function recoverPreview(cwd, dir) {
|
|
1885
|
+
const pendingFile = path.join(dir, PENDING);
|
|
1886
|
+
/** @type {any} */
|
|
1887
|
+
let p;
|
|
1888
|
+
// Unreadable, or naming a path outside the folder: the change is
|
|
1889
|
+
// treated as never started.
|
|
1890
|
+
const abandon = () => {
|
|
1891
|
+
// Its temp files are found by the names only the editor makes, when
|
|
1892
|
+
// their process is gone.
|
|
1893
|
+
for (const sub of ['', PAGES_DIR, LEGACY_PAGES_DIR]) {
|
|
1894
|
+
/** @type {string[]} */
|
|
1895
|
+
let names;
|
|
1896
|
+
try {
|
|
1897
|
+
names = fs.readdirSync(path.join(dir, sub));
|
|
1898
|
+
} catch {
|
|
1899
|
+
continue;
|
|
1900
|
+
}
|
|
1901
|
+
for (const name of names) {
|
|
1902
|
+
const m = /^\..+\.astryx-(\d+)-[a-z0-9]+\.tmp$/.exec(name);
|
|
1903
|
+
if (m && !alive(Number(m[1])))
|
|
1904
|
+
fs.rmSync(path.join(dir, sub, name), {force: true});
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
fs.rmSync(pendingFile, {force: true});
|
|
1908
|
+
const strays = unrecordedPages(dir).map(rel =>
|
|
1909
|
+
shown(cwd, path.join(dir, rel)),
|
|
1910
|
+
);
|
|
1911
|
+
return `removed ${shown(cwd, pendingFile)}, a damaged step record of a preview change that was stopped${strays.length ? `; ${strays.join(', ')} ${strays.length > 1 ? 'are' : 'is'} in no preview record and may be from that change, so ${strays.length > 1 ? 'they stay' : 'it stays'} until you remove ${strays.length > 1 ? 'them' : 'it'}` : ''}`;
|
|
1912
|
+
};
|
|
1913
|
+
try {
|
|
1914
|
+
p = JSON.parse(fs.readFileSync(pendingFile, 'utf8'));
|
|
1915
|
+
} catch (e) {
|
|
1916
|
+
if (/** @type {any} */ (e)?.code === 'ENOENT') return null;
|
|
1917
|
+
return abandon();
|
|
1918
|
+
}
|
|
1919
|
+
if (pendingEscapes(dir, p)) return abandon();
|
|
1920
|
+
const inside = (/** @type {string} */ rel) =>
|
|
1921
|
+
confined(path.join(dir, rel), dir, PENDING);
|
|
1922
|
+
for (const t of Array.isArray(p?.temps) ? p.temps : [])
|
|
1923
|
+
if (typeof t === 'string' && /\.astryx-[^/]*\.tmp$/.test(t))
|
|
1924
|
+
fs.rmSync(inside(t), {force: true});
|
|
1925
|
+
const record = p?.record;
|
|
1926
|
+
if (previewProblem(record)) {
|
|
1927
|
+
fs.rmSync(pendingFile, {force: true});
|
|
1928
|
+
return null;
|
|
1929
|
+
}
|
|
1930
|
+
const old = p.old && !previewProblem(p.old) ? p.old : null;
|
|
1931
|
+
// The route decides which way the change goes: a page.tsx that is not
|
|
1932
|
+
// the new one means the route never changed, so the change is undone and
|
|
1933
|
+
// the record stays as it was; else it is finished.
|
|
1934
|
+
const route = (() => {
|
|
1935
|
+
try {
|
|
1936
|
+
return fs.readFileSync(inside('page.tsx'));
|
|
1937
|
+
} catch {
|
|
1938
|
+
return null;
|
|
1939
|
+
}
|
|
1940
|
+
})();
|
|
1941
|
+
const newRoute = record.hashes?.['page.tsx'];
|
|
1942
|
+
if (newRoute && !(route && hashMatches(route, newRoute)))
|
|
1943
|
+
return undoStopped(cwd, dir, record, old);
|
|
1944
|
+
/** @param {string} rel */
|
|
1945
|
+
const onDisk = rel => {
|
|
1946
|
+
try {
|
|
1947
|
+
return fs.readFileSync(inside(rel));
|
|
1948
|
+
} catch {
|
|
1949
|
+
return null;
|
|
1950
|
+
}
|
|
1951
|
+
};
|
|
1952
|
+
const matches = hashMatches;
|
|
1953
|
+
const hashes = {...record.hashes};
|
|
1954
|
+
for (const rel of Object.keys(hashes)) {
|
|
1955
|
+
const text = onDisk(rel);
|
|
1956
|
+
if (!text) continue;
|
|
1957
|
+
if (matches(text, hashes[rel])) continue;
|
|
1958
|
+
if (old?.hashes?.[rel] && matches(text, old.hashes[rel]))
|
|
1959
|
+
hashes[rel] = old.hashes[rel];
|
|
1960
|
+
else delete hashes[rel];
|
|
1961
|
+
}
|
|
1962
|
+
// A page whose new file never landed keeps its old file, or else leaves
|
|
1963
|
+
// the record, so the record never lists a page the route cannot show.
|
|
1964
|
+
for (const page of [...record.pages]) {
|
|
1965
|
+
const rel = `${page.file}.tsx`;
|
|
1966
|
+
if (onDisk(rel)) continue;
|
|
1967
|
+
const was = old?.pages.find((/** @type {any} */ x) => x.id === page.id);
|
|
1968
|
+
const oldRel = was && `${was.file}.tsx`;
|
|
1969
|
+
if (oldRel && oldRel !== rel && onDisk(oldRel)) {
|
|
1970
|
+
page.file = was.file;
|
|
1971
|
+
record.files = record.files.map((/** @type {string} */ f) =>
|
|
1972
|
+
f === rel ? oldRel : f,
|
|
1973
|
+
);
|
|
1974
|
+
delete hashes[rel];
|
|
1975
|
+
if (old.hashes?.[oldRel]) hashes[oldRel] = old.hashes[oldRel];
|
|
1976
|
+
} else {
|
|
1977
|
+
record.pages = record.pages.filter((/** @type {any} */ x) => x !== page);
|
|
1978
|
+
record.files = record.files.filter(
|
|
1979
|
+
(/** @type {string} */ f) => f !== rel,
|
|
1980
|
+
);
|
|
1981
|
+
delete hashes[rel];
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
// An old file the change was removing goes when it still holds what it
|
|
1985
|
+
// held when the change planned it, and no page of the record uses it now;
|
|
1986
|
+
// one that changed since is kept and named.
|
|
1987
|
+
/** @type {string[]} */
|
|
1988
|
+
const left = [];
|
|
1989
|
+
for (const rel of Array.isArray(p.deletes) ? p.deletes : []) {
|
|
1990
|
+
if (typeof rel !== 'string' || record.files.includes(rel)) continue;
|
|
1991
|
+
const text = onDisk(rel);
|
|
1992
|
+
if (!text) continue;
|
|
1993
|
+
// A page moved from pages/ to _pages/: the old copy goes once the new
|
|
1994
|
+
// one holds the same text.
|
|
1995
|
+
const moved = /^pages\/([a-z0-9][a-z0-9-]*)\.tsx$/.exec(rel);
|
|
1996
|
+
const copy = moved && onDisk(`${PAGES_DIR}/${moved[1]}.tsx`);
|
|
1997
|
+
if (
|
|
1998
|
+
matches(text, p.deleteHashes?.[rel]) ||
|
|
1999
|
+
matches(text, old?.hashes?.[rel]) ||
|
|
2000
|
+
(copy && copy.equals(text))
|
|
2001
|
+
)
|
|
2002
|
+
fs.rmSync(inside(rel));
|
|
2003
|
+
else left.push(shown(cwd, inside(rel)));
|
|
2004
|
+
}
|
|
2005
|
+
record.hashes = hashes;
|
|
2006
|
+
writeWhole(
|
|
2007
|
+
path.join(dir, PREVIEW_DATA),
|
|
2008
|
+
`${JSON.stringify(record, null, 2)}\n`,
|
|
2009
|
+
);
|
|
2010
|
+
fs.rmSync(pendingFile, {force: true});
|
|
2011
|
+
tidyPageFolders(dir);
|
|
2012
|
+
return `finished a preview change that was stopped part way (${shown(cwd, dir) || '.'}/${PENDING})${left.length ? `; kept ${left.join(', ')}: ${left.length > 1 ? 'they' : 'it'} changed after the change began, so ${left.length > 1 ? 'they' : 'it'} may hold your changes and ${left.length > 1 ? 'stay' : 'stays'} until you remove ${left.length > 1 ? 'them' : 'it'}` : ''}`;
|
|
2013
|
+
}
|
|
2014
|
+
|
|
2015
|
+
/**
|
|
2016
|
+
* Whether a file's text matches a recorded hash, of any kind a release
|
|
2017
|
+
* wrote.
|
|
2018
|
+
* @param {Buffer} text
|
|
2019
|
+
* @param {string | undefined} h
|
|
2020
|
+
*/
|
|
2021
|
+
function hashMatches(text, h) {
|
|
2022
|
+
return !!h && sameAsRecorded(text, h);
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
/**
|
|
2026
|
+
* Undo a preview change stopped before its route landed: the record stays
|
|
2027
|
+
* as it was, each new file of the change that landed and the old record
|
|
2028
|
+
* does not list goes (only when it is as the change wrote it), and a file
|
|
2029
|
+
* both records list that now holds the change's text keeps that text's
|
|
2030
|
+
* hash, so it is not taken for a hand edit.
|
|
2031
|
+
* @param {string} cwd
|
|
2032
|
+
* @param {string} dir
|
|
2033
|
+
* @param {PreviewData} record the record the change was writing
|
|
2034
|
+
* @param {PreviewData | null} old the record before it
|
|
2035
|
+
* @returns {string}
|
|
2036
|
+
*/
|
|
2037
|
+
function undoStopped(cwd, dir, record, old) {
|
|
2038
|
+
const inside = (/** @type {string} */ rel) =>
|
|
2039
|
+
confined(path.join(dir, rel), dir, PENDING);
|
|
2040
|
+
/** @param {string} rel */
|
|
2041
|
+
const onDisk = rel => {
|
|
2042
|
+
try {
|
|
2043
|
+
return fs.readFileSync(inside(rel));
|
|
2044
|
+
} catch {
|
|
2045
|
+
return null;
|
|
2046
|
+
}
|
|
2047
|
+
};
|
|
2048
|
+
const keep = new Set(old?.files ?? []);
|
|
2049
|
+
const hashes = {...old?.hashes};
|
|
2050
|
+
for (const [rel, h] of Object.entries(record.hashes ?? {})) {
|
|
2051
|
+
const text = onDisk(rel);
|
|
2052
|
+
if (!text || !hashMatches(text, h)) continue;
|
|
2053
|
+
if (keep.has(rel)) hashes[rel] = h;
|
|
2054
|
+
else if (rel !== PREVIEW_DATA) fs.rmSync(inside(rel));
|
|
2055
|
+
}
|
|
2056
|
+
if (old) {
|
|
2057
|
+
old.hashes = hashes;
|
|
2058
|
+
writeWhole(
|
|
2059
|
+
path.join(dir, PREVIEW_DATA),
|
|
2060
|
+
`${JSON.stringify(old, null, 2)}\n`,
|
|
2061
|
+
);
|
|
2062
|
+
}
|
|
2063
|
+
fs.rmSync(path.join(dir, PENDING), {force: true});
|
|
2064
|
+
tidyPageFolders(dir);
|
|
2065
|
+
return `undid a preview change that was stopped before its route was written (${shown(cwd, dir) || '.'}/${PENDING})`;
|
|
2066
|
+
}
|
|
2067
|
+
|
|
916
2068
|
/**
|
|
917
2069
|
* Move the pages an older release wrote into pages/ to {@link PAGES_DIR}/,
|
|
918
2070
|
* in the plan and in `data`: a pages/ folder at the project root or in
|
|
@@ -984,34 +2136,69 @@ function tidyPageFolders(dir) {
|
|
|
984
2136
|
}
|
|
985
2137
|
}
|
|
986
2138
|
|
|
987
|
-
/** The themes this command made, by name. @param {string} cwd */
|
|
988
|
-
function editedThemes(cwd) {
|
|
989
|
-
const root = path.join(cwd, 'themes');
|
|
990
|
-
return fs.existsSync(root)
|
|
991
|
-
? fs
|
|
992
|
-
.readdirSync(root)
|
|
993
|
-
.filter(d => fs.existsSync(themeFiles(cwd, d).settings))
|
|
994
|
-
.sort()
|
|
995
|
-
: [];
|
|
996
|
-
}
|
|
997
|
-
|
|
998
2139
|
/**
|
|
999
|
-
* The theme the route imports
|
|
1000
|
-
*
|
|
1001
|
-
*
|
|
2140
|
+
* The theme the route imports; null for the app's own theme. A theme that
|
|
2141
|
+
* does not load is refused here, before the route or any page is written.
|
|
2142
|
+
* With `build`, a theme with no build yet is built now; without it,
|
|
2143
|
+
* `unbuilt` says so and the caller builds it once every check has passed
|
|
2144
|
+
* ({@link buildWorn}).
|
|
1002
2145
|
* @param {string} cwd
|
|
1003
2146
|
* @param {string} dir
|
|
1004
2147
|
* @param {PreviewData} data
|
|
1005
|
-
* @
|
|
2148
|
+
* @param {{build?: boolean}} [opts]
|
|
2149
|
+
* @returns {Promise<{name: string, module: string, css: string[], mode: 'system' | 'light' | 'dark', unbuilt?: boolean} | null>}
|
|
1006
2150
|
*/
|
|
1007
|
-
async function routeTheme(cwd, dir, data) {
|
|
2151
|
+
async function routeTheme(cwd, dir, data, opts = {}) {
|
|
1008
2152
|
if (!data.theme) return null;
|
|
1009
2153
|
const t = loadTheme(cwd, data.theme);
|
|
1010
2154
|
const ctx = await context(cwd);
|
|
1011
|
-
|
|
1012
|
-
|
|
2155
|
+
const unbuilt = !fs.existsSync(themeFiles(cwd, data.theme).js);
|
|
2156
|
+
if (unbuilt && opts.build !== false) await buildTheme(ctx, data.theme, t);
|
|
1013
2157
|
const ti = themeImports(ctx, data.theme, t, dir);
|
|
1014
|
-
return {
|
|
2158
|
+
return {
|
|
2159
|
+
name: data.theme,
|
|
2160
|
+
module: ti.module,
|
|
2161
|
+
css: ti.css,
|
|
2162
|
+
mode: ti.mode,
|
|
2163
|
+
...(unbuilt && opts.build === false ? {unbuilt: true} : {}),
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
/**
|
|
2168
|
+
* Run `fn` under a theme's lock when the command was given one (the
|
|
2169
|
+
* adapter's `lockTheme`), else as it is.
|
|
2170
|
+
* @param {any} options
|
|
2171
|
+
* @param {string} slug
|
|
2172
|
+
* @param {() => unknown} fn
|
|
2173
|
+
*/
|
|
2174
|
+
async function themeLocked(options, slug, fn) {
|
|
2175
|
+
if (typeof options?.lockTheme === 'function')
|
|
2176
|
+
await options.lockTheme(slug, async () => fn());
|
|
2177
|
+
else fn();
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
/**
|
|
2181
|
+
* Build the theme a preview wears when it has no build yet, holding that
|
|
2182
|
+
* theme's lock (an `editor set` on it waits), with a note: a preview
|
|
2183
|
+
* command writes the theme's build only once every check has passed.
|
|
2184
|
+
* @param {string} cwd
|
|
2185
|
+
* @param {{name: string, unbuilt?: boolean} | null} theme from {@link routeTheme}
|
|
2186
|
+
* @param {any} options the command's options, with `lockTheme` from the adapter
|
|
2187
|
+
* @param {string[]} notes
|
|
2188
|
+
*/
|
|
2189
|
+
async function buildWorn(cwd, theme, options, notes) {
|
|
2190
|
+
if (!theme?.unbuilt) return;
|
|
2191
|
+
const slug = theme.name;
|
|
2192
|
+
const build = async () => {
|
|
2193
|
+
if (fs.existsSync(themeFiles(cwd, slug).js)) return;
|
|
2194
|
+
await buildTheme(await context(cwd), slug, loadTheme(cwd, slug));
|
|
2195
|
+
};
|
|
2196
|
+
await (typeof options?.lockTheme === 'function'
|
|
2197
|
+
? options.lockTheme(slug, build)
|
|
2198
|
+
: build());
|
|
2199
|
+
notes.push(
|
|
2200
|
+
`built ${shown(cwd, themeFiles(cwd, slug).dir)}/ first: its build was missing`,
|
|
2201
|
+
);
|
|
1015
2202
|
}
|
|
1016
2203
|
|
|
1017
2204
|
/** The Colors page: its id and file, relative to the route folder. */
|
|
@@ -1061,13 +2248,7 @@ async function colorsPage(cwd, dir, slug) {
|
|
|
1061
2248
|
const uses = {};
|
|
1062
2249
|
// Only the theme's own modes have shades; text on a fill is marked on
|
|
1063
2250
|
// the neutral shade it uses, and pure black or white on no shade.
|
|
1064
|
-
const modes =
|
|
1065
|
-
data.mode === 'light-only'
|
|
1066
|
-
? ['light']
|
|
1067
|
-
: data.mode === 'dark-only'
|
|
1068
|
-
? ['dark']
|
|
1069
|
-
: ['light', 'dark']
|
|
1070
|
-
);
|
|
2251
|
+
const modes = modesOf(data);
|
|
1071
2252
|
for (const [token, v] of Object.entries(pal.tokens)) {
|
|
1072
2253
|
for (const m of modes) {
|
|
1073
2254
|
if (exact(token, m)) continue;
|
|
@@ -1132,6 +2313,25 @@ async function routeWrites(cwd, dir, data, theme, opts = {}) {
|
|
|
1132
2313
|
return out;
|
|
1133
2314
|
}
|
|
1134
2315
|
|
|
2316
|
+
/**
|
|
2317
|
+
* The theme's palette module, written as an empty stand-in when the theme
|
|
2318
|
+
* has no generated colors left and a kept Colors page still imports it.
|
|
2319
|
+
* Null when the module is there.
|
|
2320
|
+
* @param {string} cwd
|
|
2321
|
+
* @param {string} slug
|
|
2322
|
+
* @returns {string | null} the module, as shown
|
|
2323
|
+
*/
|
|
2324
|
+
function paletteStandIn(cwd, slug) {
|
|
2325
|
+
const file = path.join(cwd, paletteFiles(slug).palette);
|
|
2326
|
+
if (fs.existsSync(file)) return null;
|
|
2327
|
+
fs.mkdirSync(path.dirname(file), {recursive: true});
|
|
2328
|
+
writeWhole(
|
|
2329
|
+
file,
|
|
2330
|
+
`${PALETTE_STAND_IN}\nexport const palette = {} as const;\n`,
|
|
2331
|
+
);
|
|
2332
|
+
return shown(cwd, file);
|
|
2333
|
+
}
|
|
2334
|
+
|
|
1135
2335
|
/**
|
|
1136
2336
|
* Rewrite the in-app preview routes of a theme when their imports changed, so
|
|
1137
2337
|
* a font package installed after `set` loads on the next change or `show`,
|
|
@@ -1163,6 +2363,14 @@ export async function refreshPreviewRoute(cwd, slug) {
|
|
|
1163
2363
|
}
|
|
1164
2364
|
if (!data || data.theme !== slug || !data.files.includes('page.tsx'))
|
|
1165
2365
|
continue;
|
|
2366
|
+
// A change stopped part way is finished by the next preview command;
|
|
2367
|
+
// until then the preview is left as it is, and the result says so.
|
|
2368
|
+
if (fs.existsSync(path.join(dir, PENDING))) {
|
|
2369
|
+
stale.push(
|
|
2370
|
+
`${shownDir(cwd, dir)}/ (a preview change was stopped part way; ${PREVIEW} add finishes it and brings the preview up to date)`,
|
|
2371
|
+
);
|
|
2372
|
+
continue;
|
|
2373
|
+
}
|
|
1166
2374
|
const writes = (
|
|
1167
2375
|
await routeWrites(cwd, dir, data, await routeTheme(cwd, dir, data))
|
|
1168
2376
|
).filter(w => {
|
|
@@ -1171,7 +2379,15 @@ export async function refreshPreviewRoute(cwd, slug) {
|
|
|
1171
2379
|
if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === w.text)
|
|
1172
2380
|
return false;
|
|
1173
2381
|
if (editedByHand(dir, data, w.rel)) {
|
|
1174
|
-
|
|
2382
|
+
const standIn =
|
|
2383
|
+
w.rel === `${COLORS_PAGE.file}.tsx` &&
|
|
2384
|
+
fs.readFileSync(file, 'utf8').includes(`${slug}.palette`) &&
|
|
2385
|
+
paletteStandIn(cwd, slug);
|
|
2386
|
+
stale.push(
|
|
2387
|
+
standIn
|
|
2388
|
+
? `${shown(cwd, file)} (changed by hand, so it is kept; the theme has no generated colors now, so ${standIn}, which the page imports, holds an empty stand-in that keeps the app building. Give the page another name if you want to keep your changes, then run ${PREVIEW} add)`
|
|
2389
|
+
: shown(cwd, file),
|
|
2390
|
+
);
|
|
1175
2391
|
return false;
|
|
1176
2392
|
}
|
|
1177
2393
|
return true;
|
|
@@ -1235,16 +2451,26 @@ function recordPreview(cwd, slug, dir, keep = true) {
|
|
|
1235
2451
|
* @param {{dir: string, app: string | null}} at
|
|
1236
2452
|
*/
|
|
1237
2453
|
function openLine(cwd, at) {
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
.
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
2454
|
+
// The routes folder by place, also one this command has just made.
|
|
2455
|
+
const app =
|
|
2456
|
+
at.app ??
|
|
2457
|
+
[path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(r =>
|
|
2458
|
+
at.dir.startsWith(r + path.sep),
|
|
2459
|
+
);
|
|
2460
|
+
if (app) {
|
|
2461
|
+
// A (group) folder is not part of the URL; a [param] folder is a value
|
|
2462
|
+
// the person picks; each other folder is one URL segment, encoded.
|
|
2463
|
+
const segs = urlSegments(app, at.dir);
|
|
2464
|
+
const params = segs.filter(seg => /^\[.+\]$/.test(seg));
|
|
2465
|
+
const url = segs
|
|
2466
|
+
.map(seg =>
|
|
2467
|
+
/^\[.+\]$/.test(seg)
|
|
2468
|
+
? `<${seg.replace(/^\[+\.*|\]+$/g, '')}>`
|
|
2469
|
+
: encodeURIComponent(seg),
|
|
2470
|
+
)
|
|
1246
2471
|
.join('/');
|
|
1247
|
-
|
|
2472
|
+
const base = nextBasePath(cwd);
|
|
2473
|
+
return `open ${base ?? ''}/${url} in the running app${params.length ? `, with a value for ${params.join(', ')}` : ''}${base == null ? ', after the basePath next.config sets from code (it goes in front)' : ''}`;
|
|
1248
2474
|
}
|
|
1249
2475
|
const routes = ['app', path.join('src', 'app')].filter(r =>
|
|
1250
2476
|
fs.existsSync(path.join(cwd, r)),
|
|
@@ -1254,8 +2480,6 @@ function openLine(cwd, at) {
|
|
|
1254
2480
|
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>`;
|
|
1255
2481
|
}
|
|
1256
2482
|
|
|
1257
|
-
const STYLEX_IMPORT = /from\s+['"]@stylexjs\/stylex['"]/;
|
|
1258
|
-
|
|
1259
2483
|
/**
|
|
1260
2484
|
* Why a template page was skipped.
|
|
1261
2485
|
* @param {{missingPackages: string[], notInstalled: string[], stylexCompiler: boolean}} s
|
|
@@ -1495,41 +2719,68 @@ async function pageTemplates(cwd) {
|
|
|
1495
2719
|
* @param {string} pkg
|
|
1496
2720
|
*/
|
|
1497
2721
|
function installed(cwd, pkg) {
|
|
1498
|
-
|
|
1499
|
-
if (fs.existsSync(path.join(dir, 'node_modules', pkg, 'package.json')))
|
|
1500
|
-
return true;
|
|
1501
|
-
if (path.dirname(dir) === dir) return false;
|
|
1502
|
-
}
|
|
2722
|
+
return findNodeModulesPackage(cwd, pkg) != null;
|
|
1503
2723
|
}
|
|
1504
2724
|
|
|
1505
2725
|
/**
|
|
1506
|
-
*
|
|
1507
|
-
*
|
|
1508
|
-
*
|
|
2726
|
+
* What a template page needs that the app lacks, from its real imports:
|
|
2727
|
+
* packages the app's package.json does not name (with the command that
|
|
2728
|
+
* adds them), packages it names that are not installed (with the install
|
|
2729
|
+
* command), and a StyleX compiler.
|
|
1509
2730
|
* @param {string} cwd
|
|
1510
2731
|
* @param {string} source
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
2732
|
+
*/
|
|
2733
|
+
function pageNeeds(cwd, source) {
|
|
2734
|
+
const pkgs = [...extractImportedPackages(source)];
|
|
2735
|
+
const needs = analyzeTemplateNeeds(source, cwd);
|
|
2736
|
+
/** @type {Record<string, string>} */
|
|
2737
|
+
let declared = {};
|
|
2738
|
+
try {
|
|
2739
|
+
const pkg = JSON.parse(
|
|
2740
|
+
fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'),
|
|
2741
|
+
);
|
|
2742
|
+
declared = {
|
|
2743
|
+
...pkg.optionalDependencies,
|
|
2744
|
+
...pkg.peerDependencies,
|
|
2745
|
+
...pkg.dependencies,
|
|
2746
|
+
...pkg.devDependencies,
|
|
2747
|
+
};
|
|
2748
|
+
} catch {
|
|
2749
|
+
// No readable package.json: nothing is declared.
|
|
2750
|
+
}
|
|
2751
|
+
const absent = pkgs.filter(
|
|
2752
|
+
p =>
|
|
2753
|
+
!needs.missingPackages.includes(p) &&
|
|
2754
|
+
!/^(react|react-dom|next)$/.test(p) &&
|
|
2755
|
+
!p.startsWith('@astryxdesign/') &&
|
|
2756
|
+
!installed(cwd, p),
|
|
1520
2757
|
);
|
|
2758
|
+
const notInstalled = absent.filter(p => p in declared);
|
|
2759
|
+
const undeclared = absent.filter(p => !(p in declared));
|
|
2760
|
+
const missingPackages = [...needs.missingPackages, ...undeclared];
|
|
2761
|
+
const commands = [
|
|
2762
|
+
...(needs.installCommand
|
|
2763
|
+
? [[needs.installCommand, ...undeclared].join(' ')]
|
|
2764
|
+
: undeclared.length
|
|
2765
|
+
? [installLine(cwd, undeclared)]
|
|
2766
|
+
: []),
|
|
2767
|
+
...(notInstalled.length ? [installCommandOf(cwd)] : []),
|
|
2768
|
+
];
|
|
2769
|
+
return {
|
|
2770
|
+
missingPackages,
|
|
2771
|
+
notInstalled,
|
|
2772
|
+
installCommand: commands.length ? commands.join(' && ') : null,
|
|
2773
|
+
noCommand: needs.missingPackages.length > 0 && !needs.installCommand,
|
|
2774
|
+
stylexCompiler:
|
|
2775
|
+
pkgs.includes('@stylexjs/stylex') &&
|
|
2776
|
+
detectStylingSystem(cwd) !== 'stylex',
|
|
2777
|
+
};
|
|
1521
2778
|
}
|
|
1522
2779
|
|
|
1523
2780
|
/** The command that installs what the package.json names. @param {string} cwd */
|
|
1524
2781
|
function installCommandOf(cwd) {
|
|
1525
|
-
|
|
1526
|
-
|
|
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';
|
|
2782
|
+
// The package manager `installLine` names, with its install verb.
|
|
2783
|
+
return installLine(cwd, []).trim().replace(/ add$/, ' install');
|
|
1533
2784
|
}
|
|
1534
2785
|
|
|
1535
2786
|
/**
|
|
@@ -1546,24 +2797,34 @@ function wornTheme(cwd, slug, again, without) {
|
|
|
1546
2797
|
return loadTheme(cwd, slug);
|
|
1547
2798
|
} catch (e) {
|
|
1548
2799
|
const code = /** @type {any} */ (e)?.code;
|
|
1549
|
-
|
|
1550
|
-
|
|
2800
|
+
// A theme that is there but does not load is its own refusal.
|
|
2801
|
+
if (code === E.ERR_THEME_INVALID || code === E.ERR_THEME_LOAD) throw e;
|
|
1551
2802
|
const name = String(slug)
|
|
1552
2803
|
.trim()
|
|
1553
2804
|
.toLowerCase()
|
|
1554
|
-
.replace(/^@astryxdesign\/theme-/, '')
|
|
2805
|
+
.replace(/^@astryxdesign\/theme-/, '')
|
|
2806
|
+
.replace(/^\.?\/?themes\//, '')
|
|
2807
|
+
.replace(/\/+$/, '');
|
|
1555
2808
|
const themes = editedThemes(cwd);
|
|
1556
|
-
if (!themes.includes(name) && isPackageTheme(cwd, name))
|
|
2809
|
+
if (!themes.includes(name) && isPackageTheme(cwd, name)) {
|
|
2810
|
+
const missing =
|
|
2811
|
+
name !== 'neutral' && !installed(cwd, `@astryxdesign/theme-${name}`);
|
|
1557
2812
|
refuse(
|
|
1558
2813
|
E.ERR_UNKNOWN_THEME,
|
|
1559
2814
|
`${slug} is a package theme, not a theme made by ${EDITOR}; ${without}.`,
|
|
1560
2815
|
{
|
|
1561
2816
|
run: [
|
|
1562
2817
|
again(null),
|
|
1563
|
-
|
|
2818
|
+
...(missing
|
|
2819
|
+
? [
|
|
2820
|
+
`${installLine(cwd, [`@astryxdesign/theme-${name}`])} # then a theme of your own can start from it`,
|
|
2821
|
+
]
|
|
2822
|
+
: []),
|
|
2823
|
+
`${EDITOR} new my-${name} --like ${name} # a theme of your own that starts from it`,
|
|
1564
2824
|
],
|
|
1565
2825
|
},
|
|
1566
2826
|
);
|
|
2827
|
+
}
|
|
1567
2828
|
const near = themes.includes(name) ? [name] : nearest(name, themes);
|
|
1568
2829
|
if (near.length)
|
|
1569
2830
|
refuse(
|
|
@@ -1582,13 +2843,17 @@ function wornTheme(cwd, slug, again, without) {
|
|
|
1582
2843
|
* @param {string} name
|
|
1583
2844
|
*/
|
|
1584
2845
|
function isPackageTheme(cwd, name) {
|
|
1585
|
-
return
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
2846
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name)) return false;
|
|
2847
|
+
// The base themes ship with the CLI, installed or not.
|
|
2848
|
+
const bases = fs.existsSync(BASE_THEMES)
|
|
2849
|
+
? fs.readdirSync(BASE_THEMES)
|
|
2850
|
+
: ['neutral'];
|
|
2851
|
+
return bases.includes(name) || installed(cwd, `@astryxdesign/theme-${name}`);
|
|
1590
2852
|
}
|
|
1591
2853
|
|
|
2854
|
+
/** The base themes this CLI knows, one folder each. */
|
|
2855
|
+
const BASE_THEMES = path.join(CLI_PACKAGE, 'assets', 'templates', 'themes');
|
|
2856
|
+
|
|
1592
2857
|
/**
|
|
1593
2858
|
* The page template `--template` names, or a refusal: a block or component
|
|
1594
2859
|
* example is not a page, and the suggestions are page templates only, as
|
|
@@ -1600,11 +2865,13 @@ function isPackageTheme(cwd, name) {
|
|
|
1600
2865
|
*/
|
|
1601
2866
|
async function namedTemplate(cwd, id, flags) {
|
|
1602
2867
|
const pages = await pageTemplates(cwd);
|
|
1603
|
-
|
|
2868
|
+
// Page ids are lowercase: LOGIN names login.
|
|
2869
|
+
const hit =
|
|
2870
|
+
pages.find(t => t.id === id) ?? pages.find(t => t.id === id.toLowerCase());
|
|
1604
2871
|
if (hit)
|
|
1605
2872
|
return {
|
|
1606
|
-
name: id,
|
|
1607
|
-
displayName: hit.name ?? id,
|
|
2873
|
+
name: hit.id,
|
|
2874
|
+
displayName: hit.name ?? hit.id,
|
|
1608
2875
|
why: 'named with --template',
|
|
1609
2876
|
};
|
|
1610
2877
|
try {
|
|
@@ -1661,11 +2928,11 @@ async function pageAgain(cwd, id, defaultPage) {
|
|
|
1661
2928
|
await template(id, {cwd, type: 'page'})
|
|
1662
2929
|
);
|
|
1663
2930
|
const source = shownTemplate.data.source;
|
|
1664
|
-
const needs =
|
|
2931
|
+
const needs = pageNeeds(cwd, source);
|
|
1665
2932
|
if (
|
|
1666
2933
|
needs.missingPackages.length ||
|
|
1667
|
-
notInstalled
|
|
1668
|
-
|
|
2934
|
+
needs.notInstalled.length ||
|
|
2935
|
+
needs.stylexCompiler
|
|
1669
2936
|
)
|
|
1670
2937
|
return null;
|
|
1671
2938
|
return source;
|
|
@@ -1688,6 +2955,41 @@ async function pageAgain(cwd, id, defaultPage) {
|
|
|
1688
2955
|
* @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewAddResponse>}
|
|
1689
2956
|
*/
|
|
1690
2957
|
export async function themeEditPreviewAdd(description, options = {}) {
|
|
2958
|
+
return reportingRecovery(box => addPreview(description, options, box));
|
|
2959
|
+
}
|
|
2960
|
+
|
|
2961
|
+
/**
|
|
2962
|
+
* Run a preview command that may first finish a change stopped part way:
|
|
2963
|
+
* a refusal after that says what the recovery wrote, in place of "Nothing
|
|
2964
|
+
* was changed".
|
|
2965
|
+
* @template T
|
|
2966
|
+
* @param {(box: {note: string | null}) => Promise<T>} fn
|
|
2967
|
+
* @returns {Promise<T>}
|
|
2968
|
+
*/
|
|
2969
|
+
async function reportingRecovery(fn) {
|
|
2970
|
+
/** @type {{note: string | null}} */
|
|
2971
|
+
const box = {note: null};
|
|
2972
|
+
try {
|
|
2973
|
+
return await fn(box);
|
|
2974
|
+
} catch (e) {
|
|
2975
|
+
const err = /** @type {any} */ (e);
|
|
2976
|
+
if (box.note && typeof err?.message === 'string' && err.code)
|
|
2977
|
+
err.message = err.message.replace(
|
|
2978
|
+
/Nothing was changed\.$/,
|
|
2979
|
+
`Before that, it ${box.note}; nothing else was changed.`,
|
|
2980
|
+
);
|
|
2981
|
+
throw e;
|
|
2982
|
+
}
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
/**
|
|
2986
|
+
* {@link themeEditPreviewAdd}, with the note of a recovery in `box`.
|
|
2987
|
+
* @param {string | undefined} description
|
|
2988
|
+
* @param {import('./theme-edit.type.mjs').ThemeEditPreviewAddOptions} options
|
|
2989
|
+
* @param {{note: string | null}} box
|
|
2990
|
+
* @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewAddResponse>}
|
|
2991
|
+
*/
|
|
2992
|
+
async function addPreview(description, options, box) {
|
|
1691
2993
|
const {cwd = process.cwd()} = options;
|
|
1692
2994
|
if (isOutsideProject(cwd))
|
|
1693
2995
|
refuse(
|
|
@@ -1700,8 +3002,12 @@ export async function themeEditPreviewAdd(description, options = {}) {
|
|
|
1700
3002
|
],
|
|
1701
3003
|
},
|
|
1702
3004
|
);
|
|
1703
|
-
const pf =
|
|
1704
|
-
|
|
3005
|
+
const pf =
|
|
3006
|
+
options.path != null ? ` --path ${quoteCommandArgument(options.path)}` : '';
|
|
3007
|
+
const tf =
|
|
3008
|
+
options.theme != null
|
|
3009
|
+
? ` --theme ${quoteCommandArgument(options.theme)}`
|
|
3010
|
+
: '';
|
|
1705
3011
|
const said = (description ?? '').trim();
|
|
1706
3012
|
const named =
|
|
1707
3013
|
options.template == null ? null : String(options.template).trim();
|
|
@@ -1718,8 +3024,8 @@ export async function themeEditPreviewAdd(description, options = {}) {
|
|
|
1718
3024
|
'--template names the page; a description asks the ranking to pick one, so drop one of them.',
|
|
1719
3025
|
{
|
|
1720
3026
|
run: [
|
|
1721
|
-
`${PREVIEW} add --template ${
|
|
1722
|
-
`${PREVIEW} add ${
|
|
3027
|
+
`${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`,
|
|
3028
|
+
`${PREVIEW} add ${quoteCommandArgument(said)}${tf}${pf}`,
|
|
1723
3029
|
],
|
|
1724
3030
|
},
|
|
1725
3031
|
);
|
|
@@ -1730,7 +3036,7 @@ export async function themeEditPreviewAdd(description, options = {}) {
|
|
|
1730
3036
|
`--top takes 1, 2 or 3, not "${String(options.top)}".`,
|
|
1731
3037
|
{
|
|
1732
3038
|
run: [
|
|
1733
|
-
`${PREVIEW} add ${
|
|
3039
|
+
`${PREVIEW} add ${quoteCommandArgument(said || 'a sales dashboard')} --top 2${tf}${pf}`,
|
|
1734
3040
|
],
|
|
1735
3041
|
},
|
|
1736
3042
|
);
|
|
@@ -1743,7 +3049,7 @@ export async function themeEditPreviewAdd(description, options = {}) {
|
|
|
1743
3049
|
{
|
|
1744
3050
|
run: [
|
|
1745
3051
|
named != null
|
|
1746
|
-
? `${PREVIEW} add --template ${
|
|
3052
|
+
? `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`
|
|
1747
3053
|
: `${PREVIEW} add 'a sales dashboard' --top ${String(options.top)}${tf}${pf}`,
|
|
1748
3054
|
],
|
|
1749
3055
|
},
|
|
@@ -1768,14 +3074,20 @@ export async function themeEditPreviewAdd(description, options = {}) {
|
|
|
1768
3074
|
);
|
|
1769
3075
|
}
|
|
1770
3076
|
const retry = (/** @type {string | null} */ p) =>
|
|
1771
|
-
`${PREVIEW} add${said ? ` ${
|
|
3077
|
+
`${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${tf}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
|
|
1772
3078
|
const at = previewDir(cwd, options.path, {write: true, retry});
|
|
3079
|
+
const recovered = recoverPreview(cwd, at.dir);
|
|
3080
|
+
if (recovered) notes.push(recovered);
|
|
3081
|
+
const unstyled = coreStylesheetMissing(cwd, at);
|
|
3082
|
+
if (unstyled) notes.push(unstyled);
|
|
3083
|
+
notes.push(...nextConfigNotes(cwd));
|
|
3084
|
+
box.note = recovered;
|
|
1773
3085
|
const existing = readPreview(cwd, at.dir, pf);
|
|
1774
3086
|
/** @type {PreviewData} */
|
|
1775
3087
|
const data = existing ?? {version: 1, theme: null, pages: [], files: []};
|
|
1776
3088
|
const wore = data.theme;
|
|
1777
3089
|
const againWith = (/** @type {string | null} */ t) =>
|
|
1778
|
-
`${PREVIEW} add${said ? ` ${
|
|
3090
|
+
`${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${t == null ? '' : ` --theme ${t}`}${pf}`;
|
|
1779
3091
|
const without = "leave out --theme and the pages wear the app's own theme";
|
|
1780
3092
|
if (options.theme != null) {
|
|
1781
3093
|
wornTheme(cwd, options.theme, againWith, without);
|
|
@@ -1855,23 +3167,23 @@ export async function themeEditPreviewAdd(description, options = {}) {
|
|
|
1855
3167
|
await template(pick.name, {cwd, type: 'page'})
|
|
1856
3168
|
);
|
|
1857
3169
|
const source = shownTemplate.data.source;
|
|
1858
|
-
const needs =
|
|
1859
|
-
const absent = notInstalled(cwd, source, needs.missingPackages);
|
|
3170
|
+
const needs = pageNeeds(cwd, source);
|
|
1860
3171
|
// A StyleX page calls stylex.create when its module loads, so without
|
|
1861
3172
|
// a StyleX compiler it breaks the whole route.
|
|
1862
|
-
const needsCompiler =
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
3173
|
+
const needsCompiler = needs.stylexCompiler;
|
|
3174
|
+
if (
|
|
3175
|
+
needs.missingPackages.length ||
|
|
3176
|
+
needs.notInstalled.length ||
|
|
3177
|
+
needsCompiler
|
|
3178
|
+
) {
|
|
3179
|
+
const installCommand = needs.installCommand;
|
|
1868
3180
|
skipped.push({
|
|
1869
3181
|
page: pick.name,
|
|
1870
3182
|
reason: `${skipReason({
|
|
1871
3183
|
missingPackages: needs.missingPackages,
|
|
1872
|
-
notInstalled:
|
|
3184
|
+
notInstalled: needs.notInstalled,
|
|
1873
3185
|
stylexCompiler: needsCompiler,
|
|
1874
|
-
})}${needs.
|
|
3186
|
+
})}${needs.noCommand ? ' (the app has more than one lockfile, so install it with the package manager you use)' : ''}`,
|
|
1875
3187
|
installCommand,
|
|
1876
3188
|
});
|
|
1877
3189
|
if (installCommand) runs.push(installCommand);
|
|
@@ -1987,12 +3299,13 @@ export async function themeEditPreviewAdd(description, options = {}) {
|
|
|
1987
3299
|
);
|
|
1988
3300
|
if (!data.files.includes('page.tsx'))
|
|
1989
3301
|
checkWrite(cwd, at.dir, data, {rel: 'page.tsx', text: '\0'}, elsewhere);
|
|
1990
|
-
const theme = await routeTheme(cwd, at.dir, data);
|
|
3302
|
+
const theme = await routeTheme(cwd, at.dir, data, {build: false});
|
|
1991
3303
|
for (const w of await routeWrites(cwd, at.dir, data, theme, {gone})) {
|
|
1992
3304
|
if (!writes.has(w.rel)) checkWrite(cwd, at.dir, data, w, elsewhere);
|
|
1993
3305
|
writes.set(w.rel, w);
|
|
1994
3306
|
if (!data.files.includes(w.rel)) data.files.push(w.rel);
|
|
1995
3307
|
}
|
|
3308
|
+
await buildWorn(cwd, theme, options, notes);
|
|
1996
3309
|
commitPreview(
|
|
1997
3310
|
cwd,
|
|
1998
3311
|
at.dir,
|
|
@@ -2006,8 +3319,15 @@ export async function themeEditPreviewAdd(description, options = {}) {
|
|
|
2006
3319
|
notes.push(
|
|
2007
3320
|
`moved ${move.moved.join(', ')} from ${LEGACY_PAGES_DIR}/ to ${PAGES_DIR}/, a folder Next never serves as a route`,
|
|
2008
3321
|
);
|
|
2009
|
-
|
|
2010
|
-
|
|
3322
|
+
// previews.json is a theme file: written under that theme's lock, so a
|
|
3323
|
+
// change running on the theme never takes it back.
|
|
3324
|
+
if (wore && wore !== data.theme)
|
|
3325
|
+
await themeLocked(options, wore, () =>
|
|
3326
|
+
recordPreview(cwd, wore, at.dir, false),
|
|
3327
|
+
);
|
|
3328
|
+
const worn = data.theme;
|
|
3329
|
+
if (worn)
|
|
3330
|
+
await themeLocked(options, worn, () => recordPreview(cwd, worn, at.dir));
|
|
2011
3331
|
return {
|
|
2012
3332
|
type: 'themeEdit.previewAdd',
|
|
2013
3333
|
data: {
|
|
@@ -2051,7 +3371,8 @@ export async function themeEditPreviewApp(dir, options = {}) {
|
|
|
2051
3371
|
: wornTheme(
|
|
2052
3372
|
cwd,
|
|
2053
3373
|
slug,
|
|
2054
|
-
t =>
|
|
3374
|
+
t =>
|
|
3375
|
+
`${PREVIEW} app ${quoteCommandArgument(dir)}${t == null ? '' : ` --theme ${t}`}`,
|
|
2055
3376
|
'leave out --theme and the app wears the neutral theme',
|
|
2056
3377
|
);
|
|
2057
3378
|
// A new app has no Core installed yet: its pages come from this CLI's own
|
|
@@ -2073,18 +3394,22 @@ export async function themeEditPreviewApp(dir, options = {}) {
|
|
|
2073
3394
|
if (slug != null && theme) {
|
|
2074
3395
|
const from = themeFiles(cwd, slug);
|
|
2075
3396
|
const ctx = await context(cwd);
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
3397
|
+
// The build is judged by its content (staleBuild), never by file
|
|
3398
|
+
// times. Without the theme's lock (it cannot be taken), a change may be
|
|
3399
|
+
// in progress: nothing is built, and only a build that matches its
|
|
3400
|
+
// settings is copied.
|
|
3401
|
+
const why = staleBuild(cwd, slug, theme);
|
|
3402
|
+
if (/** @type {any} */ (options).readOnly) {
|
|
3403
|
+
if (why)
|
|
3404
|
+
refuse(
|
|
3405
|
+
E.ERR_THEME_BUSY,
|
|
3406
|
+
`The lock for ${slug} could not be taken, and its build is not current (${why}), so it is not copied. Nothing was changed.`,
|
|
3407
|
+
{run: [`${P} show ${slug}`]},
|
|
3408
|
+
);
|
|
3409
|
+
} else if (why) {
|
|
2085
3410
|
await buildTheme(ctx, slug, theme);
|
|
2086
3411
|
notes.push(
|
|
2087
|
-
`built ${shown(cwd, from.dir)}/ first: its build was ${
|
|
3412
|
+
`built ${shown(cwd, from.dir)}/ first: its build was not current (${why}), and the app gets a current copy`,
|
|
2088
3413
|
);
|
|
2089
3414
|
}
|
|
2090
3415
|
const to = themeFiles('', slug);
|
|
@@ -2195,7 +3520,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
|
|
|
2195
3520
|
cwd,
|
|
2196
3521
|
plan,
|
|
2197
3522
|
d =>
|
|
2198
|
-
`${PREVIEW} app ${
|
|
3523
|
+
`${PREVIEW} app ${quoteCommandArgument(d)}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`,
|
|
2199
3524
|
);
|
|
2200
3525
|
const folder = shownDir(cwd, plan.root);
|
|
2201
3526
|
if (
|
|
@@ -2214,7 +3539,8 @@ export async function themeEditPreviewApp(dir, options = {}) {
|
|
|
2214
3539
|
pages: data.pages.map(x => x.id),
|
|
2215
3540
|
files,
|
|
2216
3541
|
notes,
|
|
2217
|
-
|
|
3542
|
+
// A folder named like a flag (`-`, `-k`) is a path to cd only with ./.
|
|
3543
|
+
open: `cd ${quoteCommandArgument(folder.startsWith('-') ? `./${folder}` : folder)} && npm install && npm run dev, then open /theme-preview`,
|
|
2218
3544
|
},
|
|
2219
3545
|
};
|
|
2220
3546
|
}
|
|
@@ -2238,6 +3564,29 @@ function readVersion(project, pkg) {
|
|
|
2238
3564
|
}
|
|
2239
3565
|
}
|
|
2240
3566
|
|
|
3567
|
+
/**
|
|
3568
|
+
* Why the in-app preview's record is damaged, with how to fix it, or null
|
|
3569
|
+
* (no preview, or a sound one). For answers that would suggest a preview
|
|
3570
|
+
* command, which the damage refuses.
|
|
3571
|
+
* @param {string} cwd
|
|
3572
|
+
* @returns {string | null}
|
|
3573
|
+
*/
|
|
3574
|
+
export function previewRecordProblem(cwd) {
|
|
3575
|
+
try {
|
|
3576
|
+
const at = previewDir(cwd, undefined, {
|
|
3577
|
+
optional: true,
|
|
3578
|
+
retry: () => `${PREVIEW} add`,
|
|
3579
|
+
});
|
|
3580
|
+
if (at) readPreview(cwd, at.dir);
|
|
3581
|
+
return null;
|
|
3582
|
+
} catch (e) {
|
|
3583
|
+
const err = /** @type {any} */ (e);
|
|
3584
|
+
if (err?.code !== E.ERR_THEME_INVALID) return null;
|
|
3585
|
+
const fix = err.fix;
|
|
3586
|
+
return `${String(err.message).replace(/ Nothing was changed\.$/, '')}${fix ? ` To fix it: ${fix}.` : ''}`;
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
3589
|
+
|
|
2241
3590
|
/**
|
|
2242
3591
|
* The pages of the in-app theme preview. With no preview, and with no
|
|
2243
3592
|
* routes folder for one, the list is empty; a damaged theme-preview.json is
|
|
@@ -2249,18 +3598,33 @@ function readVersion(project, pkg) {
|
|
|
2249
3598
|
export async function themeEditPreviewList(options = {}) {
|
|
2250
3599
|
const {cwd = process.cwd()} = options;
|
|
2251
3600
|
requireProject(cwd);
|
|
2252
|
-
const pf =
|
|
3601
|
+
const pf =
|
|
3602
|
+
options.path != null ? ` --path ${quoteCommandArgument(options.path)}` : '';
|
|
2253
3603
|
const at = previewDir(cwd, options.path, {
|
|
2254
3604
|
optional: true,
|
|
2255
|
-
retry: p =>
|
|
3605
|
+
retry: p =>
|
|
3606
|
+
`${PREVIEW} list${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`,
|
|
2256
3607
|
});
|
|
2257
3608
|
const data = at && readPreview(cwd, at.dir, pf);
|
|
3609
|
+
/** @type {string[]} */
|
|
3610
|
+
const notes = [];
|
|
3611
|
+
const themeMissing = Boolean(
|
|
3612
|
+
data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
|
|
3613
|
+
);
|
|
3614
|
+
if (data?.theme && themeMissing) {
|
|
3615
|
+
const themes = editedThemes(cwd);
|
|
3616
|
+
notes.push(
|
|
3617
|
+
`the preview wears ${data.theme}, which is gone, so its route does not build; ${PREVIEW} add${pf} switches it to ${themes.length === 1 ? themes[0] : "the app's own theme"}`,
|
|
3618
|
+
);
|
|
3619
|
+
}
|
|
2258
3620
|
return {
|
|
2259
3621
|
type: 'themeEdit.previewList',
|
|
2260
3622
|
data: {
|
|
2261
3623
|
folder: at && data ? shownDir(cwd, at.dir) : null,
|
|
2262
3624
|
theme: data?.theme ?? null,
|
|
3625
|
+
themeMissing,
|
|
2263
3626
|
pages: (data?.pages ?? []).map(x => ({id: x.id, label: x.label})),
|
|
3627
|
+
notes,
|
|
2264
3628
|
},
|
|
2265
3629
|
};
|
|
2266
3630
|
}
|
|
@@ -2276,19 +3640,54 @@ export async function themeEditPreviewList(options = {}) {
|
|
|
2276
3640
|
* @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewRemoveResponse>}
|
|
2277
3641
|
*/
|
|
2278
3642
|
export async function themeEditPreviewRemove(page, options = {}) {
|
|
3643
|
+
return reportingRecovery(box => removePreview(page, options, box));
|
|
3644
|
+
}
|
|
3645
|
+
|
|
3646
|
+
/**
|
|
3647
|
+
* {@link themeEditPreviewRemove}, with the note of a recovery in `box`.
|
|
3648
|
+
* @param {string | undefined} page
|
|
3649
|
+
* @param {import('./theme-edit.type.mjs').ThemeEditPreviewListOptions} options
|
|
3650
|
+
* @param {{note: string | null}} box
|
|
3651
|
+
* @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewRemoveResponse>}
|
|
3652
|
+
*/
|
|
3653
|
+
async function removePreview(page, options, box) {
|
|
2279
3654
|
const {cwd = process.cwd()} = options;
|
|
2280
3655
|
requireProject(cwd);
|
|
2281
|
-
const pf =
|
|
3656
|
+
const pf =
|
|
3657
|
+
options.path != null ? ` --path ${quoteCommandArgument(options.path)}` : '';
|
|
2282
3658
|
const retry = (/** @type {string | null} */ p) =>
|
|
2283
|
-
`${PREVIEW} remove${page != null ? ` ${
|
|
3659
|
+
`${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
|
|
2284
3660
|
const at = previewDir(cwd, options.path, {retry});
|
|
3661
|
+
const recovered = recoverPreview(cwd, at.dir);
|
|
3662
|
+
box.note = recovered;
|
|
2285
3663
|
const data = readPreview(cwd, at.dir, pf);
|
|
2286
|
-
if (!data)
|
|
3664
|
+
if (!data) {
|
|
3665
|
+
// A folder that holds the app takes no preview: the way on is the
|
|
3666
|
+
// preview elsewhere, or a new one in its own folder.
|
|
3667
|
+
/** @type {string | null} */
|
|
3668
|
+
let other = null;
|
|
3669
|
+
if (holdsApp(cwd, at.dir))
|
|
3670
|
+
try {
|
|
3671
|
+
const d = previewDir(cwd, undefined, {optional: true, retry})?.dir;
|
|
3672
|
+
if (d && d !== at.dir && fs.existsSync(path.join(d, PREVIEW_DATA)))
|
|
3673
|
+
other = d;
|
|
3674
|
+
} catch {
|
|
3675
|
+
// Several previews, or none: add is the way on.
|
|
3676
|
+
}
|
|
2287
3677
|
refuse(
|
|
2288
3678
|
E.ERR_NOT_FOUND,
|
|
2289
3679
|
`There is no theme preview in ${shownDir(cwd, at.dir)}/ (no ${PREVIEW_DATA}).`,
|
|
2290
|
-
{
|
|
3680
|
+
{
|
|
3681
|
+
run: [
|
|
3682
|
+
holdsApp(cwd, at.dir)
|
|
3683
|
+
? other
|
|
3684
|
+
? `${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''} # the preview in ${shownDir(cwd, other)}/`
|
|
3685
|
+
: `${PREVIEW} add`
|
|
3686
|
+
: `${PREVIEW} add${pf}`,
|
|
3687
|
+
],
|
|
3688
|
+
},
|
|
2291
3689
|
);
|
|
3690
|
+
}
|
|
2292
3691
|
const folder = shownDir(cwd, at.dir);
|
|
2293
3692
|
// theme-preview.json is a file anyone can edit: every path in it must
|
|
2294
3693
|
// stay in the route folder before anything is removed.
|
|
@@ -2297,7 +3696,7 @@ export async function themeEditPreviewRemove(page, options = {}) {
|
|
|
2297
3696
|
for (const rel of data.files) inside(rel);
|
|
2298
3697
|
for (const p of data.pages) inside(`${p.file}.tsx`);
|
|
2299
3698
|
/** @type {string[]} */
|
|
2300
|
-
const notes = [];
|
|
3699
|
+
const notes = recovered ? [recovered] : [];
|
|
2301
3700
|
/** @type {string[]} */
|
|
2302
3701
|
const kept = [];
|
|
2303
3702
|
/** @type {string[]} */
|
|
@@ -2326,17 +3725,17 @@ export async function themeEditPreviewRemove(page, options = {}) {
|
|
|
2326
3725
|
const name = shown(cwd, inside(rel));
|
|
2327
3726
|
/** @type {string[]} */
|
|
2328
3727
|
const deletes = [];
|
|
3728
|
+
const ids = new Set(data.pages.map(p => p.id));
|
|
3729
|
+
const verdict = ownedUnchanged(at.dir, data, rel, ids);
|
|
2329
3730
|
if (!data.files.includes(rel)) {
|
|
2330
3731
|
kept.push(name);
|
|
2331
3732
|
notes.push(
|
|
2332
3733
|
`${name} was not written by the preview, so it is kept; only its nav item is gone`,
|
|
2333
3734
|
);
|
|
2334
3735
|
} else if (!fs.existsSync(inside(rel))) missing.push(name);
|
|
2335
|
-
else if (
|
|
3736
|
+
else if (verdict !== 'delete') {
|
|
2336
3737
|
kept.push(name);
|
|
2337
|
-
notes.push(
|
|
2338
|
-
`${name} was changed by hand after the preview wrote it, so it is kept`,
|
|
2339
|
-
);
|
|
3738
|
+
notes.push(keptNote(name, verdict));
|
|
2340
3739
|
} else deletes.push(rel);
|
|
2341
3740
|
data.pages = data.pages.filter(x => x !== target);
|
|
2342
3741
|
data.files = data.files.filter(f => f !== rel);
|
|
@@ -2375,8 +3774,10 @@ export async function themeEditPreviewRemove(page, options = {}) {
|
|
|
2375
3774
|
}
|
|
2376
3775
|
/** @type {Array<{rel: string, text: string}>} */
|
|
2377
3776
|
let planned;
|
|
3777
|
+
/** @type {Awaited<ReturnType<typeof routeTheme>>} */
|
|
3778
|
+
let theme;
|
|
2378
3779
|
try {
|
|
2379
|
-
|
|
3780
|
+
theme = await routeTheme(cwd, at.dir, data, {build: false});
|
|
2380
3781
|
planned = await routeWrites(cwd, at.dir, data, theme, {gone});
|
|
2381
3782
|
} catch (e) {
|
|
2382
3783
|
const err = /** @type {any} */ (e);
|
|
@@ -2406,6 +3807,7 @@ export async function themeEditPreviewRemove(page, options = {}) {
|
|
|
2406
3807
|
if (!data.files.includes(w.rel)) data.files.push(w.rel);
|
|
2407
3808
|
if (was !== 'same') rewritten.push(shown(cwd, path.join(at.dir, w.rel)));
|
|
2408
3809
|
}
|
|
3810
|
+
await buildWorn(cwd, theme, options, notes);
|
|
2409
3811
|
commitPreview(
|
|
2410
3812
|
cwd,
|
|
2411
3813
|
at.dir,
|
|
@@ -2415,7 +3817,10 @@ export async function themeEditPreviewRemove(page, options = {}) {
|
|
|
2415
3817
|
retry(options.path ?? null),
|
|
2416
3818
|
);
|
|
2417
3819
|
tidyPageFolders(at.dir);
|
|
2418
|
-
if (gone)
|
|
3820
|
+
if (gone)
|
|
3821
|
+
await themeLocked(options, gone, () =>
|
|
3822
|
+
recordPreview(cwd, gone, at.dir, false),
|
|
3823
|
+
);
|
|
2419
3824
|
return {
|
|
2420
3825
|
type: 'themeEdit.previewRemove',
|
|
2421
3826
|
data: {
|
|
@@ -2433,14 +3838,21 @@ export async function themeEditPreviewRemove(page, options = {}) {
|
|
|
2433
3838
|
// The whole preview: every entry is checked before the first delete. A
|
|
2434
3839
|
// route changed by hand would be kept and still import the pages, so it
|
|
2435
3840
|
// stops the remove instead.
|
|
3841
|
+
refuseIfLockLost();
|
|
2436
3842
|
if (data.files.includes('page.tsx') && editedByHand(at.dir, data, 'page.tsx'))
|
|
2437
3843
|
refuse(
|
|
2438
3844
|
E.ERR_FILE_EXISTS,
|
|
2439
3845
|
`${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
3846
|
{
|
|
2441
|
-
fix: `copy your changes out of ${shown(cwd, path.join(at.dir, 'page.tsx'))},
|
|
3847
|
+
fix: `copy your changes out of ${shown(cwd, path.join(at.dir, 'page.tsx'))}, give it another name, then run ${PREVIEW} remove${pf} again`,
|
|
2442
3848
|
},
|
|
2443
3849
|
);
|
|
3850
|
+
const ids = new Set(data.pages.map(p => p.id));
|
|
3851
|
+
// A route the preview keeps still imports its pages, so they stay too.
|
|
3852
|
+
const routeKept =
|
|
3853
|
+
fs.existsSync(path.join(at.dir, 'page.tsx')) &&
|
|
3854
|
+
(!data.files.includes('page.tsx') ||
|
|
3855
|
+
ownedUnchanged(at.dir, data, 'page.tsx', ids) !== 'delete');
|
|
2444
3856
|
/** @type {Array<{file: string, before: Buffer}>} */
|
|
2445
3857
|
const plan = [];
|
|
2446
3858
|
for (const rel of data.files) {
|
|
@@ -2460,10 +3872,16 @@ export async function themeEditPreviewRemove(page, options = {}) {
|
|
|
2460
3872
|
`"files" holds ${rel}, which is a folder; the preview writes only files`,
|
|
2461
3873
|
pf,
|
|
2462
3874
|
);
|
|
2463
|
-
|
|
3875
|
+
const verdict = ownedUnchanged(at.dir, data, rel, ids);
|
|
3876
|
+
if (verdict !== 'delete') {
|
|
3877
|
+
kept.push(shown(cwd, file));
|
|
3878
|
+
notes.push(keptNote(shown(cwd, file), verdict));
|
|
3879
|
+
continue;
|
|
3880
|
+
}
|
|
3881
|
+
if (routeKept && rel !== PREVIEW_DATA) {
|
|
2464
3882
|
kept.push(shown(cwd, file));
|
|
2465
3883
|
notes.push(
|
|
2466
|
-
`${shown(cwd, file)}
|
|
3884
|
+
`${shown(cwd, file)} is kept: page.tsx stays, and it imports the pages`,
|
|
2467
3885
|
);
|
|
2468
3886
|
continue;
|
|
2469
3887
|
}
|
|
@@ -2495,12 +3913,34 @@ export async function themeEditPreviewRemove(page, options = {}) {
|
|
|
2495
3913
|
);
|
|
2496
3914
|
}
|
|
2497
3915
|
tidyPageFolders(at.dir);
|
|
3916
|
+
// Files the record does not list stay: the preview never deletes what it
|
|
3917
|
+
// has no record of writing. Each is named, so the folder left is no
|
|
3918
|
+
// surprise.
|
|
3919
|
+
for (const rel of unrecordedPages(at.dir)) {
|
|
3920
|
+
const name = shown(cwd, path.join(at.dir, rel));
|
|
3921
|
+
if (kept.includes(name)) continue;
|
|
3922
|
+
kept.push(name);
|
|
3923
|
+
notes.push(
|
|
3924
|
+
`${name} is kept: the preview has no record of writing it, so it may hold your work`,
|
|
3925
|
+
);
|
|
3926
|
+
}
|
|
2498
3927
|
try {
|
|
2499
3928
|
fs.rmdirSync(at.dir);
|
|
3929
|
+
// Route group folders, such as (tools)/, that only held the preview.
|
|
3930
|
+
for (
|
|
3931
|
+
let up = path.dirname(at.dir);
|
|
3932
|
+
/^\(.+\)$/.test(path.basename(up)) && at.app && up.startsWith(at.app);
|
|
3933
|
+
up = path.dirname(up)
|
|
3934
|
+
)
|
|
3935
|
+
fs.rmdirSync(up);
|
|
2500
3936
|
} catch {
|
|
2501
3937
|
// Not empty: something there is not the preview's.
|
|
2502
3938
|
}
|
|
2503
|
-
|
|
3939
|
+
const worn = data.theme;
|
|
3940
|
+
if (worn)
|
|
3941
|
+
await themeLocked(options, worn, () =>
|
|
3942
|
+
recordPreview(cwd, worn, at.dir, false),
|
|
3943
|
+
);
|
|
2504
3944
|
return {
|
|
2505
3945
|
type: 'themeEdit.previewRemove',
|
|
2506
3946
|
data: {folder, removed, kept, missing, rewritten: [], notes, pages: []},
|