@stagepass/cli 2.2.7 → 2.3.0-beta.1

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 +196 -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 +19 -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
@@ -11,6 +11,9 @@ import {
11
11
  defaultTemplatesRoot,
12
12
  planScaffoldFiles,
13
13
  findConflicts,
14
+ assertScaffoldParentPath,
15
+ writeScaffoldFiles,
16
+ rollbackScaffold,
14
17
  } from '../lib/scaffold.js';
15
18
  import {
16
19
  buildWebflowSnippets,
@@ -28,16 +31,31 @@ import {
28
31
  resolveSnippetLoaderVersion,
29
32
  } from '../lib/registry.js';
30
33
  import { updateConfigTypes } from '../lib/project-sync.js';
34
+ import { validateOriginEntry, isBroadWebflowWildcard } from '../lib/origins.js';
35
+ import { isMacOS } from '../lib/platform.js';
36
+ import { runDoctor } from '../lib/doctor.js';
37
+ import { setup as defaultSetup } from './setup.js';
38
+ import { link as defaultLink } from './link.js';
31
39
 
32
40
  const PER_MODULE_TYPES_HINT =
33
41
  '@stagepass/modules on npm has no per-module types yet (needs 2.2.0); ' +
34
42
  'types use "@stagepass/modules" for now. Run `stagepass upgrade` once it is published to narrow them.';
35
43
 
44
+ const PRODUCTION_HINT =
45
+ 'Production domain skipped. Add it later with: stagepass link --origin example.com';
46
+
47
+ /** Core stack check ids that mean setup is likely needed. */
48
+ const SETUP_CHECK_IDS = new Set(['homebrew', 'caddy', 'dnsmasq', 'resolver']);
49
+
36
50
  /**
51
+ * Resolve a boolean flag that may appear as --foo / --no-foo.
52
+ * Only argv is trusted: Commander defaults negated pairs to true, which would
53
+ * break defaults like --install (off unless passed).
54
+ *
37
55
  * @param {object} _options
38
56
  * @param {string} key
39
57
  * @param {string[]} argv
40
- * @param {boolean|undefined} defaultValue
58
+ * @param {boolean|undefined} defaultValue undefined = still unset
41
59
  */
42
60
  export function resolveBoolFlag(_options, key, argv, defaultValue) {
43
61
  const pos = `--${key}`;
@@ -48,7 +66,34 @@ export function resolveBoolFlag(_options, key, argv, defaultValue) {
48
66
  }
49
67
 
50
68
  /**
51
- * @param {object} options
69
+ * @param {string|undefined} raw
70
+ * @param {string} label
71
+ * @returns {{ ok: true, value: string } | { ok: true, value: '' } | { ok: false, error: string }}
72
+ */
73
+ export function parseOriginFlag(raw, label) {
74
+ // Empty means "not set". Whitespace-only must fail via validateOriginEntry (AC-10).
75
+ if (raw == null || String(raw) === '') {
76
+ return { ok: true, value: '' };
77
+ }
78
+ const check = validateOriginEntry(String(raw));
79
+ if (!check.ok) {
80
+ return { ok: false, error: `Invalid --${label}: ${check.error}` };
81
+ }
82
+ return { ok: true, value: check.value };
83
+ }
84
+
85
+ /**
86
+ * @param {import('../lib/doctor.js').DoctorCheck[] | { id: string, status: string }[]} checks
87
+ * @returns {boolean}
88
+ */
89
+ export function doctorSuggestsSetup(checks) {
90
+ return (checks || []).some(
91
+ (c) => SETUP_CHECK_IDS.has(c.id) && (c.status === 'fail' || c.status === 'warn')
92
+ );
93
+ }
94
+
95
+ /**
96
+ * @param {object} options Commander options
52
97
  * @param {object} [deps]
53
98
  */
54
99
  async function resolveAuthor(options, deps) {
@@ -92,6 +137,7 @@ async function askYesNo(rl, question, defaultYes) {
92
137
  }
93
138
 
94
139
  /**
140
+ * Merge flags + optional interactive prompts into a resolved config.
95
141
  * @param {string|undefined} nameArg
96
142
  * @param {object} options
97
143
  * @param {object} deps
@@ -111,10 +157,16 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
111
157
  let styles =
112
158
  options.styles === 'css' || options.styles === 'scss' ? options.styles : '';
113
159
 
114
- // Prefer argv for --foo / --no-foo so Commander defaults do not flip.
160
+ // Prefer argv for --foo / --no-foo so Commander default quirks do not flip defaults.
115
161
  let modules = resolveBoolFlag(options, 'modules', argv, undefined);
116
162
  let git = resolveBoolFlag(options, 'git', argv, undefined);
117
163
  let install = resolveBoolFlag(options, 'install', argv, undefined);
164
+ let php = resolveBoolFlag(options, 'php', argv, undefined);
165
+ let phpExamples = resolveBoolFlag(options, 'php-examples', argv, undefined);
166
+ if (phpExamples === undefined) {
167
+ phpExamples = resolveBoolFlag(options, 'phpExamples', argv, undefined);
168
+ }
169
+ let linkAtEnd = resolveBoolFlag(options, 'link', argv, undefined);
118
170
  let remote = options.remote != null ? String(options.remote).trim() : '';
119
171
  const log = deps.log || console.log;
120
172
  const detect = deps.detectSite || detectSite;
@@ -126,22 +178,65 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
126
178
  if (!parsed.ok) return { ok: false, error: parsed.error };
127
179
  siteModules = parsed.modules;
128
180
  }
181
+
129
182
  /** @type {string} */
130
183
  let origin = '';
131
- if (options.site != null && String(options.site).trim() !== '') {
132
- const check = normalizeSiteUrl(String(options.site));
184
+ /** @type {string} */
185
+ let production = '';
186
+ /** @type {boolean} */
187
+ let productionSkipped = false;
188
+
189
+ // Pass raw flag values (no trim): whitespace/controls must abort before write/network.
190
+ const siteFlag = options.site != null && String(options.site) !== '' ? String(options.site) : '';
191
+ const stagingFlag =
192
+ options.staging != null && String(options.staging) !== '' ? String(options.staging) : '';
193
+
194
+ if (siteFlag) {
195
+ const check = normalizeSiteUrl(siteFlag);
133
196
  if (!check.ok) return { ok: false, error: check.error };
134
197
  origin = check.host;
135
198
  }
199
+ if (stagingFlag) {
200
+ const check = parseOriginFlag(stagingFlag, 'staging');
201
+ if (!check.ok) return check;
202
+ if (origin && origin !== check.value) {
203
+ return {
204
+ ok: false,
205
+ error: `--site (${origin}) and --staging (${check.value}) disagree. Pass only one, or matching values.`,
206
+ };
207
+ }
208
+ origin = check.value;
209
+ }
210
+ if (options.production != null && String(options.production) !== '') {
211
+ const check = parseOriginFlag(String(options.production), 'production');
212
+ if (!check.ok) return check;
213
+ production = check.value;
214
+ } else if (
215
+ Object.prototype.hasOwnProperty.call(options, 'production') &&
216
+ (options.production === '' || options.production == null) &&
217
+ !interactive
218
+ ) {
219
+ productionSkipped = true;
220
+ }
136
221
 
137
222
  /**
138
- * Detect modules on the live site (public GET, never executed).
139
- * @returns {Promise<string[] | null>} detected list, or null when unknown
140
- */
223
+ * Detect modules on the live site (public GET, never executed).
224
+ * @returns {Promise<string[] | null>} detected list, or null when unknown
225
+ */
141
226
  const detectFromSite = async () => {
142
227
  if (!origin) return null;
143
- log(`Checking live site https://${origin}/ for Stagepass script tags...`);
144
- const det = await detect(origin);
228
+ // Wildcards are valid CORS origins but not fetchable site hosts.
229
+ if (origin.startsWith('*.')) {
230
+ log(chalk.dim(` Staging ${origin} is a wildcard; skipping live module detection.`));
231
+ return null;
232
+ }
233
+ const siteCheck = normalizeSiteUrl(origin);
234
+ if (!siteCheck.ok) {
235
+ log(chalk.dim(` ${siteCheck.error} Skipping live module detection.`));
236
+ return null;
237
+ }
238
+ log(`Checking live site https://${siteCheck.host}/ for Stagepass script tags...`);
239
+ const det = await detect(siteCheck.host);
145
240
  log(` ${describeDetection(det)}`);
146
241
  if (det.ok && det.loader) return det.list;
147
242
  if (det.ok) log(' The page does not load @stagepass/loader yet.');
@@ -171,15 +266,51 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
171
266
  const raw = await ask(rl, 'Styles (scss|css)', 'scss');
172
267
  styles = raw === 'css' ? 'css' : 'scss';
173
268
  }
174
- if (siteModules === undefined && modules !== false) {
175
- if (!origin) {
176
- const raw = await ask(rl, 'Live Webflow site to check (optional, e.g. my-project.webflow.io)', '');
177
- if (raw) {
178
- const check = normalizeSiteUrl(raw);
179
- if (check.ok) origin = check.host;
180
- else log(chalk.yellow(` ${check.error} Skipping the live check.`));
269
+ if (!origin) {
270
+ const suggested = name ? `${String(name).trim().toLowerCase()}.webflow.io` : '';
271
+ const raw = await ask(
272
+ rl,
273
+ 'Staging domain (e.g. my-project.webflow.io)',
274
+ suggested
275
+ );
276
+ if (raw) {
277
+ const check = validateOriginEntry(raw);
278
+ if (check.ok) {
279
+ origin = check.value;
280
+ if (isBroadWebflowWildcard(origin)) {
281
+ log(
282
+ chalk.yellow(
283
+ ` Warning: ${origin} allows any Webflow user's site (CORS). Prefer a concrete staging host.`
284
+ )
285
+ );
286
+ }
287
+ } else {
288
+ log(chalk.yellow(` ${check.error} Skipping staging origin.`));
289
+ }
290
+ }
291
+ }
292
+ if (!production) {
293
+ const raw = await ask(rl, 'Production domain (optional)', '');
294
+ if (raw) {
295
+ const check = validateOriginEntry(raw);
296
+ if (check.ok) {
297
+ production = check.value;
298
+ if (isBroadWebflowWildcard(production)) {
299
+ log(
300
+ chalk.yellow(
301
+ ` Warning: ${production} is a broad wildcard; prefer an exact production host.`
302
+ )
303
+ );
304
+ }
305
+ } else {
306
+ log(chalk.yellow(` ${check.error} Skipping production origin.`));
307
+ productionSkipped = true;
181
308
  }
309
+ } else {
310
+ productionSkipped = true;
182
311
  }
312
+ }
313
+ if (siteModules === undefined && modules !== false) {
183
314
  const detected = await detectFromSite();
184
315
  if (detected && (await askYesNo(rl, `Use modules detected on the site: ${formatModules(detected)}?`, true))) {
185
316
  siteModules = detected;
@@ -195,6 +326,12 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
195
326
  else log(chalk.yellow(` ${parsed.error}`));
196
327
  }
197
328
  }
329
+ if (php === undefined) {
330
+ php = await askYesNo(rl, 'Enable PHP for this project?', false);
331
+ }
332
+ if (php && phpExamples === undefined) {
333
+ phpExamples = await askYesNo(rl, 'Include PHP examples under examples/php/?', false);
334
+ }
198
335
  if (git === undefined) {
199
336
  git = await askYesNo(rl, 'Initialize git repository?', true);
200
337
  }
@@ -204,6 +341,10 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
204
341
  if (install === undefined) {
205
342
  install = await askYesNo(rl, 'Run npm install now?', false);
206
343
  }
344
+ if (linkAtEnd === undefined) {
345
+ // Asked after create on macOS only; remember preference here when already decided.
346
+ linkAtEnd = undefined;
347
+ }
207
348
  } finally {
208
349
  rl.close();
209
350
  }
@@ -227,7 +368,7 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
227
368
  error: '--no-modules conflicts with declared site modules. Drop --no-modules or pass --site-modules none.',
228
369
  };
229
370
  }
230
- // npm package (types) follows the declared list; legacy default is included.
371
+ // The npm package (types) follows the declared list; keep the legacy default (included).
231
372
  if (siteModules.length > 0) modules = true;
232
373
 
233
374
  // Non-interactive / --yes defaults
@@ -246,6 +387,9 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
246
387
  if (modules === undefined) modules = true;
247
388
  if (git === undefined) git = true;
248
389
  if (install === undefined) install = false;
390
+ if (php === undefined) php = false;
391
+ if (phpExamples === undefined) phpExamples = false;
392
+ if (linkAtEnd === undefined) linkAtEnd = false;
249
393
 
250
394
  if (lang !== 'ts' && lang !== 'js') {
251
395
  return { ok: false, error: 'Language must be ts or js.' };
@@ -253,6 +397,12 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
253
397
  if (styles !== 'scss' && styles !== 'css') {
254
398
  return { ok: false, error: 'Styles must be scss or css.' };
255
399
  }
400
+ if (phpExamples && !php) {
401
+ return {
402
+ ok: false,
403
+ error: '--php-examples requires PHP. Pass --php or omit --php-examples.',
404
+ };
405
+ }
256
406
 
257
407
  const remoteCheck = validateGitRemote(remote);
258
408
  if (!remoteCheck.ok) {
@@ -270,6 +420,8 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
270
420
  ? String(options.author).trim()
271
421
  : authorDefault;
272
422
 
423
+ if (!production) productionSkipped = true;
424
+
273
425
  return {
274
426
  ok: true,
275
427
  config: {
@@ -281,27 +433,55 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
281
433
  modules,
282
434
  siteModules,
283
435
  origin: origin || undefined,
436
+ production: production || undefined,
437
+ productionSkipped,
438
+ php,
439
+ phpExamples,
440
+ linkAtEnd,
284
441
  git,
285
442
  remote: remoteCheck.remote,
286
443
  install,
287
444
  dryRun: options.dryRun === true,
288
- // Bundled loader until createNew resolves the published one (AC-14).
289
- loaderVersion: deps.packagesVersion || STAGEPASS_PACKAGES_VERSION,
445
+ loaderVersion:
446
+ deps.packagesVersion || deps.cliVersion || STAGEPASS_PACKAGES_VERSION,
290
447
  },
291
448
  };
292
449
  }
293
450
 
294
451
  /**
452
+ * True when `p` exists (lstat; does not follow the final symlink).
453
+ * @param {{ lstat: (p: string) => Promise<unknown> }} fse
454
+ * @param {string} p
455
+ */
456
+ async function pathExistsLstat(fse, p) {
457
+ try {
458
+ await fse.lstat(p);
459
+ return true;
460
+ } catch (err) {
461
+ if (err && /** @type {{ code?: string }} */ (err).code === 'ENOENT') return false;
462
+ throw err;
463
+ }
464
+ }
465
+
466
+ /**
467
+ * After `npm install`, align tsconfig/jsconfig types with the installed
468
+ * @stagepass/modules (per-module entries only when it ships them).
469
+ * Only rewrites configs this run created (INV-4: never mutate pre-existing files).
470
+ *
295
471
  * @param {string} targetDir
296
472
  * @param {{ siteModules: string[], perModuleTypes?: boolean }} config
297
473
  * @param {typeof fs} fse
298
474
  * @param {(msg?: string) => void} log
475
+ * @param {string[]} [createdPaths] absolute paths this run may rewrite
299
476
  */
300
- async function reconcileInstalledTypes(targetDir, config, fse, log) {
477
+ async function reconcileInstalledTypes(targetDir, config, fse, log, createdPaths) {
301
478
  const installed = await installedHasPerModuleTypes(targetDir, fse);
302
479
  if (installed === null || installed === (config.perModuleTypes !== false)) return;
480
+ const created =
481
+ createdPaths == null ? null : new Set(createdPaths.map((p) => path.resolve(p)));
303
482
  for (const name of ['tsconfig.json', 'jsconfig.json']) {
304
- const file = path.join(targetDir, name);
483
+ const file = path.resolve(targetDir, name);
484
+ if (created && !created.has(file)) continue;
305
485
  if (!(await fse.pathExists(file))) continue;
306
486
  const raw = await fse.readFile(file, 'utf8');
307
487
  const result = updateConfigTypes(raw, config.siteModules, {
@@ -317,6 +497,129 @@ async function reconcileInstalledTypes(targetDir, config, fse, log) {
317
497
  }
318
498
 
319
499
  /**
500
+ * Interactive macOS preflight: read-only doctor, optionally offer setup.
501
+ * Never runs under --yes / no-TTY. Never uses sudo by itself.
502
+ *
503
+ * @param {object} deps
504
+ * @returns {Promise<number>} 0 continue, 1 abort
505
+ */
506
+ async function maybeDoctorPreflight(deps = {}) {
507
+ const isTty = deps.isTTY != null ? Boolean(deps.isTTY) : Boolean(input.isTTY);
508
+ if (!isTty || deps.yes === true) return 0;
509
+
510
+ const platform = deps.platform || process.platform;
511
+ if (!isMacOS(platform)) return 0;
512
+
513
+ const log = deps.log || console.log;
514
+ const error = deps.error || console.error;
515
+ const run = deps.runDoctor || runDoctor;
516
+
517
+ log(chalk.dim('Running read-only doctor preflight…'));
518
+ let report;
519
+ try {
520
+ report = await run({
521
+ skipHandshake: true,
522
+ projectChecks: false,
523
+ exec: deps.exec,
524
+ pathExists: deps.pathExists,
525
+ readFile: deps.readFile,
526
+ });
527
+ } catch (err) {
528
+ error(
529
+ chalk.yellow(
530
+ `Doctor preflight failed: ${err instanceof Error ? err.message : String(err)}`
531
+ )
532
+ );
533
+ return 0;
534
+ }
535
+
536
+ const { summary, checks } = report;
537
+ log(
538
+ chalk.dim(
539
+ `Doctor: ${summary.ok} ok, ${summary.warn} warn, ${summary.fail} fail`
540
+ )
541
+ );
542
+
543
+ if (!doctorSuggestsSetup(checks)) return 0;
544
+
545
+ const rl =
546
+ deps.createReadline?.() ||
547
+ readline.createInterface({ input, output });
548
+ try {
549
+ const runSetup = await askYesNo(
550
+ rl,
551
+ 'Local Stagepass stack looks incomplete. Run `stagepass setup` now?',
552
+ false
553
+ );
554
+ if (!runSetup) {
555
+ log(chalk.dim('Skipping setup. You can run `stagepass setup` later.'));
556
+ return 0;
557
+ }
558
+ const setupFn = deps.setup || defaultSetup;
559
+ await setupFn({ verbose: deps.verbose === true });
560
+ return 0;
561
+ } finally {
562
+ rl.close();
563
+ }
564
+ }
565
+
566
+ /**
567
+ * Optionally link the new project (macOS only; interactive ask or --link).
568
+ *
569
+ * @param {object} config
570
+ * @param {string} targetDir
571
+ * @param {object} deps
572
+ */
573
+ async function maybeLinkProject(config, targetDir, deps = {}) {
574
+ const log = deps.log || console.log;
575
+ const platform = deps.platform || process.platform;
576
+ if (!isMacOS(platform)) {
577
+ if (config.linkAtEnd) {
578
+ log(chalk.dim('Skipping link (macOS only).'));
579
+ }
580
+ return;
581
+ }
582
+
583
+ let shouldLink = config.linkAtEnd === true;
584
+ const isTty = deps.isTTY != null ? Boolean(deps.isTTY) : Boolean(input.isTTY);
585
+ if (!shouldLink && isTty && deps.yes !== true) {
586
+ const rl =
587
+ deps.createReadline?.() ||
588
+ readline.createInterface({ input, output });
589
+ try {
590
+ shouldLink = await askYesNo(
591
+ rl,
592
+ `Link this project as ${config.name}.sp now?`,
593
+ false
594
+ );
595
+ } finally {
596
+ rl.close();
597
+ }
598
+ }
599
+
600
+ if (!shouldLink) return 0;
601
+
602
+ const linkFn = deps.link || defaultLink;
603
+ log(chalk.dim(`Linking ${config.name}.sp…`));
604
+ const linkCode = await linkFn(
605
+ config.name,
606
+ { verbose: deps.verbose === true },
607
+ { cwd: targetDir, log }
608
+ );
609
+ if (typeof linkCode === 'number' && linkCode !== 0) {
610
+ log(
611
+ chalk.red(
612
+ `stagepass link failed (exit ${linkCode}). Project files were kept; fix the error and run \`stagepass link\` again.`
613
+ )
614
+ );
615
+ return linkCode;
616
+ }
617
+ return 0;
618
+ }
619
+
620
+ /**
621
+ * Scaffold a new Stagepass project.
622
+ *
320
623
  * @param {string|undefined} nameArg
321
624
  * @param {object} [options]
322
625
  * @param {object} [deps]
@@ -338,6 +641,19 @@ export async function createNew(nameArg, options = {}, deps = {}) {
338
641
  }
339
642
 
340
643
  const config = resolved.config;
644
+
645
+ // Doctor/setup only after validation, never for --dry-run (no side effects).
646
+ if (config.dryRun !== true) {
647
+ const preflightDeps = {
648
+ ...deps,
649
+ yes: options.yes === true,
650
+ verbose: options.verbose === true,
651
+ log,
652
+ error,
653
+ };
654
+ const preflightCode = await maybeDoctorPreflight(preflightDeps);
655
+ if (preflightCode !== 0) return preflightCode;
656
+ }
341
657
  const targetDir = path.isAbsolute(config.dir)
342
658
  ? config.dir
343
659
  : path.resolve(cwd, config.dir);
@@ -366,7 +682,9 @@ export async function createNew(nameArg, options = {}, deps = {}) {
366
682
  }
367
683
  };
368
684
 
369
- // Per-module types since modules 2.2.0; else umbrella types so tsc passes.
685
+ // Single-module types (`@stagepass/modules/cookies`) exist since modules
686
+ // 2.2.0. Only use them when a published release in range ships them;
687
+ // otherwise (or offline) fall back to the umbrella types so tsc passes.
370
688
  const singleModuleTypes =
371
689
  config.modules === true &&
372
690
  config.siteModules.length > 0 &&
@@ -409,6 +727,12 @@ export async function createNew(nameArg, options = {}, deps = {}) {
409
727
  }
410
728
  }
411
729
 
730
+ const parentCheck = await assertScaffoldParentPath(targetDir, fse);
731
+ if (!parentCheck.ok) {
732
+ error(chalk.red(parentCheck.error));
733
+ return 1;
734
+ }
735
+
412
736
  const conflicts = await findConflicts(targetDir, files, fse);
413
737
  if (conflicts.length > 0) {
414
738
  error(chalk.red('Refusing to overwrite existing files:'));
@@ -426,27 +750,26 @@ export async function createNew(nameArg, options = {}, deps = {}) {
426
750
  if (config.git) log(' (git init)');
427
751
  if (config.remote) log(` (git remote add origin ${config.remote})`);
428
752
  if (config.install) log(' (npm install)');
753
+ if (config.linkAtEnd) log(' (stagepass link)');
754
+ if (config.productionSkipped) log(` (${PRODUCTION_HINT})`);
429
755
  return 0;
430
756
  }
431
757
 
432
- await fse.ensureDir(targetDir);
433
-
434
- for (const file of files) {
435
- const abs = path.resolve(targetDir, file.relativePath);
436
- const relToTarget = path.relative(targetDir, abs);
437
- if (
438
- relToTarget.startsWith('..') ||
439
- path.isAbsolute(relToTarget) ||
440
- relToTarget.split(path.sep).includes('..')
441
- ) {
442
- error(chalk.red(`Refusing to write outside project directory: ${file.relativePath}`));
443
- return 1;
758
+ const written = await writeScaffoldFiles(targetDir, files, fse);
759
+ if (!written.ok) {
760
+ error(chalk.red(written.error));
761
+ if (options.verbose === true && written.errorObj instanceof Error && written.errorObj.stack) {
762
+ error(written.errorObj.stack);
444
763
  }
445
- await fse.ensureDir(path.dirname(abs));
446
- await fse.writeFile(abs, file.contents, 'utf8');
764
+ return 1;
447
765
  }
448
766
 
767
+ /** Roll back every file this run created (INV-4). */
768
+ const undo = async () => rollbackScaffold(written.created, written.createdTargetDir, fse);
769
+
449
770
  if (config.git) {
771
+ const gitDir = path.join(targetDir, '.git');
772
+ const gitExisted = await pathExistsLstat(fse, gitDir);
450
773
  try {
451
774
  await exec('git', ['init'], { cwd: targetDir });
452
775
  if (config.remote) {
@@ -454,17 +777,29 @@ export async function createNew(nameArg, options = {}, deps = {}) {
454
777
  cwd: targetDir,
455
778
  });
456
779
  }
780
+ if (!gitExisted) written.created.push(gitDir);
457
781
  } catch (err) {
782
+ if (!gitExisted) written.created.push(gitDir);
783
+ await undo();
458
784
  error(
459
785
  chalk.red(
460
786
  `Git setup failed: ${err instanceof Error ? err.message : String(err)}`
461
787
  )
462
788
  );
789
+ if (options.verbose === true && err instanceof Error && err.stack) error(err.stack);
463
790
  return 1;
464
791
  }
465
792
  }
466
793
 
467
794
  if (config.install) {
795
+ const nodeModulesDir = path.join(targetDir, 'node_modules');
796
+ const lockfile = path.join(targetDir, 'package-lock.json');
797
+ const nodeModulesExisted = await pathExistsLstat(fse, nodeModulesDir);
798
+ const lockfileExisted = await pathExistsLstat(fse, lockfile);
799
+ const trackInstallArtifacts = () => {
800
+ if (!nodeModulesExisted) written.created.push(nodeModulesDir);
801
+ if (!lockfileExisted) written.created.push(lockfile);
802
+ };
468
803
  try {
469
804
  const result = await spawn('npm', ['install'], {
470
805
  cwd: targetDir,
@@ -472,19 +807,24 @@ export async function createNew(nameArg, options = {}, deps = {}) {
472
807
  shell: false,
473
808
  env: process.env,
474
809
  });
810
+ trackInstallArtifacts();
475
811
  if (result.code !== 0) {
812
+ await undo();
476
813
  error(chalk.red(`npm install exited with code ${result.code}`));
477
- return typeof result.code === 'number' ? result.code : 1;
814
+ return 1;
478
815
  }
479
816
  if (singleModuleTypes) {
480
- await reconcileInstalledTypes(targetDir, config, fse, log);
817
+ await reconcileInstalledTypes(targetDir, config, fse, log, written.created);
481
818
  }
482
819
  } catch (err) {
820
+ trackInstallArtifacts();
821
+ await undo();
483
822
  error(
484
823
  chalk.red(
485
824
  `npm install failed: ${err instanceof Error ? err.message : String(err)}`
486
825
  )
487
826
  );
827
+ if (options.verbose === true && err instanceof Error && err.stack) error(err.stack);
488
828
  return 1;
489
829
  }
490
830
  }
@@ -495,8 +835,16 @@ export async function createNew(nameArg, options = {}, deps = {}) {
495
835
  log(` cd ${path.relative(cwd, targetDir) || '.'} && npm install`);
496
836
  }
497
837
  log(' npm run build');
498
- log(` stagepass link ${config.name} --origin ${config.origin || 'my-project.webflow.io'}`);
838
+ if (config.origin || config.production) {
839
+ log(` stagepass link ${config.name}`);
840
+ } else {
841
+ log(` stagepass link ${config.name} --origin my-project.webflow.io`);
842
+ }
843
+ if (config.productionSkipped) {
844
+ log(chalk.dim(PRODUCTION_HINT));
845
+ }
499
846
  log(chalk.dim(`Declared modules (stagepass.json): ${formatModules(config.siteModules)}`));
847
+ log(chalk.dim(`PHP: ${config.php ? 'on' : 'off'}`));
500
848
 
501
849
  const snippets = buildWebflowSnippets({
502
850
  version: config.loaderVersion,
@@ -504,8 +852,16 @@ export async function createNew(nameArg, options = {}, deps = {}) {
504
852
  });
505
853
  printWebflowSnippets(snippets, log);
506
854
 
855
+ const linkCode = await maybeLinkProject(config, targetDir, {
856
+ ...deps,
857
+ yes: options.yes === true,
858
+ verbose: options.verbose === true,
859
+ log,
860
+ });
861
+ if (typeof linkCode === 'number' && linkCode !== 0) return linkCode;
862
+
507
863
  return 0;
508
864
  }
509
865
 
510
- /** Commander-facing alias */
866
+ /** Commander-facing alias */
511
867
  export const newProject = createNew;
@@ -2,6 +2,8 @@ import fs from 'fs-extra';
2
2
  import path from 'path';
3
3
  import chalk from 'chalk';
4
4
  import { defaultSpawn } from '../lib/spawn.js';
5
+ import { ensureStagepassReady } from '../lib/ensure-running.js';
6
+ import { start as defaultStart } from './start.js';
5
7
 
6
8
  /**
7
9
  * Run an npm lifecycle script in cwd via spawn (no shell).
@@ -67,10 +69,16 @@ export async function runNpmScript(scriptName, options = {}, deps = {}) {
67
69
 
68
70
  /**
69
71
  * @param {object} [options]
72
+ * @param {boolean} [options.verbose]
73
+ * @param {boolean} [options.yes]
70
74
  * @param {object} [deps]
71
75
  * @returns {Promise<number>}
72
76
  */
73
77
  export async function watch(options = {}, deps = {}) {
78
+ await (deps.ensureStagepassReady || ensureStagepassReady)(options, {
79
+ ...deps,
80
+ start: deps.start || defaultStart,
81
+ });
74
82
  return runNpmScript('watch', options, deps);
75
83
  }
76
84