@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
@@ -1,10 +1,8 @@
1
- import { execa as defaultExeca } from 'execa';
2
1
  import chalk from 'chalk';
3
2
  import path from 'path';
4
3
  import fs from 'fs-extra';
5
- import os from 'node:os';
6
- import inquirer from 'inquirer';
7
4
  import { createSpinner } from '../lib/spinner.js';
5
+ import os from 'node:os';
8
6
  import {
9
7
  getCaddyfilePath,
10
8
  getServerLogPath,
@@ -15,22 +13,22 @@ import {
15
13
  ensureCaddyfileMigrated,
16
14
  warnIfAllowAllOriginsActive,
17
15
  } from '../lib/migrate.js';
16
+ import { defaultExec } from '../lib/exec.js';
17
+ import { confirm as defaultConfirm } from '../lib/prompts.js';
18
18
  import { parseLsofListenOutput } from '../lib/doctor.js';
19
+ import { runCertsCheck, domainsNeedingSiteCertRenewal } from '../lib/certs.js';
20
+ import { loadProjects, clearStaleDevPorts, getProject } from '../lib/projects.js';
21
+ import { applySiteBlock } from '../lib/apply-site-block.js';
19
22
  import {
20
23
  getAutostartStatus,
21
- buildLaunchctlBootstrapArgs,
22
24
  buildLaunchctlKickstartArgs,
25
+ buildLaunchctlBootstrapArgs,
23
26
  LAUNCH_AGENT_LABEL,
24
27
  } from '../lib/autostart.js';
28
+ import { ensurePhpFpm } from '../lib/php-fpm.js';
29
+ import { certsTrust, certsRenew } from './certs.js';
25
30
 
26
- const PORT_IGNORE = [
27
- 'Google Chrome',
28
- 'Chrome Helper',
29
- 'OneDrive',
30
- 'Music',
31
- 'Safari',
32
- 'caddy',
33
- ];
31
+ const PORT_IGNORE = ['Google Chrome', 'Chrome Helper', 'OneDrive', 'Music', 'Safari', 'caddy'];
34
32
 
35
33
  /**
36
34
  * @param {unknown} pid
@@ -45,13 +43,13 @@ export function isSafePid(pid) {
45
43
  /**
46
44
  * Inspect TCP 443 without sudo (same approach as doctor).
47
45
  * @param {object} [opts]
48
- * @param {typeof defaultExeca} [opts.execa]
46
+ * @param {import('../lib/exec.js').ExecFn} [opts.exec]
49
47
  * @returns {Promise<{ pid: string, name: string }|null>}
50
48
  */
51
49
  export async function findPort443Conflict(opts = {}) {
52
- const run = opts.execa || defaultExeca;
50
+ const exec = opts.exec || defaultExec;
53
51
  try {
54
- const { stdout } = await run('lsof', [
52
+ const { stdout } = await exec('lsof', [
55
53
  '-nP',
56
54
  '-iTCP:443',
57
55
  '-sTCP:LISTEN',
@@ -65,73 +63,56 @@ export async function findPort443Conflict(opts = {}) {
65
63
  }
66
64
  return null;
67
65
  } catch (error) {
68
- const err = /** @type {{ exitCode?: number, code?: string|number }} */ (error);
69
- // lsof exits 1 when nothing matches
70
- if (err.exitCode === 1 || err.code === 1 || err.code === '1') return null;
66
+ const err = /** @type {{ code?: string|number }} */ (error);
67
+ if (err.code === 1 || err.code === '1') return null;
71
68
  return null;
72
69
  }
73
70
  }
74
71
 
75
- /**
76
- * @param {object} opts
77
- * @param {string} opts.message
78
- * @param {boolean} [opts.default]
79
- * @param {(message: string, o?: { default?: boolean }) => Promise<boolean>} [opts.confirm]
80
- * @param {boolean} [opts.interactive]
81
- */
82
- async function askConfirm(opts) {
83
- if (typeof opts.confirm === 'function') {
84
- return opts.confirm(opts.message, { default: opts.default === true });
85
- }
86
- if (opts.interactive === false || !process.stdin.isTTY) {
87
- return false;
72
+ /** process.kill; sudo kill only on EPERM. ESRCH=ok; else ok:false (no throw). */
73
+ async function signalProcess(pid, signal, exec, kill = process.kill) {
74
+ try {
75
+ kill(Number(pid), /** @type {NodeJS.Signals} */ (`SIG${signal}`));
76
+ return { ok: true };
77
+ } catch (e) {
78
+ const code = /** @type {{ code?: string }} */ (e)?.code;
79
+ if (code === 'ESRCH') return { ok: true };
80
+ if (code !== 'EPERM') {
81
+ return { ok: false, detail: `Failed to signal PID ${pid}: ${e?.message ?? e}` };
82
+ }
88
83
  }
89
- const { value } = await inquirer.prompt([
90
- {
91
- type: 'confirm',
92
- name: 'value',
93
- message: opts.message,
94
- default: opts.default === true,
95
- },
96
- ]);
97
- return Boolean(value);
98
- }
99
-
100
- /**
101
- * Send a signal; use sudo only if the unprivileged kill fails.
102
- * @param {string} pid
103
- * @param {'TERM'|'KILL'} signal
104
- * @param {typeof defaultExeca} run
105
- */
106
- async function signalProcess(pid, signal, run) {
107
- const flag = signal === 'KILL' ? '-KILL' : '-TERM';
108
84
  try {
109
- await run('kill', [flag, pid]);
110
- return { ok: true, usedSudo: false };
111
- } catch {
112
- await run('sudo', ['kill', flag, pid], { stdio: 'inherit' });
113
- return { ok: true, usedSudo: true };
85
+ await exec('sudo', ['kill', signal === 'KILL' ? '-KILL' : '-TERM', pid], {
86
+ stdio: 'inherit',
87
+ });
88
+ return { ok: true };
89
+ } catch (e) {
90
+ return { ok: false, detail: `sudo kill failed for PID ${pid}: ${e?.message ?? e}` };
114
91
  }
115
92
  }
116
93
 
117
94
  /**
118
95
  * Resolve a confirmed port conflict: TERM first, KILL only after a second confirm
119
96
  * if the listener is still present. Never signals without confirmation.
97
+ * Privilege-scoped: own processes without sudo; sudo only after unprivileged failure.
120
98
  *
121
99
  * @param {{ pid: string, name: string }} proc
122
100
  * @param {object} opts
123
- * @param {typeof defaultExeca} [opts.execa]
124
- * @param {(message: string, o?: { default?: boolean }) => Promise<boolean>} [opts.confirm]
101
+ * @param {import('../lib/exec.js').ExecFn} [opts.exec]
102
+ * @param {typeof process.kill} [opts.kill]
103
+ * @param {(message: string, o?: object) => Promise<boolean>} [opts.confirm]
125
104
  * @param {boolean} [opts.interactive]
126
105
  * @param {(ms: number) => Promise<void>} [opts.sleep]
127
106
  * @param {() => Promise<{ pid: string, name: string }|null>} [opts.recheck]
128
107
  * @returns {Promise<{ ok: boolean, cancelled?: boolean, detail?: string }>}
129
108
  */
130
109
  export async function resolvePort443Conflict(proc, opts = {}) {
131
- const run = opts.execa || defaultExeca;
110
+ const exec = opts.exec || defaultExec;
111
+ const kill = opts.kill || process.kill;
112
+ const confirm = opts.confirm || defaultConfirm;
132
113
  const sleep =
133
114
  opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
134
- const recheck = opts.recheck || (() => findPort443Conflict({ execa: run }));
115
+ const recheck = opts.recheck || (() => findPort443Conflict({ exec }));
135
116
  const pid = String(proc?.pid ?? '');
136
117
 
137
118
  if (!isSafePid(pid)) {
@@ -147,36 +128,36 @@ export async function resolvePort443Conflict(proc, opts = {}) {
147
128
  )
148
129
  );
149
130
 
150
- const shouldTerm = await askConfirm({
151
- message: `Send SIGTERM to ${proc.name} (PID ${pid}) to free port 443?`,
152
- default: false,
153
- confirm: opts.confirm,
154
- interactive: opts.interactive,
155
- });
131
+ const shouldTerm = await confirm(
132
+ `Send SIGTERM to ${proc.name} (PID ${pid}) to free port 443?`,
133
+ { default: false }
134
+ );
156
135
  if (!shouldTerm) {
157
136
  return { ok: false, cancelled: true };
158
137
  }
159
138
 
160
- // Prefer service stop helpers when the name is a known reverse proxy / httpd.
139
+ let signaled;
140
+ // Prefer right-free service stops before any sudo (nginx: valet, then brew).
161
141
  if (String(proc.name).includes('nginx')) {
162
142
  try {
163
- await run('valet', ['stop']);
143
+ await exec('valet', ['stop']);
164
144
  } catch {
165
145
  try {
166
- await run('brew', ['services', 'stop', 'nginx']);
146
+ await exec('brew', ['services', 'stop', 'nginx']);
167
147
  } catch {
168
- await signalProcess(pid, 'TERM', run);
148
+ signaled = await signalProcess(pid, 'TERM', exec, kill);
169
149
  }
170
150
  }
171
151
  } else if (String(proc.name).includes('httpd')) {
172
152
  try {
173
- await run('sudo', ['apachectl', 'stop'], { stdio: 'inherit' });
153
+ await exec('sudo', ['apachectl', 'stop'], { stdio: 'inherit' });
174
154
  } catch {
175
- await signalProcess(pid, 'TERM', run);
155
+ signaled = await signalProcess(pid, 'TERM', exec, kill);
176
156
  }
177
157
  } else {
178
- await signalProcess(pid, 'TERM', run);
158
+ signaled = await signalProcess(pid, 'TERM', exec, kill);
179
159
  }
160
+ if (signaled?.ok === false) return signaled;
180
161
 
181
162
  await sleep(400);
182
163
  let still = await recheck();
@@ -184,12 +165,10 @@ export async function resolvePort443Conflict(proc, opts = {}) {
184
165
  return { ok: true, detail: 'SIGTERM' };
185
166
  }
186
167
 
187
- const shouldKill = await askConfirm({
188
- message: `${proc.name} (PID ${pid}) is still listening. Send SIGKILL?`,
189
- default: false,
190
- confirm: opts.confirm,
191
- interactive: opts.interactive,
192
- });
168
+ const shouldKill = await confirm(
169
+ `${proc.name} (PID ${pid}) is still listening. Send SIGKILL?`,
170
+ { default: false }
171
+ );
193
172
  if (!shouldKill) {
194
173
  return {
195
174
  ok: false,
@@ -198,7 +177,8 @@ export async function resolvePort443Conflict(proc, opts = {}) {
198
177
  };
199
178
  }
200
179
 
201
- await signalProcess(pid, 'KILL', run);
180
+ const killed = await signalProcess(pid, 'KILL', exec, kill);
181
+ if (!killed.ok) return killed;
202
182
  await sleep(200);
203
183
  still = await recheck();
204
184
  if (still && String(still.pid) === pid) {
@@ -210,36 +190,115 @@ export async function resolvePort443Conflict(proc, opts = {}) {
210
190
  return { ok: true, detail: 'SIGKILL' };
211
191
  }
212
192
 
193
+ /**
194
+ * Summarize cert findings for start output.
195
+ * @param {Awaited<ReturnType<typeof runCertsCheck>>} report
196
+ */
197
+ export function summarizeCertFindings(report) {
198
+ const issues = [];
199
+ if (report.root?.status === 'fail') {
200
+ issues.push({ kind: 'root', message: report.root.reason });
201
+ }
202
+ if (report.trust && !report.trust.trusted) {
203
+ issues.push({ kind: 'trust', message: 'Caddy local root is not trusted in the System keychain' });
204
+ }
205
+ const needing = domainsNeedingSiteCertRenewal(report.handshakes || []);
206
+ for (const domain of needing) {
207
+ issues.push({ kind: 'site', domain, message: `TLS fail for ${domain}` });
208
+ }
209
+ if (report.orphans?.length) {
210
+ issues.push({
211
+ kind: 'orphans',
212
+ message: `${report.orphans.length} orphaned Caddy root(s) in keychain (certs renew --remove-orphans)`,
213
+ });
214
+ }
215
+ return issues;
216
+ }
217
+
213
218
  /**
214
219
  * @param {object} [options]
215
- * @param {boolean} [options.verbose]
216
- * @param {typeof defaultExeca} [options.execa]
217
- * @param {(message: string, o?: { default?: boolean }) => Promise<boolean>} [options.confirm]
218
- * @param {boolean} [options.interactive]
219
- * @param {typeof getAutostartStatus} [options.getAutostartStatus]
220
- * @param {typeof findPort443Conflict} [options.findPort443Conflict]
221
- * @param {typeof resolvePort443Conflict} [options.resolvePort443Conflict]
222
- * @param {number} [options.uid]
223
- * @param {(ms: number) => Promise<void>} [options.sleep]
224
220
  */
225
221
  export async function start(options = {}) {
226
- const run = options.execa || defaultExeca;
227
- const interactive =
228
- options.interactive !== undefined
229
- ? options.interactive
230
- : Boolean(process.stdin.isTTY);
231
222
  const caddyDir = getStagepassDir();
232
223
  const caddyFile = getCaddyfilePath();
233
224
  const logFile = getServerLogPath();
234
225
  const projectsPath = getProjectsPath();
226
+ const exec = options.exec || defaultExec;
227
+ const confirm = options.confirm || defaultConfirm;
228
+ const interactive =
229
+ options.interactive === true ||
230
+ (options.interactive !== false &&
231
+ (typeof options.confirm === 'function' || process.stdin.isTTY));
235
232
 
236
233
  console.log(chalk.bold('\nšŸš€ Starting Stagepass...'));
237
234
 
238
- // 1. Port conflict — no sudo until the user confirms a signal that needs it.
235
+ // 1. Read-only certs check (always)
236
+ let certReport = null;
237
+ try {
238
+ const doc = await loadProjects(projectsPath);
239
+ const domains = Object.keys(doc.projects || {});
240
+ certReport = await (options.runCertsCheck || runCertsCheck)({
241
+ exec,
242
+ domains,
243
+ skipHandshake: options.skipHandshake === true,
244
+ });
245
+ const findings = summarizeCertFindings(certReport);
246
+ if (findings.length > 0) {
247
+ console.log(chalk.yellow('\nCertificate findings:'));
248
+ for (const f of findings) {
249
+ console.log(chalk.yellow(` • ${f.message}`));
250
+ }
251
+ if (interactive) {
252
+ const trustIssue = findings.some((f) => f.kind === 'trust');
253
+ const siteIssue = findings.some((f) => f.kind === 'site');
254
+ if (trustIssue) {
255
+ const doTrust = await confirm('Run `stagepass certs trust` now?', {
256
+ default: false,
257
+ });
258
+ if (doTrust) {
259
+ await (options.certsTrust || certsTrust)({
260
+ yes: true,
261
+ exec,
262
+ });
263
+ }
264
+ }
265
+ if (siteIssue) {
266
+ const doRenew = await confirm(
267
+ 'Run `stagepass certs renew` for failing site certificates?',
268
+ { default: false }
269
+ );
270
+ if (doRenew) {
271
+ await (options.certsRenew || certsRenew)({
272
+ yes: true,
273
+ exec,
274
+ confirm,
275
+ });
276
+ }
277
+ }
278
+ } else {
279
+ console.log(
280
+ chalk.dim(
281
+ 'Non-interactive start: fix with `stagepass certs trust` / `stagepass certs renew` (and `--remove-orphans` / `--root` when needed).'
282
+ )
283
+ );
284
+ }
285
+ } else {
286
+ console.log(chalk.dim('Certificates: ok'));
287
+ }
288
+ } catch (error) {
289
+ console.log(
290
+ chalk.yellow(
291
+ `Certificate check skipped: ${
292
+ error instanceof Error ? error.message : String(error)
293
+ }`
294
+ )
295
+ );
296
+ }
297
+
298
+ // 2. Port conflict (no sudo until a confirmed signal needs it; never sudo -v)
239
299
  const conflict =
240
- (await (options.findPort443Conflict || findPort443Conflict)({
241
- execa: run,
242
- })) || null;
300
+ (await (options.findPort443Conflict || findPort443Conflict)({ exec })) ||
301
+ null;
243
302
  if (conflict) {
244
303
  if (!interactive && typeof options.confirm !== 'function') {
245
304
  console.log(
@@ -247,30 +306,38 @@ export async function start(options = {}) {
247
306
  `Port 443 is blocked by ${conflict.name} (PID ${conflict.pid}). Refusing to signal without confirmation.`
248
307
  )
249
308
  );
250
- return;
309
+ return 1;
251
310
  }
252
311
  const resolved = await (options.resolvePort443Conflict ||
253
312
  resolvePort443Conflict)(conflict, {
254
- execa: run,
255
- confirm: options.confirm,
313
+ exec,
314
+ kill: options.kill,
315
+ confirm,
256
316
  interactive,
257
317
  sleep: options.sleep,
258
318
  });
259
319
  if (!resolved.ok) {
260
320
  if (resolved.detail) console.log(chalk.red(resolved.detail));
261
- return;
321
+ return 1;
262
322
  }
263
323
  console.log(chalk.green(`Port freed (${resolved.detail}).`));
264
324
  }
265
325
 
266
- // 2. Migrate legacy Caddyfile blocks before boot
326
+ // 3. Migrate legacy Caddyfile blocks before boot; drop dead live-reload ports
267
327
  await fs.ensureDir(caddyDir);
268
328
  if (await fs.pathExists(caddyFile)) {
269
329
  await ensureCaddyfileMigrated({ caddyfilePath: caddyFile, projectsPath });
330
+ const stale = await clearStaleDevPorts(projectsPath);
331
+ for (const domain of stale) {
332
+ const project = await getProject(domain, projectsPath);
333
+ if (project) {
334
+ await applySiteBlock(domain, project, { caddyfilePath: caddyFile });
335
+ }
336
+ }
270
337
  await warnIfAllowAllOriginsActive({ caddyfilePath: caddyFile });
271
338
  }
272
339
 
273
- // 3. Boot services (autostart-aware kickstart when LaunchAgent is installed)
340
+ // 4. Boot services (autostart-aware)
274
341
  const spinner = createSpinner('Booting background services...').start();
275
342
 
276
343
  /** @type {number|null} */
@@ -286,29 +353,25 @@ export async function start(options = {}) {
286
353
  }
287
354
 
288
355
  try {
289
- // PHP: preserve public brew services restart (no root warm-up).
290
- try {
291
- await run('brew', ['services', 'restart', 'php'], {
292
- stdio: stdioMode === 'inherit' ? 'inherit' : 'ignore',
293
- });
294
- } catch {
295
- /* ignore php errors */
356
+ // 2.3: ensurePhpFpm prefers `brew services start php`, then `restart`
357
+ // (2.2.7 always used `restart`). Keep start-first; both stay non-sudo.
358
+ const php = await ensurePhpFpm({
359
+ exec,
360
+ stdio: stdioMode === 'inherit' ? 'inherit' : 'ignore',
361
+ });
362
+ if (!php.ok && options.verbose) {
363
+ console.log(chalk.yellow(`PHP-FPM: ${php.detail || 'failed'}`));
296
364
  }
297
365
 
298
- /** @type {{ loaded?: boolean, plistExists?: boolean, plistPath?: string }} */
299
- let status = {};
300
- try {
301
- status =
302
- (await (options.getAutostartStatus || getAutostartStatus)({})) || {};
303
- } catch {
304
- status = {};
305
- }
366
+ const status =
367
+ (await (options.getAutostartStatus || getAutostartStatus)({ exec })) ||
368
+ {};
306
369
  const uid = options.uid ?? process.getuid?.() ?? os.userInfo().uid;
307
370
 
308
371
  if (status.loaded || status.plistExists) {
309
- if (status.plistExists && !status.loaded && status.plistPath) {
372
+ if (status.plistExists && !status.loaded) {
310
373
  try {
311
- await run(
374
+ await exec(
312
375
  'launchctl',
313
376
  buildLaunchctlBootstrapArgs(uid, status.plistPath)
314
377
  );
@@ -322,11 +385,11 @@ export async function start(options = {}) {
322
385
  console.log(
323
386
  chalk.red(error instanceof Error ? error.message : String(error))
324
387
  );
325
- return;
388
+ return 1;
326
389
  }
327
390
  }
328
391
  try {
329
- await run('launchctl', buildLaunchctlKickstartArgs(uid));
392
+ await exec('launchctl', buildLaunchctlKickstartArgs(uid));
330
393
  if (!options.verbose) {
331
394
  spinner.succeed(
332
395
  chalk.green(
@@ -339,7 +402,7 @@ export async function start(options = {}) {
339
402
  chalk.green(`āœ” kickstart gui/${uid}/${LAUNCH_AGENT_LABEL}`)
340
403
  );
341
404
  }
342
- return;
405
+ return 0;
343
406
  } catch (error) {
344
407
  if (!options.verbose) spinner.fail('launchctl kickstart failed.');
345
408
  console.log(
@@ -350,13 +413,16 @@ export async function start(options = {}) {
350
413
  }
351
414
  }
352
415
 
416
+ // Direct caddy start (no LaunchAgent)
353
417
  try {
354
- await run('caddy', ['stop']);
418
+ await exec('caddy', ['stop'], { stdio: 'ignore' });
355
419
  } catch {
356
- /* ignore */
420
+ // ignore
357
421
  }
358
422
 
359
- await run('caddy', ['start', '--config', caddyFile], { stdio: stdioMode });
423
+ await exec('caddy', ['start', '--config', caddyFile], {
424
+ stdio: stdioMode,
425
+ });
360
426
 
361
427
  if (!options.verbose) {
362
428
  spinner.succeed(chalk.green('Stagepass is active.'));
@@ -364,14 +430,17 @@ export async function start(options = {}) {
364
430
  } else {
365
431
  console.log(chalk.green('āœ” Stagepass is active.'));
366
432
  }
433
+ return 0;
367
434
  } catch (error) {
368
- spinner.fail('Failed to start.');
435
+ if (!options.verbose) spinner.fail('Failed to start.');
436
+ else console.log(chalk.red('Failed to start.'));
369
437
  if (!options.verbose) {
370
438
  console.log(chalk.red('See error log for details:'));
371
439
  console.log(chalk.dim(logFile));
372
440
  } else if (error instanceof Error) {
373
441
  console.log(chalk.red(error.message));
374
442
  }
443
+ return 1;
375
444
  } finally {
376
445
  if (logFd != null) {
377
446
  try {
@@ -1,24 +1,17 @@
1
- import { execa as defaultExeca } from 'execa';
2
1
  import chalk from 'chalk';
3
- import os from 'node:os';
4
2
  import { createSpinner } from '../lib/spinner.js';
3
+ import os from 'node:os';
4
+ import { defaultExec } from '../lib/exec.js';
5
5
  import {
6
6
  getAutostartStatus,
7
7
  buildLaunchctlBootoutArgs,
8
8
  LAUNCH_AGENT_LABEL,
9
9
  } from '../lib/autostart.js';
10
10
 
11
- /**
12
- * @param {object} [options]
13
- * @param {boolean} [options.verbose]
14
- * @param {typeof defaultExeca} [options.execa]
15
- * @param {typeof getAutostartStatus} [options.getAutostartStatus]
16
- * @param {number} [options.uid]
17
- */
18
11
  export async function stop(options = {}) {
19
- const run = options.execa || defaultExeca;
20
12
  console.log(chalk.bold('\nšŸ›‘ Stopping Stagepass...'));
21
13
 
14
+ const exec = options.exec || defaultExec;
22
15
  const spinner = createSpinner('Shutting down services...').start();
23
16
  const stdioMode = options.verbose ? 'inherit' : 'ignore';
24
17
 
@@ -28,11 +21,11 @@ export async function stop(options = {}) {
28
21
  }
29
22
 
30
23
  try {
31
- /** @type {{ loaded?: boolean, plistExists?: boolean }} */
24
+ /** @type {{ loaded?: boolean, plistExists?: boolean, plistPath?: string }} */
32
25
  let status = { loaded: false, plistExists: false };
33
26
  try {
34
27
  status =
35
- (await (options.getAutostartStatus || getAutostartStatus)({})) ||
28
+ (await (options.getAutostartStatus || getAutostartStatus)({ exec })) ||
36
29
  status;
37
30
  } catch {
38
31
  // ignore status failures; still stop caddy/php
@@ -40,24 +33,24 @@ export async function stop(options = {}) {
40
33
  const uid = options.uid ?? process.getuid?.() ?? os.userInfo().uid;
41
34
  let usedBootout = false;
42
35
 
43
- // Bootout first so KeepAlive/RunAtLoad cannot immediately restart during stop.
44
36
  if (status.loaded || status.plistExists) {
45
37
  try {
46
- await run('launchctl', buildLaunchctlBootoutArgs(uid));
38
+ await exec('launchctl', buildLaunchctlBootoutArgs(uid));
47
39
  usedBootout = true;
48
40
  } catch {
49
41
  // not loaded
50
42
  }
51
43
  }
52
44
 
45
+ // Always attempt a direct caddy stop as well (covers non-autostart / leftover).
53
46
  try {
54
- await run('caddy', ['stop'], { stdio: stdioMode });
47
+ await exec('caddy', ['stop'], { stdio: stdioMode });
55
48
  } catch {
56
49
  // Ignore if already stopped
57
50
  }
58
51
 
59
52
  try {
60
- await run('brew', ['services', 'stop', 'php'], { stdio: stdioMode });
53
+ await exec('brew', ['services', 'stop', 'php'], { stdio: stdioMode });
61
54
  } catch {
62
55
  // Ignore
63
56
  }
@@ -77,8 +70,6 @@ export async function stop(options = {}) {
77
70
  }
78
71
  } catch (error) {
79
72
  if (!options.verbose) spinner.fail('Error stopping services.');
80
- console.error(
81
- chalk.red(error instanceof Error ? error.message : String(error))
82
- );
73
+ console.error(chalk.red(error instanceof Error ? error.message : String(error)));
83
74
  }
84
75
  }
@@ -15,7 +15,7 @@ export async function unlink(domain, options = {}) {
15
15
  const resolved = resolveLinkDomain(domain, folderName);
16
16
  if (!resolved.ok) {
17
17
  console.log(chalk.red(`āŒ ${resolved.error}`));
18
- return;
18
+ return 1;
19
19
  }
20
20
 
21
21
  const targetDomain = resolved.domain;
@@ -27,7 +27,7 @@ export async function unlink(domain, options = {}) {
27
27
  try {
28
28
  if (!(await fs.pathExists(caddyFilePath))) {
29
29
  spinner.warn('No Caddyfile found. Nothing to unlink.');
30
- return;
30
+ return 0;
31
31
  }
32
32
 
33
33
  let content = await fs.readFile(caddyFilePath, 'utf-8');
@@ -35,7 +35,7 @@ export async function unlink(domain, options = {}) {
35
35
 
36
36
  if (!result.removed) {
37
37
  spinner.warn(`Domain ${chalk.bold(targetDomain)} is not linked.`);
38
- return;
38
+ return 0;
39
39
  }
40
40
 
41
41
  await fs.writeFile(caddyFilePath, result.content ? `${result.content}\n` : '', 'utf-8');
@@ -43,16 +43,18 @@ export async function unlink(domain, options = {}) {
43
43
  } catch (e) {
44
44
  spinner.fail('Failed to update config.');
45
45
  if (options.verbose) console.error(e);
46
- return;
46
+ return 1;
47
47
  }
48
48
 
49
49
  try {
50
50
  const stdioMode = options.verbose ? 'inherit' : 'ignore';
51
51
  await execa('caddy', ['reload', '--config', caddyFilePath], { stdio: stdioMode });
52
52
  spinner.succeed(`Unlinked: ${targetDomain}`);
53
+ return 0;
53
54
  } catch (error) {
54
55
  spinner.warn('Config updated, but Caddy reload failed.');
55
56
  console.log(chalk.dim(' Is Stagepass running? Try: stagepass start'));
56
57
  if (options.verbose) console.error(error);
58
+ return 0;
57
59
  }
58
60
  }