@luckystack/devkit 0.2.6 → 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.
@@ -32,16 +32,18 @@ var resolveNodeEnv = () => {
32
32
  }
33
33
  return fromFiles ?? "development";
34
34
  };
35
- var CORE_WATCH_GLOBS = [
35
+ var CORE_WATCH_FILES = [
36
36
  "config.ts",
37
37
  ...getEnvFiles(),
38
38
  "server/server.ts",
39
- "server/bootstrap/**/*.ts",
40
- "server/auth/**/*.ts",
41
39
  "server/functions/db.ts",
42
40
  "server/functions/redis.ts",
43
41
  "server/functions/sentry.ts"
44
42
  ];
43
+ var CORE_WATCH_DIRS = ["server/bootstrap", "server/auth"].filter(
44
+ (dir) => existsSync(path.resolve(process.cwd(), dir))
45
+ );
46
+ var CORE_WATCH_TARGETS = [...CORE_WATCH_FILES, ...CORE_WATCH_DIRS];
45
47
  var tsxCliPath = path.resolve(process.cwd(), "node_modules", "tsx", "dist", "cli.mjs");
46
48
  var tsconfigServerArgs = existsSync(path.resolve(process.cwd(), "tsconfig.server.json")) ? ["--tsconfig", "tsconfig.server.json"] : [];
47
49
  var childArgs = [tsxCliPath, ...tsconfigServerArgs, "server/server.ts"];
@@ -169,7 +171,7 @@ if (resolveNodeEnv() === "production") {
169
171
  });
170
172
  startChild();
171
173
  } else {
172
- const watcher = watch(CORE_WATCH_GLOBS, {
174
+ const watcher = watch(CORE_WATCH_TARGETS, {
173
175
  ignoreInitial: true,
174
176
  awaitWriteFinish: {
175
177
  stabilityThreshold: 120,
@@ -177,6 +179,10 @@ if (resolveNodeEnv() === "production") {
177
179
  }
178
180
  });
179
181
  watcher.on("all", (event, changedPath) => {
182
+ if (event === "addDir" || event === "unlinkDir") return;
183
+ const normalized = changedPath.replaceAll("\\", "/");
184
+ const relevant = normalized.endsWith(".ts") || CORE_WATCH_FILES.some((file) => normalized.endsWith(file));
185
+ if (!relevant) return;
180
186
  scheduleRestart({ event, changedPath });
181
187
  });
182
188
  const handleSignal = (signalName) => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/supervisor.ts"],"sourcesContent":["#!/usr/bin/env node\n//? CRITICAL INVARIANT: this process must NEVER merge `.env` files into its own\n//? `process.env`. The child is spawned with `{ ...process.env }`, and the\n//? child's own `loadEnvFiles()` loads `.env` with `override: false` — any\n//? `.env`-derived value that leaks into the supervisor's env would therefore\n//? WIN over freshly edited file values on every restart (stale-env bug).\n//? That is why this file imports NOTHING from `@luckystack/core` (core runs\n//? `bootstrapEnv()` as an import side-effect) and reads env files via\n//? `dotenv.parse` (pure — no `process.env` mutation). The previous design\n//? (an `ambientEnvSnapshot` module imported first) broke as soon as tsup\n//? inlined the snapshot into the entry body: ESM imports are hoisted, so\n//? core's side-effect ran BEFORE the snapshot line.\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { performance } from 'node:perf_hooks';\nimport path from 'node:path';\nimport { watch } from 'chokidar';\nimport { parse as parseDotenv } from 'dotenv';\n\nconst RESTART_DEBOUNCE_MS = 150;\nconst CRASH_RESTART_DELAY_MS = 300;\n//? Rapid-crash-loop breaker. A child that exits non-zero within\n//? FAST_CRASH_THRESHOLD_MS of booting counts as a \"fast crash\" (it died during\n//? startup rather than after serving). MAX_CONSECUTIVE_FAST_CRASHES of those in\n//? a row means the startup error is not transient (a port already in use, a\n//? syntax error, a missing env) — restarting forever just spams the console, so\n//? we give up and print an actionable message. A child that survives longer than\n//? the threshold resets the counter, so a normal restart loop is unaffected.\nconst FAST_CRASH_THRESHOLD_MS = 3000;\nconst MAX_CONSECUTIVE_FAST_CRASHES = 4;\n//? Force-exit grace: how long we wait for the child to honour SIGTERM before\n//? the supervisor hard-exits. Windows does not deliver SIGKILL so the only\n//? lever is this timer. 1 500 ms is intentionally short (dev restarts should\n//? be fast); increase via LUCKYSTACK_SUPERVISOR_GRACE_MS for slow servers.\nconst SHUTDOWN_GRACE_MS = Number(process.env.LUCKYSTACK_SUPERVISOR_GRACE_MS) || 1500;\n\n//? Mirrors `getEnvFiles()` from @luckystack/core — duplicated on purpose so the\n//? supervisor never imports core (see the invariant above). Keep in sync.\nconst DEFAULT_ENV_FILES = ['.env', '.env.local'];\nconst getEnvFiles = (): string[] => {\n const override = process.env.LUCKYSTACK_ENV_FILES;\n if (override) {\n const list = override.split(',').map((entry) => entry.trim()).filter(Boolean);\n if (list.length > 0) return list;\n }\n return DEFAULT_ENV_FILES;\n};\n\n//? Resolve NODE_ENV without mutating `process.env`: a real ambient env var\n//? wins; otherwise read the env files via the pure `dotenv.parse` (\"later\n//? overrides earlier\", matching loadEnvFiles' file order).\nconst resolveNodeEnv = (): string => {\n if (process.env.NODE_ENV) return process.env.NODE_ENV;\n let fromFiles: string | undefined;\n for (const file of getEnvFiles()) {\n const filePath = path.resolve(process.cwd(), file);\n if (!existsSync(filePath)) continue;\n const parsed = parseDotenv(readFileSync(filePath, 'utf8'));\n if (typeof parsed.NODE_ENV === 'string' && parsed.NODE_ENV.length > 0) fromFiles = parsed.NODE_ENV;\n }\n return fromFiles ?? 'development';\n};\n\nconst CORE_WATCH_GLOBS = [\n 'config.ts',\n ...getEnvFiles(),\n 'server/server.ts',\n 'server/bootstrap/**/*.ts',\n 'server/auth/**/*.ts',\n 'server/functions/db.ts',\n 'server/functions/redis.ts',\n 'server/functions/sentry.ts',\n];\n\nconst tsxCliPath = path.resolve(process.cwd(), 'node_modules', 'tsx', 'dist', 'cli.mjs');\n//? Scaffolded projects carry a dedicated server tsconfig — pass it when present\n//? so the child matches a manual `tsx --tsconfig tsconfig.server.json` run.\nconst tsconfigServerArgs = existsSync(path.resolve(process.cwd(), 'tsconfig.server.json'))\n ? ['--tsconfig', 'tsconfig.server.json']\n : [];\nconst childArgs = [tsxCliPath, ...tsconfigServerArgs, 'server/server.ts'];\n\nlet childProcess: ChildProcess | null = null;\nlet pendingRestart = false;\nlet restartTimer: NodeJS.Timeout | null = null;\nlet crashRestartTimer: NodeJS.Timeout | null = null;\nlet childBootStartedAt = 0;\nlet consecutiveFastCrashes = 0;\nlet isShuttingDown = false;\n\nconst startChild = () => {\n if (isShuttingDown) return;\n childBootStartedAt = performance.now();\n const spawned = spawn(process.execPath, childArgs, {\n stdio: 'inherit',\n //? `process.env` is guaranteed `.env`-free here (see the invariant at the\n //? top of this file), so the child loads `.env` fresh on every restart and\n //? picks up edited values — mirroring a cold `npm run server` boot.\n env: {\n ...process.env,\n LUCKYSTACK_CORE_SUPERVISED: 'true',\n },\n });\n childProcess = spawned;\n\n console.log(`[Supervisor] Started server process (pid: ${String(spawned.pid)})`);\n\n //? `'error'` and `'exit'` can BOTH fire for a single spawn (a failed spawn\n //? emits `'error'`, and some platforms then emit `'exit'` too). This flag\n //? resolves THIS child's lifecycle exactly once regardless of event order, so\n //? we never double-schedule a restart.\n let handled = false;\n\n //? A failed `spawn` (ENOENT/EACCES — e.g. a missing `tsx`) emits `'error'`,\n //? NOT `'exit'`. Without this listener Node re-throws it as an uncaught\n //? exception that kills the SUPERVISOR instead of retrying — the dev wrapper\n //? would just disappear. Route it through the same crash-restart delay.\n spawned.on('error', (err) => {\n console.log(`[Supervisor] Failed to spawn server process: ${String(err)}`, 'red');\n if (handled) return;\n handled = true;\n childProcess = null;\n\n if (isShuttingDown) {\n process.exit(1);\n }\n\n console.log(`[Supervisor] Retrying server spawn in ${String(CRASH_RESTART_DELAY_MS)}ms`);\n crashRestartTimer = setTimeout(() => {\n crashRestartTimer = null;\n startChild();\n }, CRASH_RESTART_DELAY_MS);\n });\n\n spawned.on('exit', (code, signal) => {\n const uptimeMs = Math.round(performance.now() - childBootStartedAt);\n const shouldRestart = pendingRestart;\n\n if (handled) return;\n handled = true;\n childProcess = null;\n\n //? Once the user has asked us to stop, never spawn another child — no matter\n //? what the previous one's exit reason was. Without this guard a crash that\n //? races with Ctrl+C re-spawns indefinitely.\n if (isShuttingDown) {\n process.exit(0);\n }\n\n if (shouldRestart) {\n pendingRestart = false;\n //? A watcher-driven restart is an explicit edit to a watched file — give\n //? the new code a clean slate instead of inheriting a previous crash burst.\n consecutiveFastCrashes = 0;\n console.log(`[Supervisor] Restarting server after ${String(uptimeMs)}ms uptime`);\n startChild();\n return;\n }\n\n if (signal === 'SIGTERM' || signal === 'SIGINT') {\n return;\n }\n\n if (typeof code === 'number' && code !== 0) {\n //? Rapid-crash-loop breaker: a child that died within the boot window\n //? counts toward the consecutive-fast-crash tally; one that lived longer\n //? proves the startup error cleared, so reset the tally.\n if (uptimeMs < FAST_CRASH_THRESHOLD_MS) {\n consecutiveFastCrashes += 1;\n } else {\n consecutiveFastCrashes = 0;\n }\n\n if (consecutiveFastCrashes >= MAX_CONSECUTIVE_FAST_CRASHES) {\n console.log(\n `[Supervisor] Server crashed ${String(consecutiveFastCrashes)} times within ` +\n `${String(FAST_CRASH_THRESHOLD_MS / 1000)}s of starting — giving up. Fix the startup ` +\n `error above (e.g. a port already in use), then re-run \\`npm run server\\`.`,\n );\n process.exit(1);\n }\n\n console.log(`[Supervisor] Server crashed with code ${String(code)}. Restarting in ${String(CRASH_RESTART_DELAY_MS)}ms`);\n crashRestartTimer = setTimeout(() => {\n crashRestartTimer = null;\n startChild();\n }, CRASH_RESTART_DELAY_MS);\n }\n });\n};\n\nconst scheduleRestart = ({\n event,\n changedPath,\n}: {\n event: string;\n changedPath: string;\n}) => {\n if (restartTimer) {\n clearTimeout(restartTimer);\n }\n\n restartTimer = setTimeout(() => {\n restartTimer = null;\n pendingRestart = true;\n\n console.log(`[Supervisor] Core change detected (${event}): ${changedPath}. Restarting server`);\n\n if (!childProcess) {\n pendingRestart = false;\n startChild();\n return;\n }\n\n childProcess.kill('SIGTERM');\n }, RESTART_DEBOUNCE_MS);\n};\n\nconst shutdownSupervisor = () => {\n isShuttingDown = true;\n\n if (restartTimer) {\n clearTimeout(restartTimer);\n restartTimer = null;\n }\n if (crashRestartTimer) {\n clearTimeout(crashRestartTimer);\n crashRestartTimer = null;\n }\n\n pendingRestart = false;\n\n if (childProcess) {\n //? Child is still alive — its 'exit' handler will see isShuttingDown\n //? and call process.exit(0) once the child is gone. Force-exit after a\n //? short grace period in case the child ignores SIGTERM (Windows).\n childProcess.kill('SIGTERM');\n setTimeout(() => process.exit(0), SHUTDOWN_GRACE_MS).unref();\n } else {\n //? No child running (e.g. we were between crashes, sitting in the\n //? crash-restart setTimeout we just cleared above) — exit immediately.\n process.exit(0);\n }\n};\n\nif (resolveNodeEnv() === 'production') {\n //? In production the supervisor has no file watcher, but it still needs to\n //? forward shutdown signals so the child gets a chance to drain (e.g. flush\n //? error trackers, close DB connections). Without these handlers a SIGTERM\n //? from a process manager (systemd, Docker) kills the supervisor instantly\n //? and the child may never exit cleanly.\n process.on('SIGINT', () => {\n isShuttingDown = true;\n shutdownSupervisor();\n });\n process.on('SIGTERM', () => {\n isShuttingDown = true;\n shutdownSupervisor();\n });\n startChild();\n} else {\n const watcher = watch(CORE_WATCH_GLOBS, {\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 120,\n pollInterval: 20,\n },\n });\n\n watcher.on('all', (event, changedPath) => {\n scheduleRestart({ event, changedPath });\n });\n\n const handleSignal = (signalName: string) => {\n //? Set the flag synchronously so any in-flight child 'exit' handler\n //? running BEFORE watcher.close() resolves won't schedule a new spawn.\n if (isShuttingDown) {\n //? Second Ctrl+C — user is impatient. Hard-exit immediately.\n process.exit(1);\n }\n isShuttingDown = true;\n console.log(`[Supervisor] Received ${signalName}, shutting down`);\n void watcher.close().then(() => {\n shutdownSupervisor();\n }).catch(() => {\n shutdownSupervisor();\n });\n };\n\n process.on('SIGINT', () => { handleSignal('SIGINT'); });\n process.on('SIGTERM', () => { handleSignal('SIGTERM'); });\n\n startChild();\n}\n"],"mappings":";;;AAYA,SAAS,aAAgC;AACzC,SAAS,YAAY,oBAAoB;AACzC,SAAS,mBAAmB;AAC5B,OAAO,UAAU;AACjB,SAAS,aAAa;AACtB,SAAS,SAAS,mBAAmB;AAErC,IAAM,sBAAsB;AAC5B,IAAM,yB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AAC1B,qBAAiB;AACjB,uBAAmB;AAAA,EACrB,CAAC;AACD,aAAW;AACb,OAAO;AACL,QAAM,UAAU,MAAM,kBAAkB;AAAA,IACtC,eAAe;AAAA,IACf,kBAAkB;AAAA,MAChB,oBAAoB;AAAA,MACpB,cAAc;AAAA,IAChB;AAAA,EACF,CAAC;AAED,UAAQ,GAAG,OAAO,CAAC,OAAO,gBAAgB;AACxC,oBAAgB,EAAE,OAAO,YAAY,CAAC;AAAA,EACxC,CAAC;AAED,QAAM,eAAe,CAAC,eAAuB;AAG3C,QAAI,gBAAgB;AAElB,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,qBAAiB;AACjB,YAAQ,IAAI,yBAAyB,UAAU,iBAAiB;AAChE,SAAK,QAAQ,MAAM,EAAE,KAAK,MAAM;AAC9B,yBAAmB;AAAA,IACrB,CAAC,EAAE,MAAM,MAAM;AACb,yBAAmB;AAAA,IACrB,CAAC;AAAA,EACH;AAEA,UAAQ,GAAG,UAAU,MAAM;AAAE,iBAAa,QAAQ;AAAA,EAAG,CAAC;AACtD,UAAQ,GAAG,WAAW,MAAM;AAAE,iBAAa,SAAS;AAAA,EAAG,CAAC;AAExD,aAAW;AACb;","names":[]}
1
+ {"version":3,"sources":["../src/supervisor.ts"],"sourcesContent":["#!/usr/bin/env node\n//? CRITICAL INVARIANT: this process must NEVER merge `.env` files into its own\n//? `process.env`. The child is spawned with `{ ...process.env }`, and the\n//? child's own `loadEnvFiles()` loads `.env` with `override: false` — any\n//? `.env`-derived value that leaks into the supervisor's env would therefore\n//? WIN over freshly edited file values on every restart (stale-env bug).\n//? That is why this file imports NOTHING from `@luckystack/core` (core runs\n//? `bootstrapEnv()` as an import side-effect) and reads env files via\n//? `dotenv.parse` (pure — no `process.env` mutation). The previous design\n//? (an `ambientEnvSnapshot` module imported first) broke as soon as tsup\n//? inlined the snapshot into the entry body: ESM imports are hoisted, so\n//? core's side-effect ran BEFORE the snapshot line.\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { performance } from 'node:perf_hooks';\nimport path from 'node:path';\nimport { watch } from 'chokidar';\nimport { parse as parseDotenv } from 'dotenv';\n\nconst RESTART_DEBOUNCE_MS = 150;\nconst CRASH_RESTART_DELAY_MS = 300;\n//? Rapid-crash-loop breaker. A child that exits non-zero within\n//? FAST_CRASH_THRESHOLD_MS of booting counts as a \"fast crash\" (it died during\n//? startup rather than after serving). MAX_CONSECUTIVE_FAST_CRASHES of those in\n//? a row means the startup error is not transient (a port already in use, a\n//? syntax error, a missing env) — restarting forever just spams the console, so\n//? we give up and print an actionable message. A child that survives longer than\n//? the threshold resets the counter, so a normal restart loop is unaffected.\nconst FAST_CRASH_THRESHOLD_MS = 3000;\nconst MAX_CONSECUTIVE_FAST_CRASHES = 4;\n//? Force-exit grace: how long we wait for the child to honour SIGTERM before\n//? the supervisor hard-exits. Windows does not deliver SIGKILL so the only\n//? lever is this timer. 1 500 ms is intentionally short (dev restarts should\n//? be fast); increase via LUCKYSTACK_SUPERVISOR_GRACE_MS for slow servers.\nconst SHUTDOWN_GRACE_MS = Number(process.env.LUCKYSTACK_SUPERVISOR_GRACE_MS) || 1500;\n\n//? Mirrors `getEnvFiles()` from @luckystack/core — duplicated on purpose so the\n//? supervisor never imports core (see the invariant above). Keep in sync.\nconst DEFAULT_ENV_FILES = ['.env', '.env.local'];\nconst getEnvFiles = (): string[] => {\n const override = process.env.LUCKYSTACK_ENV_FILES;\n if (override) {\n const list = override.split(',').map((entry) => entry.trim()).filter(Boolean);\n if (list.length > 0) return list;\n }\n return DEFAULT_ENV_FILES;\n};\n\n//? Resolve NODE_ENV without mutating `process.env`: a real ambient env var\n//? wins; otherwise read the env files via the pure `dotenv.parse` (\"later\n//? overrides earlier\", matching loadEnvFiles' file order).\nconst resolveNodeEnv = (): string => {\n if (process.env.NODE_ENV) return process.env.NODE_ENV;\n let fromFiles: string | undefined;\n for (const file of getEnvFiles()) {\n const filePath = path.resolve(process.cwd(), file);\n if (!existsSync(filePath)) continue;\n const parsed = parseDotenv(readFileSync(filePath, 'utf8'));\n if (typeof parsed.NODE_ENV === 'string' && parsed.NODE_ENV.length > 0) fromFiles = parsed.NODE_ENV;\n }\n return fromFiles ?? 'development';\n};\n\n//? chokidar v5 removed glob support — a `server/bootstrap/**/*.ts` pattern is no\n//? longer expanded; it is watched as a LITERAL path that never exists, so changes\n//? under `server/bootstrap` / `server/auth` silently never triggered a restart.\n//? Watch the concrete files directly, and the bootstrap/auth DIRECTORIES\n//? recursively (chokidar's default for a directory), then filter events down to\n//? the file types the old globs targeted in the `all` handler below.\nconst CORE_WATCH_FILES = [\n 'config.ts',\n ...getEnvFiles(),\n 'server/server.ts',\n 'server/functions/db.ts',\n 'server/functions/redis.ts',\n 'server/functions/sentry.ts',\n];\n//? Only watch dirs that exist — chokidar watching a recursive non-existent\n//? directory is wasteful/odd; a dir created later is picked up on next boot.\nconst CORE_WATCH_DIRS = ['server/bootstrap', 'server/auth'].filter((dir) =>\n existsSync(path.resolve(process.cwd(), dir)),\n);\nconst CORE_WATCH_TARGETS = [...CORE_WATCH_FILES, ...CORE_WATCH_DIRS];\n\nconst tsxCliPath = path.resolve(process.cwd(), 'node_modules', 'tsx', 'dist', 'cli.mjs');\n//? Scaffolded projects carry a dedicated server tsconfig — pass it when present\n//? so the child matches a manual `tsx --tsconfig tsconfig.server.json` run.\nconst tsconfigServerArgs = existsSync(path.resolve(process.cwd(), 'tsconfig.server.json'))\n ? ['--tsconfig', 'tsconfig.server.json']\n : [];\nconst childArgs = [tsxCliPath, ...tsconfigServerArgs, 'server/server.ts'];\n\nlet childProcess: ChildProcess | null = null;\nlet pendingRestart = false;\nlet restartTimer: NodeJS.Timeout | null = null;\nlet crashRestartTimer: NodeJS.Timeout | null = null;\nlet childBootStartedAt = 0;\nlet consecutiveFastCrashes = 0;\nlet isShuttingDown = false;\n\nconst startChild = () => {\n if (isShuttingDown) return;\n childBootStartedAt = performance.now();\n const spawned = spawn(process.execPath, childArgs, {\n stdio: 'inherit',\n //? `process.env` is guaranteed `.env`-free here (see the invariant at the\n //? top of this file), so the child loads `.env` fresh on every restart and\n //? picks up edited values — mirroring a cold `npm run server` boot.\n env: {\n ...process.env,\n LUCKYSTACK_CORE_SUPERVISED: 'true',\n },\n });\n childProcess = spawned;\n\n console.log(`[Supervisor] Started server process (pid: ${String(spawned.pid)})`);\n\n //? `'error'` and `'exit'` can BOTH fire for a single spawn (a failed spawn\n //? emits `'error'`, and some platforms then emit `'exit'` too). This flag\n //? resolves THIS child's lifecycle exactly once regardless of event order, so\n //? we never double-schedule a restart.\n let handled = false;\n\n //? A failed `spawn` (ENOENT/EACCES — e.g. a missing `tsx`) emits `'error'`,\n //? NOT `'exit'`. Without this listener Node re-throws it as an uncaught\n //? exception that kills the SUPERVISOR instead of retrying — the dev wrapper\n //? would just disappear. Route it through the same crash-restart delay.\n spawned.on('error', (err) => {\n console.log(`[Supervisor] Failed to spawn server process: ${String(err)}`, 'red');\n if (handled) return;\n handled = true;\n childProcess = null;\n\n if (isShuttingDown) {\n process.exit(1);\n }\n\n console.log(`[Supervisor] Retrying server spawn in ${String(CRASH_RESTART_DELAY_MS)}ms`);\n crashRestartTimer = setTimeout(() => {\n crashRestartTimer = null;\n startChild();\n }, CRASH_RESTART_DELAY_MS);\n });\n\n spawned.on('exit', (code, signal) => {\n const uptimeMs = Math.round(performance.now() - childBootStartedAt);\n const shouldRestart = pendingRestart;\n\n if (handled) return;\n handled = true;\n childProcess = null;\n\n //? Once the user has asked us to stop, never spawn another child — no matter\n //? what the previous one's exit reason was. Without this guard a crash that\n //? races with Ctrl+C re-spawns indefinitely.\n if (isShuttingDown) {\n process.exit(0);\n }\n\n if (shouldRestart) {\n pendingRestart = false;\n //? A watcher-driven restart is an explicit edit to a watched file — give\n //? the new code a clean slate instead of inheriting a previous crash burst.\n consecutiveFastCrashes = 0;\n console.log(`[Supervisor] Restarting server after ${String(uptimeMs)}ms uptime`);\n startChild();\n return;\n }\n\n if (signal === 'SIGTERM' || signal === 'SIGINT') {\n return;\n }\n\n if (typeof code === 'number' && code !== 0) {\n //? Rapid-crash-loop breaker: a child that died within the boot window\n //? counts toward the consecutive-fast-crash tally; one that lived longer\n //? proves the startup error cleared, so reset the tally.\n if (uptimeMs < FAST_CRASH_THRESHOLD_MS) {\n consecutiveFastCrashes += 1;\n } else {\n consecutiveFastCrashes = 0;\n }\n\n if (consecutiveFastCrashes >= MAX_CONSECUTIVE_FAST_CRASHES) {\n console.log(\n `[Supervisor] Server crashed ${String(consecutiveFastCrashes)} times within ` +\n `${String(FAST_CRASH_THRESHOLD_MS / 1000)}s of starting — giving up. Fix the startup ` +\n `error above (e.g. a port already in use), then re-run \\`npm run server\\`.`,\n );\n process.exit(1);\n }\n\n console.log(`[Supervisor] Server crashed with code ${String(code)}. Restarting in ${String(CRASH_RESTART_DELAY_MS)}ms`);\n crashRestartTimer = setTimeout(() => {\n crashRestartTimer = null;\n startChild();\n }, CRASH_RESTART_DELAY_MS);\n }\n });\n};\n\nconst scheduleRestart = ({\n event,\n changedPath,\n}: {\n event: string;\n changedPath: string;\n}) => {\n if (restartTimer) {\n clearTimeout(restartTimer);\n }\n\n restartTimer = setTimeout(() => {\n restartTimer = null;\n pendingRestart = true;\n\n console.log(`[Supervisor] Core change detected (${event}): ${changedPath}. Restarting server`);\n\n if (!childProcess) {\n pendingRestart = false;\n startChild();\n return;\n }\n\n childProcess.kill('SIGTERM');\n }, RESTART_DEBOUNCE_MS);\n};\n\nconst shutdownSupervisor = () => {\n isShuttingDown = true;\n\n if (restartTimer) {\n clearTimeout(restartTimer);\n restartTimer = null;\n }\n if (crashRestartTimer) {\n clearTimeout(crashRestartTimer);\n crashRestartTimer = null;\n }\n\n pendingRestart = false;\n\n if (childProcess) {\n //? Child is still alive — its 'exit' handler will see isShuttingDown\n //? and call process.exit(0) once the child is gone. Force-exit after a\n //? short grace period in case the child ignores SIGTERM (Windows).\n childProcess.kill('SIGTERM');\n setTimeout(() => process.exit(0), SHUTDOWN_GRACE_MS).unref();\n } else {\n //? No child running (e.g. we were between crashes, sitting in the\n //? crash-restart setTimeout we just cleared above) — exit immediately.\n process.exit(0);\n }\n};\n\nif (resolveNodeEnv() === 'production') {\n //? In production the supervisor has no file watcher, but it still needs to\n //? forward shutdown signals so the child gets a chance to drain (e.g. flush\n //? error trackers, close DB connections). Without these handlers a SIGTERM\n //? from a process manager (systemd, Docker) kills the supervisor instantly\n //? and the child may never exit cleanly.\n process.on('SIGINT', () => {\n isShuttingDown = true;\n shutdownSupervisor();\n });\n process.on('SIGTERM', () => {\n isShuttingDown = true;\n shutdownSupervisor();\n });\n startChild();\n} else {\n const watcher = watch(CORE_WATCH_TARGETS, {\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 120,\n pollInterval: 20,\n },\n });\n\n watcher.on('all', (event, changedPath) => {\n //? Ignore pure directory churn from the recursively-watched bootstrap/auth dirs.\n if (event === 'addDir' || event === 'unlinkDir') return;\n //? Restore the old `**/*.ts` glob intent: within the watched directories only\n //? TS sources matter. A `.ts` suffix covers every concrete watched TS file too\n //? (config.ts, server.ts, functions/*.ts); the non-TS watched files are the\n //? `.env*` set, matched explicitly. A stray non-TS file under a watched dir is\n //? correctly ignored.\n const normalized = changedPath.replaceAll('\\\\', '/');\n const relevant = normalized.endsWith('.ts') || CORE_WATCH_FILES.some((file) => normalized.endsWith(file));\n if (!relevant) return;\n scheduleRestart({ event, changedPath });\n });\n\n const handleSignal = (signalName: string) => {\n //? Set the flag synchronously so any in-flight child 'exit' handler\n //? running BEFORE watcher.close() resolves won't schedule a new spawn.\n if (isShuttingDown) {\n //? Second Ctrl+C — user is impatient. Hard-exit immediately.\n process.exit(1);\n }\n isShuttingDown = true;\n console.log(`[Supervisor] Received ${signalName}, shutting down`);\n void watcher.close().then(() => {\n shutdownSupervisor();\n }).catch(() => {\n shutdownSupervisor();\n });\n };\n\n process.on('SIGINT', () => { handleSignal('SIGINT'); });\n process.on('SIGTERM', () => {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AAQ,GAAG,WAAW,MAAM;AAAE,iBAAa,SAAS;AAAA,EAAG,CAAC;AAExD,aAAW;AACb;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luckystack/devkit",
3
- "version": "0.2.6",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -56,7 +56,7 @@
56
56
  "test": "vitest run"
57
57
  },
58
58
  "dependencies": {
59
- "@luckystack/core": "^0.2.6",
59
+ "@luckystack/core": "^0.3.0",
60
60
  "chokidar": "^5.0.0",
61
61
  "dotenv": "^17.0.0"
62
62
  },