theokit 0.77.3 → 0.78.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 (39) hide show
  1. package/README.md +7 -0
  2. package/dist/{build-2VOQOWZE.js → build-WBQZWGED.js} +2 -2
  3. package/dist/{chunk-3XR6CBUA.js → chunk-ICLIUEST.js} +86 -19
  4. package/dist/chunk-ICLIUEST.js.map +1 -0
  5. package/dist/{chunk-QBK6YYZA.js → chunk-KSEPYAMJ.js} +8 -1
  6. package/dist/{chunk-QBK6YYZA.js.map → chunk-KSEPYAMJ.js.map} +1 -1
  7. package/dist/{chunk-XCPM72D6.js → chunk-ZWIKURA5.js} +52 -16
  8. package/dist/chunk-ZWIKURA5.js.map +1 -0
  9. package/dist/cli/index.js +4 -4
  10. package/dist/{dev-AE7EWSB7.js → dev-SCS6SPET.js} +4 -3
  11. package/dist/dev-SCS6SPET.js.map +1 -0
  12. package/dist/{index-CY_llLI7.d.ts → index-BGIX-H9s.d.ts} +1 -1
  13. package/dist/{job-backend-BX-PwnZW.d.ts → job-backend-BRfDfojf.d.ts} +24 -3
  14. package/dist/{netlify-GRVT3MTT.js → netlify-JLTQD3JJ.js} +41 -19
  15. package/dist/netlify-JLTQD3JJ.js.map +1 -0
  16. package/dist/{preview-XQJZ75QE.js → preview-USC6FF55.js} +3 -3
  17. package/dist/{registry-JHWY7JRY.js → registry-XLKBFOPW.js} +2 -2
  18. package/dist/server/http/index.d.ts +2 -2
  19. package/dist/server/index.d.ts +3 -3
  20. package/dist/server/index.js +4 -2
  21. package/dist/server/index.js.map +1 -1
  22. package/dist/server/jobs/index.d.ts +33 -5
  23. package/dist/server/jobs/index.js +3 -1
  24. package/dist/server/storage/index.d.ts +1 -1
  25. package/dist/server/storage/index.js +1 -1
  26. package/dist/{start-AE5YCDVS.js → start-QCGCORTH.js} +5 -5
  27. package/dist/start-QCGCORTH.js.map +1 -0
  28. package/dist/{storage-manager-3IUIEG2P.js → storage-manager-KK24UWB4.js} +8 -1
  29. package/dist/{storage-manager-3IUIEG2P.js.map → storage-manager-KK24UWB4.js.map} +1 -1
  30. package/dist/{storage-manager-Clu2RBpH.d.ts → storage-manager-vIxAHMwm.d.ts} +1 -0
  31. package/package.json +1 -1
  32. package/dist/chunk-3XR6CBUA.js.map +0 -1
  33. package/dist/chunk-XCPM72D6.js.map +0 -1
  34. package/dist/dev-AE7EWSB7.js.map +0 -1
  35. package/dist/netlify-GRVT3MTT.js.map +0 -1
  36. package/dist/start-AE5YCDVS.js.map +0 -1
  37. /package/dist/{build-2VOQOWZE.js.map → build-WBQZWGED.js.map} +0 -0
  38. /package/dist/{preview-XQJZ75QE.js.map → preview-USC6FF55.js.map} +0 -0
  39. /package/dist/{registry-JHWY7JRY.js.map → registry-XLKBFOPW.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/cache-bootstrap.ts","../src/server/cron/cron-runtime-node.ts","../src/cli/commands/start/bootstrap-stages.ts","../src/cli/commands/start/cron-bootstrap.ts","../src/cli/commands/start/job-bootstrap.ts","../src/server/jobs/job-backend.ts","../src/server/jobs/job-runner.ts","../src/server/jobs/job-worker.ts"],"sourcesContent":["import type { NormalizedCacheConfig } from '../cache/engine-singleton.js'\n\n/**\n * Initialize the singleton cache engine from `theo.config.ts > cache` (#352).\n *\n * Until this existed, `initCacheEngine` had no production caller while\n * `getCacheEngine` had three — so `revalidateTag`, `updateTag` and\n * `revalidatePath`, all exported publicly, threw \"Cache engine not initialized\"\n * in every application. The subsystem was not unreachable code; it was a bridge\n * with one half published and the other half never built.\n *\n * Three states a boot legitimately reaches, each handled by a guard rather than\n * by a `catch`, because `initCacheEngine` throws on all three and absorbing the\n * throws would absorb the real double-init bug with them:\n *\n * - no `cache` key at all — the framework stays backward compatible, no engine\n * - `enabled: false` — an explicit opt-out, not an error\n * - already initialized — HMR, a second server in one process, a test booting\n * twice in one worker\n *\n * Unlike `configureStorageManagerFromConfig`, its sibling in the CLI bootstrap,\n * a malformed config is NOT\n * degraded into a warning here, and the divergence is deliberate. Warning and\n * continuing would boot an application whose `revalidateTag` still throws — the\n * exact defect this function exists to remove, restored silently and now\n * attributable to nothing.\n */\nexport async function initCacheEngineFromConfig(cacheConfig: unknown): Promise<void> {\n if (cacheConfig === undefined || cacheConfig === null) return\n\n const { initCacheEngine, isCacheEngineInitialized } = await import('../cache/engine-singleton.js')\n if (isCacheEngineInitialized()) return\n\n const { cacheSchema } = await import('../config/schemas/index.js')\n const parsed = cacheSchema.parse(cacheConfig)\n if (!parsed.enabled) return\n\n initCacheEngine({\n enabled: parsed.enabled,\n // The schema accepts `'memory'` or a caller-supplied adapter instance, which\n // it cannot type beyond `unknown` without importing the adapter contract\n // into the config layer.\n storage: parsed.storage as NormalizedCacheConfig['storage'],\n maxEntries: parsed.maxEntries,\n defaults: parsed.defaults,\n })\n}\n","import { CronExpressionParser } from 'cron-parser'\n\nimport { generateNewTraceContext } from '../observability/trace-context-propagation.js'\n\nimport type { CronLock } from './cron-lock.js'\nimport type { CronContext, CronDefinition } from './cron-types.js'\n\n/**\n * In-process cron scheduler, run by `theokit start` (and by `theokit dev --crons`).\n *\n * Algorithm:\n * - For each cron, compute `nextFireAt = cron-parser.next()`.\n * - Schedule a `setTimeout(handler, nextFireAt - now)`.\n * - After handler invocation (sync return or Promise scheduled), recompute\n * next fire from CURRENT time (drift-free vs scheduled time).\n *\n * Per-cron isolation (EC-109):\n * - Each cron's handler invocation is fire-and-forget (`void` scheduled).\n * A hanging handler does NOT block the scheduler loop nor other crons.\n * - `concurrency: 'forbid'` (default) tracks an in-flight flag per-cron;\n * subsequent ticks skip + warn while the in-flight flag is set.\n * - `concurrency: 'allow'` runs handlers concurrently — caller's responsibility.\n *\n * Several processes (replicas) each run this scheduler under `theokit start`. Without a `lock`,\n * each one fires every tick. With one, each tick asks the lock first and only the process that\n * gets `true` runs the handler (usetheokit/theokit#1016). A lock that fails skips the tick and logs\n * the error: running unguarded would repeat the side effect on every replica, which is the defect\n * the lock exists for.\n *\n * Serverless targets use platform-native triggers (T1.5 adapter translators), which fire once.\n */\n\nexport interface CronSchedulerOptions {\n /** Shared lock deciding which process runs each tick. Absent: this process runs every tick. */\n lock?: CronLock\n}\n\nexport interface CronScheduler {\n start(): void\n stop(): void\n}\n\ninterface CronJobState {\n readonly def: CronDefinition\n inFlight: boolean\n timer: NodeJS.Timeout | null\n abortController: AbortController | null\n}\n\nexport function createCronScheduler(\n definitions: readonly CronDefinition[],\n options: CronSchedulerOptions = {},\n): CronScheduler {\n const lock = options.lock\n const states: CronJobState[] = definitions.map((def) => ({\n def,\n inFlight: false,\n timer: null,\n abortController: null,\n }))\n\n let started = false\n\n /** Run the tick if the lock (when there is one) gives it to this process. */\n const fireIfLockAllows = (state: CronJobState, scheduledAt: Date): void => {\n if (lock === undefined) {\n fireAndReschedule(state, scheduledAt)\n return\n }\n state.timer = null\n void lock.acquire(state.def.name, scheduledAt).then(\n (won) => {\n if (won) fireAndReschedule(state, scheduledAt)\n else scheduleNext(state)\n },\n (err: unknown) => {\n console.error(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()}: ` +\n 'the cron lock could not be acquired:',\n err instanceof Error ? err.message : err,\n )\n scheduleNext(state)\n },\n )\n }\n\n const fireAndReschedule = (state: CronJobState, scheduledAt: Date): void => {\n state.timer = null\n\n if (state.inFlight && state.def.concurrency === 'forbid') {\n console.warn(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()} ` +\n '— previous handler still running (concurrency: forbid).',\n )\n scheduleNext(state)\n return\n }\n\n state.inFlight = true\n state.abortController = new AbortController()\n const traceCtx = generateNewTraceContext()\n const ctx: CronContext = {\n traceId: traceCtx.trace_id,\n scheduledAt,\n signal: state.abortController.signal,\n }\n\n // Fire-and-forget: EC-109 — never await here so a hanging handler\n // can't block the scheduler loop or other crons.\n void Promise.resolve()\n .then(() => state.def.handler(ctx))\n .catch((err: unknown) => {\n console.error(\n `[theokit:cron] \"${state.def.name}\" handler error:`,\n err instanceof Error ? err.message : err,\n )\n })\n .finally(() => {\n state.inFlight = false\n })\n\n scheduleNext(state)\n }\n\n const scheduleNext = (state: CronJobState): void => {\n if (!started) return\n const interval = CronExpressionParser.parse(state.def.schedule, {\n tz: 'UTC',\n currentDate: new Date(),\n })\n const next = interval.next().toDate()\n const delayMs = Math.max(0, next.getTime() - Date.now())\n state.timer = setTimeout(() => {\n fireIfLockAllows(state, next)\n }, delayMs)\n // setTimeout returns a Timeout object; in Node, .unref() is available but\n // we DO want this to keep the event loop alive in dev — explicit no-unref.\n }\n\n return {\n start(): void {\n if (started) return\n started = true\n for (const state of states) {\n scheduleNext(state)\n }\n },\n stop(): void {\n started = false\n for (const state of states) {\n if (state.timer) {\n clearTimeout(state.timer)\n state.timer = null\n }\n state.abortController?.abort()\n state.abortController = null\n }\n },\n }\n}\n","/**\n * Bootstrap stages extracted from `start.ts` per T4.2 (architecture-cleanup, ADR-0017).\n *\n * The full goal of T4.2 is a ≤30-LOC `startCommand` spine + 6-8 stage files. This\n * file ships the first batch: the configure-from-config bootstrap helpers + the\n * SSR entry resolver. They are stand-alone, side-effect-free at module load, and\n * already individually testable.\n *\n * Remaining stages (request-handler extraction, graceful-shutdown extraction,\n * signal-handlers extraction) are deferred to a follow-up sprint — see plan\n * ks.\n */\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\n\ninterface SdkAgentRegistry {\n configure?: (opts: { maxAgents?: number; idleTimeoutMs?: number }) => void\n}\ninterface SdkModule {\n Agent?: { registry?: SdkAgentRegistry }\n}\n\n/**\n * Configure SDK's Agent.registry from `theo.config.ts > agents.registry`.\n * Lazy at boot; EC-3 sync flag flip prevents race under concurrent boot.\n * Silent no-op when registry config is absent or SDK is uninstalled.\n */\nexport async function configureAgentRegistryFromConfig(\n registryConfig: { maxAgents: number; idleTimeoutMs: number } | undefined,\n): Promise<void> {\n if (registryConfig === undefined) return\n try {\n const sdk = (await import('@theokit/sdk').catch(() => null)) as SdkModule | null\n const sdkConfigure = sdk?.Agent?.registry?.configure\n if (sdkConfigure === undefined) return\n const { configureAgentRegistryOnce } =\n await import('../../../server/agent/configure-agent-registry.js')\n configureAgentRegistryOnce(\n {\n configure: (opts) => {\n sdkConfigure(opts)\n },\n },\n registryConfig,\n )\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.agent_registry_skip', {\n event: 'bootstrap.agent_registry_skip',\n message: msg,\n })\n }\n}\n\n/**\n * Configure the StorageManager from `theo.config.ts > storage` (ADR-0007).\n * Manager enforces configure-once internally (D3); this helper bridges the\n * config to the singleton with actionable error handling.\n */\nexport async function configureStorageManagerFromConfig(storageConfig: unknown): Promise<void> {\n if (storageConfig === undefined || storageConfig === null) return\n try {\n const { getStorageManager } = await import('../../../server/storage/storage-manager.js')\n const { storageSchema } = await import('../../../config/schema.js')\n // Re-validate at boot so a malformed config from a non-Zod source\n // (test fixtures, dynamic configs) surfaces a clear error early.\n const parsed = storageSchema.parse(storageConfig)\n getStorageManager().configure(parsed)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.storage_skip', {\n event: 'bootstrap.storage_skip',\n message: msg,\n })\n }\n}\n\nconst SSR_EXTENSIONS = ['.mjs', '.js'] as const\n\n/**\n * Resolve the SSR entry-server module path. tsup may emit `.mjs` or `.js`\n * depending on output format. Try `.mjs` first (modern default) then fall\n * back to `.js`. Returns null when neither exists — SSR stays disabled.\n *\n * Exported so unit tests can pin the resolution order without booting the\n * full CLI.\n */\nexport function resolveSsrEntry(distDir: string): string | null {\n for (const ext of SSR_EXTENSIONS) {\n const path = resolve(distDir, `server/entry-server${ext}`)\n\n if (existsSync(path)) return path\n }\n return null\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { CronManifest } from '../../../server/cron/cron-manifest.js'\nimport type { CronDefinition } from '../../../server/cron/cron-types.js'\n\n/**\n * Reads the cron manifest `theokit build` writes and re-loads each handler so\n * `theokit start` can drive the in-process scheduler.\n *\n * The build prints \"Cron → in-process scheduler (theokit start)\" for\n * `target: node`, but nothing on the serving side ever read `dist/crons.json`\n * — the crons were declared, validated, written, and then never ran\n * (theokit#324).\n *\n * The manifest names WHICH files hold a cron; the definition itself is taken\n * from the module, which is the source `defineCron` produced. Trusting the\n * manifest's copy of the schedule would let a stale build silently run a cron\n * on the wrong cadence.\n */\nexport async function loadCronDefinitions(\n manifestPath: string,\n projectRoot: string,\n loadModule: (filePath: string) => unknown,\n): Promise<CronDefinition[]> {\n if (!existsSync(manifestPath)) return []\n\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as CronManifest\n return loadCronModules(\n manifest.crons.map((entry) => resolve(projectRoot, entry.filePath)),\n loadModule,\n )\n}\n\n/**\n * Import each file and take its `defineCron` default export, refusing a file without one. Shared\n * with `theokit dev --crons`, which lists the files itself and loads them through Vite.\n */\nexport async function loadCronModules(\n filePaths: readonly string[],\n loadModule: (filePath: string) => unknown,\n): Promise<CronDefinition[]> {\n const definitions: CronDefinition[] = []\n for (const filePath of filePaths) {\n const mod = (await loadModule(filePath)) as { default?: unknown }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `\"${filePath}\" is listed as a cron but has no valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`. ' +\n 'Re-run `theokit build` if the file changed since the last build.',\n )\n }\n definitions.push(exported)\n }\n return definitions\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.schedule === 'string' &&\n typeof candidate.handler === 'function'\n )\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../../../config/schema.js'\nimport { jobBackendFromConfig } from '../../../server/jobs/job-backend-from-config.js'\nimport type { JobBackend } from '../../../server/jobs/job-backend.js'\nimport type { JobManifest } from '../../../server/jobs/job-manifest.js'\nimport { createJobRunner } from '../../../server/jobs/job-runner.js'\nimport type { JobDefinition } from '../../../server/jobs/job-types.js'\nimport { createJobWorker, type JobWorker } from '../../../server/jobs/job-worker.js'\n\n/**\n * Reads the job manifest `theokit build` writes and re-loads each definition, the jobs twin of\n * `loadCronDefinitions`. The manifest names WHICH files hold a job; the definition comes from the\n * module, so a stale build cannot run a handler the source no longer has.\n *\n * Before usetheokit/theokit#1010 nothing on the serving side read `jobs.json`.\n */\nexport async function loadJobDefinitions(\n manifestPath: string,\n projectRoot: string,\n loadModule: (filePath: string) => unknown,\n): Promise<JobDefinition[]> {\n if (!existsSync(manifestPath)) return []\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as JobManifest\n return loadJobModules(\n manifest.jobs.map((entry) => resolve(projectRoot, entry.filePath)),\n loadModule,\n )\n}\n\n/** Import each file and take its `defineJob` default export, refusing a file without one. */\nexport async function loadJobModules(\n filePaths: readonly string[],\n loadModule: (filePath: string) => unknown,\n): Promise<JobDefinition[]> {\n const definitions: JobDefinition[] = []\n for (const filePath of filePaths) {\n const mod = (await loadModule(filePath)) as { default?: unknown }\n if (!isJobDefinition(mod.default)) {\n throw new Error(\n `\"${filePath}\" is listed as a job but has no valid default export. ` +\n \"Expected `export default defineJob(name, { handler })` from 'theokit/server/jobs'. \" +\n 'Re-run `theokit build` if the file changed since the last build.',\n )\n }\n definitions.push(mod.default)\n }\n return definitions\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.handler === 'function' &&\n typeof candidate.maxAttempts === 'number'\n )\n}\n\n/**\n * `migrate()` of the configured `jobs.backend` rejected at boot. The process must not serve: every\n * route would answer 2xx while the outbox dropped each job it enqueued (usetheokit/theokit#1072).\n */\nclass JobBackendSetupError extends Error {\n readonly code = 'JOB_BACKEND_SETUP_FAILED'\n readonly backend: string\n constructor(backend: string, cause: unknown) {\n const reason = describeCause(cause)\n super(\n `jobs.backend (${backend}) could not create its storage at boot: ${reason}. ` +\n 'Jobs enqueued now would be lost, so the server did not start. Check that the database ' +\n 'in theo.config.ts is reachable and that its user may create tables.',\n { cause },\n )\n this.name = 'JobBackendSetupError'\n this.backend = backend\n }\n}\n\n/**\n * The text of a setup failure. `pg` connecting to `localhost` tries every address it resolves to\n * and rejects with an `AggregateError` whose own message is empty, which printed \"could not create\n * its storage at boot: .\" on a CI runner. The attempts are listed instead, and an error without a\n * message falls back to its code.\n */\nfunction describeCause(cause: unknown): string {\n if (cause instanceof AggregateError && cause.message === '') {\n return cause.errors.map(describeCause).join('; ')\n }\n if (cause instanceof Error) {\n const code = (cause as { code?: unknown }).code\n if (cause.message !== '') return cause.message\n return typeof code === 'string' ? code : cause.name\n }\n return String(cause)\n}\n\n/**\n * Run `migrate()` on the configured `jobs.backend`, when it has one, before anything can enqueue\n * or dequeue. `theokit start` and `theokit dev` call it at boot whether or not this process runs\n * the worker: a web-only process enqueues into the same table.\n *\n * It used to be the app's job, and nothing told the app: the README configured a\n * `PostgresJobBackend` without the call, and a fresh database answered 2xx while every job was\n * dropped. Calling it from `theo.config.ts` instead made `theokit build` need a database.\n */\nexport async function prepareJobBackend(config: Pick<TheoConfig, 'jobs'>): Promise<void> {\n const backend = jobBackendFromConfig(config)\n if (backend?.migrate === undefined) return\n try {\n await backend.migrate()\n } catch (err) {\n throw new JobBackendSetupError(backend.name, err)\n }\n}\n\nexport interface JobWorkerBootstrap {\n /** The running worker, or `undefined` when none was started (see `summary`). */\n readonly worker: JobWorker | undefined\n /** One line for the boot log saying what happens to the declared jobs, or `undefined` if none. */\n readonly summary: string | undefined\n}\n\n/**\n * Start the in-process job worker when there is something to run and somewhere to run it from.\n *\n * - no declared jobs: no worker. A worker with no definitions would lease other processes' jobs\n * and fail them as \"No job definition\".\n * - jobs but no `jobs.backend`: no worker, and the summary says the jobs cannot run.\n * - `jobs.worker.enabled: false`: no worker, said in the summary, so a web-only process is visibly\n * one.\n */\nexport function startJobWorker(\n config: Pick<TheoConfig, 'jobs'>,\n definitions: readonly JobDefinition[],\n): JobWorkerBootstrap {\n if (definitions.length === 0) return { worker: undefined, summary: undefined }\n const declared = `Jobs: ${String(definitions.length)} declared`\n const backend: JobBackend | undefined = jobBackendFromConfig(config)\n if (backend === undefined) {\n return {\n worker: undefined,\n summary:\n `${declared}, NOT running: theo.config.ts sets no jobs.backend, so ctx.queue is absent ` +\n 'and nothing can enqueue or run them.',\n }\n }\n const options = config.jobs?.worker\n if (options?.enabled === false) {\n return {\n worker: undefined,\n summary: `${declared}, worker disabled (jobs.worker.enabled: false); another process must run them.`,\n }\n }\n const worker = createJobWorker(createJobRunner(backend, definitions), {\n pollIntervalMs: options?.pollIntervalMs,\n batchSize: options?.batchSize,\n lockSeconds: options?.lockSeconds,\n })\n worker.start()\n return {\n worker,\n summary: `${declared}, worker polling the ${backend.name} backend in-process`,\n }\n}\n","/**\n * Neutral `JobBackend` interface.\n *\n * Implementations ship in core:\n * - `InMemoryJobBackend` (T2.2) — dev + tests; no external deps\n * - `PostgresJobBackend` (T3.1) — production; requires `pg` peer dep\n *\n * Community packages (`@theokit/jobs-redis`, `@theokit/jobs-sqs`, etc.)\n * implement this same interface to plug in alternate substrates without\n * modifying TheoKit core.\n */\n\nimport type { PoolLike } from '../storage/storage-types.js'\n\nexport interface JobEnqueueInput {\n /** The job name (matches a `defineJob` declaration). */\n name: string\n /** Validated input (already passed through Zod or equivalent at the queue-client layer). */\n input: unknown\n /**\n * Optional idempotency key, scoped to `name`: a second enqueue of the same (name, key) returns the\n * first job's id instead of creating a job, including when the two calls race. The window is\n * backend-specific: `PostgresJobBackend` holds the key while the row exists (until `ack`, or for\n * good once the job has failed); `InMemoryJobBackend` holds it for 60 seconds.\n */\n idempotencyKey?: string\n /** Optional delay before the job becomes available for dispatch. */\n delaySeconds?: number\n /** W3C Trace Context propagation per ADR/R0.5.9. */\n traceparent?: string\n /**\n * Maximum dispatch attempts stored with the job (default 1). The queue client has no access to\n * the job definitions and leaves it unset; `createJobRunner` passes the definition's\n * `maxAttempts` to `nack`, which takes precedence over this stored value.\n */\n maxAttempts?: number\n}\n\nexport interface JobLease {\n readonly jobId: string\n readonly name: string\n readonly input: unknown\n readonly attempts: number\n readonly maxAttempts: number\n readonly traceparent?: string\n readonly lockExpiresAt: Date\n /**\n * Identifies THIS lease. Pass it back to `ack`/`nack` so a worker whose lease expired, and was\n * handed to another worker, cannot finish the job on the new holder's behalf. Both first-party\n * backends set it; optional so a backend written against the earlier contract still compiles.\n */\n readonly leaseToken?: string\n}\n\n/** What `nack` is told about the failure. */\nexport interface JobNackOptions extends JobLeaseFence {\n /** The failure message. */\n error: string\n /** The handler threw `NonRetryableError`: no retry, whatever the attempts left. */\n nonRetryable?: boolean\n /**\n * The retry ceiling from the job's definition. Takes precedence over the value stored at\n * enqueue, which is 1 for every job enqueued through the queue client.\n */\n maxAttempts?: number\n}\n\n/** Fences `ack`/`nack` to the lease that is finishing the job. */\nexport interface JobLeaseFence {\n /** The `leaseToken` of the `JobLease` being finished. Omitted, the call is not fenced. */\n leaseToken?: string\n}\n\nexport interface JobBackend {\n /** Human-readable name for logging (e.g., \"memory\", \"postgres\"). */\n readonly name: string\n\n /** Persist a job for later dispatch. Returns the generated jobId. */\n enqueue(input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /** Worker loop polls for the next available leases. */\n dequeue(opts: { batchSize?: number; lockSeconds?: number }): Promise<JobLease[]>\n\n /**\n * Mark a job complete (success). With `leaseToken`, rejects with `JobLeaseLostError` and leaves\n * the job alone when that lease no longer holds it.\n */\n ack(jobId: string, fence?: JobLeaseFence): Promise<void>\n\n /**\n * Mark a job failed; backend decides retry vs DLQ via attempts. With `leaseToken`, rejects with\n * `JobLeaseLostError` and leaves the job alone when that lease no longer holds it.\n */\n nack(jobId: string, opts: JobNackOptions): Promise<void>\n\n /**\n * Optional: persist a job through `client`, a connection inside a transaction the caller opened,\n * so the job commits or rolls back with the caller's writes (usetheokit/theokit#1077). Only a\n * backend whose jobs live in the caller's database can offer it; `ctx.queue.enqueueInTransaction`\n * refuses a backend without it rather than enqueueing outside the transaction.\n */\n enqueueInTransaction?(client: PoolLike, input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /**\n * Optional: resolve when the backend's store answers, reject when it does not. `GET /__theo/ready`\n * calls it under `theokit start` and `theokit dev`, so an unreachable job store answers 503\n * (usetheokit/theokit#1071). A backend with nothing remote to reach leaves it out.\n */\n ping?(): Promise<void>\n\n /**\n * Optional: create or upgrade whatever storage the backend needs (a table, an index). Must be\n * idempotent and safe to run from several processes at once. `theokit start` and `theokit dev`\n * call it once at boot, before serving a request or starting the worker, and refuse to boot when\n * it rejects (usetheokit/theokit#1072). A backend that needs no setup leaves it out.\n */\n migrate?(): Promise<void>\n\n /**\n * Optional: return the existing jobId if `key` was enqueued within `ttlSeconds`. Pass `name` to\n * scope the lookup to one job type, as `enqueue` deduplicates on (name, key); without it, a key\n * shared by two job types may return either job.\n */\n idempotency?(key: string, ttlSeconds: number, name?: string): Promise<{ jobId: string } | null>\n}\n\n/**\n * Thrown from a job handler to opt out of retry policy. The runner nacks with\n * `nonRetryable: true` and the backend never retries the job: `PostgresJobBackend`\n * keeps it as failed with the error, `InMemoryJobBackend` drops it with a warning.\n */\nexport class NonRetryableError extends Error {\n readonly code = 'NON_RETRYABLE'\n constructor(message: string) {\n super(message)\n this.name = 'NonRetryableError'\n }\n}\n\n/**\n * `ack`/`nack` was called with a lease token that no longer holds the job: the lease expired and\n * another worker leased the job again (or the job is gone). The job is left untouched, because the\n * current holder owns its outcome. The runner logs it and moves on; a direct caller decides.\n */\nexport class JobLeaseLostError extends Error {\n readonly code = 'JOB_LEASE_LOST'\n readonly jobId: string\n readonly operation: 'ack' | 'nack'\n constructor(jobId: string, operation: 'ack' | 'nack') {\n super(\n `Cannot ${operation} job \"${jobId}\": its lease expired and another worker holds it now, ` +\n 'or the job no longer exists. The current holder decides its outcome.',\n )\n this.name = 'JobLeaseLostError'\n this.jobId = jobId\n this.operation = operation\n }\n}\n","import { createLogger } from '../observability/logger.js'\nimport {\n extractTraceContext,\n generateNewTraceContext,\n} from '../observability/trace-context-propagation.js'\n\nimport {\n type JobBackend,\n type JobLease,\n JobLeaseLostError,\n NonRetryableError,\n} from './job-backend.js'\nimport type { JobContext, JobDefinition } from './job-types.js'\n\n/**\n * Job runner — pulls leases from a backend and invokes the matching\n * handler. Each invocation wires up `JobContext` with:\n * - `traceId` extracted from the lease's `traceparent` header (W3C\n * Trace Context per R0.5.9), OR a fresh generated trace_id when\n * the upstream had no traceparent OR it was malformed.\n * - `attempt` from the lease.\n * - `signal` that aborts when the lease times out.\n *\n * `tick()` runs one dequeue+dispatch cycle and returns when all leases\n * have been ack'd or nack'd. `createJobWorker` (`job-worker.ts`) is the loop\n * around it, with idle polling and error backoff; `theokit start` and\n * `theokit dev` run one.\n *\n * EC-6 (trace continuity edge): when a lease has no traceparent OR a\n * malformed one, the handler still gets a valid traceId (generated) —\n * never null/undefined. The job MAY itself enqueue child jobs that\n * continue the new trace_id.\n */\n\nconst runnerLogger = createLogger({ context: { component: 'theokit:jobs:runner' } })\n\n/**\n * Run an ack or nack, fenced by the lease. A lost lease means another worker owns the job now, so\n * its outcome is not ours to write: log it and move on. Any other failure propagates.\n */\nasync function finish(\n lease: JobLease,\n outcome: 'ack' | 'nack',\n write: () => Promise<void>,\n): Promise<void> {\n try {\n await write()\n } catch (err) {\n if (!(err instanceof JobLeaseLostError)) throw err\n runnerLogger.warn('job lease lost before the outcome was written; the new holder decides it', {\n jobId: lease.jobId,\n job: lease.name,\n attempt: lease.attempts,\n outcome,\n code: err.code,\n })\n }\n}\n\nexport interface JobRunner {\n /** Run one dequeue+dispatch cycle. */\n tick(opts?: { batchSize?: number; lockSeconds?: number }): Promise<number>\n}\n\nexport function createJobRunner(\n backend: JobBackend,\n definitions: readonly JobDefinition[],\n): JobRunner {\n const byName = new Map<string, JobDefinition>()\n for (const def of definitions) {\n byName.set(def.name, def)\n }\n\n const runOne = async (lease: JobLease): Promise<void> => {\n const def = byName.get(lease.name)\n if (!def) {\n // Job name not registered in this runner's definition set. Nack\n // permanently — the lease can't be processed by this runner.\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: `No job definition for \"${lease.name}\"`,\n nonRetryable: true,\n leaseToken: lease.leaseToken,\n }),\n )\n return\n }\n\n // Resolve trace ID from lease's traceparent, or fall back to fresh.\n let traceId: string\n if (lease.traceparent) {\n const headers = new Headers({ traceparent: lease.traceparent })\n const ctx = extractTraceContext(headers)\n traceId = ctx?.trace_id ?? generateNewTraceContext().trace_id\n } else {\n traceId = generateNewTraceContext().trace_id\n }\n\n // Optional Zod validation on input.\n let parsedInput: unknown = lease.input\n if (def.inputSchema) {\n try {\n parsedInput = def.inputSchema.parse(lease.input)\n } catch (err) {\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: `Input validation failed: ${err instanceof Error ? err.message : String(err)}`,\n nonRetryable: true,\n leaseToken: lease.leaseToken,\n }),\n )\n return\n }\n }\n\n const abortController = new AbortController()\n // Auto-abort when lease expires\n const lockMs = lease.lockExpiresAt.getTime() - Date.now()\n const lockTimer = setTimeout(\n () => {\n abortController.abort()\n },\n Math.max(0, lockMs),\n )\n\n const jobCtx: JobContext = {\n traceId,\n input: parsedInput,\n signal: abortController.signal,\n attempt: lease.attempts,\n }\n\n let failure: unknown\n let failed = false\n try {\n await def.handler(jobCtx)\n } catch (err) {\n failed = true\n failure = err\n } finally {\n clearTimeout(lockTimer)\n }\n // The outcome is written outside the handler's try, so a failed ack is never mistaken for a\n // failed handler and nacked.\n if (!failed) {\n await finish(lease, 'ack', () => backend.ack(lease.jobId, { leaseToken: lease.leaseToken }))\n return\n }\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: failure instanceof Error ? failure.message : String(failure),\n nonRetryable: failure instanceof NonRetryableError,\n leaseToken: lease.leaseToken,\n // The definition is the source of truth: a job enqueued through the queue client was stored\n // with the backend default of 1 (usetheokit/theokit#1013).\n maxAttempts: def.maxAttempts,\n }),\n )\n }\n\n return {\n async tick(opts) {\n const leases = await backend.dequeue({\n batchSize: opts?.batchSize ?? 10,\n lockSeconds: opts?.lockSeconds ?? 30,\n })\n // Process leases sequentially — caller controls concurrency via\n // batchSize and tick frequency.\n for (const lease of leases) {\n await runOne(lease)\n }\n return leases.length\n },\n }\n}\n","import { createLogger } from '../observability/logger.js'\n\nimport type { JobRunner } from './job-runner.js'\n\n/**\n * The loop around `JobRunner.tick()`.\n *\n * `tick()` runs one dequeue-and-dispatch cycle and left the loop to its caller, and `theokit start`\n * never wrote one, so jobs were enqueued into a backend nothing drained (usetheokit/theokit#1010).\n * This is that loop, shared by `theokit start`, `theokit dev` and anyone running a worker process\n * of their own:\n *\n * - a tick that leased jobs is followed by another at once, so a backlog drains at full speed;\n * - an empty tick waits `pollIntervalMs` before asking again;\n * - a tick that throws (the database is down) is logged and retried with exponential backoff\n * capped at `maxErrorBackoffMs`, so an outage neither kills the process nor spins;\n * - `stop()` lets the tick in progress finish (its jobs are acked or nacked) and resolves after it.\n * A wait in progress is cut short.\n */\nexport interface JobWorkerOptions {\n /** Wait after a tick that leased nothing. Default 1000 ms. */\n pollIntervalMs?: number\n /** Leases per tick, passed to `tick()`. Default 10. */\n batchSize?: number\n /** Lease duration per job, passed to `tick()`. Default 30 s. */\n lockSeconds?: number\n /** Ceiling of the backoff after consecutive failed ticks. Default 30 000 ms. */\n maxErrorBackoffMs?: number\n}\n\nexport interface JobWorker {\n /** Start polling. A second call is a no-op. */\n start(): void\n /** Stop polling; resolves once the tick in progress, if any, has finished. */\n stop(): Promise<void>\n}\n\nconst workerLogger = createLogger({ context: { component: 'theokit:jobs:worker' } })\n\nexport function createJobWorker(runner: JobRunner, options: JobWorkerOptions = {}): JobWorker {\n const pollIntervalMs = options.pollIntervalMs ?? 1000\n const maxErrorBackoffMs = options.maxErrorBackoffMs ?? 30_000\n const tickOptions = { batchSize: options.batchSize ?? 10, lockSeconds: options.lockSeconds ?? 30 }\n\n let running = false\n let loop: Promise<void> | undefined\n let wake: (() => void) | undefined\n\n const wait = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(done, ms)\n function done(): void {\n clearTimeout(timer)\n wake = undefined\n resolve()\n }\n wake = done\n })\n\n const run = async (): Promise<void> => {\n let failures = 0\n while (running) {\n try {\n const leased = await runner.tick(tickOptions)\n failures = 0\n if (leased > 0) continue\n await wait(pollIntervalMs)\n } catch (err) {\n failures++\n const delayMs = Math.min(pollIntervalMs * 2 ** failures, maxErrorBackoffMs)\n workerLogger.error('job worker tick failed; retrying', {\n error: err instanceof Error ? err.message : String(err),\n consecutiveFailures: failures,\n retryInMs: delayMs,\n })\n await wait(delayMs)\n }\n }\n }\n\n return {\n start() {\n if (running) return\n running = true\n loop = run()\n },\n async stop() {\n running = false\n wake?.()\n await loop\n loop = undefined\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,eAAsB,0BAA0B,aAAqC;AACnF,MAAI,gBAAgB,UAAa,gBAAgB,KAAM;AAEvD,QAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAAO,gCAA8B;AACjG,MAAI,yBAAyB,EAAG;AAEhC,QAAM,EAAE,YAAY,IAAI,MAAM,OAAO,uBAA4B;AACjE,QAAM,SAAS,YAAY,MAAM,WAAW;AAC5C,MAAI,CAAC,OAAO,QAAS;AAErB,kBAAgB;AAAA,IACd,SAAS,OAAO;AAAA;AAAA;AAAA;AAAA,IAIhB,SAAS,OAAO;AAAA,IAChB,YAAY,OAAO;AAAA,IACnB,UAAU,OAAO;AAAA,EACnB,CAAC;AACH;;;AC9CA,SAAS,4BAA4B;AAiD9B,SAAS,oBACd,aACA,UAAgC,CAAC,GAClB;AACf,QAAM,OAAO,QAAQ;AACrB,QAAM,SAAyB,YAAY,IA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,OAAO,YAAY,MAAM,CAAC;AACpD,QAAM,UAAkC,qBAAqB,MAAM;AACnE,MAAI,YAAY,QAAW;AACzB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SACE,GAAG,QAAQ;AAAA,IAEf;AAAA,EACF;AACA,QAAM,UAAU,OAAO,MAAM;AAC7B,MAAI,SAAS,YAAY,OAAO;AAC9B,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SAAS,GAAG,QAAQ;AAAA,IACtB;AAAA,EACF;AACA,QAAM,SAAS,gBAAgB,gBAAgB,SAAS,WAAW,GAAG;AAAA,IACpE,gBAAgB,SAAS;AAAA,IACzB,WAAW,SAAS;AAAA,IACpB,aAAa,SAAS;AAAA,EACxB,CAAC;AACD,SAAO,MAAM;AACb,SAAO;AAAA,IACL;AAAA,IACA,SAAS,GAAG,QAAQ,wBAAwB,QAAQ,IAAI;AAAA,EAC1D;AACF;","names":["existsSync","resolve","existsSync","readFileSync","resolve","resolve","existsSync","readFileSync","resolve"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/dev.ts"],"sourcesContent":["import { resolve } from 'node:path'\n\nimport react from '@vitejs/plugin-react'\nimport { createServer, type Plugin, type ServerOptions, type ViteDevServer } from 'vite'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport type { TheoConfig } from '../../config/schema.js'\nimport { validateProjectStructure } from '../../config/validate-structure.js'\nimport { initCacheEngineFromConfig } from '../../server/cache-bootstrap.js'\nimport { createCronScheduler } from '../../server/cron/cron-runtime-node.js'\nimport { cronScanDirs, listCronFiles } from '../../server/cron/cron-scan.js'\nimport { listJobFiles } from '../../server/jobs/job-scan.js'\nimport { orchestrateDev } from '../../services/index.js'\nimport { theoPluginAsync } from '../../vite-plugin/index.js'\nimport { preflightNodeAndBindings } from '../preflight-node-version.js'\n\nimport { configureStorageManagerFromConfig } from './start/bootstrap-stages.js'\nimport { loadCronModules } from './start/cron-bootstrap.js'\nimport { loadJobModules, prepareJobBackend, startJobWorker } from './start/job-bootstrap.js'\n\ninterface DevOptions {\n port?: number\n /** Schedule the crons in dev (`theokit dev --crons`). Off by default (usetheokit/theokit#1017). */\n crons?: boolean\n}\n\n/**\n * The Vite `server` block, as a pure function of the loaded config — the same reasoning\n * `buildSecurityHeaders` is written down with: a setting that reaches Vite only from inside a\n * booted dev server can be asserted only by booting one, and a setting nobody can assert is how a\n * config field ends up existing and doing nothing (#555).\n *\n * Every key here is omitted rather than set to `undefined` when the app said nothing, so Vite's own\n * defaults apply. That matters most for `allowedHosts`, where the falsy value is `[]` — an empty\n * allowlist blocks every host, loopback included, so writing one on silence would turn \"no opinion\"\n * into \"refuse everything\".\n */\nexport function buildDevServerOptions(config: TheoConfig, port: number): ServerOptions {\n return {\n port,\n host: config.host,\n open: config.open,\n strictPort: config.strictPort,\n ...(config.allowedHosts !== undefined ? { allowedHosts: config.allowedHosts } : {}),\n warmup: config.warmup ?? {\n clientFiles: ['./app/**/*.tsx', './app/**/*.ts'],\n },\n }\n}\n\nexport async function startDevServer(cwd: string, options?: DevOptions): Promise<ViteDevServer> {\n // Preflight (FIRST — BEFORE anything that touches native bindings):\n // verifies Node version + native binding ABI match. Emits actionable\n // error referencing `nvm use` + `pnpm rebuild` when the dev server\n // was spawned under the wrong Node (common gotcha with `nohup env ...`\n // stripping the nvm PATH prefix).\n preflightNodeAndBindings(cwd)\n\n // Phase 1 (T1.2) — Load .env files into process.env BEFORE any module\n // reads them. Must run before loadConfig() so theo.config.ts functions\n // referencing process.env.* resolve correctly.\n loadEnv({ cwd, mode: 'development' })\n\n const config = await loadConfig(cwd)\n // #95 — pass config.appDir so the structure gate honors a custom frontend dir (e.g. apps/web).\n validateProjectStructure(cwd, config.appDir)\n\n // #352 — same engine, same config key, so `revalidateTag` behaves identically\n // under `theo dev` and `theo start`. A cache that only exists in production is\n // a cache nobody develops against.\n await initCacheEngineFromConfig(config.cache)\n\n // #1020 — the storage counterpart. `start` applied `config.storage` and `dev` did not, so every\n // `usePostgres(...)` threw \"Database not configured\" in development.\n await configureStorageManagerFromConfig(config.storage)\n\n // #1072 — create the job table before Vite serves a route that enqueues into it. A failure stops\n // the boot here, before any service or port is taken.\n await prepareJobBackend(config)\n\n // Wave 2 (T1.1) — spawn polyglot services BEFORE Vite. Healthcheck gates\n // readiness. Empty `services: {}` → early return (Wave 1 BC preserved).\n const orchestration = await orchestrateDev({\n cwd,\n services: config.services,\n })\n if (!orchestration.allHealthy) {\n await orchestration.stop()\n throw new Error(\n `[services] services failed healthcheck: ${orchestration.unhealthy.join(', ')}. ` +\n `Check that each declared service binds its port and responds 200 on its ` +\n `healthcheck path within 30s.`,\n )\n }\n\n // Phase 7 — legacy fs-mtime sweep removed: SDK's Agent.registry handles\n // LRU + idle eviction natively (configurable via theo.config.ts >\n // agents.registry; lazy-configured on first request).\n\n const port = options?.port ?? config.port\n // Narrow the rateLimit union: only the legacy flat shape (windowMs+max)\n // flows into the theoPlugin's RateLimitConfig parameter. The per-route\n // variant is consumed inside the api-middleware via the loaded user\n // config separately.\n const flatRateLimit =\n config.rateLimit && 'windowMs' in config.rateLimit && 'max' in config.rateLimit\n ? config.rateLimit\n : undefined\n // theoPluginAsync auto-chains @theokit/ui + @tailwindcss/vite via\n // top-level Plugin[] return (sync `theoPlugin()` factory's config()\n // hook returning {plugins:[...]} is silently dropped by Vite — see\n // commit history). Spread the result so Vite flattens them.\n let server: ViteDevServer\n try {\n const theoPlugins = await theoPluginAsync({\n root: cwd,\n rateLimit: flatRateLimit,\n ssr: config.ssr,\n // #95 — honor config `serverDir` (default \"server\") so route/action discovery scans it.\n serverDir: config.serverDir,\n // #95 follow-up — honor config `agentsDir` (default \"agents\") for the agent scan/middleware.\n agentsDir: config.agentsDir,\n // #95 follow-up — honor config `appDir` (default \"app\") for the file-based router + SSR/client entry.\n appDir: config.appDir,\n // Wave 2 (T3.1) — wire typed-client plugin when services declared.\n services: config.services,\n // T4.1 (canvas-ecosystem-refactor / ADR D6) — passthrough peer-deps\n // that plugins import dynamically (e.g., mermaid via plugin-canvas).\n viteOptimizeDeps: config.viteOptimizeDeps,\n })\n server = await createServer({\n root: cwd,\n plugins: [react(), ...theoPlugins] as Plugin[],\n server: buildDevServerOptions(config, port),\n logLevel: options?.port === 0 ? 'silent' : undefined,\n })\n\n await server.listen()\n } catch (err) {\n // EC-1 / try-finally pattern: if Vite create/listen fails AFTER services\n // started, stop them so we don't leak child processes.\n await orchestration.stop()\n throw err\n }\n\n // EC-1 fix: attach orchestration.stop() to the underlying HTTP server's\n // close event via Node-native API. We do NOT mutate `server.close`\n // (fragile across Vite upgrades). httpServer is `http.Server | null`.\n server.httpServer?.on('close', () => {\n void orchestration.stop()\n })\n\n await startDevJobWorker(server, cwd, config)\n await startDevCrons(server, cwd, config, options?.crons === true)\n\n return server\n}\n\n/**\n * The job worker `theokit start` runs, in development too (usetheokit/theokit#1010): `ctx.queue`\n * works in dev since #1009, and a queue nothing drains would make every job untestable without a\n * production build. Job files load through Vite, like routes, and the worker stops with the server.\n */\nasync function startDevJobWorker(\n server: ViteDevServer,\n cwd: string,\n config: TheoConfig,\n): Promise<void> {\n const files = listJobFiles(resolve(cwd, config.serverDir, 'jobs'))\n const definitions = await loadJobModules(files, (filePath) => server.ssrLoadModule(filePath))\n const jobs = startJobWorker(config, definitions)\n if (jobs.summary !== undefined) console.log(`\\n ${jobs.summary}`)\n server.httpServer?.on('close', () => {\n void jobs.worker?.stop()\n })\n}\n\n/**\n * Crons in development (usetheokit/theokit#1017). `dev` had no cron code path and said nothing, so\n * a new cron neither fired nor got explained until `build` plus `start`. Scheduling is opt-in\n * (`--crons`): a cron that sends an email or charges a card should not do it on every dev boot\n * unasked. Either way the boot log says what happens to the declared crons. Files load through\n * Vite once at boot, so an edit to a cron applies after a restart. Single process, so no lock.\n */\nasync function startDevCrons(\n server: ViteDevServer,\n cwd: string,\n config: TheoConfig,\n schedule: boolean,\n): Promise<void> {\n const dirs = cronScanDirs(cwd, config.serverDir, config.agentsDir)\n const files = listCronFiles([dirs.crons, dirs.schedules])\n if (files.length === 0) return\n if (!schedule) {\n console.log(\n `\\n Crons: ${String(files.length)} declared, not scheduled in dev. ` +\n 'Run `theokit dev --crons` to schedule them (edits apply after a restart).',\n )\n return\n }\n const definitions = await loadCronModules(files, (filePath) => server.ssrLoadModule(filePath))\n const scheduler = createCronScheduler(definitions)\n scheduler.start()\n console.log(\n `\\n Crons: ${String(definitions.length)} scheduled in dev (--crons); edits apply after a restart.`,\n )\n server.httpServer?.on('close', () => {\n scheduler.stop()\n })\n}\n\nexport async function devCommand(options: DevOptions): Promise<void> {\n try {\n const cwd = process.cwd()\n const server = await startDevServer(cwd, options)\n server.printUrls()\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n console.error(`\\n ✗ ${msg}\\n`)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,eAAe;AAExB,OAAO,WAAW;AAClB,SAAS,oBAAyE;AAmC3E,SAAS,sBAAsB,QAAoB,MAA6B;AACrF,SAAO;AAAA,IACL;AAAA,IACA,MAAM,OAAO;AAAA,IACb,MAAM,OAAO;AAAA,IACb,YAAY,OAAO;AAAA,IACnB,GAAI,OAAO,iBAAiB,SAAY,EAAE,cAAc,OAAO,aAAa,IAAI,CAAC;AAAA,IACjF,QAAQ,OAAO,UAAU;AAAA,MACvB,aAAa,CAAC,kBAAkB,eAAe;AAAA,IACjD;AAAA,EACF;AACF;AAEA,eAAsB,eAAe,KAAa,SAA8C;AAM9F,2BAAyB,GAAG;AAK5B,UAAQ,EAAE,KAAK,MAAM,cAAc,CAAC;AAEpC,QAAM,SAAS,MAAM,WAAW,GAAG;AAEnC,2BAAyB,KAAK,OAAO,MAAM;AAK3C,QAAM,0BAA0B,OAAO,KAAK;AAI5C,QAAM,kCAAkC,OAAO,OAAO;AAItD,QAAM,kBAAkB,MAAM;AAI9B,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AM,eAAe,OAAO,CAAC,aAAa,OAAO,cAAc,QAAQ,CAAC;AAC5F,QAAM,OAAO,eAAe,QAAQ,WAAW;AAC/C,MAAI,KAAK,YAAY,OAAW,SAAQ,IAAI;AAAA,IAAO,KAAK,OAAO,EAAE;AACjE,SAAO,YAAY,GAAG,SAAS,MAAM;AACnC,SAAK,KAAK,QAAQ,KAAK;AAAA,EACzB,CAAC;AACH;AASA,eAAe,cACb,QACA,KACA,QACA,UACe;AACf,QAAM,OAAO,aAAa,KAAK,OAAO,WAAW,OAAO,SAAS;AACjE,QAAM,QAAQ,cAAc,CAAC,KAAK,OAAO,KAAK,SAAS,CAAC;AACxD,MAAI,MAAM,WAAW,EAAG;AACxB,MAAI,CAAC,UAAU;AACb,YAAQ;AAAA,MACN;AAAA,WAAc,OAAO,MAAM,MAAM,CAAC;AAAA,IAEpC;AACA;AAAA,EACF;AACA,QAAM,cAAc,MAAM,gBAAgB,OAAO,CAAC,aAAa,OAAO,cAAc,QAAQ,CAAC;AAC7F,QAAM,YAAY,oBAAoB,WAAW;AACjD,YAAU,MAAM;AAChB,UAAQ;AAAA,IACN;AAAA,WAAc,OAAO,YAAY,MAAM,CAAC;AAAA,EAC1C;AACA,SAAO,YAAY,GAAG,SAAS,MAAM;AACnC,cAAU,KAAK;AAAA,EACjB,CAAC;AACH;AAEA,eAAsB,WAAW,SAAoC;AACnE,MAAI;AACF,UAAM,MAAM,QAAQ,IAAI;AACxB,UAAM,SAAS,MAAM,eAAe,KAAK,OAAO;AAChD,WAAO,UAAU;AAAA,EACnB,SAAS,KAAK;AACZ,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,YAAQ,MAAM;AAAA,WAAS,GAAG;AAAA,CAAI;AAC9B,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/netlify.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Netlify deploy adapter. All paths derived from `cwd` and a fixed\n * `.theokit/netlify/` output layout. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport {\n bundleDeployedFunction,\n type BundleDeployedFunctionOptions,\n} from './bundle-deployed-function.js'\nimport { deployedAgentsFragment, JSON_NOT_FOUND_RESPONSE } from './deployed-agents.js'\nimport { renderBakedRoutes, routeRuntimeLines, type BakedRoute } from './deployed-baked-routes.js'\nimport { type DeployedCorsOptions } from './deployed-cors.js'\nimport { type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport { deployedRateLimitFragment, rateLimitCheckFragment } from './deployed-rate-limit.js'\nimport type { DeployedRateLimitOptions } from './deployed-rate-limit.js'\nimport { deployedReservedRoutesFragment, reservedRouteBranch } from './deployed-reserved-routes.js'\nimport type { DeployedReservedRoutesOptions } from './deployed-reserved-routes.js'\nimport {\n deployedRuntimeConfigFragment,\n type DeployedRuntimeConfigOptions,\n serverDirLiteral,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { buildSecurityHeaders, describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport class NetlifyConflictError extends Error {\n constructor(path: string, currentTo: string) {\n super(\n `netlify.toml has a conflicting redirect: \"${path}\" → \"${currentTo}\". ` +\n `Remove it manually or edit it to point to \"/.netlify/functions/theo\" ` +\n `before running the Netlify adapter again.`,\n )\n this.name = 'NetlifyConflictError'\n }\n}\n\nexport class NetlifyFunctionsConflictError extends Error {\n constructor(key: string, declared: string, required: string) {\n super(\n `netlify.toml declares \\`[functions] ${key} = \"${declared}\"\\`, and this adapter needs ` +\n `\"${required}\". Measured on the Netlify emulator: \\`directory\\` is what makes the generated ` +\n `function discoverable at all (without it the redirect answers \"Function not found\"), and ` +\n `\\`node_bundler = \"none\"\\` is what stops Netlify re-bundling a function theokit already ` +\n `bundled — which produces a SyntaxError. Change the value, or remove the key and let this ` +\n `adapter write it.`,\n )\n this.name = 'NetlifyFunctionsConflictError'\n }\n}\n\nexport interface NetlifyBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeFile?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n readTomlIfExists?: () => string | null\n /**\n * Seam for the bundling step, alongside `runNodeBuild` above.\n *\n * The entry cannot be written as source: it imports `theokit/server/scan` and five sibling\n * sub-paths by bare specifier, and Netlify's own bundler breaks on the result (measured on the\n * emulator — see `the-netlify-function-ships-pre-bundled.test.ts`). Bundling here rather than\n * through `writeFile` is what lets the toml then say `node_bundler = \"none\"`.\n */\n bundleFunction?: (options: BundleDeployedFunctionOptions) => Promise<void>\n}\n\nexport function renderNetlifyFunction(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions &\n DeployedReservedRoutesOptions &\n DeployedServerDirOptions & {\n routes?: readonly BakedRoute[]\n /**\n * The agents, baked at build time — for the same reason the routes are (B-339).\n *\n * Netlify uploads a BUNDLE now, so the runtime scan cannot work here at any value: there is no\n * source tree to read, and `createProductionLoader()` would `import()` a path that was never\n * shipped. Vercel's own comment on this says it best — a fallback \"would preserve a behaviour\n * that is broken by construction: an entry that scans, finds nothing, and answers 404 while\n * looking like it tried.\"\n */\n agents?: readonly { filePath: string; agentPath: string; name: string }[]\n contextModule?: string\n } = {},\n): string {\n // B-338 — the routes are baked, not scanned. The scan was a `readdirSync` over the server directory,\n // and on the Netlify emulator it FOUND `src/server/routes/health.ts` and answered 500\n // `SyntaxError: Unexpected token ')'` — a TypeScript source a plain JS runtime cannot compile. On a real\n // deploy it finds nothing at all, because Netlify uploads the bundled function. The fix B-319 made for\n // Vercel and #369 for Cloudflare, on the fourth target; the emitter is shared and its own docblock says\n // \"the target only supplies what its own error message says\".\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n // B-235. Netlify's handler is `(request, context)` and already RECEIVES a Web `Request`, which\n // is the shape this branch needs — the item filed against it counted `new Request` occurrences\n // and concluded the opposite, measuring how the entry OBTAINS a request rather than whether it\n // has one. It used to take `scannedFromLoaderCache` with Deno as the model — same `loaderCache`,\n // same filesystem `serverDir`. That stopped being right when this target began bundling: the\n // emitted `if (!loaderCache) loaderCache = createProductionLoader()` referenced two names the\n // host no longer declared, which is a ReferenceError on the first /api/agents/<name> request and\n // is what `a-generated-entry-declares-every-identifier.test.ts` was written to catch.\n const agentsFragment = deployedAgentsFragment(\n { kind: 'baked', agents: opts.agents ?? [], contextModule: opts.contextModule },\n {\n // Netlify answers its own 404 inline rather than through a helper, so the fragment is given\n // the expression instead of a call it would have to declare.\n notFound: `new Response('Not Found', { status: 404 })`,\n },\n )\n return [\n `// Generated by Theo — Netlify Functions adapter`,\n `import { resolve } from 'node:path'`,\n `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`,\n ...routeImports,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `const cwd = process.cwd()`,\n // B-338 — was `resolve(cwd, 'server')`, a literal. A project declaring `src/server` got a function\n // scanning a directory that does not exist, and every `/api/*` answered 404 — measured on the Netlify\n // emulator. The FOURTH target with this shape: B-185 (bun, deno), B-235 (agentsDir here), B-315\n // (vercel, aws-lambda, cloudflare), and this file's own call site already names two of them.\n `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries, 'netlify'),\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed function has no`,\n `// theo.config.ts to read. The netlify.toml redirect routes only /api/* here,`,\n `// so this covers the API and not the document Netlify's static host serves`,\n `// (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(\n runtimeConfig,\n agentsFragment,\n opts,\n 'netlify',\n deployedReservedRoutesFragment(opts),\n ),\n ``,\n // B-027 — emitted only when a limit is declared.\n ...(opts.rateLimit === undefined\n ? []\n : [\n // B-338 — the sub-path, not the umbrella. The umbrella re-exports the whole server half and\n // @swc/core's native .node addon is down that graph; the guard against it could not see this\n // adapter, because the shared comment stripper read this file's \"/*\" redirect glob as a\n // comment opener and deleted 36% of it before the sweep looked.\n `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ``,\n ]),\n ...deployedRateLimitFragment(\n opts.rateLimit,\n 'netlify',\n // `context.ip` is the platform's own answer, read from the handler context Netlify passes.\n // The forwarded fallback covers a function shape that carries no context, and returns\n // `undefined` unless a `trustProxy` was declared — which is the named 503, not a shared key.\n `context?.ip ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n // Both names are bound in the OUTER handler, which is where the check runs. Threading\n // `context` into `handleRequest` — which the plan called for — buys nothing: the limiter\n // never runs in there.\n 'request, context',\n ),\n ``,\n `export default async (request, context) => {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(opts.rateLimit, ' ', 'request, context'),\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n `}`,\n ``,\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ...reservedRouteBranch('url.pathname', ' '),\n ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,\n ` return new Response('Not Found', { status: 404 })`,\n ` }`,\n ``,\n\n ``,\n ...agentsFragment.branch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ` if (!match) return ${JSON_NOT_FOUND_RESPONSE}`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is not awaited: toResponse() settles at the headers and`,\n ` // carries a live body, so Netlify streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeConfig.executeRouteSpread} }))`,\n `}`,\n ].join('\\n')\n}\n\nconst THEO_REDIRECT_FROM = '/api/*'\nconst THEO_REDIRECT_TO = '/.netlify/functions/theo'\n\n/**\n * TOML merge (EC-2) — non-destructive.\n *\n * We avoid adding a TOML parser dependency by working at the line level. The\n * supported subset is sufficient for the Netlify use case:\n * - detect existing `[[redirects]]` blocks\n * - find a block whose `from = \"...\"` matches our target\n * - error if such a block points elsewhere\n * - otherwise append our block\n *\n * Unknown sections (e.g. `[build]`, `[[headers]]`, `[context.production.environment]`)\n * are preserved as-is.\n */\ninterface NetlifyRedirectBlock {\n startLine: number\n endLine: number\n from?: string\n to?: string\n}\n\nfunction parseRedirectBlocks(lines: readonly string[]): NetlifyRedirectBlock[] {\n const blocks: NetlifyRedirectBlock[] = []\n let current: NetlifyRedirectBlock | null = null\n\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i].trim()\n if (trimmed === '[[redirects]]') {\n if (current) {\n current.endLine = i - 1\n blocks.push(current)\n }\n current = { startLine: i, endLine: i }\n continue\n }\n if (current && /^\\[(\\[|[^[])/.test(trimmed)) {\n // Entering another section — close current.\n current.endLine = i - 1\n blocks.push(current)\n current = null\n }\n if (current) {\n const fromMatch = /^from\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (fromMatch) current.from = fromMatch[1]\n const toMatch = /^to\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (toMatch) current.to = toMatch[1]\n current.endLine = i\n }\n }\n if (current) blocks.push(current)\n return blocks\n}\n\n/**\n * The `[functions]` keys this adapter requires, and why each one is not optional.\n *\n * `directory` — measured on the Netlify emulator 2026-09-29: without it the CLI scans its default\n * `netlify/functions/`, finds nothing, and `/api/*` answers `Function not found...` with a 404. The\n * adapter writes to `.netlify/functions/` deliberately (generated output belongs in an ignored\n * directory, not in the source tree the project commits), so the location has to be declared.\n *\n * `node_bundler` — the entry is already bundled here. Netlify re-bundling it produced\n * `SyntaxError: Invalid left-hand side in assignment`.\n */\nconst THEO_FUNCTIONS_DIR = '.netlify/functions'\nconst THEO_FUNCTION_NAME = 'theo'\nconst THEO_FUNCTIONS_KEYS: readonly (readonly [string, string])[] = [\n ['directory', THEO_FUNCTIONS_DIR],\n ['node_bundler', 'none'],\n]\nconst THEO_FUNCTIONS_TARGET = [\n '[functions]',\n ...THEO_FUNCTIONS_KEYS.map(([key, value]) => ` ${key} = \"${value}\"`),\n].join('\\n')\n\nconst THEO_REDIRECT_TARGET = [\n '[[redirects]]',\n ' from = \"/api/*\"',\n ' to = \"/.netlify/functions/theo\"',\n ' status = 200',\n ' force = true',\n].join('\\n')\n\n/**\n * The client router's fallback: a path that no file and no earlier rule answers gets the document.\n *\n * #949 — measured 2026-10-03 on Netlify production: `GET /about` answered 404 while the same build\n * answered 200 on Vercel and Cloudflare (whose `wrangler.toml` carries `not_found_handling =\n * \"single-page-application\"` for this). Unforced, so a real file such as `/assets/*.js` still wins,\n * and appended after `/api/*` because Netlify applies the first rule that matches.\n */\nconst THEO_SPA_FALLBACK_FROM = '/*'\nconst THEO_SPA_FALLBACK_TARGET = [\n '[[redirects]]',\n ' from = \"/*\"',\n ' to = \"/index.html\"',\n ' status = 200',\n].join('\\n')\n\n/**\n * #1097 — the reserved routes the function answers. No file matches them, so without this rule\n * they reached the SPA fallback and were answered with the document.\n */\nconst THEO_RESERVED_FROM = '/__theo/*'\nconst THEO_RESERVED_TARGET = [\n '[[redirects]]',\n ` from = \"${THEO_RESERVED_FROM}\"`,\n ` to = \"${THEO_REDIRECT_TO}\"`,\n ' status = 200',\n ' force = true',\n].join('\\n')\n\n/**\n * Add the reserved-routes rule unless one exists, AHEAD of any `/*` rule: Netlify applies the\n * first rule that matches, so a rule appended after a project's own fallback would never fire.\n */\nfunction withReservedRoutesRedirect(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const blocks = parseRedirectBlocks(lines)\n if (blocks.some((b) => b.from === THEO_RESERVED_FROM)) return source\n const fallback = blocks.find((b) => b.from === THEO_SPA_FALLBACK_FROM)\n if (fallback === undefined) {\n const sep = source.endsWith('\\n') ? '' : '\\n'\n return `${source}${sep}\\n${THEO_RESERVED_TARGET}\\n`\n }\n return [\n ...lines.slice(0, fallback.startLine),\n THEO_RESERVED_TARGET,\n '',\n ...lines.slice(fallback.startLine),\n ].join('\\n')\n}\n\n/** Append the fallback unless some `/*` rule exists — the project's own wins. */\nfunction withSpaFallback(source: string): string {\n const declared = parseRedirectBlocks(source.split(/\\r?\\n/)).some(\n (b) => b.from === THEO_SPA_FALLBACK_FROM,\n )\n if (declared) return source\n const sep = source.endsWith('\\n') ? '' : '\\n'\n return `${source}${sep}\\n${THEO_SPA_FALLBACK_TARGET}\\n`\n}\n\n/**\n * Marks the block this build owns, so it can be REGENERATED rather than merely not duplicated.\n *\n * Idempotence alone would be the wrong contract here: the block carries configuration, so a\n * `security.headers` change has to reach the file. Leaving an existing block in place — which is\n * what the redirect above correctly does, because its content is fixed — would silently pin the\n * baseline to whatever the first build emitted.\n */\nconst THEO_HEADERS_MARKER = '# Generated by Theo — security baseline (usetheokit/theokit#412)'\n\n/**\n * The `[[headers]]` block telling Netlify's static host the baseline.\n *\n * The emitted function applies these to every response IT returns, and it never returns the HTML\n * document: the `[[redirects]]` block routes only `/api/*`, so the page comes from Netlify's static\n * host and carried none of them. The values come from `buildSecurityHeaders` — the same function\n * the handler calls — rather than being written out here, because two lists of headers that must\n * agree are two lists that eventually do not.\n */\nfunction renderHeadersBlock(securityHeaders: SecurityHeadersConfig | undefined): string {\n const values = buildSecurityHeaders(securityHeaders ?? {}, { production: true })\n return [\n THEO_HEADERS_MARKER,\n '[[headers]]',\n ' for = \"/*\"',\n ' [headers.values]',\n ...Object.entries(values).map(([k, v]) => ` ${k} = ${JSON.stringify(v)}`),\n ].join('\\n')\n}\n\n/**\n * Drop a previously generated block, so the next one replaces it.\n *\n * Bounded by the marker and the next top-level section at column 0 (or EOF) — the shape TOML gives\n * a block. A user's own `[[headers]]` is untouched because it does not carry the marker: their\n * file, their rules, and Netlify applies both.\n */\nfunction withoutGeneratedHeaders(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const start = lines.indexOf(THEO_HEADERS_MARKER)\n if (start < 0) return source\n\n const opensSection = (line: string | undefined): boolean => (line ?? '').startsWith('[')\n\n let end = start + 1\n while (end < lines.length && !opensSection(lines[end])) end += 1\n // The marker line itself opens the block, so `end` now sits on the NEXT section — but the block's\n // own `[[headers]]` is the first `[` after the marker, so step past it before scanning again.\n end += 1\n while (end < lines.length && !opensSection(lines[end])) end += 1\n\n return [...lines.slice(0, start), ...lines.slice(end)].join('\\n').replace(/\\n{3,}/gu, '\\n\\n')\n}\n\n/**\n * Declare the `[functions]` keys this adapter requires, without emitting a second table.\n *\n * A duplicate table is a TOML parse error, so this is not tidiness: a project that already declares\n * `[functions]` for `directory`, `included_files` or `external_node_modules` must keep it and gain\n * one key. Line-level like the rest of this merge, and for the same reason — no TOML parser\n * dependency. `[functions.\"name\"]` is a DIFFERENT table and is left alone, which is why the match\n * is exact rather than a prefix.\n *\n * An explicit conflicting value is refused rather than overwritten, on the same argument\n * `NetlifyConflictError` makes about a `/api/*` redirect pointing elsewhere: it is a deliberate\n * declaration, and silently replacing it breaks their build for a reason nothing states.\n */\n/**\n * Read a TOML scalar exactly as written, with no parser.\n *\n * Neither \"strip the quotes\" nor \"cut at the first #\" is correct alone: TOML allows an inline\n * comment after a value, and a `#` INSIDE a quoted value is legal. Stripping quotes alone read\n * `node_bundler = \"none\" # keep` as `none\" # keep` and refused a legal file; cutting at `#` alone\n * would mangle `directory = \"a#b\"`. Both cases are asserted, in both directions, in\n * `the-netlify-function-ships-pre-bundled.test.ts`.\n */\nfunction readTomlScalar(raw: string): string {\n for (const quote of ['\"', \"'\"]) {\n if (!raw.startsWith(quote)) continue\n const close = raw.indexOf(quote, 1)\n return close < 0 ? raw.slice(1) : raw.slice(1, close)\n }\n const hash = raw.indexOf('#')\n return (hash < 0 ? raw : raw.slice(0, hash)).trim()\n}\n\n/**\n * The value a key carries inside one table's line range, or `null` when the table does not set it.\n *\n * Split rather than matched: the rest of this merge is line-level by design, and a regex with `\\s*`\n * either side of a lazy group backtracks (sonarjs/slow-regex) for no gain here. A commented-out\n * `# node_bundler = …` reads as the key `# node_bundler`, which matches nothing — correct, and free.\n */\nfunction declaredIn(\n lines: readonly string[],\n from: number,\n to: number,\n key: string,\n): string | null {\n for (let i = from; i < to; i += 1) {\n const line = lines[i] ?? ''\n const eq = line.indexOf('=')\n if (eq < 0 || line.slice(0, eq).trim() !== key) continue\n return readTomlScalar(line.slice(eq + 1).trim())\n }\n return null\n}\n\nfunction withFunctionsDeclared(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const at = lines.findIndex((line) => line.trimEnd() === '[functions]')\n\n if (at < 0) {\n const sep = source.endsWith('\\n') ? '' : '\\n'\n return `${source}${sep}\\n${THEO_FUNCTIONS_TARGET}\\n`\n }\n\n let end = at + 1\n while (end < lines.length && !(lines[end] ?? '').startsWith('[')) end += 1\n\n const missing: string[] = []\n for (const [key, required] of THEO_FUNCTIONS_KEYS) {\n const declared = declaredIn(lines, at + 1, end, key)\n if (declared === null) {\n missing.push(` ${key} = \"${required}\"`)\n continue\n }\n if (declared !== required) throw new NetlifyFunctionsConflictError(key, declared, required)\n }\n\n if (missing.length === 0) return source\n return [...lines.slice(0, at + 1), ...missing, ...lines.slice(at + 1)].join('\\n')\n}\n\nexport function mergeNetlifyToml(\n existing: string | null,\n securityHeaders?: SecurityHeadersConfig,\n): string {\n const headersBlock = renderHeadersBlock(securityHeaders)\n\n if (existing === null || existing.trim().length === 0) {\n return withFunctionsDeclared(\n withSpaFallback(withReservedRoutesRedirect(`${THEO_REDIRECT_TARGET}\\n\\n${headersBlock}\\n`)),\n )\n }\n\n existing = withoutGeneratedHeaders(existing)\n\n const blocks = parseRedirectBlocks(existing.split(/\\r?\\n/))\n\n // Detect conflict: every `/api/*` block must point at our function.\n for (const b of blocks) {\n if (b.from !== THEO_REDIRECT_FROM) continue\n if (b.to === THEO_REDIRECT_TO) {\n // The redirect is already there. The headers block is regenerated regardless, because it\n // carries configuration and the redirect does not.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return withFunctionsDeclared(\n withSpaFallback(withReservedRoutesRedirect(`${existing}${sep}\\n${headersBlock}\\n`)),\n )\n }\n throw new NetlifyConflictError(b.from, b.to ?? '(unknown)')\n }\n\n // No conflict — append target block.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return withFunctionsDeclared(\n withSpaFallback(\n withReservedRoutesRedirect(`${existing}${sep}\\n${THEO_REDIRECT_TARGET}\\n\\n${headersBlock}\\n`),\n ),\n )\n}\n\n/**\n * Resolve the build's effective dependencies once.\n *\n * Extracted when `buildNetlify` crossed the complexity ceiling after B-339 added a fifth seam. The\n * defaults are a separate concern from the build's sequence (SRP), and the sequence is the part a\n * reader comes here to follow.\n */\nfunction resolveNetlifyDeps(\n cwd: string,\n deps: NetlifyBuildDeps,\n): {\n runNodeBuild: NonNullable<NetlifyBuildDeps['runNodeBuild']>\n writeFile: NonNullable<NetlifyBuildDeps['writeFile']>\n ensureDir: NonNullable<NetlifyBuildDeps['ensureDir']>\n readTomlIfExists: NonNullable<NetlifyBuildDeps['readTomlIfExists']>\n bundleFunction: NonNullable<NetlifyBuildDeps['bundleFunction']>\n} {\n return {\n runNodeBuild: deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter),\n writeFile:\n deps.writeFile ??\n ((path, content) => {\n writeFileSync(path, content)\n }),\n ensureDir: deps.ensureDir ?? ((path: string) => mkdirSync(path, { recursive: true })),\n readTomlIfExists:\n deps.readTomlIfExists ??\n (() => {\n const path = resolve(cwd, 'netlify.toml')\n return existsSync(path) ? readFileSync(path, 'utf-8') : null\n }),\n bundleFunction: deps.bundleFunction ?? bundleDeployedFunction,\n }\n}\n\nexport async function buildNetlify(\n config: TheoConfig,\n cwd: string,\n deps: NetlifyBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('netlify', readManifest(cwd))\n\n const { runNodeBuild, writeFile, ensureDir, readTomlIfExists, bundleFunction } =\n resolveNetlifyDeps(cwd, deps)\n\n const merged = mergeNetlifyToml(readTomlIfExists(), config.security?.headers)\n\n await runNodeBuild(config, cwd, ctx)\n\n const scanned = ctx?.scanRoutes?.(config.serverDir)\n\n const fnDir = resolve(cwd, THEO_FUNCTIONS_DIR)\n ensureDir(fnDir)\n // B-339 — bundled, not written as source. The entry imports `theokit/server/scan` and five\n // sibling sub-paths by bare specifier; Netlify's own bundler produced a `ReferenceError` on\n // an identifier that was base64 of the source, and re-bundled an already-bundled file into a\n // `SyntaxError`. Measured on the emulator: bundled here plus `node_bundler = \"none\"` below,\n // `GET /api/health` answers 200. Cloudflare and Vercel already bundle; this was the target\n // shipping raw source and trusting the platform to resolve it.\n await bundleFunction({\n projectRoot: cwd,\n entrySource: renderNetlifyFunction({\n routes: scanned?.routes,\n // B-339 — from the same scan as the routes, for the same reason: this target bundles, so a\n // runtime agents scan has no source tree to read.\n agents: scanned?.agents,\n contextModule: scanned?.contextModule,\n securityHeaders: config.security?.headers,\n // B-235 wired `agentsDir` through to this renderer, and B-339 made it unreadable here: the\n // agents are baked from the BUILD's scan now, so the entry never resolves a directory. An\n // option a renderer accepts and ignores is the defect `rules/foreign-config-surfaces.md` is\n // about, so it is dropped rather than left looking wired. The scan the build performs still\n // honours `config.agentsDir` — that is where the option belongs.\n // B-338 — the same pillar as the comment above, one option over. The sweep in\n // `every-deployed-entry-is-told-its-server-dir.test.ts` could not see this adapter: its\n // population was the adapters that CALL `serverDirLiteral(opts)`, so the one that never\n // adopted it was outside the population the case iterates.\n serverDir: config.serverDir,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #1097 — a probe cannot ride as a literal; the entry fails `/__theo/ready` closed instead.\n readyProbeDeclared: config.ready !== undefined,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n }),\n stagePath: '.theokit/netlify/entry.mjs',\n // A DIRECTORY, not a bare file. The bundler code-splits: this project emitted `theo.mjs` plus\n // 40 chunks under `assets/`, which `theo.mjs` imports. Netlify zips a directory-shaped function\n // whole, so the chunks travel; a bare `theo.mjs` with a sibling `assets/` loads in `netlify dev`\n // (it reads from disk) and would reach a deploy without them. Vercel already uses a dedicated\n // `functions/api.func` for the same reason.\n outDir: resolve(fnDir, THEO_FUNCTION_NAME),\n entryFileName: `${THEO_FUNCTION_NAME}.mjs`,\n })\n\n writeFile(resolve(cwd, 'netlify.toml'), merged)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(`\\n ✓ Netlify output → ${THEO_FUNCTIONS_DIR}/${THEO_FUNCTION_NAME}/ + netlify.toml`)\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'netlify',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-configured',\n })}\\n`,\n )\n}\n\nexport const netlifyAdapter: DeployAdapter = {\n // B-339 / B-341 / B-343 — measured on the Netlify emulator. Its own bundler turned the raw\n // source into a `ReferenceError`, and re-bundled an already-bundled file into a `SyntaxError`;\n // the toml declares `node_bundler = \"none\"` so the bundle this adapter produces ships intact.\n readsSourceAtRunTime: false,\n specifiersResolvedBy: 'this-adapter',\n name: 'netlify',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this function returns.\n // The document is served by Netlify's static host and does not pass through\n // it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n build(config, cwd, ctx) {\n return buildNetlify(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AA8BjB,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAAY,MAAc,WAAmB;AAC3C;AAAA,MACE,6CAA6C,IAAI,aAAQ,SAAS;AAAA,IAGpE;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YAAY,KAAa,UAAkB,UAAkB;AAC3D;AAAA,MACE,uCAAuC,GAAG,OAAO,QAAQ,gCACnD,QAAQ;AAAA,IAKhB;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAkBO,SAAS,sBACd,OAkBM,CAAC,GACC;AAOR,QAAM,EAAE,cAAc,oBAAoB,kBAAkB,IAAI;AAAA,IAC9D,KAAK,UAAU,CAAC;AAAA,EAClB;AACA,QAAM,gBAAgB,8BAA8B,IAAI;AASxD,QAAM,iBAAiB;AAAA,IACrB,EAAE,MAAM,SAAS,QAAQ,KAAK,UAAU,CAAC,GAAG,eAA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