@stagepass/cli 2.0.0 → 2.2.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 (42) hide show
  1. package/README.md +87 -7
  2. package/TESTING-macos.md +58 -0
  3. package/bin/index.js +2 -2
  4. package/package.json +3 -1
  5. package/src/cli.js +204 -0
  6. package/src/commands/autostart.js +85 -0
  7. package/src/commands/certs.js +185 -0
  8. package/src/commands/daemon.js +126 -0
  9. package/src/commands/doctor.js +57 -0
  10. package/src/commands/new.js +455 -0
  11. package/src/commands/npm-run.js +84 -0
  12. package/src/commands/stop.js +15 -0
  13. package/src/commands/upgrade.js +276 -0
  14. package/src/lib/ai-guide.js +161 -0
  15. package/src/lib/autostart.js +360 -0
  16. package/src/lib/cdn-snippets.js +27 -0
  17. package/src/lib/certs.js +476 -0
  18. package/src/lib/doctor-site.js +89 -0
  19. package/src/lib/doctor.js +521 -0
  20. package/src/lib/exec.js +71 -0
  21. package/src/lib/paths.js +58 -0
  22. package/src/lib/platform.js +47 -0
  23. package/src/lib/project-modules.js +98 -0
  24. package/src/lib/project-name.js +47 -0
  25. package/src/lib/project-sync.js +394 -0
  26. package/src/lib/remote-url.js +63 -0
  27. package/src/lib/scaffold.js +212 -0
  28. package/src/lib/site-detect.js +242 -0
  29. package/src/lib/snippets.js +94 -0
  30. package/src/lib/spawn.js +30 -0
  31. package/src/lib/versions.js +27 -0
  32. package/templates/project/AGENTS.md.tmpl +39 -0
  33. package/templates/project/README.md.tmpl +44 -0
  34. package/templates/project/gitignore +7 -0
  35. package/templates/project/jsconfig.json.tmpl +14 -0
  36. package/templates/project/scripts/build.mjs +110 -0
  37. package/templates/project/src/main.js.tmpl +29 -0
  38. package/templates/project/src/main.ts.tmpl +29 -0
  39. package/templates/project/src/styles.css.tmpl +8 -0
  40. package/templates/project/src/styles.scss.tmpl +8 -0
  41. package/templates/project/stagepass.json.tmpl +8 -0
  42. package/templates/project/tsconfig.json.tmpl +13 -0
@@ -0,0 +1,455 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'node:path';
3
+ import readline from 'node:readline/promises';
4
+ import { stdin as input, stdout as output } from 'node:process';
5
+ import chalk from 'chalk';
6
+ import { defaultExec } from '../lib/exec.js';
7
+ import { defaultSpawn } from '../lib/spawn.js';
8
+ import { validateProjectName } from '../lib/project-name.js';
9
+ import { validateGitRemote } from '../lib/remote-url.js';
10
+ import {
11
+ defaultTemplatesRoot,
12
+ planScaffoldFiles,
13
+ findConflicts,
14
+ } from '../lib/scaffold.js';
15
+ import {
16
+ buildWebflowSnippets,
17
+ printWebflowSnippets,
18
+ } from '../lib/snippets.js';
19
+
20
+ import { STAGEPASS_PACKAGES_VERSION } from '../lib/versions.js';
21
+ import { formatModules, normalizeModulesList } from '../lib/project-modules.js';
22
+ import { describeDetection, detectSite, normalizeSiteUrl } from '../lib/site-detect.js';
23
+
24
+ /**
25
+ * Resolve a boolean flag that may appear as --foo / --no-foo.
26
+ * Only argv is trusted: Commander defaults negated pairs to true, which would
27
+ * break defaults like --install (off unless passed).
28
+ *
29
+ * @param {object} _options
30
+ * @param {string} key
31
+ * @param {string[]} argv
32
+ * @param {boolean|undefined} defaultValue undefined = still unset
33
+ */
34
+ export function resolveBoolFlag(_options, key, argv, defaultValue) {
35
+ const pos = `--${key}`;
36
+ const neg = `--no-${key}`;
37
+ if (argv.includes(neg)) return false;
38
+ if (argv.includes(pos)) return true;
39
+ return defaultValue;
40
+ }
41
+
42
+ /**
43
+ * @param {object} options Commander options
44
+ * @param {object} [deps]
45
+ */
46
+ async function resolveAuthor(options, deps) {
47
+ if (options.author != null && String(options.author).trim() !== '') {
48
+ return String(options.author).trim();
49
+ }
50
+ const exec = deps.exec || defaultExec;
51
+ try {
52
+ const { stdout } = await exec('git', ['config', 'user.name']);
53
+ return String(stdout || '').trim();
54
+ } catch {
55
+ return '';
56
+ }
57
+ }
58
+
59
+ /**
60
+ * @param {import('node:readline/promises').Interface} rl
61
+ * @param {string} question
62
+ * @param {string} [defaultValue]
63
+ */
64
+ async function ask(rl, question, defaultValue = '') {
65
+ const suffix = defaultValue ? ` (${defaultValue})` : '';
66
+ const answer = await rl.question(`${question}${suffix}: `);
67
+ const trimmed = String(answer || '').trim();
68
+ return trimmed === '' ? defaultValue : trimmed;
69
+ }
70
+
71
+ /**
72
+ * @param {import('node:readline/promises').Interface} rl
73
+ * @param {string} question
74
+ * @param {boolean} defaultYes
75
+ */
76
+ async function askYesNo(rl, question, defaultYes) {
77
+ const hint = defaultYes ? 'Y/n' : 'y/N';
78
+ const answer = await rl.question(`${question} (${hint}): `);
79
+ const trimmed = String(answer || '').trim().toLowerCase();
80
+ if (trimmed === '') return defaultYes;
81
+ if (['y', 'yes'].includes(trimmed)) return true;
82
+ if (['n', 'no'].includes(trimmed)) return false;
83
+ return defaultYes;
84
+ }
85
+
86
+ /**
87
+ * Merge flags + optional interactive prompts into a resolved config.
88
+ * @param {string|undefined} nameArg
89
+ * @param {object} options
90
+ * @param {object} deps
91
+ */
92
+ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
93
+ const isTty =
94
+ deps.isTTY != null ? Boolean(deps.isTTY) : Boolean(input.isTTY);
95
+ const interactive = isTty && options.yes !== true;
96
+ const authorDefault = await resolveAuthor(options, deps);
97
+ const argv = Array.isArray(deps.argv) ? deps.argv : process.argv;
98
+
99
+ /** @type {string} */
100
+ let name = nameArg ? String(nameArg).trim() : '';
101
+ /** @type {string} */
102
+ let dir = options.dir != null ? String(options.dir) : '';
103
+ let lang = options.lang === 'js' || options.lang === 'ts' ? options.lang : '';
104
+ let styles =
105
+ options.styles === 'css' || options.styles === 'scss' ? options.styles : '';
106
+
107
+ // Prefer argv for --foo / --no-foo so Commander default quirks do not flip defaults.
108
+ let modules = resolveBoolFlag(options, 'modules', argv, undefined);
109
+ let git = resolveBoolFlag(options, 'git', argv, undefined);
110
+ let install = resolveBoolFlag(options, 'install', argv, undefined);
111
+ let remote = options.remote != null ? String(options.remote).trim() : '';
112
+ const log = deps.log || console.log;
113
+ const detect = deps.detectSite || detectSite;
114
+
115
+ /** @type {string[] | undefined} */
116
+ let siteModules;
117
+ if (options.siteModules != null) {
118
+ const parsed = normalizeModulesList(String(options.siteModules));
119
+ if (!parsed.ok) return { ok: false, error: parsed.error };
120
+ siteModules = parsed.modules;
121
+ }
122
+ /** @type {string} */
123
+ let origin = '';
124
+ if (options.site != null && String(options.site).trim() !== '') {
125
+ const check = normalizeSiteUrl(String(options.site));
126
+ if (!check.ok) return { ok: false, error: check.error };
127
+ origin = check.host;
128
+ }
129
+
130
+ /**
131
+ * Detect modules on the live site (public GET, never executed).
132
+ * @returns {Promise<string[] | null>} detected list, or null when unknown
133
+ */
134
+ const detectFromSite = async () => {
135
+ if (!origin) return null;
136
+ log(`Checking live site https://${origin}/ for Stagepass script tags...`);
137
+ const det = await detect(origin);
138
+ log(` ${describeDetection(det)}`);
139
+ if (det.ok && det.loader) return det.list;
140
+ if (det.ok) log(' The page does not load @stagepass/loader yet.');
141
+ return null;
142
+ };
143
+
144
+ if (interactive) {
145
+ const rl =
146
+ deps.createReadline?.() ||
147
+ readline.createInterface({ input, output });
148
+ try {
149
+ if (!name) {
150
+ name = await ask(rl, 'Project name (DNS-safe)');
151
+ }
152
+ if (!dir) {
153
+ dir = await ask(rl, 'Directory', name || '.');
154
+ }
155
+ if (!options.author) {
156
+ const nextAuthor = await ask(rl, 'Author', authorDefault);
157
+ options = { ...options, author: nextAuthor };
158
+ }
159
+ if (!lang) {
160
+ const raw = await ask(rl, 'Language (ts|js)', 'ts');
161
+ lang = raw === 'js' ? 'js' : 'ts';
162
+ }
163
+ if (!styles) {
164
+ const raw = await ask(rl, 'Styles (scss|css)', 'scss');
165
+ styles = raw === 'css' ? 'css' : 'scss';
166
+ }
167
+ if (siteModules === undefined && modules !== false) {
168
+ if (!origin) {
169
+ const raw = await ask(rl, 'Live Webflow site to check (optional, e.g. my-project.webflow.io)', '');
170
+ if (raw) {
171
+ const check = normalizeSiteUrl(raw);
172
+ if (check.ok) origin = check.host;
173
+ else log(chalk.yellow(` ${check.error} Skipping the live check.`));
174
+ }
175
+ }
176
+ const detected = await detectFromSite();
177
+ if (detected && (await askYesNo(rl, `Use modules detected on the site: ${formatModules(detected)}?`, true))) {
178
+ siteModules = detected;
179
+ }
180
+ while (siteModules === undefined) {
181
+ const raw = await ask(
182
+ rl,
183
+ 'Modules your Webflow site loads (none | all | inject,cookies,maintenance)',
184
+ detected ? formatModules(detected) : 'none'
185
+ );
186
+ const parsed = normalizeModulesList(raw);
187
+ if (parsed.ok) siteModules = parsed.modules;
188
+ else log(chalk.yellow(` ${parsed.error}`));
189
+ }
190
+ }
191
+ if (git === undefined) {
192
+ git = await askYesNo(rl, 'Initialize git repository?', true);
193
+ }
194
+ if (git && !remote) {
195
+ remote = await ask(rl, 'Git remote URL (optional)', '');
196
+ }
197
+ if (install === undefined) {
198
+ install = await askYesNo(rl, 'Run npm install now?', false);
199
+ }
200
+ } finally {
201
+ rl.close();
202
+ }
203
+ } else if (siteModules === undefined && modules !== false) {
204
+ const detected = await detectFromSite();
205
+ if (detected) {
206
+ siteModules = detected;
207
+ log(`Modules: ${formatModules(detected)} (detected on ${origin}; change "modules" in stagepass.json if needed).`);
208
+ }
209
+ }
210
+
211
+ if (siteModules === undefined) {
212
+ siteModules = [];
213
+ if (!interactive && modules !== false) {
214
+ log(chalk.dim('Modules: none declared. Pass --site <host> or --site-modules <list>, or edit stagepass.json and run stagepass upgrade.'));
215
+ }
216
+ }
217
+ if (modules === false && siteModules.length > 0) {
218
+ return {
219
+ ok: false,
220
+ error: '--no-modules conflicts with declared site modules. Drop --no-modules or pass --site-modules none.',
221
+ };
222
+ }
223
+ // The npm package (types) follows the declared list; keep the legacy default (included).
224
+ if (siteModules.length > 0) modules = true;
225
+
226
+ // Non-interactive / --yes defaults
227
+ if (!name) {
228
+ return { ok: false, error: 'Project name is required (pass [name] or use a TTY).' };
229
+ }
230
+ const nameCheck = validateProjectName(name);
231
+ if (!nameCheck.ok) {
232
+ return { ok: false, error: nameCheck.error };
233
+ }
234
+ name = nameCheck.name;
235
+
236
+ if (!dir) dir = name;
237
+ if (!lang) lang = 'ts';
238
+ if (!styles) styles = 'scss';
239
+ if (modules === undefined) modules = true;
240
+ if (git === undefined) git = true;
241
+ if (install === undefined) install = false;
242
+
243
+ if (lang !== 'ts' && lang !== 'js') {
244
+ return { ok: false, error: 'Language must be ts or js.' };
245
+ }
246
+ if (styles !== 'scss' && styles !== 'css') {
247
+ return { ok: false, error: 'Styles must be scss or css.' };
248
+ }
249
+
250
+ const remoteCheck = validateGitRemote(remote);
251
+ if (!remoteCheck.ok) {
252
+ return { ok: false, error: remoteCheck.error };
253
+ }
254
+ if (remoteCheck.remote && !git) {
255
+ return {
256
+ ok: false,
257
+ error: 'A git remote requires git init. Pass --git or omit --no-git.',
258
+ };
259
+ }
260
+
261
+ const author =
262
+ options.author != null && String(options.author).trim() !== ''
263
+ ? String(options.author).trim()
264
+ : authorDefault;
265
+
266
+ return {
267
+ ok: true,
268
+ config: {
269
+ name,
270
+ dir,
271
+ author,
272
+ lang,
273
+ styles,
274
+ modules,
275
+ siteModules,
276
+ origin: origin || undefined,
277
+ git,
278
+ remote: remoteCheck.remote,
279
+ install,
280
+ dryRun: options.dryRun === true,
281
+ loaderVersion:
282
+ deps.packagesVersion || deps.cliVersion || STAGEPASS_PACKAGES_VERSION,
283
+ },
284
+ };
285
+ }
286
+
287
+ /**
288
+ * Scaffold a new Stagepass project.
289
+ *
290
+ * @param {string|undefined} nameArg
291
+ * @param {object} [options]
292
+ * @param {object} [deps]
293
+ * @returns {Promise<number>} exit code
294
+ */
295
+ export async function createNew(nameArg, options = {}, deps = {}) {
296
+ const fse = deps.fs || fs;
297
+ const exec = deps.exec || defaultExec;
298
+ const spawn = deps.spawn || defaultSpawn;
299
+ const log = deps.log || console.log;
300
+ const error = deps.error || console.error;
301
+ const cwd = deps.cwd || process.cwd();
302
+ const templatesRoot = deps.templatesRoot || defaultTemplatesRoot();
303
+
304
+ const resolved = await resolveNewOptions(nameArg, options, deps);
305
+ if (!resolved.ok) {
306
+ error(chalk.red(resolved.error));
307
+ return 1;
308
+ }
309
+
310
+ const config = resolved.config;
311
+ const targetDir = path.isAbsolute(config.dir)
312
+ ? config.dir
313
+ : path.resolve(cwd, config.dir);
314
+
315
+ const templatesRootResolved = path.resolve(templatesRoot);
316
+ const readTemplate = async (rel) => {
317
+ const abs = path.resolve(templatesRootResolved, rel);
318
+ const relToRoot = path.relative(templatesRootResolved, abs);
319
+ if (
320
+ relToRoot.startsWith('..') ||
321
+ path.isAbsolute(relToRoot) ||
322
+ relToRoot.split(path.sep).includes('..')
323
+ ) {
324
+ throw new Error(`Template path escapes templates root: ${rel}`);
325
+ }
326
+ try {
327
+ return await fse.readFile(abs, 'utf8');
328
+ } catch (err) {
329
+ if (err && err.code === 'ENOENT') {
330
+ throw new Error(
331
+ `Template "${rel}" is missing from the @stagepass/cli install (${templatesRootResolved}). ` +
332
+ 'Reinstall the CLI (npm install -g @stagepass/cli) and try again. Nothing was written.'
333
+ );
334
+ }
335
+ throw err;
336
+ }
337
+ };
338
+
339
+ let files;
340
+ try {
341
+ files = await planScaffoldFiles(config, { readTemplate });
342
+ } catch (err) {
343
+ error(chalk.red(err instanceof Error ? err.message : String(err)));
344
+ return 1;
345
+ }
346
+
347
+ for (const file of files) {
348
+ const rel = String(file.relativePath || '');
349
+ if (
350
+ !rel ||
351
+ path.isAbsolute(rel) ||
352
+ rel.split(/[\\/]/).includes('..')
353
+ ) {
354
+ error(chalk.red(`Refusing unsafe output path: ${rel || '(empty)'}`));
355
+ return 1;
356
+ }
357
+ }
358
+
359
+ const conflicts = await findConflicts(targetDir, files, fse);
360
+ if (conflicts.length > 0) {
361
+ error(chalk.red('Refusing to overwrite existing files:'));
362
+ for (const rel of conflicts) {
363
+ error(` ${rel}`);
364
+ }
365
+ return 1;
366
+ }
367
+
368
+ if (config.dryRun) {
369
+ log(chalk.bold(`Dry run: would create project in ${targetDir}`));
370
+ for (const file of files) {
371
+ log(` ${file.relativePath}`);
372
+ }
373
+ if (config.git) log(' (git init)');
374
+ if (config.remote) log(` (git remote add origin ${config.remote})`);
375
+ if (config.install) log(' (npm install)');
376
+ return 0;
377
+ }
378
+
379
+ await fse.ensureDir(targetDir);
380
+
381
+ for (const file of files) {
382
+ const abs = path.resolve(targetDir, file.relativePath);
383
+ const relToTarget = path.relative(targetDir, abs);
384
+ if (
385
+ relToTarget.startsWith('..') ||
386
+ path.isAbsolute(relToTarget) ||
387
+ relToTarget.split(path.sep).includes('..')
388
+ ) {
389
+ error(chalk.red(`Refusing to write outside project directory: ${file.relativePath}`));
390
+ return 1;
391
+ }
392
+ await fse.ensureDir(path.dirname(abs));
393
+ await fse.writeFile(abs, file.contents, 'utf8');
394
+ }
395
+
396
+ if (config.git) {
397
+ try {
398
+ await exec('git', ['init'], { cwd: targetDir });
399
+ if (config.remote) {
400
+ await exec('git', ['remote', 'add', 'origin', config.remote], {
401
+ cwd: targetDir,
402
+ });
403
+ }
404
+ } catch (err) {
405
+ error(
406
+ chalk.red(
407
+ `Git setup failed: ${err instanceof Error ? err.message : String(err)}`
408
+ )
409
+ );
410
+ return 1;
411
+ }
412
+ }
413
+
414
+ if (config.install) {
415
+ try {
416
+ const result = await spawn('npm', ['install'], {
417
+ cwd: targetDir,
418
+ stdio: 'inherit',
419
+ shell: false,
420
+ env: process.env,
421
+ });
422
+ if (result.code !== 0) {
423
+ error(chalk.red(`npm install exited with code ${result.code}`));
424
+ return typeof result.code === 'number' ? result.code : 1;
425
+ }
426
+ } catch (err) {
427
+ error(
428
+ chalk.red(
429
+ `npm install failed: ${err instanceof Error ? err.message : String(err)}`
430
+ )
431
+ );
432
+ return 1;
433
+ }
434
+ }
435
+
436
+ log(chalk.green(`Created Stagepass project at ${targetDir}`));
437
+ log(chalk.dim('Next:'));
438
+ if (!config.install) {
439
+ log(` cd ${path.relative(cwd, targetDir) || '.'} && npm install`);
440
+ }
441
+ log(' npm run build');
442
+ log(` stagepass link ${config.name} --origin ${config.origin || 'my-project.webflow.io'}`);
443
+ log(chalk.dim(`Declared modules (stagepass.json): ${formatModules(config.siteModules)}`));
444
+
445
+ const snippets = buildWebflowSnippets({
446
+ version: config.loaderVersion,
447
+ moduleList: config.siteModules,
448
+ });
449
+ printWebflowSnippets(snippets, log);
450
+
451
+ return 0;
452
+ }
453
+
454
+ /** Commander-facing alias */
455
+ export const newProject = createNew;
@@ -0,0 +1,84 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import chalk from 'chalk';
4
+ import { defaultSpawn } from '../lib/spawn.js';
5
+
6
+ /**
7
+ * Run an npm lifecycle script in cwd via spawn (no shell).
8
+ *
9
+ * @param {string} scriptName
10
+ * @param {object} [options]
11
+ * @param {boolean} [options.verbose]
12
+ * @param {object} [deps]
13
+ * @param {typeof fs} [deps.fs]
14
+ * @param {string} [deps.cwd]
15
+ * @param {import('../lib/spawn.js').SpawnFn} [deps.spawn]
16
+ * @param {(msg?: string) => void} [deps.log]
17
+ * @param {(msg?: string) => void} [deps.error]
18
+ * @returns {Promise<number>} exit code
19
+ */
20
+ export async function runNpmScript(scriptName, options = {}, deps = {}) {
21
+ const fse = deps.fs || fs;
22
+ const cwd = deps.cwd || process.cwd();
23
+ const spawn = deps.spawn || defaultSpawn;
24
+ const log = deps.log || console.log;
25
+ const error = deps.error || console.error;
26
+ const pkgPath = path.join(cwd, 'package.json');
27
+
28
+ if (!(await fse.pathExists(pkgPath))) {
29
+ error(chalk.red('No package.json found in the current directory.'));
30
+ return 1;
31
+ }
32
+
33
+ let pkg;
34
+ try {
35
+ pkg = JSON.parse(await fse.readFile(pkgPath, 'utf8'));
36
+ } catch {
37
+ error(chalk.red('package.json is not valid JSON.'));
38
+ return 1;
39
+ }
40
+
41
+ if (!pkg.scripts || typeof pkg.scripts[scriptName] !== 'string') {
42
+ error(
43
+ chalk.red(
44
+ `No "${scriptName}" script in package.json. Add one, or run this command inside a Stagepass project created with \`stagepass new\`.`
45
+ )
46
+ );
47
+ return 1;
48
+ }
49
+
50
+ if (options.verbose) {
51
+ log(chalk.dim(`Running: npm run ${scriptName}`));
52
+ }
53
+
54
+ try {
55
+ const result = await spawn('npm', ['run', scriptName], {
56
+ cwd,
57
+ stdio: 'inherit',
58
+ shell: false,
59
+ env: process.env,
60
+ });
61
+ return typeof result.code === 'number' ? result.code : 1;
62
+ } catch (err) {
63
+ error(chalk.red(err instanceof Error ? err.message : String(err)));
64
+ return 1;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * @param {object} [options]
70
+ * @param {object} [deps]
71
+ * @returns {Promise<number>}
72
+ */
73
+ export async function watch(options = {}, deps = {}) {
74
+ return runNpmScript('watch', options, deps);
75
+ }
76
+
77
+ /**
78
+ * @param {object} [options]
79
+ * @param {object} [deps]
80
+ * @returns {Promise<number>}
81
+ */
82
+ export async function build(options = {}, deps = {}) {
83
+ return runNpmScript('build', options, deps);
84
+ }
@@ -1,6 +1,7 @@
1
1
  import { execa } from 'execa';
2
2
  import chalk from 'chalk';
3
3
  import ora from 'ora';
4
+ import { getAutostartStatus } from '../lib/autostart.js';
4
5
 
5
6
  export async function stop(options = {}) {
6
7
  console.log(chalk.bold('\nšŸ›‘ Stopping Stagepass...'));
@@ -34,6 +35,20 @@ export async function stop(options = {}) {
34
35
  console.log(chalk.green('āœ” Services stopped.'));
35
36
  }
36
37
 
38
+ // Non-breaking hint only: existing stop semantics stay unchanged.
39
+ try {
40
+ const status = await getAutostartStatus();
41
+ if (status.loaded || status.plistExists) {
42
+ console.log(
43
+ chalk.dim(
44
+ 'Autostart is enabled; Caddy may start again at next login. Use `stagepass autostart off` to disable permanently.'
45
+ )
46
+ );
47
+ }
48
+ } catch {
49
+ // ignore status failures
50
+ }
51
+
37
52
  } catch (error) {
38
53
  if (!options.verbose) spinner.fail('Error stopping services.');
39
54
  console.error(chalk.red(error.message));