@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
@@ -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,139 @@ 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
+
218
+ /**
219
+ * Honest one-line cert summary when nothing failed hard enough to offer repair.
220
+ * Never says "ok" for a root or a site check that did not run or was not ok.
221
+ * The Caddy :443 reason is included only when every skip came from that check.
222
+ * @param {{ root?: { status?: string }, handshakes?: { status?: string, reason?: string }[] }} report
223
+ */
224
+ function certStatusLine(report) {
225
+ const root = report?.root?.status;
226
+ const rootLabel =
227
+ root === 'ok' ? 'root ok' : root === 'warn' ? 'root warning' : 'root not checked';
228
+ const hs = report?.handshakes || [];
229
+ if (!hs.length) return `Certificates: ${rootLabel}, site TLS not checked.`;
230
+ const skips = hs.filter((h) => h.status === 'skip');
231
+ if (skips.length) {
232
+ const why = skips.every((h) => /not serving :443/.test(String(h.reason || '')))
233
+ ? ' (Caddy not serving :443)'
234
+ : '';
235
+ return `Certificates: ${rootLabel}, site TLS not checkable${why}.`;
236
+ }
237
+ const sitesOk = hs.every((h) => h.status === 'ok');
238
+ if (root === 'ok' && sitesOk) return 'Certificates: ok';
239
+ return `Certificates: ${rootLabel}, site TLS ${sitesOk ? 'ok' : 'not ok'}.`;
240
+ }
241
+
213
242
  /**
214
243
  * @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
244
  */
225
245
  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
246
  const caddyDir = getStagepassDir();
232
247
  const caddyFile = getCaddyfilePath();
233
248
  const logFile = getServerLogPath();
234
249
  const projectsPath = getProjectsPath();
250
+ const exec = options.exec || defaultExec;
251
+ const confirm = options.confirm || defaultConfirm;
252
+ const interactive =
253
+ options.interactive === true ||
254
+ (options.interactive !== false &&
255
+ (typeof options.confirm === 'function' || process.stdin.isTTY));
235
256
 
236
257
  console.log(chalk.bold('\nšŸš€ Starting Stagepass...'));
237
258
 
238
- // 1. Port conflict — no sudo until the user confirms a signal that needs it.
259
+ // 1. Read-only certs check (always)
260
+ let certReport = null;
261
+ try {
262
+ const doc = await loadProjects(projectsPath);
263
+ const domains = Object.keys(doc.projects || {});
264
+ certReport = await (options.runCertsCheck || runCertsCheck)({
265
+ exec,
266
+ domains,
267
+ skipHandshake: options.skipHandshake === true,
268
+ });
269
+ const findings = summarizeCertFindings(certReport);
270
+ if (findings.length > 0) {
271
+ console.log(chalk.yellow('\nCertificate findings:'));
272
+ for (const f of findings) {
273
+ console.log(chalk.yellow(` • ${f.message}`));
274
+ }
275
+ if (interactive) {
276
+ const trustIssue = findings.some((f) => f.kind === 'trust');
277
+ const siteIssue = findings.some((f) => f.kind === 'site');
278
+ if (trustIssue) {
279
+ const doTrust = await confirm('Run `stagepass certs trust` now?', {
280
+ default: false,
281
+ });
282
+ if (doTrust) {
283
+ await (options.certsTrust || certsTrust)({
284
+ yes: true,
285
+ exec,
286
+ });
287
+ }
288
+ }
289
+ if (siteIssue) {
290
+ const doRenew = await confirm(
291
+ 'Run `stagepass certs renew` for failing site certificates?',
292
+ { default: false }
293
+ );
294
+ if (doRenew) {
295
+ await (options.certsRenew || certsRenew)({
296
+ yes: true,
297
+ exec,
298
+ confirm,
299
+ });
300
+ }
301
+ }
302
+ } else {
303
+ console.log(
304
+ chalk.dim(
305
+ 'Non-interactive start: fix with `stagepass certs trust` / `stagepass certs renew` (and `--remove-orphans` / `--root` when needed).'
306
+ )
307
+ );
308
+ }
309
+ } else {
310
+ console.log(chalk.dim(certStatusLine(certReport)));
311
+ }
312
+ } catch (error) {
313
+ console.log(
314
+ chalk.yellow(
315
+ `Certificate check skipped: ${
316
+ error instanceof Error ? error.message : String(error)
317
+ }`
318
+ )
319
+ );
320
+ }
321
+
322
+ // 2. Port conflict (no sudo until a confirmed signal needs it; never sudo -v)
239
323
  const conflict =
240
- (await (options.findPort443Conflict || findPort443Conflict)({
241
- execa: run,
242
- })) || null;
324
+ (await (options.findPort443Conflict || findPort443Conflict)({ exec })) ||
325
+ null;
243
326
  if (conflict) {
244
327
  if (!interactive && typeof options.confirm !== 'function') {
245
328
  console.log(
@@ -247,30 +330,38 @@ export async function start(options = {}) {
247
330
  `Port 443 is blocked by ${conflict.name} (PID ${conflict.pid}). Refusing to signal without confirmation.`
248
331
  )
249
332
  );
250
- return;
333
+ return 1;
251
334
  }
252
335
  const resolved = await (options.resolvePort443Conflict ||
253
336
  resolvePort443Conflict)(conflict, {
254
- execa: run,
255
- confirm: options.confirm,
337
+ exec,
338
+ kill: options.kill,
339
+ confirm,
256
340
  interactive,
257
341
  sleep: options.sleep,
258
342
  });
259
343
  if (!resolved.ok) {
260
344
  if (resolved.detail) console.log(chalk.red(resolved.detail));
261
- return;
345
+ return 1;
262
346
  }
263
347
  console.log(chalk.green(`Port freed (${resolved.detail}).`));
264
348
  }
265
349
 
266
- // 2. Migrate legacy Caddyfile blocks before boot
350
+ // 3. Migrate legacy Caddyfile blocks before boot; drop dead live-reload ports
267
351
  await fs.ensureDir(caddyDir);
268
352
  if (await fs.pathExists(caddyFile)) {
269
353
  await ensureCaddyfileMigrated({ caddyfilePath: caddyFile, projectsPath });
354
+ const stale = await clearStaleDevPorts(projectsPath);
355
+ for (const domain of stale) {
356
+ const project = await getProject(domain, projectsPath);
357
+ if (project) {
358
+ await applySiteBlock(domain, project, { caddyfilePath: caddyFile });
359
+ }
360
+ }
270
361
  await warnIfAllowAllOriginsActive({ caddyfilePath: caddyFile });
271
362
  }
272
363
 
273
- // 3. Boot services (autostart-aware kickstart when LaunchAgent is installed)
364
+ // 4. Boot services (autostart-aware)
274
365
  const spinner = createSpinner('Booting background services...').start();
275
366
 
276
367
  /** @type {number|null} */
@@ -286,29 +377,25 @@ export async function start(options = {}) {
286
377
  }
287
378
 
288
379
  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 */
380
+ // 2.3: ensurePhpFpm prefers `brew services start php`, then `restart`
381
+ // (2.2.7 always used `restart`). Keep start-first; both stay non-sudo.
382
+ const php = await ensurePhpFpm({
383
+ exec,
384
+ stdio: stdioMode === 'inherit' ? 'inherit' : 'ignore',
385
+ });
386
+ if (!php.ok && options.verbose) {
387
+ console.log(chalk.yellow(`PHP-FPM: ${php.detail || 'failed'}`));
296
388
  }
297
389
 
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
- }
390
+ const status =
391
+ (await (options.getAutostartStatus || getAutostartStatus)({ exec })) ||
392
+ {};
306
393
  const uid = options.uid ?? process.getuid?.() ?? os.userInfo().uid;
307
394
 
308
395
  if (status.loaded || status.plistExists) {
309
- if (status.plistExists && !status.loaded && status.plistPath) {
396
+ if (status.plistExists && !status.loaded) {
310
397
  try {
311
- await run(
398
+ await exec(
312
399
  'launchctl',
313
400
  buildLaunchctlBootstrapArgs(uid, status.plistPath)
314
401
  );
@@ -322,11 +409,11 @@ export async function start(options = {}) {
322
409
  console.log(
323
410
  chalk.red(error instanceof Error ? error.message : String(error))
324
411
  );
325
- return;
412
+ return 1;
326
413
  }
327
414
  }
328
415
  try {
329
- await run('launchctl', buildLaunchctlKickstartArgs(uid));
416
+ await exec('launchctl', buildLaunchctlKickstartArgs(uid));
330
417
  if (!options.verbose) {
331
418
  spinner.succeed(
332
419
  chalk.green(
@@ -339,7 +426,7 @@ export async function start(options = {}) {
339
426
  chalk.green(`āœ” kickstart gui/${uid}/${LAUNCH_AGENT_LABEL}`)
340
427
  );
341
428
  }
342
- return;
429
+ return 0;
343
430
  } catch (error) {
344
431
  if (!options.verbose) spinner.fail('launchctl kickstart failed.');
345
432
  console.log(
@@ -350,13 +437,16 @@ export async function start(options = {}) {
350
437
  }
351
438
  }
352
439
 
440
+ // Direct caddy start (no LaunchAgent)
353
441
  try {
354
- await run('caddy', ['stop']);
442
+ await exec('caddy', ['stop'], { stdio: 'ignore' });
355
443
  } catch {
356
- /* ignore */
444
+ // ignore
357
445
  }
358
446
 
359
- await run('caddy', ['start', '--config', caddyFile], { stdio: stdioMode });
447
+ await exec('caddy', ['start', '--config', caddyFile], {
448
+ stdio: stdioMode,
449
+ });
360
450
 
361
451
  if (!options.verbose) {
362
452
  spinner.succeed(chalk.green('Stagepass is active.'));
@@ -364,14 +454,17 @@ export async function start(options = {}) {
364
454
  } else {
365
455
  console.log(chalk.green('āœ” Stagepass is active.'));
366
456
  }
457
+ return 0;
367
458
  } catch (error) {
368
- spinner.fail('Failed to start.');
459
+ if (!options.verbose) spinner.fail('Failed to start.');
460
+ else console.log(chalk.red('Failed to start.'));
369
461
  if (!options.verbose) {
370
462
  console.log(chalk.red('See error log for details:'));
371
463
  console.log(chalk.dim(logFile));
372
464
  } else if (error instanceof Error) {
373
465
  console.log(chalk.red(error.message));
374
466
  }
467
+ return 1;
375
468
  } finally {
376
469
  if (logFd != null) {
377
470
  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
  }