/** * The build-independent half of sprout compilation: the binding/trigger wrapper * that turns a user's `export default { fetch }` into a native-fetch module, plus * the `Bindings` shape and the `SPROUTBOAT_*_JSON` env readers. * * This module has no imports on purpose — the monorepo consumes it via the * `sproutboat/runtime/wrap` export to drive its own (host-native, non-musl) * compile path without pulling in `toolchain.ts` / `patch-porffor.ts`. */ /** The prelude file (Web API shims + broker binding shim + trigger dispatcher). * It is read as text and string-prepended before Porffor sees it, never * imported — callers do `readFile(preludePath, "utf8")`. */ export const preludePath = new URL("./native-fetch-prelude.js", import.meta.url); /** * #15 — the two transports the prelude can be built with. * * Both define `__sbCall(reqJson) -> replyJson` and nothing else; every binding * shim above that line is identical, which is what lets one conformance suite * hold both honest. `broker` talks to the per-deployment broker over loopback * (deployed, dev, phase-0 standalone); `embedded` compiles SQLite into the * sprout and needs no second process at all. */ export type Transport = "broker" | "embedded"; export const transportPath = (transport: Transport): URL => new URL(transport === "embedded" ? "./transport-embedded.js" : "./transport-broker.js", import.meta.url); /** Where the prelude expects its transport spliced in. */ export const TRANSPORT_MARKER = "// TRANSPORT: wrap.ts splices one of transport-broker.js / transport-embedded.js here."; // The server honours $PORT at runtime (patches/porffor-render.patch); this baked // value is only a fallback for a directly-run binary. const DEFAULT_PORT = 8080; /** * What an artifact with no `compatibilityDate` means. Artifacts built before * the field existed keep the semantics of that day forever, because the binary * is immutable and `rollback` can reactivate it at any time. * * How to use it: when a runtime behaviour has to change in a way that would * break a deployed handler, don't change it unconditionally — gate it in the * prelude on `__sbCompat >= "YYYY-MM-DD"` (ISO dates compare correctly as * strings) and document the flip date. Old binaries carry their old date and * keep the old behaviour; a project opts in by moving `compatibility_date` in * its `sproutboat.jsonc` and rebuilding. */ export const BASELINE_COMPATIBILITY_DATE = "2026-08-26"; /** * Binding names a project declares. `do` maps a binding name to a Durable Object * class name; `crons` are schedule expressions with no name. */ export type Bindings = { kv: string[]; secrets: string[]; d1: string[]; r2: string[]; queues: string[]; /** Each queue binding's queue name and consumer settings (`queueSettings` in * @sproutboat/config). Absent from older artifacts: every queue is then named by its * binding, with the default settings. */ queueConfig?: QueueSettings[]; analytics: string[]; do: Array<{ binding: string; className: string }>; /** #48 — worker-to-worker: binding name -> the project it calls. The hostname * it resolves to is a runtime input, not part of the artifact. */ services: Array<{ binding: string; service: string }>; crons: string[]; /** #69 — rate limiters: `env..limit({ key }) -> { success }`, a * fixed window of `limit` calls per `period` seconds, per key. */ ratelimiters: Array<{ binding: string; limit: number; period: number }>; /** Static-asset binding name for `env..fetch(request)`; `""` when assets are edge-only. */ assets: string; }; /** One queue binding's name and consumer settings; unset settings are absent. */ export type QueueSettings = { binding: string; queue: string; maxBatchSize?: number; maxBatchTimeout?: number; maxRetries?: number; retryDelay?: number; deadLetterQueue?: string; }; export const EMPTY_BINDINGS: Bindings = { kv: [], secrets: [], d1: [], r2: [], queues: [], analytics: [], do: [], services: [], crons: [], ratelimiters: [], assets: "", }; /** A default export something can invoke: fetch(), scheduled(), queue(), or a WorkerEntrypoint (RPC). */ export function hasEntryHandler(source: string): boolean { return /\b(fetch|scheduled|queue)\s*\(/.test(source) || /\bextends\s+WorkerEntrypoint\b/.test(source); } function hasBindings(b: Bindings): boolean { return ( b.kv.length > 0 || b.secrets.length > 0 || b.d1.length > 0 || b.r2.length > 0 || b.queues.length > 0 || b.analytics.length > 0 || b.do.length > 0 || b.services.length > 0 || b.ratelimiters.length > 0 || b.assets !== "" ); } /** * Turn the module's exports into plain top-level declarations, so the handler * object is reachable as `__sbHandlers` and Durable Object classes stay * addressable by name. * * Two shapes reach us. A hand-written file exports inline * (`export default { fetch }`), while a bundled one declares everything first * and re-exports at the end (`export { src_default as default, Counter }`) — * #89 made the second shape the normal case. Returns null when neither matches. */ /** * `cloudflare:workers` is not a module here: WorkerEntrypoint, DurableObject, RpcTarget * and env are globals the prelude defines. Each import of it becomes a destructuring * of globalThis, `as` renames included, so the handler's names still resolve. The CLI * leaves the specifier external for this. */ export function inlineWorkersImports(source: string): string { // `cloudflare:sockets` (compatibility date 2026-11-17): connect() lives on a prelude global. // postgres/cf loads it lazily: `await import("cloudflare:sockets")`. source = source.replace(/\bimport\(\s*["'`]cloudflare:sockets["'`]\s*\)/g, "Promise.resolve(globalThis.__sbSockets)"); // The dynamic form of cloudflare:workers (Alchemy: `import("cloudflare:workers").catch(() => ({ env: {} }))`) // resolves to a namespace of the same four names the static form can destructure. Read when the // import runs, so a handler that imports at module top level sees the env the tail already set. source = source.replace( /\bimport\(\s*["'`]cloudflare:workers["'`]\s*\)/g, "Promise.resolve({ env: globalThis.env, WorkerEntrypoint: globalThis.WorkerEntrypoint, DurableObject: globalThis.DurableObject, RpcTarget: globalThis.RpcTarget })", ); source = source.replace( /^import\s*\{([^}]*)\}\s*from\s*["']cloudflare:sockets["'];?[ \t]*$/gm, (_match, names: string) => { const pairs = names .split(",") .map((part) => part.trim()) .filter(Boolean) .map((part) => part.replace(/^(\S+)\s+as\s+(\S+)$/, "$1: $2")); return `const { ${pairs.join(", ")} } = globalThis.__sbSockets;`; }, ); return source.replace( /^import\s*\{([^}]*)\}\s*from\s*["']cloudflare:workers["'];?[ \t]*$/gm, (_match, names: string) => { const pairs = names .split(",") .map((part) => part.trim()) .filter(Boolean) .map((part) => part.replace(/^(\S+)\s+as\s+(\S+)$/, "$1: $2")); return `const { ${pairs.join(", ")} } = globalThis;`; }, ); } /** What `import.meta.url` is in a compiled app: a stable name, as in workerd, never the build machine's path. */ export const IMPORT_META_URL = "file:///bundle/index.js"; const HAS_IMPORT_META = /(? { used = true; return "__sbImportMeta"; }; const out = body.replace(IMPORT_META_SCAN, (match) => { if (match.startsWith("import")) return use(); // `...${import.meta.url}...`: only the interpolations are code. if (match[0] === "`") return match.replace(/\$\{[^}]*\}/g, (part) => part.replace(IMPORT_META, use)); return match; }); if (!used) return body; const url = JSON.stringify(IMPORT_META_URL); return `const __sbImportMeta = { url: ${url}, main: true, resolve(specifier) { return new URL(String(specifier), ${url}).href; } };\n${out}`; } export function neutraliseExports(source: string): string | null { // `export default class Name extends WorkerEntrypoint {`: the class is the handler. if (/^\s*export\s+default\s+class\b/m.test(source)) { return source .replace(/^(\s*)export\s+default\s+class\b/m, "$1const __sbHandlers = class") .replace(/^export\s+(async\s+function|function|class|const|let|var)\b/gm, "$1"); } if (/\bexport\s+default\s*\{/.test(source)) { return source .replace(/^(\s*)export\s+default\s*/m, "$1const __sbHandlers = ") .replace(/^export\s+(async\s+function|function|class|const|let|var)\b/gm, "$1"); } // Not anchored to a line: a minified bundle puts the whole module on one // line. Bundlers emit exactly one such block, at the end. const blocks = [...source.matchAll(/export\s*\{([^}]*)\}\s*;?/g)]; const block = blocks[blocks.length - 1]; if (block === undefined) return null; let handler: string | null = null; const aliases: string[] = []; for (const entry of block[1] .split(",") .map((part) => part.trim()) .filter(Boolean)) { const parts = entry.match(/^(\S+)(?:\s+as\s+(\S+))?$/); if (parts === null) continue; const local = parts[1]; const exported = parts[2] ?? local; if (exported === "default") handler = local; // `export { Counter as Counter }` needs no alias; a renamed one does, so // `durable_objects` in the config can still name the class it expects. else if (exported !== local) aliases.push(`const ${exported} = ${local};`); } if (handler === null) return null; return source.replace(block[0], [`const __sbHandlers = ${handler};`, ...aliases].join("\n")); } /** * Build the final native-fetch module: the prelude (Web API shims + the broker * binding shim + the trigger dispatcher), then `const env = {…}` with the baked * `vars`, then — if any binding is declared — one `__sbInstallBindings(env, …)` * line, then the user's source with its `export` keywords neutralised (so its * `export default {…}` becomes a plain object we can hand to the dispatcher), * then our single `export default { fetch }` that routes every request through * `__sbEntry` (HTTP → `handlers.fetch`; `x-sb-trigger` → scheduled / queue / DO). * * With no bindings and no `scheduled`/`queue`/DO the output behaves exactly like * a plain `export default { fetch }` sprout. * * `port` is only the baked fallback in `export default { port }`; the runtime * reads `$PORT` first. The monorepo's bench path overrides it. * * ponytail: the sprout process is long-lived, so a handler that mutates `env` * leaks that change to later requests. Freeze upstream once Porffor supports * Object.freeze in native mode. */ /** * What a handler needs of crypto.subtle: `"always"` (the default for the embedded transport) leaves the prelude as it is, which * is what a shared template needs (sproutd compiles apps against one prelude). `"auto"` drops the * workerd-style crypto.subtle (its JavaScript, and the BearSSL and Monocypher C behind it) from a * handler whose source never mentions `subtle`, `DigestStream` or `CryptoKey`: such a handler cannot * reach it, and the code is about 330 KB of a 5.3 MB standalone binary and about 2 s of its build. * A handler that reaches crypto.subtle without naming it (a computed property name) gets the * digest/HMAC/PBKDF2 subset that earlier dates have. */ export type SubtleMode = "always" | "auto"; const SUBTLE_BLOCKS: Array<[string, string]> = [ ["// SUBTLE-JS:BEGIN", "// SUBTLE-JS:END"], ["// SUBTLE:BEGIN", "// SUBTLE:END"], ]; /** The prelude without workerd-style crypto.subtle. Throws if a marker is missing: a silent no-op would ship the code. */ export function pruneSubtle(prelude: string): string { let out = prelude; for (const [begin, end] of SUBTLE_BLOCKS) { const start = out.indexOf(begin); const stop = out.indexOf(end, start); if (start < 0 || stop < 0) { throw new Error(`the prelude has no ${begin} ... ${end} block to prune`); } out = out.slice(0, start) + out.slice(out.indexOf("\n", stop) + 1); } return out; } export const reachesSubtle = (source: string) => /\b(?:subtle|DigestStream|CryptoKey)\b/.test(source); export function wrapNativeFetchHandler( source: string, prelude: string, vars: Record = {}, bindings: Bindings = EMPTY_BINDINGS, port: number = DEFAULT_PORT, compatibilityDate: string = BASELINE_COMPATIBILITY_DATE, appName: string = "app", /** #15 — assets baked into the module for a binary that has no files beside it. */ assets?: { manifest: unknown; files: Record }, /** The selected transport determines whether the direct-transfer C ABI is real or stubbed. */ transport: Transport = "broker", /** * #126 — `env. = { id, tag, timestamp }`. Baked at build time from the * artifact digest, like `vars`: the control plane's own deployment id is a * separate, later-assigned thing (minted at upload), so this is the artifact's * own self-describing identity rather than a broker round trip. */ versionMetadata?: { binding: string; id: string; tag: string; timestamp: string }, subtle?: SubtleMode, ): string { // The shared template (sproutd) is the embedded transport and needs it all; a broker build links BearSSL only for // a handler that uses crypto.subtle (the CLI does that), so it defaults to pruning. // A prelude without the block (a test stub) is left alone; prune.test.ts holds the real one to it. if ( (subtle ?? (transport === "embedded" ? "always" : "auto")) === "auto" && !reachesSubtle(source) && prelude.includes("// SUBTLE-JS:BEGIN") ) prelude = pruneSubtle(prelude); const neutralised = neutraliseExports(inlineWorkersImports(source)); // A WorkerEntrypoint may serve only RPC, and a Worker only scheduled() or queue(), with // no fetch() at all, as in workerd. if (neutralised === null || !hasEntryHandler(source)) { throw new Error( "handler must default-export an object with a fetch(request), scheduled() or queue() method, or a WorkerEntrypoint class", ); } const env = `const env = ${JSON.stringify(vars)};\nglobalThis.env = env;\n__sbSetEnv(env);\n`; const versionMetadataLine = versionMetadata ? `env[${JSON.stringify(versionMetadata.binding)}] = ${JSON.stringify({ id: versionMetadata.id, tag: versionMetadata.tag, timestamp: versionMetadata.timestamp, })};\n` : ""; // Baked, not a binding: the date belongs to the artifact, and a handler must // not be able to change the semantics it was compiled against at runtime. const compat = `globalThis.__sbCompat = ${JSON.stringify(compatibilityDate)};\n` + `__sbSetCompat(${JSON.stringify(compatibilityDate)});\n` + // #15 — the embedded transport derives its default data directory from this. `globalThis.__sbAppName = ${JSON.stringify(appName)};\n` + (assets ? `globalThis.__sbAssets = ${JSON.stringify(assets)};\n` : ""); // The native transfer hook runs before JavaScript receives its Request. It // has a real file-backed implementation only in embedded builds. The broker // transport supplies ABI-compatible stubs because its separate transfer // listener owns these URLs, while the shared uWebSockets patch is global. const nativeTransferAbi = transport === "embedded" ? `Porffor.c\`const char* sb_standalone_app_name(void) { return ${JSON.stringify(appName)}; }\`;\n` : 'Porffor.c`typedef struct sb_r2_transfer_ctx { int unused; } sb_r2_transfer_ctx; int sb_r2_transfer_open(const char* a, const char* b, size_t c, sb_r2_transfer_ctx** d) { if (d) *d = 0; return 404; } int sb_r2_transfer_write(sb_r2_transfer_ctx* a, const char* b, size_t c) { return 404; } int sb_r2_transfer_finish(sb_r2_transfer_ctx* a) { return 404; } void sb_r2_transfer_abort(sb_r2_transfer_ctx* a) {} int sb_r2_transfer_download_open(const char* a, const char* b, sb_r2_transfer_ctx** c) { if (c) *c = 0; return 404; } size_t sb_r2_transfer_download_size(sb_r2_transfer_ctx* a) { return 0; } const char* sb_r2_transfer_download_etag(sb_r2_transfer_ctx* a) { return ""; } size_t sb_r2_transfer_download_read(sb_r2_transfer_ctx* a, size_t b, char* c, size_t d) { return 0; } void sb_r2_transfer_download_close(sb_r2_transfer_ctx* a) {}`;\n'; // #174 — fetch() needs no binding: every sprout gets it. const wire = "__sbInstallFetch();\n" + (hasBindings(bindings) ? `__sbInstallBindings(env, ${JSON.stringify(bindings)});\n` : ""); const registerDO = bindings.do.length ? `__sbRegisterDO({ ${bindings.do.map((d) => `${d.className}: ${d.className}`).join(", ")} });\n` : ""; // Cron / queue / alarm timers, for a transport that has no broker to deliver // them. The broker transport defines this as a no-op, so the emitted module // is the same either way. // A Worker with crons and no other binding needs them too (B22): its crons never ran. const triggers = hasBindings(bindings) || bindings.crons.length > 0 ? `__sbStartLocalTriggers(__sbHandlers, ${JSON.stringify(bindings)});\n` : ""; // baronunread/sproutboat#238: the handler runs in its own function scope. // Spliced in at the prelude's top level, a bundle's own top-level // `const URL = ...` (uuid exports one) replaced the URL class for the whole // module, prelude included, and the binary died at startup. Porffor resolves // a top-level name module-wide, so a block is not enough; a function is. // Static imports (a direct-ESM handler, no bundler in front) are only legal // at module top level, so they stay outside the function. const importPattern = /^import\s(?:[\s\S]*?\sfrom\s*)?["'][^"'\n]+["'];?[ \t]*$/gm; const imports = (neutralised.match(importPattern) ?? []).join("\n"); const body = inlineImportMeta(neutralised.replace(importPattern, "")); return ( `${prelude}\n${nativeTransferAbi}${compat}${env}${versionMetadataLine}${wire}` + `${imports ? `${imports}\n` : ""}const __sbUserHandlers = (() => {\n${body}\n` + `${registerDO}${triggers}return __sbHandlers;\n})();\n` + `export default {\n port: ${port},\n fetch(request) { return __sbEntry(__sbUserHandlers, request); }\n};\n` ); } type VarsJson = string | number | boolean | null | { readonly [key: string]: VarsJson } | VarsJson[]; function isVarsObject(value: VarsJson): value is { readonly [key: string]: VarsJson } { return value !== null && Object(value) === value && !Array.isArray(value); } function isVarsString(value: VarsJson): value is string { return Object(value) !== value && value === String(value); } /** `SPROUTBOAT_VARS_JSON` (set by the build) → a validated flat string map. */ export function readVarsFromEnv(): Record { const raw = process.env.SPROUTBOAT_VARS_JSON; if (!raw) return {}; const parsed: VarsJson = JSON.parse(raw); if (!isVarsObject(parsed)) throw new Error("SPROUTBOAT_VARS_JSON must be a JSON object"); return Object.fromEntries( Object.entries(parsed).map(([key, value]): [string, string] => { if (!/^[A-Z][A-Z0-9_]*$/.test(key) || !isVarsString(value)) throw new Error(`SPROUTBOAT_VARS_JSON.${key} must map an UPPER_SNAKE name to a string`); return [key, value]; }), ); } /** * `SPROUTBOAT_BINDINGS_JSON` (the artifact's `bindings.json`, passed by the * build) → a `Bindings` shape. Every field is re-validated here; unknown keys * are dropped and a missing / empty payload is `EMPTY_BINDINGS`, so an old build * with no bindings still compiles. */ export function readBindingsFromEnv(): Bindings { const raw = process.env.SPROUTBOAT_BINDINGS_JSON; if (!raw) return EMPTY_BINDINGS; const parsed: VarsJson = JSON.parse(raw); if (!isVarsObject(parsed)) throw new Error("SPROUTBOAT_BINDINGS_JSON must be a JSON object"); const strings = (v: VarsJson): string[] => (Array.isArray(v) ? v.filter(isVarsString) : []); const services: Array<{ binding: string; service: string }> = []; if (Array.isArray(parsed.services)) { for (const entry of parsed.services) { if (isVarsObject(entry) && isVarsString(entry.binding) && isVarsString(entry.service)) { services.push({ binding: entry.binding, service: entry.service }); } } } const dos: Array<{ binding: string; className: string }> = []; if (Array.isArray(parsed.do)) { for (const entry of parsed.do) { if (isVarsObject(entry) && isVarsString(entry.binding) && isVarsString(entry.className)) { dos.push({ binding: entry.binding, className: entry.className }); } } } const isCount = (v: VarsJson): v is number => Number(v) === v && Number.isInteger(v) && v >= 1; const ratelimiters: Array<{ binding: string; limit: number; period: number }> = []; if (Array.isArray(parsed.ratelimiters)) { for (const entry of parsed.ratelimiters) { if (isVarsObject(entry) && isVarsString(entry.binding) && isCount(entry.limit) && isCount(entry.period)) { ratelimiters.push({ binding: entry.binding, limit: entry.limit, period: entry.period }); } } } const queueConfig: QueueSettings[] = []; if (Array.isArray(parsed.queueConfig)) { const num = (v: VarsJson | undefined): v is number => Number(v) === v && Number.isFinite(v) && v >= 0; for (const entry of parsed.queueConfig) { if (!isVarsObject(entry) || !isVarsString(entry.binding) || !isVarsString(entry.queue)) continue; const q: QueueSettings = { binding: entry.binding, queue: entry.queue }; if (num(entry.maxBatchSize)) q.maxBatchSize = entry.maxBatchSize; if (num(entry.maxBatchTimeout)) q.maxBatchTimeout = entry.maxBatchTimeout; if (num(entry.maxRetries)) q.maxRetries = entry.maxRetries; if (num(entry.retryDelay)) q.retryDelay = entry.retryDelay; if (isVarsString(entry.deadLetterQueue)) q.deadLetterQueue = entry.deadLetterQueue; queueConfig.push(q); } } const out: Bindings = { kv: strings(parsed.kv), secrets: strings(parsed.secrets), d1: strings(parsed.d1), r2: strings(parsed.r2), queues: strings(parsed.queues), analytics: strings(parsed.analytics), do: dos, services, crons: strings(parsed.crons), ratelimiters, assets: isVarsString(parsed.assets) ? parsed.assets : "", }; if (queueConfig.length) out.queueConfig = queueConfig; return out; }