@wave-rf/cloudflare-md-router 0.2.1 → 0.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.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  A tiny Cloudflare Worker that serves the `.md` twin of any static page when the request is from a known LLM crawler or explicitly asks for `text/markdown`. Falls back to the HTML response when the `.md` twin doesn't exist.
4
4
 
5
+ It also ships `cloudflare-md-router dev`, a local dev loop that serves real builds through `wrangler dev`, so the Worker's routing works while you edit (see [Dev loop](#dev-loop-cloudflare-md-router-dev)).
6
+
5
7
  If you're building a docs site that already emits a per-page raw-markdown twin (e.g. `/foo/bar` and `/foo/bar.md`), this lets every page do content negotiation transparently — Claude, ChatGPT, Perplexity, etc. fetch the model-friendly version automatically; humans keep getting the styled HTML page.
6
8
 
7
9
  ## Behavior
@@ -89,6 +91,57 @@ export default createMdRouter({
89
91
  });
90
92
  ```
91
93
 
94
+ ## Dev loop (`cloudflare-md-router dev`)
95
+
96
+ `astro dev` (or any framework dev server) skips everything the Worker adds in production: the `.md` twins, the `Link` header, and any outputs that only exist in a real build. If your Worker serves something the dev server can't, use this instead of it. If the Worker adds nothing you are iterating on, keep using the dev server — it has HMR and an error overlay; this does not.
97
+
98
+ The command runs a **full build on every save** into a staging directory, copies it into your output directory **only if the build succeeded**, and serves that directory through `wrangler dev --live-reload`. A failed build (or the emptied-output window during one) never reaches the browser: you keep the last good build, with a red banner and a terminal bell. Ctrl-C stops the build (its whole process tree) and wrangler, with SIGTERM and then SIGKILL after 5 s, and the command does not exit until they are gone. Each save costs a real build, with errors in the terminal rather than the page.
99
+
100
+ ```sh
101
+ pnpm add -D @wave-rf/cloudflare-md-router wrangler
102
+ pnpm exec cloudflare-md-router dev
103
+ ```
104
+
105
+ ```jsonc
106
+ // package.json
107
+ { "scripts": { "dev:worker": "cloudflare-md-router dev" } }
108
+ ```
109
+
110
+ Needs Node 20+ (recursive `fs.watch`; checked at startup, tested in CI on Node 24 only; POSIX is the supported platform, Windows is best-effort) and a locally-installed `wrangler`. It is never downloaded: the site's own `wrangler` package is resolved the way `require` would (so a workspace-root install works) and its `bin` is run directly with Node, with no package manager or shell in between to swallow Ctrl-C. If the package can't be resolved (Yarn PnP, or not installed) it falls back to your package manager's local exec (`pnpm exec`, `npm exec --no`, `yarn`, `bun x --no-install`). That fallback is best-effort on shutdown: on Debian-based images, where `/bin/sh` is dash, npm and pnpm run it through an `sh` that does not pass signals on, so the CLI also signals wrangler's descendants directly (the smoke test `wrangler run through the <pm> fallback is stopped too` covers this under npm and pnpm). Add the staging directory (`.dev-<outDir>`, so `.dev-dist/` by default) to `.gitignore`.
111
+
112
+ | Option | Default |
113
+ | ------ | ------- |
114
+ | `--build <cmd>` (`MD_ROUTER_DEV_BUILD`) | the site's `build` script, via the package manager its lockfile indicates (pnpm, yarn, bun or npm; the lockfile is searched up the tree, so monorepos work), else the `packageManager` field in `package.json`, else npm. A custom command runs through the shell with `node_modules/.bin` on `PATH`, so `--build "astro build"` works. |
115
+ | `--out-dir <dir>` | `assets.directory` from `wrangler.jsonc` / `wrangler.json` / `wrangler.toml` (JSONC comments and trailing commas are fine), else `dist`. A relative path resolves against the wrangler config's directory. The staging directory is `.dev-<name>` next to it. Both are emptied and refilled on every build, so the command refuses (and says why) an output directory that is: the site root, or any directory outside it (a sibling such as `../shared/dist` too); `src/`, `public/`, `node_modules/` or `.git/`, inside one of them, or enclosing one; or the wrangler config's directory, or one enclosing it. Neither the output nor the staging directory may hold a `package.json` or any git-tracked file. The Worker's directory (the directory of wrangler `main`) depends on where it is: at or above the root or the config's directory, it falls under the rules above (no equal or enclosing output dir); inside `assets.directory`, where the config itself declares the Worker to be build output (Astro's `dist/_worker.js`), only an output dir equal to it or inside it is refused; anywhere else it is treated like `src/`. Directories are compared by identity (device and inode), not by spelling, so `SRC` on a case-insensitive disk is `src` even on Linux over a macOS bind mount, and git-tracked files are matched case-insensitively. |
116
+ | `--out-dir-flag <flag>` | `--outDir`: appended to the build as `<flag> <staging>` so it writes to staging, not the served directory. Pass `""` to disable. Put `{outDir}` anywhere in `--build` to place the path yourself (and skip the flag). The staging path (relative to the site root) is also exported as `MD_ROUTER_DEV_OUT_DIR`. |
117
+ | `--watch <path>` | Added to the defaults: `src/`, `public/`, `astro.config.*`, `vite.config.*`, `tsconfig.json`, `package.json`, `.env*`. Directories recurse; other entries are root-level file names (a trailing `*` matches a prefix). A nested file path (`config/site.json`) can't be watched (watch its directory) and a directory that doesn't exist is skipped; either one, when you passed it, is reported at startup. Repeatable or comma-separated. `--no-default-watch` drops the defaults. The Worker directory is deliberately not watched — wrangler reloads the Worker itself. Changes never trigger a build when they are under the output or staging directory, `node_modules/`, `.git/`, `.wrangler/` or a common framework cache (`.astro/`, `.svelte-kit/`, `.next/`, `.nuxt/`, `.output/`, `.cache/`, `.turbo/`, `.vercel/`, `.parcel-cache/`). In a git work tree, a path below a watched directory that git ignores is dropped too — except under a watched directory that is itself gitignored. Root-level files matching an exact name (`tsconfig.json`, `package.json`), `.env*`, or a name you pass are never git-filtered; the prefix-glob defaults (`astro.config.*`, `vite.config.*`) are, and Vite's temporary `*.timestamp-<ms>[-<hex>].[cm]?js` config files (Vite 3-5) are always skipped, anywhere under a watched path. That makes `--watch .` usable, as long as everything your build writes outside the output directory is in that list or gitignored. Otherwise each build triggers the next. |
118
+ | `--port <n>` (`PORT`) | `4321`. If it is taken, the next free port (up to 19 higher, both IPv4 and IPv6 loopback checked) is used and printed — wrangler itself would just die on a busy explicit port. |
119
+ | `--config <file>` | `wrangler.jsonc`, `wrangler.json`, then `wrangler.toml` in the root. A `--config` that doesn't exist is an error. |
120
+ | `--root <dir>` | the current directory. |
121
+ | `--strict` (`MD_ROUTER_DEV_STRICT=1`) | off. See below. |
122
+ | `-- <args>` | everything after `--` is passed to `wrangler dev`. |
123
+ | `--help`, `-h` | prints the options and exits. |
124
+
125
+ Flags win over env. A failed build, and a build that exits 0 but writes nothing, are both handled: the previous good build stays up. A build that ignores the staging directory and writes straight into the output directory (say `astro build && node postbuild.mjs` without `{outDir}`) is called out as such: what is served is whatever it left there, with no last-good-build protection, until you point it at `{outDir}` or set `--out-dir-flag`. On a cold start with no output directory yet, the first build must succeed or the command exits 1. When wrangler exits, so does the command, with wrangler's exit code (1 if wrangler was killed by a signal); a Ctrl-C you send exits 0.
126
+
127
+ ### Relaxing checks in watch builds
128
+
129
+ Every build in the loop runs with `MD_ROUTER_DEV=1` (unless `--strict`). Use it in your site config to turn off checks that are right for CI but wrong mid-edit — typically a link validator, since a page you are still writing links to pages that don't exist yet. The rendered output should be identical; only the gate differs:
130
+
131
+ ```js
132
+ // astro.config.mjs
133
+ const watchBuild = Boolean(process.env.MD_ROUTER_DEV);
134
+
135
+ export default defineConfig({
136
+ integrations: [
137
+ // Fails the build on a broken link: keep it for CI and `astro build`, skip it in the dev loop.
138
+ ...(watchBuild ? [] : [starlightLinksValidator({ errorOnRelativeLinks: true })]),
139
+ ],
140
+ });
141
+ ```
142
+
143
+ Run `cloudflare-md-router dev --strict` (or `MD_ROUTER_DEV_STRICT=1`) to leave the variable unset and get the CI behaviour in the loop.
144
+
92
145
  ## Why content-negotiate?
93
146
 
94
147
  Most LLMs do better with raw markdown than with rendered HTML — less DOM noise, no Starlight nav chrome, no script tags. Serving the same content at one URL with two representations means:
package/bin/cli.mjs ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ /* `cloudflare-md-router <command>` — currently one command: `dev`. */
3
+ import { dev } from "./dev.mjs";
4
+ import { HELP, parseArgs, resolveOptions } from "./lib.mjs";
5
+
6
+ if (Number(process.versions.node.split(".")[0]) < 20) {
7
+ console.error(`cloudflare-md-router dev needs Node 20+ (running ${process.versions.node})`);
8
+ process.exit(1);
9
+ }
10
+
11
+ const [command, ...rest] = process.argv.slice(2);
12
+
13
+ if (command !== "dev") {
14
+ console.log(
15
+ command && command !== "--help" && command !== "-h" ? `unknown command ${command}\n` : ""
16
+ );
17
+ console.log(HELP);
18
+ process.exit(command === undefined || command === "--help" || command === "-h" ? 0 : 1);
19
+ }
20
+
21
+ let opts;
22
+ try {
23
+ const flags = parseArgs(rest);
24
+ if (flags.help) {
25
+ console.log(HELP);
26
+ process.exit(0);
27
+ }
28
+ opts = resolveOptions(flags, process.env, process.cwd());
29
+ } catch (err) {
30
+ console.error(`\x1b[1;31mcloudflare-md-router dev: ${err.message}\x1b[0m\x07`);
31
+ process.exit(1);
32
+ }
33
+
34
+ process.exitCode = await dev(opts);
package/bin/dev.mjs ADDED
@@ -0,0 +1,575 @@
1
+ /* `cloudflare-md-router dev` — a production-faithful dev loop for a site that runs a Cloudflare
2
+ * Worker in front of static assets.
3
+ *
4
+ * Why not the framework's dev server (`astro dev`, `vite`, …)? It skips everything the Worker adds
5
+ * in production — content negotiation for `.md` twins, any outputs only a real build produces. So
6
+ * this runs a full build on every save into a staging directory and swaps it into the served output
7
+ * directory only when the build succeeded; `wrangler dev --live-reload` serves that directory.
8
+ * A failed build (or the emptied-outDir window during one) never takes down the served site: you
9
+ * keep the last good build, with a red banner and a terminal bell.
10
+ *
11
+ * Node built-ins only; never imported by the Worker (`src/` does not reference `bin/`). */
12
+
13
+ import { spawn, spawnSync } from "node:child_process";
14
+ import { existsSync, readdirSync, statSync, watch } from "node:fs";
15
+ import { cp, readdir, rm, stat } from "node:fs/promises";
16
+ import { delimiter, dirname, join, relative, sep } from "node:path";
17
+ import { setTimeout as sleep } from "node:timers/promises";
18
+ import {
19
+ buildInvocation,
20
+ canonicalPath,
21
+ classifyWatch,
22
+ descendantsOf,
23
+ execLocalCommand,
24
+ findFreePort,
25
+ IGNORED,
26
+ isAlive,
27
+ lastPortFor,
28
+ matchesName,
29
+ PORT_TRIES,
30
+ processTable,
31
+ resolveWranglerBin,
32
+ } from "./lib.mjs";
33
+
34
+ const DEBOUNCE_MS = 300;
35
+ /** How long a child gets to stop after SIGTERM before SIGKILL, and then to be reaped. */
36
+ const GRACE_MS = 5000;
37
+ const REAP_MS = 2000;
38
+ const POSIX = process.platform !== "win32";
39
+ /** Never a build input, and written to by the build, wrangler, git or a framework's cache (Astro
40
+ * writes `.astro/types.d.ts` on every build): watching them loops. Always skipped, git or not. In a
41
+ * git work tree, gitignored paths are skipped too, except the inputs the user named: see `flush`. */
42
+ const NOISE_DIRS =
43
+ /(^|[\\/])(node_modules|\.git|\.wrangler|\.astro|\.svelte-kit|\.next|\.nuxt|\.output|\.cache|\.turbo|\.vercel|\.parcel-cache)([\\/]|$)/;
44
+
45
+ /** node_modules/.bin of the root and every ancestor, so a custom `--build "astro build"` resolves. */
46
+ function binPath(root) {
47
+ const dirs = [];
48
+ for (let d = root; ; d = dirname(d)) {
49
+ dirs.push(join(d, "node_modules", ".bin"));
50
+ if (dirname(d) === d) break;
51
+ }
52
+ return [...dirs, process.env.PATH ?? ""].join(delimiter);
53
+ }
54
+
55
+ /** Sync staging → outDir in place (same directory inode, so wrangler's asset watcher sees an
56
+ * incremental update, not a directory swap): prune entries the new build dropped, then copy over.
57
+ * Prune runs FIRST so a path that changed type between builds (file ↔ dir) is removed before cp
58
+ * would trip over it. */
59
+ export async function syncDirs(staging, dist) {
60
+ await prune(staging, dist);
61
+ await cp(staging, dist, { recursive: true, force: true });
62
+ }
63
+
64
+ async function prune(stagingDir, distDir) {
65
+ let entries;
66
+ try {
67
+ entries = await readdir(distDir, { withFileTypes: true });
68
+ } catch {
69
+ return; // first build: the output dir doesn't exist yet — cp creates it
70
+ }
71
+ for (const entry of entries) {
72
+ const s = join(stagingDir, entry.name);
73
+ const d = join(distDir, entry.name);
74
+ const sStat = await stat(s).catch(() => null);
75
+ if (!sStat || sStat.isDirectory() !== entry.isDirectory()) {
76
+ await rm(d, { recursive: true, force: true });
77
+ } else if (entry.isDirectory()) {
78
+ await prune(s, d);
79
+ }
80
+ }
81
+ }
82
+
83
+ const hasOutput = (dir) => existsSync(dir) && readdirSync(dir).length > 0;
84
+
85
+ /** Paths (relative to `root`) minus the ones git ignores — a framework cache such as `.astro/` is
86
+ * written by every build, so under `--watch .` it would trigger the next one. A path that no
87
+ * longer exists, or is a directory, is also asked about as `path/`, because a dir-only pattern
88
+ * (`tmpbuild/`) doesn't match a path that no longer exists (a temp dir the build created and
89
+ * removed); an existing regular file is not, so `lib/` never hides a file named `lib`. Outside a
90
+ * git work tree, or if git fails or takes over 2 s, nothing is dropped. */
91
+ export function gitIgnoredFilter(root) {
92
+ const probe = spawnSync("git", ["-C", root, "rev-parse", "--is-inside-work-tree"], {
93
+ encoding: "utf8",
94
+ stdio: ["ignore", "pipe", "ignore"],
95
+ timeout: 2000,
96
+ });
97
+ if (probe.status !== 0 || probe.stdout.trim() !== "true") return (files) => files;
98
+ return (files) => {
99
+ if (files.length === 0) return files;
100
+ // `f/` only where f could be a directory: for an existing regular file it would match a
101
+ // dir-only pattern (`lib/`) that git itself does not apply to that file.
102
+ const isFile = (f) => {
103
+ try {
104
+ return !statSync(join(root, f)).isDirectory();
105
+ } catch {
106
+ return false;
107
+ }
108
+ };
109
+ const queries = files.flatMap((f) => (isFile(f) ? [f] : [f, `${f}/`]));
110
+ const r = spawnSync("git", ["-C", root, "check-ignore", "--stdin", "-z"], {
111
+ input: `${queries.join("\0")}\0`,
112
+ encoding: "utf8",
113
+ stdio: ["pipe", "pipe", "ignore"],
114
+ timeout: 2000,
115
+ });
116
+ if (r.status !== 0 && r.status !== 1) return files; // 1 = none ignored; else error or timeout
117
+ const ignored = new Set(r.stdout.split("\0").filter(Boolean));
118
+ return files.filter((f) => !ignored.has(f) && !ignored.has(`${f}/`));
119
+ };
120
+ }
121
+
122
+ /** Every child the loop starts, tracked until it is gone; `stopAll` never returns before that.
123
+ *
124
+ * - A build runs in its own process group on POSIX (`detached`; it never reads the terminal), so
125
+ * one kill(-pgid) reaches everything a package manager or shell started under it — dash, Debian's
126
+ * sh, does not exec its last command, so signalling only the shell would orphan the real build.
127
+ * Its record is dropped as soon as its group is seen empty, so a pgid the OS later reuses is never
128
+ * signalled. A build that exits but leaves processes in its group has left strays: they get
129
+ * SIGTERM at once and SIGKILL after the grace period.
130
+ * - wrangler must NOT get its own group: it reads hotkeys from the terminal, and a background
131
+ * process group that reads the TTY is stopped by SIGTTIN. So it is run directly with node (no
132
+ * package manager or shell between us), and at shutdown its descendants are snapshotted and
133
+ * signalled too, in case they outlive it (the package-manager fallback, or a crashed wrapper). */
134
+ export class ChildSet {
135
+ constructor({ log = () => {}, grace = GRACE_MS, reap = REAP_MS } = {}) {
136
+ this.recs = new Set();
137
+ this.log = log;
138
+ this.grace = grace;
139
+ this.reap = reap;
140
+ }
141
+
142
+ get size() {
143
+ return this.recs.size;
144
+ }
145
+
146
+ add(proc, { group = false } = {}) {
147
+ const rec = { proc, group: group && POSIX, exited: !proc.pid, tree: [] };
148
+ if (rec.exited) return rec; // never started (spawn error): nothing to track
149
+ this.recs.add(rec);
150
+ proc.on("exit", () => {
151
+ rec.exited = true;
152
+ rec.exitedAt = Date.now();
153
+ this.settle(rec);
154
+ });
155
+ return rec;
156
+ }
157
+
158
+ /** Drop an exited child's record once nothing of it is left; deal with a build's strays. */
159
+ settle(rec) {
160
+ if (!rec.exited || !this.recs.has(rec)) return;
161
+ if (!rec.group || !isAlive(-rec.proc.pid)) {
162
+ this.recs.delete(rec);
163
+ return;
164
+ }
165
+ const late = Date.now() - rec.exitedAt >= this.grace;
166
+ if (!rec.straysTold || late) {
167
+ if (!rec.straysTold) this.log(`build exited but left processes in its group — stopping them`);
168
+ rec.straysTold = true;
169
+ try {
170
+ process.kill(-rec.proc.pid, late ? "SIGKILL" : "SIGTERM");
171
+ } catch {}
172
+ }
173
+ setTimeout(() => this.settle(rec), 100).unref();
174
+ }
175
+
176
+ /** Re-check every exited child (before each build). */
177
+ sweep() {
178
+ for (const rec of this.recs) this.settle(rec);
179
+ }
180
+
181
+ topAlive(rec) {
182
+ return rec.group ? isAlive(-rec.proc.pid) : !rec.exited;
183
+ }
184
+
185
+ alive(rec) {
186
+ return this.topAlive(rec) || rec.tree.length > 0;
187
+ }
188
+
189
+ /** Forget snapshotted descendants that have died: a pid seen dead is never signalled again, so a
190
+ * reused pid can't be hit. */
191
+ prune(rec) {
192
+ rec.tree = rec.tree.filter(isAlive);
193
+ }
194
+
195
+ signal(rec, sig, pids = []) {
196
+ try {
197
+ if (rec.group) process.kill(-rec.proc.pid, sig);
198
+ else if (!rec.exited) rec.proc.kill(sig);
199
+ } catch {}
200
+ for (const pid of pids) {
201
+ try {
202
+ process.kill(pid, sig);
203
+ } catch {}
204
+ }
205
+ }
206
+
207
+ /** SIGTERM everything, SIGKILL whatever is left after the grace period, and resolve only once it
208
+ * is all gone (or, if the OS will not reap it, after saying so). Returns pids it could not
209
+ * confirm stopped. */
210
+ async stopAll() {
211
+ const table = processTable();
212
+ const recs = [...this.recs].filter((r) => this.topAlive(r));
213
+ for (const rec of recs) {
214
+ if (!rec.group) rec.tree = descendantsOf(table, rec.proc.pid);
215
+ this.signal(rec, "SIGTERM");
216
+ }
217
+ const deadline = Date.now() + this.grace;
218
+ const busy = () =>
219
+ recs.filter((r) => {
220
+ this.prune(r);
221
+ return this.alive(r);
222
+ });
223
+ while (busy().length > 0 && Date.now() < deadline) {
224
+ for (const rec of recs) {
225
+ // The direct child exited but left descendants behind (a wrapper that didn't forward the
226
+ // signal): they are orphans now, so tell them directly.
227
+ if (rec.exited && !rec.orphansTold && rec.tree.length > 0) {
228
+ rec.orphansTold = true;
229
+ this.signal(rec, "SIGTERM", rec.tree);
230
+ }
231
+ }
232
+ await sleep(50);
233
+ }
234
+ const stubborn = busy();
235
+ if (stubborn.length === 0) return [];
236
+ this.log(`still running ${this.grace / 1000}s after SIGTERM — sending SIGKILL`);
237
+ const now = processTable();
238
+ for (const rec of stubborn) {
239
+ if (!rec.group && !rec.exited) {
240
+ rec.tree = [...new Set([...rec.tree, ...descendantsOf(now, rec.proc.pid)])];
241
+ }
242
+ this.signal(rec, "SIGKILL", rec.tree);
243
+ }
244
+ const reapBy = Date.now() + this.reap;
245
+ while (busy().length > 0 && Date.now() < reapBy) await sleep(50);
246
+ return busy().flatMap((r) => [
247
+ ...(this.topAlive(r) ? [r.group ? `group ${r.proc.pid}` : r.proc.pid] : []),
248
+ ...r.tree,
249
+ ]);
250
+ }
251
+ }
252
+
253
+ /** Cheap fingerprint of a directory's top level (its mtime and each entry's), to tell whether a
254
+ * build wrote into it. null if it doesn't exist. */
255
+ function fingerprint(dir) {
256
+ try {
257
+ const entries = readdirSync(dir).sort();
258
+ return [statSync(dir).mtimeMs, ...entries.map((e) => `${e}:${statSync(join(dir, e)).mtimeMs}`)];
259
+ } catch {
260
+ return null;
261
+ }
262
+ }
263
+ const sameFingerprint = (a, b) => JSON.stringify(a) === JSON.stringify(b);
264
+
265
+ /** Run the loop until wrangler exits or a signal arrives. Resolves to the process exit code. */
266
+ export async function dev(opts) {
267
+ const tag = "\x1b[36m[md-router-dev]\x1b[0m";
268
+ const log = (msg) => console.log(`${tag} ${msg}`);
269
+ // Loud-failure banner: bold red + terminal bell (most terminals flash/bounce).
270
+ const fail = (msg) => console.log(`${tag} \x1b[1;31m${msg}\x1b[0m\x07`);
271
+ const warn = (msg) => console.log(`${tag} \x1b[33m${msg}\x1b[0m`);
272
+
273
+ const stagingRel = relative(opts.root, opts.staging) || opts.staging;
274
+ const outRel = relative(opts.root, opts.outDir) || opts.outDir;
275
+ const inv = buildInvocation(opts);
276
+ const buildEnv = {
277
+ ...process.env,
278
+ PATH: binPath(opts.root),
279
+ MD_ROUTER_DEV_OUT_DIR: stagingRel,
280
+ ...(opts.strict ? {} : { MD_ROUTER_DEV: "1" }),
281
+ };
282
+
283
+ let shuttingDown = false;
284
+ let wrangler;
285
+ let timer;
286
+ const watchers = [];
287
+ let exitResolve;
288
+ const exited = new Promise((r) => {
289
+ exitResolve = r;
290
+ });
291
+ let exitCode = 0;
292
+ const children = new ChildSet({ log });
293
+
294
+ function runBuild() {
295
+ return new Promise((done) => {
296
+ const stdio = ["ignore", "inherit", "inherit"];
297
+ const base = { cwd: opts.root, stdio, env: buildEnv, detached: POSIX };
298
+ const child =
299
+ inv.shell !== undefined
300
+ ? spawn(inv.shell, { ...base, shell: true })
301
+ : spawn(inv.cmd, inv.args, { ...base, shell: process.platform === "win32" });
302
+ children.add(child, { group: true });
303
+ child.on("error", () => done(127)); // e.g. binary not found
304
+ child.on("close", (code) => done(code ?? 1));
305
+ });
306
+ }
307
+
308
+ let building = false;
309
+ let dirty = false;
310
+ let pendingReason = "startup";
311
+ let buildCount = 0;
312
+
313
+ async function rebuild() {
314
+ if (shuttingDown) return; // a debounce callback can fire after the signal
315
+ if (building) {
316
+ dirty = true;
317
+ return;
318
+ }
319
+ building = true;
320
+ do {
321
+ dirty = false;
322
+ const n = ++buildCount;
323
+ const t0 = Date.now();
324
+ log(`build #${n} (${pendingReason})…`);
325
+ // Start from an empty staging dir so a stale file from a failed build can never be synced.
326
+ await rm(opts.staging, { recursive: true, force: true });
327
+ if (shuttingDown) break;
328
+ children.sweep();
329
+ const outBefore = fingerprint(opts.outDir);
330
+ const code = await runBuild();
331
+ if (shuttingDown) break;
332
+ const pointAtStaging =
333
+ `make the build write to the staging dir: --out-dir-flag <the flag your build takes> ` +
334
+ `(now ${opts.outDirFlag ? JSON.stringify(opts.outDirFlag) : "disabled"}), or {outDir} in --build`;
335
+ if (
336
+ code === 0 &&
337
+ !hasOutput(opts.staging) &&
338
+ !sameFingerprint(fingerprint(opts.outDir), outBefore)
339
+ ) {
340
+ fail(
341
+ `build #${n} exited 0 but wrote to ${outRel}/ directly, not ${stagingRel}/ — what is ` +
342
+ `served is whatever it left there, with no last-good-build protection. To fix, ${pointAtStaging}`
343
+ );
344
+ } else if (code === 0 && !hasOutput(opts.staging)) {
345
+ fail(
346
+ `build #${n} exited 0 but wrote nothing to ${stagingRel}/ — still serving the previous ` +
347
+ `good build. To fix, ${pointAtStaging}`
348
+ );
349
+ } else if (code === 0) {
350
+ try {
351
+ await syncDirs(opts.staging, opts.outDir);
352
+ log(
353
+ `build #${n} live in ${((Date.now() - t0) / 1000).toFixed(1)}s — browser reloads itself`
354
+ );
355
+ } catch (err) {
356
+ // A failed sync degrades like a failed build — never crash the loop (that would orphan
357
+ // wrangler on the port).
358
+ fail(
359
+ `build #${n} sync FAILED (${err?.code ?? err}) — ${outRel}/ may be partial; next green build re-syncs`
360
+ );
361
+ }
362
+ } else {
363
+ fail(
364
+ `build #${n} FAILED (exit ${code}) — error above; still serving the previous good build`
365
+ );
366
+ }
367
+ } while (dirty && !shuttingDown);
368
+ building = false;
369
+ }
370
+
371
+ // Changes are batched per debounce window. A path that git ignores (a framework cache the build
372
+ // itself writes) is dropped before it may trigger a build, except: root-level matches of an exact
373
+ // name, `.env*` or a name the user passed (`.env` is gitignored almost everywhere, yet a default
374
+ // trigger), and anything under a watched directory that is itself gitignored (`--watch content`
375
+ // where content/ is ignored) — the user asked for those explicitly.
376
+ const pending = new Map(); // path → may be git-filtered
377
+ const notIgnored = gitIgnoredFilter(opts.root);
378
+ function onChange(file, filterable) {
379
+ pending.set(file, (pending.get(file) ?? true) && filterable);
380
+ clearTimeout(timer);
381
+ timer = setTimeout(flush, DEBOUNCE_MS);
382
+ }
383
+ function flush() {
384
+ if (shuttingDown) return;
385
+ const always = [...pending].filter(([, f]) => !f).map(([p]) => p);
386
+ const files = [...always, ...notIgnored([...pending].filter(([, f]) => f).map(([p]) => p))];
387
+ pending.clear();
388
+ if (files.length === 0) return;
389
+ pendingReason = files.length > 1 ? `${files[0]} +${files.length - 1} more` : files[0];
390
+ void rebuild();
391
+ }
392
+
393
+ function startWatchers() {
394
+ const { dirs: rawDirs, names, dropped } = classifyWatch(opts.root, opts.watch);
395
+ for (const { entry, why } of dropped) {
396
+ if (opts.userWatch?.includes(entry)) warn(`not watching --watch ${entry}: ${why}`);
397
+ }
398
+ // Canonical, and without dirs already covered by another (`--watch .` contains src/).
399
+ const canon = [...new Set(rawDirs.map((d) => canonicalPath(d)))];
400
+ const dirs = canon.filter(
401
+ (d) => !canon.some((o) => o !== d && d.startsWith(o === sep ? o : o + sep))
402
+ );
403
+ // The build's own output (and staging) is never an input: a watch that covers it — `--watch .`
404
+ // — would otherwise rebuild forever. Both are canonical (resolveOptions), as are `dirs`, so the
405
+ // prefix check matches the spelling the filesystem reports.
406
+ const ignoredRoots = [opts.outDir, opts.staging];
407
+ const under = (abs, roots) => roots.some((r) => abs === r || abs.startsWith(r + sep));
408
+ // Watched dirs (nested ones included) that git itself ignores: their events are never filtered.
409
+ const exempt = canon.filter(
410
+ (d) => d !== opts.root && notIgnored([relative(opts.root, d)]).length === 0
411
+ );
412
+ for (const dir of dirs) {
413
+ if (under(dir, ignoredRoots)) continue;
414
+ watchers.push(
415
+ watch(dir, { recursive: true }, (_event, file) => {
416
+ if (!file || IGNORED.test(file) || NOISE_DIRS.test(file)) return;
417
+ const abs = join(dir, file);
418
+ if (under(abs, ignoredRoots)) return;
419
+ onChange(relative(opts.root, abs), !under(abs, exempt));
420
+ })
421
+ );
422
+ }
423
+ // Root-level names that skip the git filter: exact names, `.env*` (gitignored almost everywhere,
424
+ // yet an input), and anything the user passed. A prefix-glob default like `vite.config.*` still
425
+ // goes through it, since tools drop gitignored temp files next to their config.
426
+ const explicitName = (n) => !n.endsWith("*") || n === ".env*" || opts.userWatch?.includes(n);
427
+ // Root-level files: a non-recursive watch on the directory survives editors that replace files
428
+ // on save (watching a file itself would not).
429
+ if (names.length > 0) {
430
+ watchers.push(
431
+ watch(opts.root, (_event, file) => {
432
+ if (file && !IGNORED.test(file) && matchesName(names, file)) {
433
+ onChange(file, !names.some((n) => matchesName([n], file) && explicitName(n)));
434
+ }
435
+ })
436
+ );
437
+ }
438
+ return { dirs, names };
439
+ }
440
+
441
+ /** Idempotent: the first caller's exit code wins (a user's Ctrl-C stays 0 even though wrangler
442
+ * then dies of the signal). Resolves `exited` only once every child is gone. */
443
+ function shutdown(code) {
444
+ if (shuttingDown) return;
445
+ shuttingDown = true;
446
+ exitCode = code;
447
+ clearTimeout(timer);
448
+ for (const w of watchers) w.close(); // open watchers would keep the event loop alive
449
+ children
450
+ .stopAll()
451
+ .then((left) => {
452
+ if (left.length > 0)
453
+ fail(`could not confirm these stopped: ${left.join(", ")} — check with ps`);
454
+ })
455
+ .catch((err) => fail(`stopping children failed: ${err?.stack ?? err}`))
456
+ .finally(() => exitResolve(exitCode));
457
+ }
458
+
459
+ const onSignal = () => shutdown(0);
460
+ process.on("SIGINT", onSignal);
461
+ process.on("SIGTERM", onSignal);
462
+ process.on("SIGHUP", onSignal); // closed terminal / dropped ssh
463
+ // Backstop for anything the loop doesn't catch (incl. fs.watch 'error' events): tear wrangler
464
+ // down with us rather than orphaning it on the port.
465
+ const onFatal = (event) => (err) => {
466
+ fail(`fatal (${event}): ${err?.stack ?? err}`);
467
+ shutdown(1);
468
+ };
469
+ const fatalHandlers = ["uncaughtException", "unhandledRejection"].map((e) => [e, onFatal(e)]);
470
+ for (const [e, h] of fatalHandlers) process.on(e, h);
471
+ const cleanup = () => {
472
+ process.off("SIGINT", onSignal);
473
+ process.off("SIGTERM", onSignal);
474
+ process.off("SIGHUP", onSignal);
475
+ for (const [e, h] of fatalHandlers) process.off(e, h);
476
+ };
477
+
478
+ const run = async () => {
479
+ log(
480
+ `build: ${inv.shell ?? `${inv.cmd} ${inv.args.join(" ")}`} → ${stagingRel}/ → ${outRel}/`
481
+ );
482
+ if (hasOutput(opts.outDir)) {
483
+ log(`serving the existing ${outRel}/ while a fresh build runs`);
484
+ void rebuild();
485
+ } else {
486
+ log(`no ${outRel}/ yet — first build must finish before serving starts`);
487
+ await rebuild();
488
+ if (!hasOutput(opts.outDir) && !shuttingDown) {
489
+ fail("first build failed and there is no previous output to serve — exiting");
490
+ return 1;
491
+ }
492
+ }
493
+ if (shuttingDown) return exitCode;
494
+
495
+ // Resolved here rather than at startup so the gap between "it was free" and "wrangler has it"
496
+ // stays small — a cold-start build is minutes of window for someone else to take the port.
497
+ const port = await findFreePort(opts.port, PORT_TRIES);
498
+ if (port === null) {
499
+ fail(
500
+ `no free port in ${opts.port}–${lastPortFor(opts.port, PORT_TRIES)}. ` +
501
+ `Stop one of the servers holding them, or pass --port / set PORT to a clear range.`
502
+ );
503
+ return 1;
504
+ }
505
+ if (shuttingDown) return exitCode;
506
+ if (port !== opts.port) {
507
+ log(`port ${opts.port} is busy (often a dev server from another checkout) — using ${port}`);
508
+ }
509
+
510
+ // wrangler treats an explicit --port as strict (dies rather than moving), which is why the
511
+ // walk-up above is ours.
512
+ const wranglerArgs = [
513
+ "dev",
514
+ "--live-reload",
515
+ "--port",
516
+ String(port),
517
+ ...(opts.wranglerConfig ? ["--config", opts.wranglerConfig] : []),
518
+ ...opts.wranglerArgs,
519
+ ];
520
+ // The site's own wrangler, run by node itself: nothing in between to swallow our signals.
521
+ const wranglerJs = resolveWranglerBin(opts.root);
522
+ let cmd = process.execPath;
523
+ let args = [wranglerJs, ...wranglerArgs];
524
+ if (!wranglerJs) {
525
+ // Not resolvable from the site (not installed, or Yarn PnP): let the package manager find
526
+ // its local one — still never downloads. Its signal handling is the package manager's.
527
+ [cmd, args] = execLocalCommand(opts.pm, "wrangler", wranglerArgs);
528
+ log(
529
+ `no wrangler package resolvable from ${opts.root} — running \`${cmd} ${args.slice(0, 2).join(" ")}…\` ` +
530
+ `instead. If wrangler is not installed: ${opts.pm} add -D wrangler`
531
+ );
532
+ }
533
+ if (shuttingDown) return exitCode;
534
+ wrangler = spawn(cmd, args, {
535
+ cwd: opts.root,
536
+ stdio: "inherit",
537
+ shell: !wranglerJs && process.platform === "win32",
538
+ });
539
+ children.add(wrangler);
540
+ wrangler.on("error", (err) => {
541
+ fail(
542
+ `could not start wrangler via ${cmd}: ${err.message} — install it in the site: ${opts.pm} add -D wrangler`
543
+ );
544
+ shutdown(1);
545
+ });
546
+ // wrangler owns the terminal UX; when it exits (its `x` hotkey, a crash), take the loop down.
547
+ // Death by signal is a failure, not a clean exit.
548
+ wrangler.on("exit", (code, sig) => shutdown(code ?? (sig ? 1 : 0)));
549
+
550
+ const { dirs, names } = startWatchers();
551
+ const shown = [...dirs.map((d) => `${relative(opts.root, d) || "."}/`), ...names];
552
+ log(`watching ${shown.join(", ") || "nothing"} — wrangler serves http://localhost:${port}`);
553
+ log(
554
+ opts.strict
555
+ ? "strict mode: MD_ROUTER_DEV is NOT set for builds"
556
+ : "MD_ROUTER_DEV=1 is set for builds (use --strict to unset it)"
557
+ );
558
+ return undefined;
559
+ };
560
+
561
+ try {
562
+ let early;
563
+ try {
564
+ early = await run();
565
+ } catch (err) {
566
+ // e.g. fs.watch throwing ENOSPC (inotify limit) after wrangler started: never leave it running.
567
+ fail(`fatal: ${err?.message ?? err} — stopping`);
568
+ early = 1;
569
+ }
570
+ if (early !== undefined) shutdown(early);
571
+ return await exited;
572
+ } finally {
573
+ cleanup();
574
+ }
575
+ }