@stagepass/cli 2.2.7 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +37 -18
  2. package/TESTING-macos.md +28 -10
  3. package/bin/index.js +4 -1
  4. package/package.json +9 -8
  5. package/src/cli.js +62 -7
  6. package/src/commands/certs.js +375 -19
  7. package/src/commands/daemon.js +75 -7
  8. package/src/commands/dev.js +419 -0
  9. package/src/commands/link.js +64 -23
  10. package/src/commands/new.js +397 -41
  11. package/src/commands/npm-run.js +8 -0
  12. package/src/commands/start.js +220 -127
  13. package/src/commands/stop.js +10 -19
  14. package/src/commands/unlink.js +6 -4
  15. package/src/commands/upgrade.js +51 -12
  16. package/src/lib/apply-site-block.js +48 -0
  17. package/src/lib/caddyfile.js +72 -13
  18. package/src/lib/cdn-snippets.js +145 -3
  19. package/src/lib/certs.js +334 -47
  20. package/src/lib/dev-port.js +45 -0
  21. package/src/lib/doctor-site.js +61 -5
  22. package/src/lib/doctor.js +48 -4
  23. package/src/lib/ensure-running.js +89 -0
  24. package/src/lib/exec.js +72 -24
  25. package/src/lib/live-server.js +484 -0
  26. package/src/lib/node-engine.js +55 -0
  27. package/src/lib/notify.js +62 -0
  28. package/src/lib/origins.js +27 -5
  29. package/src/lib/package-versions.js +9 -0
  30. package/src/lib/paths.js +18 -0
  31. package/src/lib/php-fpm.js +33 -0
  32. package/src/lib/project-sync.js +165 -20
  33. package/src/lib/projects.js +137 -7
  34. package/src/lib/prompts.js +47 -0
  35. package/src/lib/registry.js +27 -6
  36. package/src/lib/scaffold.js +288 -11
  37. package/src/lib/site-detect.js +78 -25
  38. package/src/lib/snippets.js +14 -11
  39. package/src/lib/versions.js +20 -8
  40. package/templates/project/AGENTS.md.tmpl +4 -3
  41. package/templates/project/README.md.tmpl +35 -6
  42. package/templates/project/api/README.md.tmpl +7 -0
  43. package/templates/project/examples/php/README.md.tmpl +18 -0
  44. package/templates/project/examples/php/form.php +105 -0
  45. package/templates/project/examples/php/proxy.php +171 -0
  46. package/templates/project/scripts/build.mjs +200 -37
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Early Node engine gate for the CLI bin.
3
+ * Kept free of heavy deps so it can run before importing commander/inquirer.
4
+ */
5
+
6
+ export const MIN_NODE_MAJOR = 20;
7
+ export const MIN_NODE_MINOR = 17;
8
+
9
+ /**
10
+ * @param {string} [version] process.version-style (e.g. v20.10.0)
11
+ * @returns {{ major: number, minor: number, patch: number } | null}
12
+ */
13
+ export function parseNodeVersion(version = process.version) {
14
+ const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(version || ''));
15
+ if (!m) return null;
16
+ return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) };
17
+ }
18
+
19
+ /**
20
+ * @param {string} [version]
21
+ * @returns {boolean}
22
+ */
23
+ export function meetsNodeEngine(version = process.version) {
24
+ const parsed = parseNodeVersion(version);
25
+ if (!parsed) return false;
26
+ if (parsed.major > MIN_NODE_MAJOR) return true;
27
+ if (parsed.major < MIN_NODE_MAJOR) return false;
28
+ return parsed.minor >= MIN_NODE_MINOR;
29
+ }
30
+
31
+ /**
32
+ * @param {string} [version]
33
+ * @returns {string}
34
+ */
35
+ export function unsupportedNodeMessage(version = process.version) {
36
+ return (
37
+ `@stagepass/cli requires Node.js >=${MIN_NODE_MAJOR}.${MIN_NODE_MINOR}.0 ` +
38
+ `(current: ${version}). Upgrade Node, or pin @stagepass/cli@2.2.7 on Node 18.`
39
+ );
40
+ }
41
+
42
+ /**
43
+ * @param {object} [opts]
44
+ * @param {string} [opts.version]
45
+ * @param {(msg: string) => void} [opts.write]
46
+ * @param {(code: number) => void} [opts.exit]
47
+ */
48
+ export function assertNodeEngine(opts = {}) {
49
+ const version = opts.version || process.version;
50
+ if (meetsNodeEngine(version)) return;
51
+ const write = opts.write || ((msg) => console.error(msg));
52
+ const exit = opts.exit || ((code) => process.exit(code));
53
+ write(unsupportedNodeMessage(version));
54
+ exit(1);
55
+ }
@@ -0,0 +1,62 @@
1
+ import { defaultExec } from './exec.js';
2
+
3
+ const DEFAULT_TITLE = 'Stagepass';
4
+ const MAX_TITLE = 80;
5
+ const MAX_BODY = 200;
6
+
7
+ /**
8
+ * Truncate notification text for display.
9
+ * @param {unknown} value
10
+ * @param {number} max
11
+ */
12
+ export function truncateNotifyText(value, max) {
13
+ const text = String(value == null ? '' : value).replace(/\s+/g, ' ').trim();
14
+ if (text.length <= max) return text;
15
+ return `${text.slice(0, Math.max(0, max - 1))}…`;
16
+ }
17
+
18
+ /**
19
+ * Build `osascript` argv so title/body are passed via AppleScript `argv`
20
+ * (never interpolated into the script source).
21
+ *
22
+ * @param {string} title
23
+ * @param {string} body
24
+ * @returns {string[]}
25
+ */
26
+ export function buildOsascriptNotificationArgs(title, body) {
27
+ const safeTitle = truncateNotifyText(title || DEFAULT_TITLE, MAX_TITLE) || DEFAULT_TITLE;
28
+ const safeBody = truncateNotifyText(body || '', MAX_BODY) || 'Stagepass reported a problem.';
29
+ // argv items after -- are positional; script never embeds caller text.
30
+ const script = [
31
+ 'on run argv',
32
+ ' set theTitle to item 1 of argv',
33
+ ' set theMessage to item 2 of argv',
34
+ ' display notification theMessage with title theTitle',
35
+ 'end run',
36
+ ].join('\n');
37
+ return ['-e', script, '--', safeTitle, safeBody];
38
+ }
39
+
40
+ /**
41
+ * Fire-and-forget macOS notification. Never throws; never blocks callers long.
42
+ *
43
+ * @param {object} opts
44
+ * @param {string} [opts.title]
45
+ * @param {string} opts.body
46
+ * @param {import('./exec.js').ExecFn} [opts.exec]
47
+ * @param {(ms: number) => Promise<void>} [opts.sleep]
48
+ * @param {number} [opts.timeoutMs]
49
+ * @returns {Promise<boolean>} true if the process exited 0
50
+ */
51
+ export async function notifyMac(opts) {
52
+ const exec = opts.exec || defaultExec;
53
+ const timeoutMs = opts.timeoutMs ?? 3000;
54
+ const args = buildOsascriptNotificationArgs(opts.title || DEFAULT_TITLE, opts.body);
55
+ try {
56
+ const run = exec('osascript', args, { timeout: timeoutMs });
57
+ await run;
58
+ return true;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
@@ -11,6 +11,29 @@
11
11
 
12
12
  const UNSAFE_ORIGIN_RE = /[\s#"'{}$\\;()[\],<>|/]/;
13
13
  const HOSTNAME_LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
14
+ /** Whitespace (incl. Unicode) or C0/DEL controls; reject on the raw CLI string before trim/URL parse. */
15
+ const HOST_WHITESPACE_OR_CONTROL_RE = /[\s\x00-\x1f\x7f]/;
16
+ export const HOST_WHITESPACE_ERROR =
17
+ 'Host must not contain whitespace or control characters.';
18
+
19
+ /**
20
+ * Reject hosts / site inputs that contain whitespace or control characters.
21
+ * Call on the raw string before any trim or `new URL()`.
22
+ *
23
+ * @param {unknown} input
24
+ * @param {string} [label]
25
+ * @returns {{ ok: true } | { ok: false, error: string }}
26
+ */
27
+ export function rejectWhitespaceOrControls(input, label = 'Host') {
28
+ const raw = String(input == null ? '' : input);
29
+ if (HOST_WHITESPACE_OR_CONTROL_RE.test(raw)) {
30
+ return {
31
+ ok: false,
32
+ error: `${label} must not contain whitespace or control characters.`,
33
+ };
34
+ }
35
+ return { ok: true };
36
+ }
14
37
 
15
38
  /** Built-in Origin regex alternatives (without leading ^ / trailing $ / (?i)). */
16
39
  export const DEFAULT_ORIGIN_ALTERNATIVES = Object.freeze([
@@ -40,15 +63,14 @@ export function isBroadWebflowWildcard(entry) {
40
63
  * @returns {{ ok: true, value: string } | { ok: false, error: string }}
41
64
  */
42
65
  export function validateOriginEntry(input) {
43
- if (typeof input !== 'string' || input.trim() === '') {
66
+ if (typeof input !== 'string' || input === '') {
44
67
  return { ok: false, error: 'Origin entry is empty.' };
45
68
  }
46
69
 
47
- let raw = input.trim().toLowerCase();
70
+ const ws = rejectWhitespaceOrControls(input, 'Origin');
71
+ if (!ws.ok) return ws;
48
72
 
49
- if (/[\x00-\x1f\x7f]/.test(raw)) {
50
- return { ok: false, error: 'Origin contains control characters.' };
51
- }
73
+ let raw = input.toLowerCase();
52
74
 
53
75
  // Optional https:// only (http reserved for localhost defaults)
54
76
  if (raw.startsWith('http://')) {
@@ -0,0 +1,9 @@
1
+ /**
2
+ * GENERATED FILE. Do not edit by hand.
3
+ * Run: node scripts/sync-cli-versions.mjs
4
+ *
5
+ * Sourced from packages/loader and packages/modules package.json at generate time.
6
+ * The published CLI ships this snapshot; it cannot read the monorepo at runtime.
7
+ */
8
+ export const LOADER_VERSION = "2.4.0";
9
+ export const MODULES_VERSION = "2.2.2";
package/src/lib/paths.js CHANGED
@@ -65,6 +65,24 @@ export function getCaddyRootCaPath(opts = {}) {
65
65
  return path.join(dataDir, 'pki', 'authorities', 'local', 'root.crt');
66
66
  }
67
67
 
68
+ /**
69
+ * Caddy local CA authority directory (contains root.crt / intermediate).
70
+ * @param {{ home?: string, env?: NodeJS.ProcessEnv, dataDir?: string }} [opts]
71
+ */
72
+ export function getCaddyPkiAuthoritiesLocalDir(opts = {}) {
73
+ const dataDir = opts.dataDir || getCaddyDataDir(opts);
74
+ return path.join(dataDir, 'pki', 'authorities', 'local');
75
+ }
76
+
77
+ /**
78
+ * Caddy on-disk site certificate store for the internal ("local") issuer.
79
+ * @param {{ home?: string, env?: NodeJS.ProcessEnv, dataDir?: string }} [opts]
80
+ */
81
+ export function getCaddyCertificatesLocalDir(opts = {}) {
82
+ const dataDir = opts.dataDir || getCaddyDataDir(opts);
83
+ return path.join(dataDir, 'certificates', 'local');
84
+ }
85
+
68
86
  /**
69
87
  * Common secondary data dir when Homebrew's Caddy service sets XDG_DATA_HOME.
70
88
  * Report-only helper for doctor/certs (never delete).
@@ -0,0 +1,33 @@
1
+ import { defaultExec } from './exec.js';
2
+
3
+ /**
4
+ * Ensure Homebrew PHP-FPM is running (non-interactive, never sudo).
5
+ * Uses `brew services start php`, falling back to `restart` if start fails.
6
+ *
7
+ * @param {object} [opts]
8
+ * @param {import('./exec.js').ExecFn} [opts.exec]
9
+ * @param {'ignore'|'inherit'} [opts.stdio]
10
+ * @returns {Promise<{ ok: boolean, action: string, detail?: string }>}
11
+ */
12
+ export async function ensurePhpFpm(opts = {}) {
13
+ const exec = opts.exec || defaultExec;
14
+ const stdio = opts.stdio || 'ignore';
15
+
16
+ try {
17
+ await exec('brew', ['services', 'start', 'php'], { stdio });
18
+ return { ok: true, action: 'start' };
19
+ } catch (startError) {
20
+ try {
21
+ await exec('brew', ['services', 'restart', 'php'], { stdio });
22
+ return { ok: true, action: 'restart' };
23
+ } catch (restartError) {
24
+ const detail = [
25
+ startError instanceof Error ? startError.message : String(startError),
26
+ restartError instanceof Error ? restartError.message : String(restartError),
27
+ ]
28
+ .filter(Boolean)
29
+ .join(' | ');
30
+ return { ok: false, action: 'failed', detail };
31
+ }
32
+ }
33
+ }
@@ -1,5 +1,12 @@
1
1
  /**
2
- * Sync generated project files with declared Stagepass modules
2
+ * Sync generated project files with the declared Stagepass modules
3
+ * (used by `stagepass upgrade` and `stagepass doctor`).
4
+ *
5
+ * Writes only:
6
+ * - stagepass.json `modules` (and `origin` when passed via --site)
7
+ * - AGENTS.md managed block (created when missing)
8
+ * - .cursor/rules/stagepass.mdc (created when missing, managed block refreshed)
9
+ * - tsconfig.json / jsconfig.json `compilerOptions.types` (plain JSON only)
3
10
  */
4
11
 
5
12
  import path from 'node:path';
@@ -18,9 +25,11 @@ import {
18
25
  typesForModules,
19
26
  } from './project-modules.js';
20
27
  import { loadProjects } from './projects.js';
28
+ import { validateOriginEntry, validateOriginList } from './origins.js';
21
29
  import { describeDetection, normalizeSiteUrl, SITE_PORT_ERROR } from './site-detect.js';
22
30
 
23
31
  /**
32
+ * Read and parse stagepass.json (null when missing or invalid).
24
33
  * @param {string} cwd
25
34
  * @param {typeof fs} [fse]
26
35
  * @returns {Promise<{ exists: boolean, data: Record<string, unknown> | null, raw: string, error?: string }>}
@@ -41,6 +50,7 @@ export async function readStagepassJson(cwd, fse = fs) {
41
50
  }
42
51
 
43
52
  /**
53
+ * Declared modules from stagepass.json (`null` when missing or legacy boolean).
44
54
  * @param {Record<string, unknown> | null} data
45
55
  * @returns {string[] | null}
46
56
  */
@@ -50,11 +60,56 @@ export function declaredModules(data) {
50
60
  return result.ok ? result.modules : null;
51
61
  }
52
62
 
63
+ /**
64
+ * CORS origins declared in stagepass.json for `stagepass link` with no --origin flags.
65
+ * Reads `origin` (staging) and optional `production`. Invalid entries are skipped.
66
+ *
67
+ * @param {Record<string, unknown> | null} data
68
+ * @returns {string[]}
69
+ */
70
+ export function originsFromStagepassConfig(data) {
71
+ if (!data || typeof data !== 'object') return [];
72
+ const raw = [];
73
+ for (const key of ['origin', 'production']) {
74
+ const value = data[key];
75
+ if (typeof value !== 'string' || value.trim() === '') continue;
76
+ // Stored config may have incidental spaces; CLI flags are validated raw (AC-10).
77
+ const check = validateOriginEntry(value.trim());
78
+ if (check.ok) raw.push(check.value);
79
+ }
80
+ const validated = validateOriginList(raw);
81
+ return validated.ok ? validated.origins : [];
82
+ }
83
+
84
+ /**
85
+ * PHP toggle from stagepass.json (`undefined` when unset).
86
+ * @param {Record<string, unknown> | null} data
87
+ * @returns {boolean|undefined}
88
+ */
89
+ export function phpFromStagepassConfig(data) {
90
+ if (!data || typeof data !== 'object') return undefined;
91
+ if (data.php === true) return true;
92
+ if (data.php === false) return false;
93
+ return undefined;
94
+ }
95
+
96
+ /**
97
+ * Validate a staging/production hostname for `stagepass new` (origins.js rules).
98
+ * @param {string} input
99
+ * @returns {{ ok: true, value: string } | { ok: false, error: string }}
100
+ */
101
+ export function validateProjectOriginHost(input) {
102
+ return validateOriginEntry(input);
103
+ }
104
+
53
105
  function warnPortSkip(log, source) {
54
106
  if (log) log(`Skipped ${source}: it contains a port. Use the host only, e.g. my-site.webflow.io.`);
55
107
  }
56
108
 
57
109
  /**
110
+ * Live origin for a project: stagepass.json `origin`, else the first concrete
111
+ * (non-wildcard) origin stored by `stagepass link` for this project folder.
112
+ *
58
113
  * @param {string} cwd
59
114
  * @param {Record<string, unknown> | null} data
60
115
  * @param {{ loadProjects?: typeof loadProjects, realpath?: (p: string) => Promise<string> }} [deps]
@@ -99,11 +154,15 @@ export async function resolveProjectOrigin(cwd, data, deps = {}) {
99
154
  }
100
155
 
101
156
  /**
157
+ * Decide the declared modules list for `upgrade`.
158
+ * Order: --site-modules flag, live site detection, existing stagepass.json,
159
+ * interactive prompt. The npm dependency is only mentioned as a hint.
160
+ *
102
161
  * @param {object} input
103
162
  * @param {string} input.cwd
104
- * @param {Record<string, unknown> | null} input.data
105
- * @param {object} input.pkg
106
- * @param {object} input.options
163
+ * @param {Record<string, unknown> | null} input.data stagepass.json
164
+ * @param {object} input.pkg package.json
165
+ * @param {object} input.options { siteModules?, site?, skipSite?, yes? }
107
166
  * @param {object} deps
108
167
  * @param {(site: string) => Promise<any>} deps.detectSite
109
168
  * @param {(question: string, def: string) => Promise<string>} [deps.ask]
@@ -137,7 +196,7 @@ export async function resolveUpgradeModules(input, deps) {
137
196
  if (!check.ok) return { ok: false, error: check.error };
138
197
  origin = check.host;
139
198
  } else {
140
- const found = await resolveProjectOrigin(cwd, data, { loadProjects: deps.loadProjects, log });
199
+ const found = await resolveProjectOrigin(cwd, data, { loadProjects: deps.loadProjects });
141
200
  origin = found ? found.origin : null;
142
201
  }
143
202
 
@@ -169,7 +228,9 @@ export async function resolveUpgradeModules(input, deps) {
169
228
  source = 'stagepass.json';
170
229
  }
171
230
 
172
- // Legacy `"modules": true` meant all modules typed; keep as `["all"]` without a live site.
231
+ // Legacy `"modules": true` (CLI 2.0/2.1) meant "modules included", typed via
232
+ // `@stagepass/modules` (all modules). Keep that as `["all"]` so an upgrade
233
+ // without a live site result never removes types the project relied on.
173
234
  if (!candidate && data?.modules === true) {
174
235
  candidate = ['all'];
175
236
  source = 'legacy "modules": true in stagepass.json';
@@ -216,7 +277,9 @@ export async function resolveUpgradeModules(input, deps) {
216
277
  }
217
278
 
218
279
  /**
219
- * @param {string} raw
280
+ * Update `compilerOptions.types` in a tsconfig/jsconfig source.
281
+ *
282
+ * @param {string} raw file contents
220
283
  * @param {string[]} modules
221
284
  * @param {{ modulesDependency: boolean, perModuleTypes?: boolean }} opts
222
285
  * @returns {{ status: 'updated' | 'unchanged' | 'skipped', content?: string, reason?: string, types?: string[] }}
@@ -258,13 +321,24 @@ export function updateConfigTypes(raw, modules, opts) {
258
321
  return { status: 'updated', content: `${JSON.stringify(json, null, 2)}${trailing}`, types: nextTypes };
259
322
  }
260
323
 
324
+ /** @param {string} abs @param {typeof fs} fse */
325
+ async function isSymlink(abs, fse) {
326
+ try {
327
+ return (await fse.lstat(abs)).isSymbolicLink();
328
+ } catch {
329
+ return false;
330
+ }
331
+ }
332
+
261
333
  /**
334
+ * Plan file changes for the declared modules (pure, no writes).
335
+ *
262
336
  * @param {object} input
263
337
  * @param {string} input.cwd
264
338
  * @param {string[]} input.modules
265
- * @param {string | null} [input.origin]
266
- * @param {object} input.pkg
267
- * @param {boolean} [input.perModuleTypes]
339
+ * @param {string | null} [input.origin] stored in stagepass.json when set
340
+ * @param {object} input.pkg package.json
341
+ * @param {boolean} [input.perModuleTypes] false when @stagepass/modules has no per-module types (umbrella entry)
268
342
  * @param {typeof fs} [fse]
269
343
  * @returns {Promise<{ writes: { file: string, content: string, action: string }[], notes: string[] }>}
270
344
  */
@@ -278,12 +352,29 @@ export async function planProjectSync(input, fse = fs) {
278
352
  pkg?.dependencies?.['@stagepass/modules'] || pkg?.devDependencies?.['@stagepass/modules']
279
353
  );
280
354
  const perModuleTypes = input.perModuleTypes;
355
+ /** Skip target when it (or a path ancestor under cwd) is a symlink. */
356
+ const skipSymlink = async (rel) => {
357
+ const abs = path.join(cwd, rel);
358
+ const root = path.resolve(cwd);
359
+ let cur = abs;
360
+ for (;;) {
361
+ if (await isSymlink(cur, fse)) {
362
+ notes.push(`${rel} is a symlink; left unchanged`);
363
+ return true;
364
+ }
365
+ const parent = path.dirname(cur);
366
+ if (parent === cur || path.resolve(parent) === root) break;
367
+ if (!path.resolve(parent).startsWith(root + path.sep) && path.resolve(parent) !== root) break;
368
+ cur = parent;
369
+ }
370
+ return false;
371
+ };
281
372
 
282
373
  // stagepass.json
283
374
  const sp = await readStagepassJson(cwd, fse);
284
375
  if (sp.exists && !sp.data) {
285
376
  notes.push(`stagepass.json skipped: ${sp.error}`);
286
- } else {
377
+ } else if (!(await skipSymlink('stagepass.json'))) {
287
378
  /** @type {Record<string, unknown>} */
288
379
  let data;
289
380
  if (sp.data) {
@@ -307,7 +398,9 @@ export async function planProjectSync(input, fse = fs) {
307
398
  // AGENTS.md
308
399
  const block = buildManagedBlock(modules);
309
400
  const agentsPath = path.join(cwd, 'AGENTS.md');
310
- if (await fse.pathExists(agentsPath)) {
401
+ if (await skipSymlink('AGENTS.md')) {
402
+ // note already added
403
+ } else if (await fse.pathExists(agentsPath)) {
311
404
  const raw = await fse.readFile(agentsPath, 'utf8');
312
405
  const result = upsertManagedBlock(raw, block);
313
406
  if (result.action === 'invalid') {
@@ -330,7 +423,9 @@ export async function planProjectSync(input, fse = fs) {
330
423
 
331
424
  // Cursor rule
332
425
  const rulePath = path.join(cwd, CURSOR_RULE_PATH);
333
- if (await fse.pathExists(rulePath)) {
426
+ if (await skipSymlink(CURSOR_RULE_PATH)) {
427
+ // note already added
428
+ } else if (await fse.pathExists(rulePath)) {
334
429
  const raw = await fse.readFile(rulePath, 'utf8');
335
430
  if (raw.includes(BLOCK_BEGIN)) {
336
431
  const result = upsertManagedBlock(raw, block);
@@ -352,6 +447,7 @@ export async function planProjectSync(input, fse = fs) {
352
447
  const file = path.join(cwd, name);
353
448
  if (!(await fse.pathExists(file))) continue;
354
449
  sawConfig = true;
450
+ if (await skipSymlink(name)) continue;
355
451
  const raw = await fse.readFile(file, 'utf8');
356
452
  const result = updateConfigTypes(raw, modules, { modulesDependency, perModuleTypes });
357
453
  if (result.status === 'skipped') {
@@ -372,19 +468,68 @@ export async function planProjectSync(input, fse = fs) {
372
468
  }
373
469
 
374
470
  /**
471
+ * Write planned changes. On failure restores prior file contents (INV-4).
375
472
  * @param {string} cwd
376
473
  * @param {{ file: string, content: string }[]} writes
377
474
  * @param {typeof fs} [fse]
378
475
  */
379
476
  export async function applyProjectSync(cwd, writes, fse = fs) {
380
477
  const root = path.resolve(cwd);
381
- for (const w of writes) {
382
- const abs = path.resolve(root, w.file);
383
- const rel = path.relative(root, abs);
384
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
385
- throw new Error(`Refusing to write outside the project: ${w.file}`);
478
+ const rootReal = await fse.realpath(root);
479
+ /** @type {{ abs: string, previous: string | null, createdDir: string | null }[]} */
480
+ const journal = [];
481
+ try {
482
+ for (const w of writes) {
483
+ const abs = path.resolve(root, w.file);
484
+ const rel = path.relative(root, abs);
485
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
486
+ throw new Error(`Refusing to write outside the project: ${w.file}`);
487
+ }
488
+ if (await isSymlink(abs, fse)) {
489
+ throw new Error(`Refusing to write through symlink: ${w.file}`);
490
+ }
491
+ const parent = path.dirname(abs);
492
+ let parentProbe = parent;
493
+ for (;;) {
494
+ try {
495
+ const parentReal = await fse.realpath(parentProbe);
496
+ if (parentReal !== rootReal && !parentReal.startsWith(rootReal + path.sep)) {
497
+ throw new Error(`Refusing to write outside the project: ${w.file}`);
498
+ }
499
+ break;
500
+ } catch (err) {
501
+ if (err instanceof Error && err.message.startsWith('Refusing')) throw err;
502
+ const up = path.dirname(parentProbe);
503
+ if (up === parentProbe) throw err;
504
+ parentProbe = up;
505
+ }
506
+ }
507
+ let previous = null;
508
+ try {
509
+ previous = await fse.readFile(abs, 'utf8');
510
+ } catch (err) {
511
+ if (!(err && /** @type {{ code?: string }} */ (err).code === 'ENOENT')) throw err;
512
+ }
513
+ let createdDir = null;
514
+ if (!(await fse.pathExists(parent))) {
515
+ await fse.ensureDir(parent);
516
+ createdDir = parent;
517
+ } else {
518
+ await fse.ensureDir(parent);
519
+ }
520
+ await fse.writeFile(abs, w.content, 'utf8');
521
+ journal.push({ abs, previous, createdDir });
522
+ }
523
+ } catch (err) {
524
+ for (const entry of [...journal].reverse()) {
525
+ try {
526
+ if (entry.previous == null) await fse.remove(entry.abs);
527
+ else await fse.writeFile(entry.abs, entry.previous, 'utf8');
528
+ if (entry.createdDir) await fse.remove(entry.createdDir);
529
+ } catch {
530
+ /* best effort */
531
+ }
386
532
  }
387
- await fse.ensureDir(path.dirname(abs));
388
- await fse.writeFile(abs, w.content, 'utf8');
533
+ throw err;
389
534
  }
390
535
  }