@stagepass/cli 2.3.0 → 2.4.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 +35 -24
  2. package/package.json +1 -1
  3. package/src/cli.js +48 -5
  4. package/src/commands/daemon.js +18 -2
  5. package/src/commands/dev.js +14 -0
  6. package/src/commands/link.js +11 -1
  7. package/src/commands/new.js +39 -16
  8. package/src/commands/npm-run.js +14 -0
  9. package/src/commands/reload.js +5 -1
  10. package/src/commands/start.js +1 -1
  11. package/src/commands/upgrade.js +84 -32
  12. package/src/lib/autostart.js +66 -8
  13. package/src/lib/build-script-upgrade.js +244 -0
  14. package/src/lib/caddy-version.js +31 -0
  15. package/src/lib/caddyfile.js +76 -36
  16. package/src/lib/doctor-site.js +15 -10
  17. package/src/lib/doctor.js +131 -30
  18. package/src/lib/migrate.js +29 -2
  19. package/src/lib/package-versions.js +1 -1
  20. package/src/lib/paths.js +5 -0
  21. package/src/lib/php-runtime.js +249 -0
  22. package/src/lib/scaffold.js +22 -16
  23. package/templates/project/README.md.tmpl +8 -6
  24. package/templates/project/api/README.md.tmpl +172 -5
  25. package/templates/project/api/action.php +100 -0
  26. package/templates/project/api/actions/boom.php +21 -0
  27. package/templates/project/api/actions/contact.php +46 -0
  28. package/templates/project/api/actions/ping.php +23 -0
  29. package/templates/project/api/actions.php +59 -0
  30. package/templates/project/api/env.example +25 -0
  31. package/templates/project/api/lib/bootstrap.php +44 -0
  32. package/templates/project/api/lib/config.php +180 -0
  33. package/templates/project/api/lib/request.php +94 -0
  34. package/templates/project/api/lib/response.php +97 -0
  35. package/templates/project/api/lib/security.php +114 -0
  36. package/templates/project/api/lib/validate.php +69 -0
  37. package/templates/project/gitignore +4 -0
  38. package/templates/project/php-private/config.php +24 -0
  39. package/templates/project/scripts/build.mjs +114 -8
  40. package/templates/project/examples/php/README.md.tmpl +0 -18
  41. package/templates/project/examples/php/form.php +0 -105
  42. package/templates/project/examples/php/proxy.php +0 -171
package/README.md CHANGED
@@ -6,7 +6,7 @@ The CLI sets up and manages the local Stagepass infrastructure (`.sp` domains, C
6
6
 
7
7
  ## Install
8
8
 
9
- Published CLI 2.2.7 requires Node.js **18+** (`engines.node`: `>=18.0.0`) on **macOS** with Homebrew. CLI 2.3.0 (unreleased) raises the floor to `>=20.17.0` because `@inquirer/prompts@8` requires it. Development and CI use Node 22 or 24.
9
+ Published CLI 2.3.1 requires Node.js **20.17+** (`engines.node`: `>=20.17.0`) on **macOS** with Homebrew, because `@inquirer/prompts@8` requires it. Node 18 is no longer supported; stay on `@stagepass/cli@2.2.7` if you must remain on Node 18. Development and CI use Node 22 or 24.
10
10
 
11
11
  ```bash
12
12
  npm install -g @stagepass/cli@2
@@ -21,7 +21,7 @@ npx @stagepass/cli@2 setup
21
21
  ## Requirements
22
22
 
23
23
  - **macOS** (system commands refuse other platforms with exit code 1; this is not a breaking change because those commands never worked off macOS)
24
- - Published CLI 2.2.7: Node.js 18+ (`engines.node` `>=18.0.0`). CLI 2.3.0 (unreleased): Node.js `>=20.17.0`. Use Node 22 or 24 for local development and CI
24
+ - Published CLI 2.3.1: Node.js `>=20.17.0`. Use Node 22 or 24 for local development and CI
25
25
  - Homebrew
26
26
 
27
27
  `stagepass --version` and `stagepass --help` work on any platform. For tests/CI only, set `STAGEPASS_SKIP_PLATFORM_CHECK=1` to bypass the macOS guard (not for production use).
@@ -36,6 +36,8 @@ stagepass start
36
36
 
37
37
  # inside your project folder
38
38
  stagepass link my-project --origin www.example.com --origin my-project.webflow.io
39
+ stagepass build
40
+ stagepass dev
39
41
  ```
40
42
 
41
43
  Your project is then available at `https://my-project.sp`. Success output:
@@ -49,36 +51,35 @@ Linked: https://my-project.sp -> /absolute/path/to/project
49
51
  | Command | Description |
50
52
  | :--- | :--- |
51
53
  | `stagepass setup` | Install Caddy, PHP, Dnsmasq via Homebrew and configure the local `.sp` resolver (`address=/.sp/127.0.0.1` + `/etc/resolver/sp`). |
52
- | `stagepass start` | Start Caddy & PHP. Runs `certs check` (offers repair when interactive). No unconditional root warm-up: inspects port 443 without sudo; signals only after confirm (TERM then optional KILL; sudo only if unprivileged kill fails). With autostart installed, bootstraps/kickstarts the LaunchAgent (else direct `caddy start`). Migrates legacy Caddyfile blocks if needed. |
53
- | `stagepass link [domain]` | Link the current directory to a `.sp` domain, write/update the Caddyfile + `~/.stagepass/projects.json`, reload Caddy. |
54
+ | `stagepass start` | Start Caddy & PHP. Runs `certs check` (offers repair when interactive). No unconditional root warm-up: inspects port 443 without sudo; signals only after confirm (TERM then optional KILL; sudo only if unprivileged kill fails). With autostart installed, bootstraps/kickstarts the LaunchAgent (else direct `caddy start`). Migrates legacy Caddyfile blocks if needed, except when Caddy is known to be older than 2.9 (`brew upgrade caddy`). |
55
+ | `stagepass link [domain]` | Link the current directory to a `.sp` domain, write/update the Caddyfile + `~/.stagepass/projects.json`, reload Caddy. The linked block is v3. On Caddy older than 2.9, other existing blocks are left unchanged and CORS on success responses may be missing (`brew upgrade caddy`). |
54
56
  | `stagepass unlink [domain]` | Remove the site block and `projects.json` entry, reload Caddy. |
55
- | `stagepass reload` | Reload Caddy configuration. Migrates legacy Caddyfile blocks if needed. |
57
+ | `stagepass reload` | Reload Caddy configuration. Migrates legacy Caddyfile blocks if needed, except when Caddy is known to be older than 2.9 (`brew upgrade caddy`). |
56
58
  | `stagepass stop` | Stop Caddy & PHP. If autostart is installed/loaded, `launchctl bootout` first (until next login); use `autostart off` to disable permanently. |
57
- | `stagepass doctor` | Read-only diagnostics (Homebrew, Caddy, PHP/php-fpm, dnsmasq, resolver, port 443, Caddyfile, projects, certs, LaunchAgent, declared modules vs. live site). CDN pin warnings in docs + project files: **(unreleased, CLI 2.3.0)**. Never uses sudo. `--json`, `--skip-site`. Exit `1` if any fail. |
59
+ | `stagepass doctor` | Read-only diagnostics (Homebrew, Caddy, PHP/php-fpm, dnsmasq, resolver, port 443, Caddyfile, projects, certs, LaunchAgent, declared modules vs. live site). CDN pin warnings in docs + project files. Reports the Caddy version and warns (does not fail) when it is older than 2.9 (`brew upgrade caddy`); the v3 site block needs 2.9 or newer. Published CLI 2.3.1 fails when a LaunchAgent node or CLI path is missing, and warns on a versioned Homebrew Cellar node path or a daemon version that differs from the CLI (fix hint: `stagepass autostart on`). Never uses sudo. `--json`, `--skip-site`. Exit `1` if any fail. |
58
60
  | `stagepass certs check` | Read-only Caddy local CA check (validity, System keychain trust, orphans, optional TLS handshake per linked domain). `--json`, `--skip-handshake`. |
59
61
  | `stagepass certs trust` | Run `caddy trust` after interactive confirmation (or `--yes`). |
60
- | `stagepass certs renew` | **(unreleased, CLI 2.3.0)** Repair failing linked site certs; `--root` moves the CA folder to a backup (double confirm, or `--yes --i-understand-root-renewal`); `--remove-orphans` deletes keychain orphans by SHA-1 after confirm. |
62
+ | `stagepass certs renew` | Repair failing linked site certs; `--root` moves the CA folder to a backup (double confirm, or `--yes --i-understand-root-renewal`); `--remove-orphans` deletes keychain orphans by SHA-1 after confirm. |
61
63
  | `stagepass autostart on\|off\|status` | Manage a user LaunchAgent (`io.github.arobertherz.stagepass`) that runs `stagepass daemon` at login. |
62
64
  | `stagepass daemon` | Non-interactive LaunchAgent helper (PHP-FPM ensure, certs log-only, `caddy run`, macOS notifications). Never uses sudo. |
63
65
  | `stagepass new [name]` | Scaffold a lean Webflow project (TypeScript + SCSS by default). |
64
66
  | `stagepass build` | Run `npm run build` in the current project (forwards exit code). |
65
67
  | `stagepass watch` | Run `npm run watch` in the current project (forwards exit code). If Stagepass is not running, asks to start it (TTY) or prints a `stagepass start` hint (non-TTY / CI); warns with `stagepass link` when the cwd is not linked. |
66
- | `stagepass dev` | **(unreleased, CLI 2.3.0)** Like watch, plus live reload on the linked `.sp` domain. Same running check as watch; requires `stagepass link` (hard error if unlinked). |
68
+ | `stagepass dev` | Like `stagepass watch`, plus live reload on the linked `.sp` domain (CSS can swap without a full reload). Same running check as watch; requires `stagepass link` (hard error if unlinked). |
67
69
  | `stagepass upgrade` | Bump `@stagepass/*`, sync declared modules, `AGENTS.md`, the Cursor rule and `types`, print Webflow snippets. |
68
70
 
69
71
  All commands support `-v, --verbose` where applicable.
70
72
 
71
73
  ### Doctor / certificates / autostart
72
74
 
73
- Features marked **(unreleased, CLI 2.3.0)** are not in published npm `latest` (`2.2.7`).
74
-
75
75
  - `doctor` and `certs check` are read-only. They never delete keychain items or certificate files.
76
- - Prefer CDN major pin `@2` in Webflow custom code. Doctor unpinned-CDN warnings (`@latest`, bare `@1`, or unversioned `@stagepass/loader` / `@stagepass/modules` in recommended snippets and in the current project's `README.md`, `stagepass.json`, and `*.html` files directly in the project root and in `snippets/` — non-recursive, regular files ≤ 1 MB, symlinks skipped): **(unreleased, CLI 2.3.0)**.
77
- - `certs renew` **(unreleased, CLI 2.3.0)** is opt-in and confirmation-gated. Site repair only deletes `certificates/local/<linked-domain>` after checks fail. `--root` moves the CA folder to a timestamped backup (never deletes; needs two interactive confirmations without `--yes`, or `--yes --i-understand-root-renewal`). `--yes` alone always aborts for `--root` (TTY or not). Do not combine `--root` with `--remove-orphans`; run them as separate commands. Orphans are removed only by SHA-1 via `renew --remove-orphans`.
76
+ - Prefer CDN major pin `@2` in Webflow custom code. Doctor warns on unpinned CDN URLs (`@latest`, bare `@1`, or unversioned `@stagepass/loader` / `@stagepass/modules` in recommended snippets and in the current project's `README.md`, `stagepass.json`, and `*.html` files directly in the project root and in `snippets/`; non-recursive, regular files ≤ 1 MB, symlinks skipped).
77
+ - `certs renew` is opt-in and confirmation-gated. Site repair only deletes `certificates/local/<linked-domain>` after checks fail. `--root` moves the CA folder to a timestamped backup (never deletes; needs two interactive confirmations without `--yes`, or `--yes --i-understand-root-renewal`). `--yes` alone always aborts for `--root` (TTY or not). Do not combine `--root` with `--remove-orphans`; run them as separate commands. Orphans are removed only by SHA-1 via `renew --remove-orphans`.
78
78
  - Chrome may require Local Network Access permission for public HTTPS pages that load `https://*.sp` assets.
79
79
  - Autostart runs as your user (same privilege model as interactive `caddy start`). `start` kickstarts the agent when present; `stop` bootouts until the next login. If port 443 cannot be bound, `daemon` logs a clear error, may notify, and exits `0` so launchd KeepAlive does not restart-loop. Interactive `start` confirms before signalling any non-caddy listener (name + PID; SIGTERM then optional SIGKILL). Own processes are signalled without elevated rights first; `sudo` only when needed after confirmation. There is no standby `sudo -v`.
80
- - `stagepass autostart on` records a launchd-safe `PATH` from `brew --prefix` (Apple Silicon `/opt/homebrew`, Intel `/usr/local`) plus `/usr/bin:/bin:/usr/sbin:/sbin`. It does **not** copy your interactive shell environment. `brew` and `caddy` must resolve to shims under that prefix's `bin`/`sbin` (normal Homebrew Cellar symlinks are fine). Missing Homebrew/Caddy aborts **before** writing the plist.
81
- - Published CLI requires Node `>=18.0.0`. CLI 2.3.0 (unreleased) raises it to `>=20.17.0`.
80
+ - `stagepass autostart on` records a launchd-safe `PATH` from `brew --prefix` (Apple Silicon `/opt/homebrew`, Intel `/usr/local`) plus `/usr/bin:/bin:/usr/sbin:/sbin`. It does **not** copy your interactive shell environment. `brew` and `caddy` must resolve to shims under that prefix's `bin`/`sbin` (normal Homebrew Cellar symlinks are fine). Missing Homebrew/Caddy aborts **before** writing the plist. Published CLI 2.3.1 uses the Homebrew `bin/node` shim when the running node is a versioned Cellar path.
81
+ - Published CLI 2.3.1 `stagepass doctor` fails when a LaunchAgent node or CLI path is missing. It warns when that node path is a versioned Homebrew Cellar path, or when the running daemon version differs from the CLI. The fix hint is `stagepass autostart on`.
82
+ - Published CLI requires Node `>=20.17.0`. Node 18 is no longer supported; stay on `@stagepass/cli@2.2.7` if you must remain on Node 18.
82
83
  - Manual macOS checklist: [`TESTING-macos.md`](./TESTING-macos.md).
83
84
 
84
85
  #### macOS permissions (keep these separate)
@@ -94,7 +95,7 @@ These are different prompts. Grant only the narrow dialog macOS shows. Stagepass
94
95
  #### Install location and LaunchAgent paths
95
96
 
96
97
  - Prefer a **stable** global install (`npm install -g @stagepass/cli` into the normal npm prefix, or another fixed absolute path). Avoid pointing autostart at a temporary Desktop unpack / ad-hoc test tarball when you can use the published package instead.
97
- - `autostart on` records **absolute** Node and CLI paths (often Homebrew Cellar Node + the realpathed `stagepass` entry) plus the validated Homebrew `PATH`. It does not follow later `brew` upgrades automatically.
98
+ - `autostart on` records **absolute** Node and CLI paths plus the validated Homebrew `PATH`. Published CLI 2.3.1 uses the Homebrew `bin/node` shim when the running node is a versioned Cellar path (it does not store that versioned binary). It does not follow later `brew` upgrades automatically.
98
99
  - After a Homebrew Node upgrade/cleanup, moving the CLI, or changing the npm prefix, run `stagepass autostart on` again so ProgramArguments stay valid. A brief local outage while the agent reloads is expected.
99
100
  - Upgrading the global CLI package does **not** rewrite an existing LaunchAgent that still points at an older test path. Switch deliberately: `stagepass autostart off` then `autostart on` with the stable CLI you want. Do **not** delete a test directory while a loaded agent still references it; disable/refresh the agent first.
100
101
  - Development checkouts (`packages/cli`, Desktop test packs) and the published global install are different binaries; compare behaviour with one style at a time.
@@ -111,12 +112,12 @@ Scaffold a project with flags for every choice (interactive prompts only on a TT
111
112
  | `--styles scss\|css` | Styles (default: `scss`). |
112
113
  | `--modules` / `--no-modules` | Include `@stagepass/modules` as npm dependency (default: yes; forced on when `--site-modules` lists a module). |
113
114
  | `--site <host>` | Live Webflow site (https) to detect the loaded modules from. Also sets `origin` in `stagepass.json`. |
114
- | `--staging <domain>` | **(unreleased, CLI 2.3.0)** Staging hostname (hostname only; same validation as `--origin`). Stored as `origin`. Must match `--site` when both are set. |
115
- | `--production <domain>` | **(unreleased, CLI 2.3.0)** Optional production hostname. Stored as `production`. When omitted, prints a short hint to add it later via `stagepass link --origin`. |
115
+ | `--staging <domain>` | Staging hostname (hostname only; same validation as `--origin`). Stored as `origin`. Must match `--site` when both are set. |
116
+ | `--production <domain>` | Optional production hostname. Stored as `production`. When omitted, prints a short hint to add it later via `stagepass link --origin`. |
116
117
  | `--site-modules <list>` | Modules the site loads: `none`, `all`, or a comma list of `inject`, `cookies`, `maintenance`. Takes precedence over `--site`. |
117
- | `--php` / `--no-php` | **(unreleased, CLI 2.3.0)** Enable PHP for the project (`api/` + `php_fastcgi` on link). Default: off. Existing linked projects without `"php"` keep PHP on. |
118
- | `--php-examples` / `--no-php-examples` | **(unreleased, CLI 2.3.0)** Include `examples/php/` samples (requires `--php`). Default: off. |
119
- | `--link` / `--no-link` | **(unreleased, CLI 2.3.0)** After scaffolding, run `stagepass link` (macOS only). Default: off; interactive macOS may offer it. |
118
+ | `--php` / `--no-php` | Enable the PHP boilerplate (`api/`, `.php/config.php`, `php_fastcgi` on link). Default: off. Existing linked projects without `"php"` keep PHP on. |
119
+ | `--php-examples` / `--no-php-examples` | Deprecated. Sample actions ship with `--php` in `api/actions/`. The flags are accepted and do not copy a second sample set. |
120
+ | `--link` / `--no-link` | After scaffolding, run `stagepass link` (macOS only). Default: off; interactive macOS may offer it. |
120
121
  | `--git` / `--no-git` | `git init` (default: yes). |
121
122
  | `--remote <url>` | Set `origin` after git init (rejects URLs with embedded credentials). |
122
123
  | `--install` / `--no-install` | Run `npm install` (default: no). |
@@ -125,7 +126,11 @@ Scaffold a project with flags for every choice (interactive prompts only on a TT
125
126
 
126
127
  The name must be DNS-safe (lowercase `a-z`, `0-9`, hyphens; 1 to 63 chars; no leading/trailing hyphen). Existing files are never overwritten. Generated projects include `scripts/build.mjs` (content-hashed `dist/` + SRI `integrity` in `manifest.json`), scripts `build` / `watch` / `dev` (`dev` aliases `watch`), Webflow head/footer snippets (jsDelivr `@2`, loader plus the declared modules), `stagepass.json`, an `AGENTS.md` with the full `sp` API reference, `.cursor/rules/stagepass.mdc`, and a `.gitignore`. `@stagepass/loader` / `@stagepass/modules` are added as `^2` (same major as the CDN pin `@2`; npm installs the newest published 2.x). Per-module types are written only when the published or installed `@stagepass/modules` ships them (2.2.0 and later); otherwise `types` lists the umbrella `@stagepass/modules`.
127
128
 
128
- Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `stagepass setup` if the local stack looks incomplete (never automatic, never under `--yes` / no-TTY, never sudo by itself). On published CLI 2.2.7, without a TTY (or with `--yes`) it uses `--site-modules`, then `--site` detection, else `[]` with a hint. Staging / production prompts, PHP prompts, `--staging` detection, and `link` reading `origin` / `production` from `stagepass.json` are **(unreleased, CLI 2.3.0)**.
129
+ Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `stagepass setup` if the local stack looks incomplete (never automatic, never under `--yes` / no-TTY, never sudo by itself). Without a TTY (or with `--yes`) it uses `--site-modules`, then `--site` detection, else `[]` with a hint. The interactive wizard always asks whether to enable PHP unless `--php` / `--no-php` was passed. Staging / production prompts, `--staging` detection, and `link` reading `origin` / `production` from `stagepass.json` are part of this release.
130
+
131
+ ### PHP
132
+
133
+ `--php` writes a plain PHP 8.2 boilerplate: `api/action.php` is the only public entry, actions are an allowlist in `api/actions.php`, and `.php/config.php` stays outside that folder. Copy `api/.env.example` to `.env` and set `ALLOWED_ORIGINS` (include `https://<name>.sp`). There is no mail. Caddy already returns 404 for hidden segments such as `/.env`, `/api/.env`, and `/.php/`. `stagepass new` and `doctor` warn when `php` is missing, older than 8.2, or has no `php-fpm` / `php-cgi` (`brew install php` on macOS). `stagepass dev` and `stagepass watch` on a `"php": true` project do the same check and start Homebrew php-fpm (`brew services start php`, and `brew services restart php` only if start fails), the same helper `stagepass start` has used since 2.3. The JS build still runs. `stagepass build` copies `api/` and `.php/config.php` into `dist/` and skips `.env`, `.php/rate-limit/`, logs, pid files, and key, certificate, or database files (`.pem`, `.key`, `.p12`, `.pfx`, `.crt`, `.cer`, `.sqlite`, `.db`). It keeps `.htaccess` and `.env.example`. `stagepass dev` / `watch` serve PHP from the project root, so edits show up on the next request. A longer draft for the website lives in [docs/php.md](https://github.com/arobertherz/stagepass/blob/master/docs/php.md); that page is not live yet.
129
134
 
130
135
  ### Declared modules (`stagepass.json`)
131
136
 
@@ -158,7 +163,7 @@ Still not recognised: tags without `src`, `data-src` only, other hosts without a
158
163
  | `--site <host>` | Live site to detect modules from (default: the origin linked in `~/.stagepass/projects.json` for this folder). Stored in `stagepass.json` when given. |
159
164
  | `--site-modules <list>` | Set the modules list directly (`none`, `all`, or a comma list). |
160
165
  | `--skip-site` | Do not fetch the live site. |
161
- | `-y, --yes` | Accept the detected or existing list without asking. |
166
+ | `-y, --yes` | Accept the detected or existing list without asking. With `--yes`, CLI 2.4.0 also replaces an unmodified `scripts/build.mjs`. |
162
167
  | `--dry-run` | Print every planned change; write no file. |
163
168
 
164
169
  `upgrade` bumps `@stagepass/*` in `package.json`, then resolves the modules list (`--site-modules`, else live detection, confirmed interactively; if the site is unreachable or no origin is known it asks; without a TTY it keeps the existing list or `[]` and prints a hint). It then syncs the project:
@@ -167,6 +172,7 @@ Still not recognised: tags without `src`, `data-src` only, other hosts without a
167
172
  - `AGENTS.md`: created if missing, otherwise only the managed block is replaced (or appended when there is none). Your own text stays. Broken markers are left alone with a hint.
168
173
  - `.cursor/rules/stagepass.mdc`: created if missing, otherwise only its managed block is refreshed.
169
174
  - `tsconfig.json` / `jsconfig.json`: only `compilerOptions.types` changes, the rest of the JSON is preserved. Files with comments, or without a `types` array, are skipped with a hint.
175
+ - `scripts/build.mjs`: CLI 2.4.0 replaces it when it is still an unmodified scaffold from an earlier CLI (line endings ignored; `src/main.js` / `src/main.ts` and `src/styles.css` / `src/styles.scss` still count). The interactive prompt defaults to yes. Without a TTY, and with `--yes`, the file is replaced. `--dry-run` writes nothing. An edited script is left unchanged and the CLI prints what `stagepass build`, `stagepass watch` and `stagepass dev` do now. A missing script stays missing. Published CLI 2.3.1 does not replace that file.
170
176
 
171
177
  Every change is printed as `file: action` (unchanged files are not listed; skipped files appear as hints). `npm install` is printed, not run. Snippets use the major pin `@2` plus an optional exact pin note.
172
178
 
@@ -188,7 +194,7 @@ Every change is printed as `file: action` (unchanged files are not listed; skipp
188
194
  | `--no-allow-all-origins` | Disable allow-all mode and use the origin allowlist. |
189
195
  | `-v, --verbose` | Show Caddy reload output / errors. |
190
196
 
191
- Published CLI 2.2.7 still needs explicit `link --origin` for CORS (even when `new --site` wrote `origin` into `stagepass.json`). `link` reading `origin` / `production` from `stagepass.json` when no `--origin` / `--remove-origin` flags are passed is **(unreleased, CLI 2.3.0)**. The project's `"php"` flag (when set) controlling whether the Caddy site block includes `php_fastcgi` is also **(unreleased, CLI 2.3.0)**; missing `"php"` keeps the legacy PHP-on behaviour.
197
+ `link` reads `origin` / `production` from `stagepass.json` when no `--origin` / `--remove-origin` flags are passed. You can still pass `--origin` explicitly for CORS. The project's `"php"` flag (when set) controls whether the Caddy site block includes `php_fastcgi`; missing `"php"` keeps the legacy PHP-on behaviour.
192
198
 
193
199
  **`--origin` / `--remove-origin` format:** `example.com`, `www.example.com`, `*.example.com`, or `https://example.com`. Hostnames only (optional leading `*.`); no path, port, or `http://` for live origins.
194
200
 
@@ -232,7 +238,7 @@ Stagepass reflects `Access-Control-Allow-Origin` for **allowed** browser `Origin
232
238
 
233
239
  Webflow staging/live hosts are **not** included by default. Add them per project, e.g. `--origin my-project.webflow.io`. An explicit `--origin *.webflow.io` (or `*.webflow.com`) is accepted but prints a warning (any Webflow user's site would then be allowed).
234
240
 
235
- Matching responses also send `Vary: Origin`. Preflight (`OPTIONS`) for allowed origins returns `204` with reflected ACAO, `Access-Control-Allow-Methods: GET, HEAD, POST, OPTIONS`, reflected `Access-Control-Allow-Headers`, `Access-Control-Max-Age: 86400`, and `Access-Control-Allow-Private-Network: true` (Chrome Private Network Access from public HTTPS → loopback).
241
+ Matching responses also send `Vary: Origin`. On HTTP 2xx, Caddy sets a single `Access-Control-Allow-Origin` with a deferred replace, so a PHP app that sends the same header does not produce a second value. Other status codes are not given an ACAO by Caddy. Preflight (`OPTIONS`) for allowed origins returns `204` with reflected ACAO, `Access-Control-Allow-Methods: GET, HEAD, POST, OPTIONS`, reflected `Access-Control-Allow-Headers`, `Access-Control-Max-Age: 86400`, and `Access-Control-Allow-Private-Network: true` (Chrome Private Network Access from public HTTPS → loopback).
236
242
 
237
243
  Non-matching origins get **no** ACAO. Non-allowlisted `OPTIONS` still get `204` without CORS headers.
238
244
 
@@ -267,6 +273,8 @@ On `stagepass link`, `reload`, and `start`, legacy Caddyfile blocks (no `# stage
267
273
  3. **`allowAllOrigins` is enabled** for migrated blocks so existing Webflow / live-domain embedding keeps working
268
274
  4. A short notice recommends tightening CORS
269
275
 
276
+ Blocks already marked `# stagepass-block: v2` are rewritten to the current marker on those same commands. Saved options (`allowAllOrigins`, origins, `php`, `devPort`) stay as they are.
277
+
270
278
  Recommended after migration:
271
279
 
272
280
  ```bash
@@ -276,6 +284,8 @@ stagepass link --no-allow-all-origins
276
284
 
277
285
  Hand-written content outside `# START:` / `# END:` markers is left untouched. Unparsable legacy blocks are left unchanged with a warning. Migration is idempotent (second run does nothing and creates no new backup).
278
286
 
287
+ The v3 block needs Caddy 2.9 or newer (`brew upgrade caddy`). Homebrew does not upgrade an existing Caddy when you `brew install caddy`. On a known older Caddy, `link`, `reload`, and `start` do not rewrite existing blocks. `link` still writes that project's block as v3 and warns that CORS on success responses may be missing until you upgrade. If `caddy version` cannot be read, the rewrite stays as before. `stagepass doctor` reports the version and warns below 2.9.
288
+
279
289
  ## Troubleshooting (CLI)
280
290
 
281
291
  | Symptom | What to check |
@@ -283,6 +293,7 @@ Hand-written content outside `# START:` / `# END:` markers is left untouched. Un
283
293
  | Autostart runs at login but `caddy: command not found` / daemon exits | Re-run `stagepass autostart on` so the plist embeds Homebrew `PATH`. Confirm `brew --prefix` and that `which caddy` points at `$prefix/bin/caddy` (Cellar symlink OK). |
284
294
  | macOS asks Node for Desktop access | Normal TCC when the CLI/agent reads a project under Desktop. Grant the folder or move the project / use a stable global CLI install. Not the same as browser Local Network or CA trust. |
285
295
  | Autostart still runs an old Desktop test binary after `npm i -g` | Global upgrade does not migrate LaunchAgent ProgramArguments. `autostart off` then `on` with the stable CLI; do not remove the old path while the agent still references it. |
296
+ | Login autostart points at a deleted Homebrew Node, or `doctor` warns that the daemon version differs from the CLI | Published CLI 2.3.1. Run `stagepass autostart on`. `doctor` fails on a missing LaunchAgent node or CLI path, and warns on a versioned Cellar node path or a daemon/CLI version mismatch. The fix hint is `stagepass autostart on`. |
286
297
  | `stagepass start` spinner floods the terminal (weird ANSI) | Upgrade to a build with the spinner geometry guard. Rare with TTY width `0`. |
287
298
  | `start` asks for a password at every boot | There is no unconditional `sudo -v`. Only confirmed conflict resolution may use `sudo kill` / `apachectl`. |
288
299
  | Port 443 bind failure under LaunchAgent | Expected when something else owns 443; daemon exits `0` (no restart loop). Free the port or use interactive `stagepass start`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/cli",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "Local Development Orchestrator for Webflow",
5
5
  "type": "module",
6
6
  "main": "bin/index.js",
package/src/cli.js CHANGED
@@ -62,6 +62,35 @@ export function rewriteArgvForUpgrade(argv) {
62
62
  return out;
63
63
  }
64
64
 
65
+ // Suggest subcommands for a top-level unknown option. Strip control chars. Do not run.
66
+ function suggestMisplacedOption(program, errorText) {
67
+ if (!errorText.startsWith("error: unknown option '")) return '';
68
+ const args = (program.args || []).map((s) => String(s).replace(/\p{C}/gu, ''));
69
+ const flag = args[0];
70
+ if (!flag || flag[0] !== '-' || flag === '--') return '';
71
+ const name = flag.split('=')[0];
72
+ const hits = [];
73
+ const walk = (cmd, prefix) => {
74
+ for (const sub of cmd.commands) {
75
+ const path = prefix.concat(sub.name());
76
+ if (sub.options.some((o) => o.long === name || o.short === name)) hits.push(path);
77
+ walk(sub, path);
78
+ }
79
+ };
80
+ walk(program, []);
81
+ if (!hits.length) return '';
82
+ const bin = program.name();
83
+ hits.sort((a, b) => (a.join(' ') < b.join(' ') ? -1 : a.join(' ') > b.join(' ') ? 1 : 0));
84
+ return hits
85
+ .map((cmdPath) => {
86
+ const rest = args.slice(1);
87
+ const echoed = cmdPath.every((part, i) => rest[i] === part);
88
+ const tail = echoed ? [flag, ...rest.slice(cmdPath.length)] : args;
89
+ return `Did you mean: ${bin} ${cmdPath.join(' ')} ${tail.join(' ')}\n`;
90
+ })
91
+ .join('');
92
+ }
93
+
65
94
  /**
66
95
  * Build the Commander program (no parse). Injectable handlers for unit tests.
67
96
  *
@@ -294,13 +323,13 @@ export function createProgram(deps = {}) {
294
323
  program
295
324
  .command('upgrade')
296
325
  .description(
297
- 'Bump @stagepass/*, sync modules, AGENTS.md, Cursor rule and types, print Webflow snippets'
326
+ 'Bump @stagepass/*, sync project files, replace an unmodified scripts/build.mjs, print Webflow snippets'
298
327
  )
299
328
  .option('--dry-run', 'Show changes without writing any file')
300
329
  .option('--site <host>', 'Live Webflow site to detect loaded modules from (https)')
301
330
  .option('--site-modules <list>', 'Modules the site loads: none, all, or inject,cookies,maintenance')
302
331
  .option('--skip-site', 'Do not fetch the live site')
303
- .option('-y, --yes', 'Non-interactive; accept detected or existing modules')
332
+ .option('-y, --yes', 'Non-interactive; accept detected or existing modules and an unmodified scripts/build.mjs')
304
333
  .option(
305
334
  '--target <version>',
306
335
  'Target version, range or dist-tag; must be published on npm (default: ^<latest published 2.x>, ^2 offline)'
@@ -359,10 +388,10 @@ export function createProgram(deps = {}) {
359
388
  .option('--staging <domain>', 'Staging hostname written to stagepass.json as origin')
360
389
  .option('--production <domain>', 'Optional production hostname written to stagepass.json')
361
390
  .option('--site-modules <list>', 'Modules the site loads: none, all, or inject,cookies,maintenance')
362
- .option('--php', 'Enable PHP (api/ + php_fastcgi on link)')
391
+ .option('--php', 'Enable PHP (api/ boilerplate + php_fastcgi on link)')
363
392
  .option('--no-php', 'Disable PHP for this project (default)')
364
- .option('--php-examples', 'Include examples/php samples (requires --php)')
365
- .option('--no-php-examples', 'Skip PHP examples (default)')
393
+ .option('--php-examples', 'Deprecated: sample actions ship with --php under api/actions/')
394
+ .option('--no-php-examples', 'Deprecated no-op (examples are not a separate copy)')
366
395
  .option('--link', 'Run stagepass link after scaffolding (macOS)')
367
396
  .option('--no-link', 'Do not link after scaffolding (default)')
368
397
  .option('--git', 'Initialize a git repository')
@@ -378,5 +407,19 @@ export function createProgram(deps = {}) {
378
407
  process.exitCode = code;
379
408
  });
380
409
 
410
+ // Typo suggestions (commander). Root-only writer: subcommands already copied output config.
411
+ const enableSuggest = (cmd) => {
412
+ cmd.showSuggestionAfterError();
413
+ cmd.commands.forEach(enableSuggest);
414
+ };
415
+ enableSuggest(program);
416
+ program.configureOutput({
417
+ outputError(str, write) {
418
+ write(str);
419
+ const hint = suggestMisplacedOption(program, str);
420
+ if (hint) write(hint);
421
+ },
422
+ });
423
+
381
424
  return program;
382
425
  }
@@ -1,13 +1,15 @@
1
1
  import fs from 'fs-extra';
2
+ import { createRequire } from 'node:module';
2
3
  import chalk from 'chalk';
3
4
  import { defaultExec } from '../lib/exec.js';
4
- import { getCaddyfilePath, getLogsDir } from '../lib/paths.js';
5
+ import { getCaddyfilePath, getDaemonStatePath, getLogsDir, getProjectsPath } from '../lib/paths.js';
5
6
  import { runCertsCheck } from '../lib/certs.js';
6
7
  import { loadProjects } from '../lib/projects.js';
7
- import { getProjectsPath } from '../lib/paths.js';
8
8
  import { ensurePhpFpm } from '../lib/php-fpm.js';
9
9
  import { notifyMac } from '../lib/notify.js';
10
10
 
11
+ const CLI_VERSION = createRequire(import.meta.url)('../../package.json').version;
12
+
11
13
  /**
12
14
  * Detect bind / permission failures that will not self-heal on immediate restart.
13
15
  * LaunchAgent KeepAlive (SuccessfulExit=false) must not restart-loop on these.
@@ -61,6 +63,20 @@ export async function daemon(options = {}) {
61
63
 
62
64
  await fs.ensureDir(options.logsDir || getLogsDir());
63
65
 
66
+ // Doctor reads this to see the version that is actually running (#74).
67
+ if (options.recordState !== false) {
68
+ try {
69
+ const writeFile = options.writeFile || ((p, c) => fs.writeFile(p, c, 'utf8'));
70
+ const version = options.version || CLI_VERSION;
71
+ await writeFile(
72
+ options.statePath || getDaemonStatePath(),
73
+ JSON.stringify({ version, pid: process.pid })
74
+ );
75
+ } catch {
76
+ // diagnostic only
77
+ }
78
+ }
79
+
64
80
  if (!(await pathExists(caddyfilePath))) {
65
81
  log(`Caddyfile missing: ${caddyfilePath}`);
66
82
  log('Refusing to start. Run: stagepass setup && stagepass link');
@@ -20,6 +20,8 @@ import { readStagepassJson } from '../lib/project-sync.js';
20
20
  import { getCaddyfilePath, getProjectsPath, validateRoot } from '../lib/paths.js';
21
21
  import { isPidAlive, isValidDevPort } from '../lib/dev-port.js';
22
22
  import { ensureStagepassReady } from '../lib/ensure-running.js';
23
+ import { warnPhpProject } from '../lib/php-runtime.js';
24
+ import { ensurePhpFpm } from '../lib/php-fpm.js';
23
25
  import { start as defaultStart } from './start.js';
24
26
 
25
27
  /** Grace before SIGKILL after a forwarded stop signal (overridable in tests). */
@@ -328,6 +330,18 @@ export async function dev(options = {}, deps = {}) {
328
330
 
329
331
  setupDone = true;
330
332
 
333
+ await warnPhpProject(cwd, {
334
+ fs: fse,
335
+ exec: deps.exec,
336
+ platform: deps.platform,
337
+ pathExists: deps.pathExists,
338
+ resolveCommand: deps.resolveCommand,
339
+ brewPrefix: deps.brewPrefix,
340
+ domain,
341
+ warn: (m) => log(chalk.yellow(m)),
342
+ ensurePhpFpm: deps.ensurePhpFpm || ensurePhpFpm,
343
+ });
344
+
331
345
  log(chalk.green(`Live reload on https://${domain}/__stagepass/live (127.0.0.1:${live.port})`));
332
346
  if (options.verbose) {
333
347
  log(chalk.dim('Running: npm run watch'));
@@ -17,6 +17,7 @@ import {
17
17
  isBroadWebflowWildcard,
18
18
  } from '../lib/origins.js';
19
19
  import { ensureCaddyfileMigrated } from '../lib/migrate.js';
20
+ import { CADDY_UPGRADE_HINT, readCaddyVersion } from '../lib/caddy-version.js';
20
21
  import {
21
22
  originsFromStagepassConfig,
22
23
  phpFromStagepassConfig,
@@ -36,6 +37,7 @@ import { isPhpEnabled } from '../lib/caddyfile.js';
36
37
  * @param {string} [deps.cwd]
37
38
  * @param {(msg?: string) => void} [deps.log]
38
39
  * @param {(msg?: string) => void} [deps.error]
40
+ * @param {import('../lib/exec.js').ExecFn} [deps.exec]
39
41
  */
40
42
  export async function link(domain, options = {}, deps = {}) {
41
43
  const log = deps.log || console.log;
@@ -127,7 +129,15 @@ export async function link(domain, options = {}, deps = {}) {
127
129
  await fs.ensureDir(caddyDir);
128
130
 
129
131
  spinner.stop();
130
- await ensureCaddyfileMigrated({ caddyfilePath: caddyFilePath, projectsPath });
132
+ const caddy = await readCaddyVersion(deps.exec);
133
+ await ensureCaddyfileMigrated({ caddyfilePath: caddyFilePath, projectsPath, caddy });
134
+ if (caddy.known && !caddy.ok) {
135
+ log(
136
+ chalk.yellow(
137
+ ` This site block is v3 and needs Caddy 2.9 or newer for CORS on success responses. ${CADDY_UPGRADE_HINT}`
138
+ )
139
+ );
140
+ }
131
141
  await clearStaleDevPorts(projectsPath);
132
142
  spinner.start(`Linking ${chalk.bold(targetDomain)}...`);
133
143
 
@@ -33,6 +33,7 @@ import {
33
33
  import { updateConfigTypes } from '../lib/project-sync.js';
34
34
  import { validateOriginEntry, isBroadWebflowWildcard } from '../lib/origins.js';
35
35
  import { isMacOS } from '../lib/platform.js';
36
+ import { checkPhpRuntime, phpOriginsHint, phpProjectWarning } from '../lib/php-runtime.js';
36
37
  import { runDoctor } from '../lib/doctor.js';
37
38
  import { setup as defaultSetup } from './setup.js';
38
39
  import { link as defaultLink } from './link.js';
@@ -329,9 +330,6 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
329
330
  if (php === undefined) {
330
331
  php = await askYesNo(rl, 'Enable PHP for this project?', false);
331
332
  }
332
- if (php && phpExamples === undefined) {
333
- phpExamples = await askYesNo(rl, 'Include PHP examples under examples/php/?', false);
334
- }
335
333
  if (git === undefined) {
336
334
  git = await askYesNo(rl, 'Initialize git repository?', true);
337
335
  }
@@ -341,10 +339,7 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
341
339
  if (install === undefined) {
342
340
  install = await askYesNo(rl, 'Run npm install now?', false);
343
341
  }
344
- if (linkAtEnd === undefined) {
345
- // Asked after create on macOS only; remember preference here when already decided.
346
- linkAtEnd = undefined;
347
- }
342
+ // Asked after create on macOS only when the link flag was omitted.
348
343
  } finally {
349
344
  rl.close();
350
345
  }
@@ -389,7 +384,7 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
389
384
  if (install === undefined) install = false;
390
385
  if (php === undefined) php = false;
391
386
  if (phpExamples === undefined) phpExamples = false;
392
- if (linkAtEnd === undefined) linkAtEnd = false;
387
+ if (linkAtEnd == null && !interactive) linkAtEnd = false;
393
388
 
394
389
  if (lang !== 'ts' && lang !== 'js') {
395
390
  return { ok: false, error: 'Language must be ts or js.' };
@@ -397,11 +392,12 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
397
392
  if (styles !== 'scss' && styles !== 'css') {
398
393
  return { ok: false, error: 'Styles must be scss or css.' };
399
394
  }
400
- if (phpExamples && !php) {
401
- return {
402
- ok: false,
403
- error: '--php-examples requires PHP. Pass --php or omit --php-examples.',
404
- };
395
+ if (phpExamples) {
396
+ log(
397
+ chalk.yellow(
398
+ '--php-examples is deprecated. Sample actions (ping, contact) are included with --php under api/actions/. This flag no longer copies examples/php/.'
399
+ )
400
+ );
405
401
  }
406
402
 
407
403
  const remoteCheck = validateGitRemote(remote);
@@ -564,7 +560,7 @@ async function maybeDoctorPreflight(deps = {}) {
564
560
  }
565
561
 
566
562
  /**
567
- * Optionally link the new project (macOS only; interactive ask or --link).
563
+ * Optionally link the new project (macOS only; --link, or ask when unset).
568
564
  *
569
565
  * @param {object} config
570
566
  * @param {string} targetDir
@@ -580,9 +576,9 @@ async function maybeLinkProject(config, targetDir, deps = {}) {
580
576
  return;
581
577
  }
582
578
 
583
- let shouldLink = config.linkAtEnd === true;
579
+ let shouldLink = config.linkAtEnd;
584
580
  const isTty = deps.isTTY != null ? Boolean(deps.isTTY) : Boolean(input.isTTY);
585
- if (!shouldLink && isTty && deps.yes !== true) {
581
+ if (shouldLink == null && isTty && deps.yes !== true) {
586
582
  const rl =
587
583
  deps.createReadline?.() ||
588
584
  readline.createInterface({ input, output });
@@ -752,6 +748,7 @@ export async function createNew(nameArg, options = {}, deps = {}) {
752
748
  if (config.install) log(' (npm install)');
753
749
  if (config.linkAtEnd) log(' (stagepass link)');
754
750
  if (config.productionSkipped) log(` (${PRODUCTION_HINT})`);
751
+ await reportPhpChoice(config, deps, log);
755
752
  return 0;
756
753
  }
757
754
 
@@ -845,6 +842,7 @@ export async function createNew(nameArg, options = {}, deps = {}) {
845
842
  }
846
843
  log(chalk.dim(`Declared modules (stagepass.json): ${formatModules(config.siteModules)}`));
847
844
  log(chalk.dim(`PHP: ${config.php ? 'on' : 'off'}`));
845
+ await reportPhpChoice(config, deps, log);
848
846
 
849
847
  const snippets = buildWebflowSnippets({
850
848
  version: config.loaderVersion,
@@ -863,5 +861,30 @@ export async function createNew(nameArg, options = {}, deps = {}) {
863
861
  return 0;
864
862
  }
865
863
 
864
+ /**
865
+ * Origins hint plus a non-fatal PHP 8.2 / php-fpm check. The project is kept either way.
866
+ * @param {{ php?: boolean, name: string }} config
867
+ * @param {object} deps
868
+ * @param {(msg?: string) => void} log
869
+ */
870
+ async function reportPhpChoice(config, deps, log) {
871
+ if (config.php !== true) return;
872
+ log(chalk.dim(phpOriginsHint(config.name)));
873
+ try {
874
+ const runtime = await checkPhpRuntime({
875
+ exec: deps.exec,
876
+ platform: deps.platform,
877
+ pathExists: deps.pathExists,
878
+ resolveCommand: deps.resolveCommand,
879
+ brewPrefix: deps.brewPrefix,
880
+ });
881
+ if (!runtime.ok) {
882
+ log(chalk.yellow(phpProjectWarning(runtime, `${config.name}.sp`)));
883
+ }
884
+ } catch {
885
+ log(chalk.yellow('PHP could not be checked. The project was still created.'));
886
+ }
887
+ }
888
+
866
889
  /** Commander-facing alias */
867
890
  export const newProject = createNew;
@@ -3,6 +3,8 @@ import path from 'path';
3
3
  import chalk from 'chalk';
4
4
  import { defaultSpawn } from '../lib/spawn.js';
5
5
  import { ensureStagepassReady } from '../lib/ensure-running.js';
6
+ import { warnPhpProject } from '../lib/php-runtime.js';
7
+ import { ensurePhpFpm } from '../lib/php-fpm.js';
6
8
  import { start as defaultStart } from './start.js';
7
9
 
8
10
  /**
@@ -75,6 +77,18 @@ export async function runNpmScript(scriptName, options = {}, deps = {}) {
75
77
  * @returns {Promise<number>}
76
78
  */
77
79
  export async function watch(options = {}, deps = {}) {
80
+ const cwd = deps.cwd || process.cwd();
81
+ await warnPhpProject(cwd, {
82
+ fs: deps.fs,
83
+ exec: deps.exec,
84
+ platform: deps.platform,
85
+ pathExists: deps.pathExists,
86
+ resolveCommand: deps.resolveCommand,
87
+ brewPrefix: deps.brewPrefix,
88
+ domain: deps.domain,
89
+ warn: (m) => (deps.log || console.log)(chalk.yellow(m)),
90
+ ensurePhpFpm: deps.ensurePhpFpm || ensurePhpFpm,
91
+ });
78
92
  await (deps.ensureStagepassReady || ensureStagepassReady)(options, {
79
93
  ...deps,
80
94
  start: deps.start || defaultStart,
@@ -29,7 +29,11 @@ export async function reload(options = {}) {
29
29
 
30
30
  try {
31
31
  spinner.stop();
32
- await ensureCaddyfileMigrated({ caddyfilePath: caddyFilePath, projectsPath });
32
+ await ensureCaddyfileMigrated({
33
+ caddyfilePath: caddyFilePath,
34
+ projectsPath,
35
+ exec: (file, args, opts) => execa(file, args, opts),
36
+ });
33
37
  await warnIfAllowAllOriginsActive({ caddyfilePath: caddyFilePath });
34
38
  spinner.start('Reloading Caddy...');
35
39
 
@@ -350,7 +350,7 @@ export async function start(options = {}) {
350
350
  // 3. Migrate legacy Caddyfile blocks before boot; drop dead live-reload ports
351
351
  await fs.ensureDir(caddyDir);
352
352
  if (await fs.pathExists(caddyFile)) {
353
- await ensureCaddyfileMigrated({ caddyfilePath: caddyFile, projectsPath });
353
+ await ensureCaddyfileMigrated({ caddyfilePath: caddyFile, projectsPath, exec });
354
354
  const stale = await clearStaleDevPorts(projectsPath);
355
355
  for (const domain of stale) {
356
356
  const project = await getProject(domain, projectsPath);