@widgetic/dev-tools 0.3.10 → 0.3.12

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.
@@ -0,0 +1,390 @@
1
+ /**
2
+ * What a package would take to the registry, read before it goes: every relative import of a packed file must land on
3
+ * another packed file.
4
+ *
5
+ * `npm pack` takes the files the `files` field names. A file of that list that imports `../shared/format.js`, where the
6
+ * import goes out of the package, or `./format.js` that the build did not write, installs fine and then throws when a
7
+ * consumer loads it (`@widgetic/editor` 4.1.19 was such a release). A bundler or `svelte-package` that leaves `$lib/...`
8
+ * in its output has the same effect. Nothing in the repository sees it: the files are all there on the laptop that
9
+ * publishes.
10
+ *
11
+ * The reading is of code, not of text. Comments, strings, template literals and regular expression literals are taken out
12
+ * before the imports are looked for, so a comment that shows `import x from '../y'` as an example, or a string that
13
+ * holds the source of a file a tool writes, is never mistaken for an import. A `.svelte` file is read in its `<script>`
14
+ * blocks only. This is a tokenizer, not a parser: it does not tell a `/` that divides from one that starts a regular
15
+ * expression in every position (it uses the token before it), and an import it cannot see is missed, never invented.
16
+ */
17
+
18
+ import { spawnSync } from 'node:child_process';
19
+ import { readFileSync } from 'node:fs';
20
+ import { posix, extname, join } from 'node:path';
21
+
22
+ /** The files whose imports are read. Everything else of the pack (json, css, images, markdown) has none. */
23
+ export const SCANNED_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.svelte']);
24
+
25
+ /**
26
+ * What an import may name, by what the importing file is. A file that runs (`.js`, `.mjs`, `.cjs`, `.svelte`) can only load
27
+ * a file that runs, so a `./x.js` that is only a `./x.d.ts` in the pack is a break. A `.d.ts` file is read by TypeScript,
28
+ * which takes `./x.js` and `./x.ts` for `./x.d.ts`. A `.ts` source file takes `./x.js` for `./x.ts`.
29
+ */
30
+ const RUNTIME_SUFFIXES = ['', '.js', '.mjs', '.cjs', '.json', '.node', '.svelte'];
31
+ const RUNTIME_INDEXES = ['/index.js', '/index.mjs', '/index.cjs', '/index.json', '/index.svelte'];
32
+ const SOURCE_SUFFIXES = ['.ts', '.mts', '.cts'];
33
+ const SOURCE_INDEXES = ['/index.ts', '/index.mts', '/index.cts'];
34
+ const DECLARATION_SUFFIXES = ['.d.ts', '.d.mts', '.d.cts'];
35
+ const DECLARATION_INDEXES = ['/index.d.ts', '/index.d.mts', '/index.d.cts'];
36
+
37
+ /** Words after which a `/` starts a regular expression and does not divide. */
38
+ const WORDS_BEFORE_REGEX = new Set([
39
+ 'return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else', 'yield', 'await'
40
+ ]);
41
+ /** Characters after which a `/` starts a regular expression and does not divide. */
42
+ const CHARACTERS_BEFORE_REGEX = '(,=:[!&|?{};+-*%<>~^';
43
+
44
+ /**
45
+ * Where a template literal that starts at `start` (the backtick) ends. The `${ }` expressions inside it may hold braces,
46
+ * strings and templates of their own.
47
+ * @param {string} source
48
+ * @param {number} start
49
+ * @returns {number} the index after the closing backtick
50
+ */
51
+ function skipTemplate(source, start) {
52
+ let index = start + 1;
53
+ while (index < source.length) {
54
+ const character = source[index];
55
+ if (character === '\\') {
56
+ index += 2;
57
+ } else if (character === '`') {
58
+ return index + 1;
59
+ } else if (character === '$' && source[index + 1] === '{') {
60
+ index = skipTemplateExpression(source, index + 2);
61
+ } else {
62
+ index += 1;
63
+ }
64
+ }
65
+ return source.length;
66
+ }
67
+
68
+ /**
69
+ * Where the `${ }` expression whose content starts at `start` ends.
70
+ * @param {string} source
71
+ * @param {number} start
72
+ * @returns {number} the index after the closing brace
73
+ */
74
+ function skipTemplateExpression(source, start) {
75
+ let depth = 1;
76
+ let index = start;
77
+ while (index < source.length && depth > 0) {
78
+ const character = source[index];
79
+ if (character === '`') {
80
+ index = skipTemplate(source, index);
81
+ } else if (character === '"' || character === "'") {
82
+ index += 1;
83
+ while (index < source.length && source[index] !== character && source[index] !== '\n') {
84
+ index += source[index] === '\\' ? 2 : 1;
85
+ }
86
+ index += 1;
87
+ } else {
88
+ if (character === '{') depth += 1;
89
+ if (character === '}') depth -= 1;
90
+ index += 1;
91
+ }
92
+ }
93
+ return index;
94
+ }
95
+
96
+ /**
97
+ * Where the regular expression literal that starts at `start` (the first slash) ends, or `start + 1` when what follows is
98
+ * not one (the line ends first).
99
+ * @param {string} source
100
+ * @param {number} start
101
+ * @returns {number}
102
+ */
103
+ function skipRegularExpression(source, start) {
104
+ let index = start + 1;
105
+ let insideClass = false;
106
+ while (index < source.length) {
107
+ const character = source[index];
108
+ if (character === '\n') return start + 1;
109
+ if (character === '\\') {
110
+ index += 2;
111
+ continue;
112
+ }
113
+ if (character === '[') insideClass = true;
114
+ else if (character === ']') insideClass = false;
115
+ else if (character === '/' && !insideClass) {
116
+ index += 1;
117
+ while (index < source.length && /[a-z]/i.test(source[index])) index += 1;
118
+ return index;
119
+ }
120
+ index += 1;
121
+ }
122
+ return start + 1;
123
+ }
124
+
125
+ /**
126
+ * The code of `source` with comments, template literals and regular expressions taken out, and every string literal
127
+ * replaced by a placeholder (`'§0§'`, `'§1§'`, ...) whose text is kept in `strings`. A specifier is a string, so an
128
+ * import statement stays recognisable, while text that only looks like one, inside a string or a template, does not.
129
+ * @param {string} source
130
+ * @returns {{ code: string, strings: string[] }}
131
+ */
132
+ export function maskSource(source) {
133
+ /** @type {string[]} */
134
+ const strings = [];
135
+ let code = '';
136
+ let index = 0;
137
+ let lastCharacter = '';
138
+ let lastWord = '';
139
+ let currentWord = '';
140
+ const endWord = () => {
141
+ if (currentWord !== '') lastWord = currentWord;
142
+ currentWord = '';
143
+ };
144
+ while (index < source.length) {
145
+ const character = source[index];
146
+ const following = source[index + 1];
147
+ if (character === '/' && following === '/') {
148
+ while (index < source.length && source[index] !== '\n') index += 1;
149
+ continue;
150
+ }
151
+ if (character === '/' && following === '*') {
152
+ const end = source.indexOf('*/', index + 2);
153
+ index = end === -1 ? source.length : end + 2;
154
+ endWord();
155
+ code += ' ';
156
+ continue;
157
+ }
158
+ if (character === '"' || character === "'") {
159
+ endWord();
160
+ let end = index + 1;
161
+ let value = '';
162
+ while (end < source.length && source[end] !== character && source[end] !== '\n') {
163
+ if (source[end] === '\\') {
164
+ value += source[end] + (source[end + 1] ?? '');
165
+ end += 2;
166
+ } else {
167
+ value += source[end];
168
+ end += 1;
169
+ }
170
+ }
171
+ strings.push(value);
172
+ code += `'§${strings.length - 1}§'`;
173
+ lastCharacter = "'";
174
+ lastWord = '';
175
+ index = end + 1;
176
+ continue;
177
+ }
178
+ if (character === '`') {
179
+ endWord();
180
+ index = skipTemplate(source, index);
181
+ code += '``';
182
+ lastCharacter = '`';
183
+ lastWord = '';
184
+ continue;
185
+ }
186
+ if (character === '/') {
187
+ endWord();
188
+ const startsRegularExpression =
189
+ lastCharacter === '' ||
190
+ (CHARACTERS_BEFORE_REGEX.includes(lastCharacter) && lastWord === '') ||
191
+ WORDS_BEFORE_REGEX.has(lastWord);
192
+ if (startsRegularExpression) {
193
+ const end = skipRegularExpression(source, index);
194
+ if (end > index + 1) {
195
+ code += '/x/';
196
+ lastCharacter = ')';
197
+ lastWord = '';
198
+ index = end;
199
+ continue;
200
+ }
201
+ }
202
+ }
203
+ if (/[\w$]/.test(character)) {
204
+ currentWord += character;
205
+ } else {
206
+ endWord();
207
+ }
208
+ code += character;
209
+ if (!/\s/.test(character)) {
210
+ lastCharacter = character;
211
+ if (!/[\w$]/.test(character)) lastWord = '';
212
+ }
213
+ index += 1;
214
+ }
215
+ return { code, strings };
216
+ }
217
+
218
+ /**
219
+ * The text of the `<script>` blocks of a Svelte file, one after the other.
220
+ * @param {string} source
221
+ * @returns {string}
222
+ */
223
+ export function svelteScriptText(source) {
224
+ let text = '';
225
+ for (const match of source.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)) text += `${match[1]}\n`;
226
+ return text;
227
+ }
228
+
229
+ // `import x from 'a'`, `import { a, b } from 'a'`, `import * as x from 'a'`, `import 'a'`, `import type { A } from 'a'`,
230
+ // `export * from 'a'`, `export { a } from 'a'`. What stands between the keyword and `from` has no quote, no semicolon, no
231
+ // parenthesis and no equals sign, which `export const x = 'a'` and `export default 'a'` would have.
232
+ const STATIC_IMPORT = /(?<![\w$.])(?:import|export)\b\s*(?:[\w$*{},\s]*?\bfrom\s*)?'§(\d+)§'/g;
233
+ const DYNAMIC_IMPORT = /(?<![\w$.])import\s*\(\s*'§(\d+)§'\s*[,)]/g;
234
+ const REQUIRE_CALL = /(?<![\w$.])require\s*\(\s*'§(\d+)§'\s*\)/g;
235
+ const REFERENCE_PATH = /^\s*\/\/\/\s*<reference\s+path\s*=\s*["']([^"']+)["']/gm;
236
+
237
+ /**
238
+ * The module specifiers a file imports, with the comments, strings and templates out of the way.
239
+ * @param {string} source the text of a `.js`, `.mjs`, `.cjs`, `.ts`, `.mts`, `.cts` file, or the scripts of a `.svelte` one
240
+ * @returns {string[]}
241
+ */
242
+ export function findSpecifiers(source) {
243
+ const { code, strings } = maskSource(source);
244
+ /** @type {Set<string>} */
245
+ const specifiers = new Set();
246
+ for (const pattern of [STATIC_IMPORT, DYNAMIC_IMPORT, REQUIRE_CALL]) {
247
+ for (const match of code.matchAll(pattern)) specifiers.add(strings[Number(match[1])]);
248
+ }
249
+ for (const match of source.matchAll(REFERENCE_PATH)) specifiers.add(match[1]);
250
+ return [...specifiers];
251
+ }
252
+
253
+ /**
254
+ * What a relative import of `fromFile` lands on, among the packed files.
255
+ * @param {string} fromFile a path of the pack, with `/` separators
256
+ * @param {string} specifier an import that starts with `.`
257
+ * @param {ReadonlySet<string>} packedFiles
258
+ * @returns {{ status: 'ok' | 'missing' | 'outside', target: string }}
259
+ */
260
+ export function resolvePackedTarget(fromFile, specifier, packedFiles) {
261
+ const joined = posix.normalize(posix.join(posix.dirname(fromFile), specifier));
262
+ if (joined === '..' || joined.startsWith('../')) return { status: 'outside', target: joined };
263
+ const base = joined.replace(/\/$/, '');
264
+ const importerIsDeclaration = /\.d\.[mc]?ts$/.test(fromFile);
265
+ const importerIsSource = !importerIsDeclaration && /\.[mc]?ts$/.test(fromFile);
266
+ /** @type {string[]} */
267
+ const candidates = [...RUNTIME_SUFFIXES.map((suffix) => base + suffix), ...RUNTIME_INDEXES.map((suffix) => base + suffix)];
268
+ // `./x.js` and `./x.ts` name a script by the extension TypeScript wrote or reads, whatever the pack holds for it.
269
+ const scriptName = /\.([mc]?)(js|ts)$/.exec(base);
270
+ const stem = scriptName && !base.endsWith('.d.ts') ? base.slice(0, -scriptName[0].length) : null;
271
+ const flavour = scriptName ? scriptName[1] : '';
272
+ if (importerIsDeclaration) {
273
+ candidates.push(...DECLARATION_SUFFIXES.map((suffix) => base + suffix), ...DECLARATION_INDEXES.map((suffix) => base + suffix));
274
+ if (stem !== null) candidates.push(`${stem}.d.${flavour}ts`);
275
+ }
276
+ if (importerIsSource) {
277
+ candidates.push(...SOURCE_SUFFIXES.map((suffix) => base + suffix), ...SOURCE_INDEXES.map((suffix) => base + suffix));
278
+ if (stem !== null) candidates.push(`${stem}.${flavour}ts`);
279
+ }
280
+ const found = candidates.find((candidate) => packedFiles.has(candidate));
281
+ return found ? { status: 'ok', target: found } : { status: 'missing', target: joined };
282
+ }
283
+
284
+ /**
285
+ * @typedef {{ file: string, specifier: string, reason: 'outside' | 'missing' | 'alias', target?: string }} PackedImportProblem
286
+ */
287
+
288
+ /**
289
+ * Every import of the packed files that cannot be loaded from the installed package.
290
+ * @param {ReadonlyMap<string, string>} packedFiles path (with `/` separators) to the text of each file that is read
291
+ * for imports; a path the pack holds that is not read (an image, a json) is in `unreadPaths`
292
+ * @param {Iterable<string>} [unreadPaths] the other paths of the pack: an import may land on them
293
+ * @returns {PackedImportProblem[]}
294
+ */
295
+ export function findPackedImportProblems(packedFiles, unreadPaths = []) {
296
+ const allPaths = new Set([...packedFiles.keys(), ...unreadPaths]);
297
+ /** @type {PackedImportProblem[]} */
298
+ const problems = [];
299
+ for (const [file, text] of packedFiles) {
300
+ const source = file.endsWith('.svelte') ? svelteScriptText(text) : text;
301
+ for (const specifier of findSpecifiers(source)) {
302
+ if (specifier === '$lib' || specifier.startsWith('$lib/')) {
303
+ problems.push({ file, specifier, reason: 'alias' });
304
+ continue;
305
+ }
306
+ if (!(specifier === '.' || specifier === '..' || specifier.startsWith('./') || specifier.startsWith('../'))) continue;
307
+ // A bundler's suffix (`./a.css?inline`, `./a.svg#icon`) is not part of the file name.
308
+ const resolved = resolvePackedTarget(file, specifier.replace(/[?#].*$/, ''), allPaths);
309
+ if (resolved.status !== 'ok') problems.push({ file, specifier, reason: resolved.status, target: resolved.target });
310
+ }
311
+ }
312
+ return problems;
313
+ }
314
+
315
+ /**
316
+ * The paths `npm pack` would put in the package in `packageDir`, with `/` separators. Nothing is written and no script
317
+ * of the package runs (`--ignore-scripts`, the way the publish runs).
318
+ * @param {string} packageDir
319
+ * @returns {string[]}
320
+ */
321
+ export function listPackedPaths(packageDir) {
322
+ const result = spawnSync('npm', ['pack', '--dry-run', '--json', '--ignore-scripts'], {
323
+ cwd: packageDir,
324
+ encoding: 'utf8',
325
+ maxBuffer: 256 * 1024 * 1024
326
+ });
327
+ if (result.status !== 0) {
328
+ throw new Error(`npm pack --dry-run exited ${result.status ?? 'without a status'}: ${(result.stderr || '').trim().slice(0, 400)}`);
329
+ }
330
+ const text = result.stdout.trim();
331
+ /** @type {{ files?: { path: string }[] }[]} */
332
+ let parsed;
333
+ try {
334
+ parsed = JSON.parse(text.slice(text.indexOf('[')));
335
+ } catch (error) {
336
+ throw new Error(`npm pack --dry-run --json printed something that is not JSON: ${text.slice(0, 200)}`);
337
+ }
338
+ const files = parsed?.[0]?.files;
339
+ if (!Array.isArray(files)) throw new Error('npm pack --dry-run --json did not list the files of the package');
340
+ return files.map((file) => String(file.path).replaceAll('\\', '/'));
341
+ }
342
+
343
+ /**
344
+ * Checks the package in `packageDir`: reads the files the pack holds and returns the imports that cannot be loaded from
345
+ * the installed package.
346
+ * @param {string} packageDir
347
+ * @param {{ listPaths?: (packageDir: string) => string[] }} [options] `listPaths` is for tests
348
+ * @returns {{ packedCount: number, scannedCount: number, problems: PackedImportProblem[] }}
349
+ */
350
+ export function checkPackedImports(packageDir, { listPaths = listPackedPaths } = {}) {
351
+ const paths = listPaths(packageDir);
352
+ /** @type {Map<string, string>} */
353
+ const readable = new Map();
354
+ /** @type {string[]} */
355
+ const unread = [];
356
+ for (const path of paths) {
357
+ if (!SCANNED_EXTENSIONS.has(extname(path))) {
358
+ unread.push(path);
359
+ continue;
360
+ }
361
+ try {
362
+ readable.set(path, readFileSync(join(packageDir, path), 'utf8'));
363
+ } catch (error) {
364
+ // A path the pack lists and the disk does not have is a problem of its own: say so, do not skip it quietly.
365
+ throw new Error(`${path} is in the pack but cannot be read: ${error instanceof Error ? error.message : String(error)}`);
366
+ }
367
+ }
368
+ return {
369
+ packedCount: paths.length,
370
+ scannedCount: readable.size,
371
+ problems: findPackedImportProblems(readable, unread)
372
+ };
373
+ }
374
+
375
+ /**
376
+ * The lines to print for the problems found: one per import, with what is wrong with it.
377
+ * @param {PackedImportProblem[]} problems
378
+ * @returns {string[]}
379
+ */
380
+ export function describePackedImportProblems(problems) {
381
+ return problems.map((problem) => {
382
+ if (problem.reason === 'alias') {
383
+ return `${problem.file} imports '${problem.specifier}', an alias that only exists in the source tree`;
384
+ }
385
+ if (problem.reason === 'outside') {
386
+ return `${problem.file} imports '${problem.specifier}', a file outside the package (${problem.target})`;
387
+ }
388
+ return `${problem.file} imports '${problem.specifier}', which is not in the package (${problem.target})`;
389
+ });
390
+ }
@@ -14,6 +14,8 @@ export const PUBLISHABLE_PACKAGES = [
14
14
  { dir: 'cache-layer', script: 'publish-to-npm' },
15
15
  { dir: 'design-system', script: 'publish-to-npm' },
16
16
  { dir: 'dev-tools', script: 'publish-to-npm' },
17
+ // Before widget-creator (and the apps), which take it as a peer for the Agent's mascot.
18
+ { dir: 'brand', script: 'publish-to-npm' },
17
19
  { dir: 'canvas', script: 'publish-to-npm' },
18
20
  { dir: 'chat', script: 'publish-to-npm' },
19
21
  { dir: 'editor', script: 'publish-to-npm' },
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Bring every git checkout under `Frontend/` to its remote, and drop the Vite
3
+ * dep caches that keep serving yesterday's `@widgetic/*` source.
4
+ *
5
+ * The sibling layout (`frontend-layout.mjs`) names the packages an app may
6
+ * alias. This walk is wider: `site`, `blog`, `docs-site` and anything else
7
+ * that has a `.git` next to them, because a stale checkout of any of those
8
+ * looks like a product bug in the browser. Discovery is the disk: a directory
9
+ * with a `.git` entry is a checkout; a directory without one is skipped.
10
+ *
11
+ * `git pull --ff-only` never rewrites local history. A dirty working tree is
12
+ * committed first (paths named in the message, secrets such as `.env` left
13
+ * unstaged), then pulled. A branch with no upstream, or a divergence that
14
+ * cannot fast-forward, is reported and left as it was. Vite caches
15
+ * (`node_modules/.vite` and `node_modules/.vite-temp`) are removed after the
16
+ * pull so the next `npm run dev` re-optimizes against the files that are
17
+ * actually on disk.
18
+ *
19
+ * Zero dependencies. Git and the filesystem are injected so the tests can
20
+ * drive a throwaway tree without touching a real checkout.
21
+ */
22
+
23
+ import { existsSync, readdirSync, rmSync, statSync } from 'node:fs';
24
+ import { join } from 'node:path';
25
+ import { spawnSync } from 'node:child_process';
26
+
27
+ /** Relative to a checkout root: Vite's prebundle, and the temp dir it uses while writing one. */
28
+ export const VITE_CACHE_RELATIVE_PATHS = Object.freeze(['node_modules/.vite', 'node_modules/.vite-temp']);
29
+
30
+ /**
31
+ * Immediate child directories of `frontendRoot` that are git checkouts.
32
+ *
33
+ * @param {string} frontendRoot
34
+ * @returns {string[]} Absolute paths, sorted by directory name.
35
+ */
36
+ export function listGitCheckouts(frontendRoot) {
37
+ if (!existsSync(frontendRoot)) return [];
38
+ /** @type {string[]} */
39
+ const checkouts = [];
40
+ for (const name of readdirSync(frontendRoot)) {
41
+ if (name.startsWith('.')) continue;
42
+ const root = join(frontendRoot, name);
43
+ try {
44
+ if (!statSync(root).isDirectory()) continue;
45
+ } catch {
46
+ continue;
47
+ }
48
+ if (!existsSync(join(root, '.git'))) continue;
49
+ checkouts.push(root);
50
+ }
51
+ return checkouts.sort((a, b) => a.localeCompare(b));
52
+ }
53
+
54
+ /**
55
+ * Absolute Vite cache directories that currently exist under a checkout.
56
+ *
57
+ * @param {string} checkoutRoot
58
+ * @returns {string[]}
59
+ */
60
+ export function existingViteCacheDirectories(checkoutRoot) {
61
+ return VITE_CACHE_RELATIVE_PATHS.map((relative) => join(checkoutRoot, relative)).filter((path) => existsSync(path));
62
+ }
63
+
64
+ /**
65
+ * @typedef {{
66
+ * code: number | null,
67
+ * stdout: string,
68
+ * stderr: string
69
+ * }} GitRunResult
70
+ */
71
+
72
+ /**
73
+ * @typedef {{
74
+ * name: string,
75
+ * root: string,
76
+ * pull: 'pulled' | 'already-up-to-date' | 'skipped-dirty' | 'skipped-no-upstream' | 'skipped-secrets' | 'failed' | 'dry-run' | 'skipped',
77
+ * pullDetail?: string,
78
+ * committed?: boolean,
79
+ * commitDetail?: string,
80
+ * cachesRemoved: string[],
81
+ * cachesWouldRemove: string[]
82
+ * }} CheckoutSyncResult
83
+ */
84
+
85
+ /**
86
+ * Run `git` in a checkout. The default talks to the real binary; tests pass a stub.
87
+ *
88
+ * @param {string} checkoutRoot
89
+ * @param {string[]} args
90
+ * @returns {GitRunResult}
91
+ */
92
+ export function runGit(checkoutRoot, args) {
93
+ const result = spawnSync('git', args, {
94
+ cwd: checkoutRoot,
95
+ encoding: 'utf8',
96
+ // A hung remote must not freeze the whole walk.
97
+ timeout: 120_000
98
+ });
99
+ return {
100
+ code: result.status,
101
+ stdout: result.stdout ?? '',
102
+ stderr: result.stderr ?? (result.error ? result.error.message : '')
103
+ };
104
+ }
105
+
106
+ /**
107
+ * @param {string} checkoutRoot
108
+ * @param {(root: string, args: string[]) => GitRunResult} git
109
+ * @returns {{ dirty: boolean, hasUpstream: boolean, dirtyDetail: string }}
110
+ */
111
+ export function inspectCheckout(checkoutRoot, git = runGit) {
112
+ const status = git(checkoutRoot, ['status', '--porcelain']);
113
+ const dirtyDetail = `${status.stdout}${status.stderr}`.trim();
114
+ const dirty = status.code !== 0 || dirtyDetail.length > 0;
115
+ const upstream = git(checkoutRoot, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
116
+ const hasUpstream = upstream.code === 0 && upstream.stdout.trim().length > 0;
117
+ return { dirty, hasUpstream, dirtyDetail };
118
+ }
119
+
120
+ const SECRET_PATH = /(^|[\\/])(\.env([.].*)?|credentials\.json|id_rsa|\.pem)$/i;
121
+
122
+ /**
123
+ * Paths from `git status --porcelain` (including untracked), without the XY prefix.
124
+ *
125
+ * @param {string} porcelain
126
+ * @returns {string[]}
127
+ */
128
+ export function pathsFromPorcelain(porcelain) {
129
+ const paths = [];
130
+ for (const line of porcelain.split('\n')) {
131
+ if (!line.trim()) continue;
132
+ const path = line.slice(3).trim().replace(/ -> .*$/, '');
133
+ if (path) paths.push(path);
134
+ }
135
+ return paths;
136
+ }
137
+
138
+ /**
139
+ * @param {string} path
140
+ * @returns {boolean}
141
+ */
142
+ export function isSecretPath(path) {
143
+ return SECRET_PATH.test(path);
144
+ }
145
+
146
+ /**
147
+ * Conventional subject + body from the checkout name and the files that will be committed.
148
+ *
149
+ * @param {string} checkoutName
150
+ * @param {string[]} paths
151
+ * @returns {{ subject: string, body: string }}
152
+ */
153
+ export function commitMessageForDirtyCheckout(checkoutName, paths) {
154
+ const docsOnly = paths.length > 0 && paths.every((path) => /(^|[\\/])__docs([\\/]|$)/.test(path) || /\.md$/i.test(path));
155
+ const kind = docsOnly ? 'docs' : 'chore';
156
+ const subject = `${kind}(${checkoutName}): commit local changes before sync pull`;
157
+ const body = paths.map((path) => `- ${path}`).join('\n');
158
+ return { subject, body };
159
+ }
160
+
161
+ /**
162
+ * Stage and commit restorable local work. `.env` and similar secrets stay unstaged.
163
+ *
164
+ * @param {string} checkoutRoot
165
+ * @param {string} checkoutName
166
+ * @param {(root: string, args: string[]) => GitRunResult} git
167
+ * @returns {{ committed: boolean, detail: string, skip?: 'secrets' | 'nothing' | 'failed' }}
168
+ */
169
+ export function commitDirtyCheckout(checkoutRoot, checkoutName, git = runGit) {
170
+ const inspection = inspectCheckout(checkoutRoot, git);
171
+ if (!inspection.dirty) return { committed: false, detail: 'clean', skip: 'nothing' };
172
+ const paths = pathsFromPorcelain(inspection.dirtyDetail);
173
+ const rest = paths.filter((path) => !isSecretPath(path) && path !== '.DS_Store');
174
+ if (rest.length === 0) {
175
+ return { committed: false, detail: 'only secrets or ignored files', skip: 'secrets' };
176
+ }
177
+ const staged = git(checkoutRoot, ['add', '--', ...rest]);
178
+ if (staged.code !== 0) {
179
+ return {
180
+ committed: false,
181
+ detail: `${staged.stdout}${staged.stderr}`.trim() || 'git add failed',
182
+ skip: 'failed'
183
+ };
184
+ }
185
+ const { subject, body } = commitMessageForDirtyCheckout(checkoutName, rest);
186
+ const committed = git(checkoutRoot, ['commit', '-m', subject, '-m', body]);
187
+ if (committed.code !== 0) {
188
+ return {
189
+ committed: false,
190
+ detail: `${committed.stdout}${committed.stderr}`.trim() || 'git commit failed',
191
+ skip: 'failed'
192
+ };
193
+ }
194
+ return { committed: true, detail: subject };
195
+ }
196
+
197
+ /**
198
+ * Walk every Frontend git checkout: fast-forward pull, then drop Vite caches.
199
+ *
200
+ * @param {{
201
+ * frontendRoot: string,
202
+ * pull?: boolean,
203
+ * cleanVite?: boolean,
204
+ * dryRun?: boolean,
205
+ * commitDirty?: boolean,
206
+ * git?: (root: string, args: string[]) => GitRunResult,
207
+ * removeDirectory?: (path: string) => void
208
+ * }} options
209
+ * @returns {CheckoutSyncResult[]}
210
+ */
211
+ export function syncFrontendCheckouts({
212
+ frontendRoot,
213
+ pull = true,
214
+ cleanVite = true,
215
+ dryRun = false,
216
+ commitDirty = true,
217
+ git = runGit,
218
+ removeDirectory = (path) => rmSync(path, { recursive: true, force: true })
219
+ }) {
220
+ const checkouts = listGitCheckouts(frontendRoot);
221
+ /** @type {CheckoutSyncResult[]} */
222
+ const results = [];
223
+
224
+ for (const root of checkouts) {
225
+ const name = root.slice(frontendRoot.length).replace(/^[/\\]/, '');
226
+ /** @type {CheckoutSyncResult} */
227
+ const row = {
228
+ name,
229
+ root,
230
+ pull: 'skipped',
231
+ cachesRemoved: [],
232
+ cachesWouldRemove: []
233
+ };
234
+
235
+ if (pull) {
236
+ if (dryRun) {
237
+ row.pull = 'dry-run';
238
+ } else {
239
+ let inspection = inspectCheckout(root, git);
240
+ if (inspection.dirty && commitDirty) {
241
+ const saved = commitDirtyCheckout(root, name, git);
242
+ row.committed = saved.committed;
243
+ row.commitDetail = saved.detail;
244
+ if (!saved.committed) {
245
+ row.pull = saved.skip === 'secrets' ? 'skipped-secrets' : 'failed';
246
+ row.pullDetail = saved.detail;
247
+ } else {
248
+ inspection = inspectCheckout(root, git);
249
+ }
250
+ } else if (inspection.dirty && !commitDirty) {
251
+ row.pull = 'skipped-dirty';
252
+ row.pullDetail = inspection.dirtyDetail.split('\n')[0] ?? 'working tree is not clean';
253
+ }
254
+ if (row.pull !== 'skipped-secrets' && row.pull !== 'failed' && row.pull !== 'skipped-dirty') {
255
+ if (!inspection.hasUpstream) {
256
+ row.pull = 'skipped-no-upstream';
257
+ row.pullDetail = 'no upstream branch';
258
+ } else {
259
+ const pulled = git(root, ['pull', '--ff-only']);
260
+ const output = `${pulled.stdout}${pulled.stderr}`.trim();
261
+ if (pulled.code === 0) {
262
+ row.pull = /already up to date/i.test(output) ? 'already-up-to-date' : 'pulled';
263
+ row.pullDetail = output.split('\n').filter(Boolean).at(-1);
264
+ } else {
265
+ row.pull = 'failed';
266
+ row.pullDetail = output.split('\n').filter(Boolean).at(-1) || `git exited ${pulled.code}`;
267
+ }
268
+ }
269
+ }
270
+ }
271
+ }
272
+
273
+ if (cleanVite) {
274
+ const caches = existingViteCacheDirectories(root);
275
+ row.cachesWouldRemove = caches;
276
+ if (!dryRun) {
277
+ for (const cache of caches) {
278
+ removeDirectory(cache);
279
+ row.cachesRemoved.push(cache);
280
+ }
281
+ }
282
+ }
283
+
284
+ results.push(row);
285
+ }
286
+
287
+ return results;
288
+ }