@onetype/stack-api-kit 1.0.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugins/kernel/internal/faults.ts","../src/plugins/kernel/internal/answer.ts","../src/plugins/kernel/internal/permissions.ts","../src/plugins/kernel/internal/context.ts","../src/plugins/kernel/internal/events.ts","../src/plugins/kernel/internal/hooks.ts","../src/plugins/kernel/internal/order.ts","../src/plugins/kernel/internal/request.ts","../src/plugins/kernel/internal/names.ts","../src/plugins/kernel/internal/output.ts","../src/plugins/kernel/internal/validate.ts","../src/plugins/kernel/internal/kernel.ts","../src/plugins/kernel/internal/define.ts","../src/plugins/database/internal/migrate.ts","../src/plugins/database/internal/narrow.ts","../src/plugins/database/internal/outbox.ts","../src/plugins/database/internal/schedule.ts","../src/plugins/database/internal/connect.ts","../src/plugins/database/internal/queue.ts","../src/plugins/database/internal/store.ts","../src/plugins/database/api.ts","../src/plugins/guard/internal/compare.ts","../src/plugins/guard/internal/limit.ts"],"names":["fields","plugin","store","made","declared","told","context","KEPT","named","path","taken","AsyncLocalStorage","parsed","settings"],"mappings":";;;;;;;;;AAkDO,IAAM,WAAA,GAAN,cAA0B,KAAA,CACjC;AAAA,EACa,IAAA;AAAA,EAEA,MAAA;AAAA,EAEA,MAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAiB,OAAA,EAAiB,IAAA,GAAa,EAAC,EAC5D;AACI,IAAA,KAAA,CAAM,OAAA,EAAS,KAAK,KAAA,KAAU,MAAA,GAAY,SAAY,EAAE,KAAA,EAAO,IAAA,CAAK,KAAA,EAAO,CAAA;AAE3E,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,MAAA,IAAU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AAA,GAAW,CAAA,EAAG,QAAA,EAAU,MAAA,CAAO,OAAA,EAAQ;AAAA,MACrF;AAEA,MAAA,IAAA,CAAK,IAAA,IAAQ,CAAA;AAEb,MAAA,OAAO;AAAA,QACH,OAAA,EAAS,IAAA,CAAK,IAAA,IAAQ,MAAA,CAAO,QAAA;AAAA,QAC7B,WAAW,IAAA,CAAK,GAAA,CAAI,GAAG,MAAA,CAAO,QAAA,GAAW,KAAK,IAAI,CAAA;AAAA,QAClD,UAAU,IAAA,CAAK,IAAA,CAAA,CAAM,IAAA,CAAK,KAAA,GAAQ,MAAM,GAAK;AAAA,OACjD;AAAA,IACJ,CAAA;AAAA;AAAA;AAAA,IAIA,OAAO,MACP;AACI,MAAA,MAAM,KAAK,GAAA,EAAI;AAEf,MAAA,IAAI,OAAA,GAAU,CAAA;AAEd,MAAA,KAAA,MAAW,CAAC,GAAA,EAAK,IAAI,CAAA,IAAK,OAAA,EAC1B;AACI,QAAA,IAAI,IAAA,CAAK,SAAS,EAAA,EAClB;AACI,UAAA,OAAA,CAAQ,OAAO,GAAG,CAAA;AAClB,UAAA,OAAA,IAAW,CAAA;AAAA,QACf;AAAA,MACJ;AAEA,MAAA,OAAO,OAAA;AAAA,IACX,CAAA;AAAA,IAEA,MAAM,MACN;AACI,MAAA,OAAO,OAAA,CAAQ,IAAA;AAAA,IACnB;AAAA,GACJ;AACJ","file":"chunk-UCWOCNTI.js","sourcesContent":["/**\n * What the kernel refuses.\n *\n * A closed union rather than a string: a caller branches on it, and a new\n * member is a compile error everywhere it is handled exhaustively.\n */\nexport type FaultCode =\n | \"DUPLICATE_PLUGIN\"\n | \"UNKNOWN_DEPENDENCY\"\n | \"DEPENDENCY_CYCLE\"\n | \"INVALID_NAME\"\n | \"INVALID_CONFIG\"\n | \"INVALID_ROUTE\"\n | \"INVALID_PAYLOAD\"\n | \"WRONG_PAYLOAD\"\n | \"INVALID_OUTPUT\"\n | \"UNDECLARED_EVENT\"\n | \"UNDECLARED_HOOK\"\n | \"UNDECLARED_COMMAND\"\n | \"UNDECLARED_SCOPE\"\n | \"OUT_OF_SCOPE\"\n | \"UNDECLARED_PERMISSION\"\n | \"UNDECLARED_DEPENDENCY\"\n | \"UNDECLARED_HOST\"\n | \"DUPLICATE_ROUTE\"\n | \"DUPLICATE_EVENT\"\n | \"DUPLICATE_HOOK\"\n | \"DUPLICATE_COMMAND\"\n | \"DUPLICATE_PERMISSION\"\n | \"DUPLICATE_TABLE\"\n | \"UNAUTHENTICATED\"\n | \"PERMISSION_DENIED\"\n | \"RATE_LIMITED\"\n | \"NOT_STARTED\";\n\ntype Made = {\n plugin?: string;\n detail?: Readonly<Record<string, unknown>>;\n cause?: unknown;\n};\n\n/**\n * A refusal, naming the plugin it came from.\n *\n * What makes a message worth the line is the plugin, the key, the owner, and\n * what to do about it. A code alone costs an hour.\n *\n * This is what the kernel says to whoever wrote the plugin. It is never what\n * a client is told: `internal/answer.ts` decides that, and it says less.\n */\nexport class KernelFault extends Error\n{\n readonly code: FaultCode;\n\n readonly plugin: string | undefined;\n\n readonly detail: Readonly<Record<string, unknown>>;\n\n constructor(code: FaultCode, message: string, made: Made = {})\n {\n super(message, made.cause === undefined ? undefined : { cause: made.cause });\n\n this.name = \"KernelFault\";\n this.code = code;\n this.plugin = made.plugin;\n this.detail = made.detail ?? {};\n }\n\n override toString(): string\n {\n return this.plugin === undefined\n ? `${this.name} [${this.code}]: ${this.message}`\n : `${this.name} [${this.code}] in plugin \"${this.plugin}\": ${this.message}`;\n }\n}\n","import { KernelFault } from \"./faults\";\n\n/** What a client is told: a status, a stable code, and one sentence. */\nexport type Answer = {\n status: number;\n code: string;\n message: string;\n\n /** Field-level detail, only ever from an input schema. */\n fields?: Readonly<Record<string, string>>;\n};\n\n/**\n * What a handler returns when the body alone is not the answer.\n *\n * A route returning a plain value gets 200, or 201 for a POST, which is what\n * almost every route wants. This is for the rest: a redirect, a created\n * resource naming where it went, a 304, a download with a filename.\n *\n * The body still passes the output schema. Status and headers are the only\n * things this adds, because they are the only things a schema cannot carry.\n */\nexport class Answered\n{\n readonly status: number;\n\n readonly body: unknown;\n\n readonly headers: Readonly<Record<string, string>>;\n\n constructor(status: number, body: unknown, headers: Readonly<Record<string, string>> = {})\n {\n this.status = status;\n this.body = body;\n this.headers = headers;\n }\n\n /** Sends the caller somewhere else. */\n static redirect(to: string, permanent = false): Answered\n {\n return new Answered(permanent ? 308 : 307, { to }, { location: to });\n }\n}\n\n/** A refusal a plugin raises on purpose, meant to reach the caller. */\nexport class Refusal extends Error\n{\n readonly status: number;\n\n readonly code: string;\n\n readonly fields: Readonly<Record<string, string>> | undefined;\n\n constructor(status: number, code: string, message: string, fields?: Readonly<Record<string, string>>)\n {\n super(message);\n\n this.name = \"Refusal\";\n this.status = status;\n this.code = code;\n this.fields = fields;\n }\n}\n\nconst SPOKEN: Readonly<Record<string, { status: number; message: string }>> = {\n UNAUTHENTICATED: { status: 401, message: \"This request needs to be signed in.\" },\n PERMISSION_DENIED: { status: 403, message: \"This request is not permitted.\" },\n RATE_LIMITED: { status: 429, message: \"Too many requests. Try again shortly.\" },\n INVALID_PAYLOAD: { status: 400, message: \"The request body is not valid.\" },\n};\n\n// WRONG_PAYLOAD is deliberately absent: an event or hook payload failing its\n// own schema is this API's mistake, not the caller's, and telling them their\n// body was wrong sends whoever debugs it looking at the wrong thing. It falls\n// through to the fixed 500, and the log line names the event and the issue.\n\n/**\n * What the caller is told about a failure.\n *\n * Nothing that was not written for a caller ever reaches one. A thrown thing\n * is either a Refusal, which a plugin wrote deliberately, or one of the few\n * kernel codes that mean something to a client. Everything else answers 500\n * with one fixed sentence, whatever it actually was.\n *\n * This is the whole point: a stack, a file path, a SQL fragment, a column\n * name, a driver message and a config value are all things an attacker learns\n * from, and none of them are things a caller needs.\n */\nexport function answer(cause: unknown): Answer\n{\n if (cause instanceof Refusal)\n {\n return {\n status: cause.status,\n code: cause.code,\n message: cause.message,\n ...(cause.fields !== undefined && { fields: cause.fields }),\n };\n }\n\n if (cause instanceof KernelFault)\n {\n const known = SPOKEN[cause.code];\n\n if (known !== undefined)\n {\n return { status: known.status, code: cause.code, message: known.message };\n }\n }\n\n return { status: 500, code: \"INTERNAL\", message: \"The request could not be completed.\" };\n}\n\n/**\n * Whether a failure is the caller's doing or ours.\n *\n * Anything answering 500 is logged in full, because nobody saw it. A 4xx was\n * already explained to whoever caused it.\n */\nexport function ours(given: Answer): boolean\n{\n return given.status >= 500;\n}\n","import type { Caller } from \"./contract\";\n\n/**\n * What the caller of this request may do.\n *\n * Read from the caller every time rather than kept: one kernel serves every\n * request, and a cached list would answer for whoever asked before.\n *\n * A project decides what fills this. The kernel only compares it against what\n * a route declared, and never grants anything of its own.\n */\nexport function permissions(caller: () => Caller | undefined)\n{\n const granted = (): ReadonlySet<string> =>\n {\n return new Set(caller()?.permissions ?? []);\n };\n\n return {\n has: (permission: string): boolean =>\n {\n return granted().has(permission);\n },\n\n all: (wanted: readonly string[]): boolean =>\n {\n const carries = granted();\n\n return wanted.every((one) => carries.has(one));\n },\n\n /**\n * What the project attached to this caller: a tenant, a role, a\n * session. Read back as it was given, and never interpreted here.\n *\n * The kernel cannot know what a tenant means, so it carries the value\n * and refuses to guess. A plugin scoping by tenant reads it and puts\n * it in its own queries.\n */\n claims: (): Readonly<Record<string, unknown>> =>\n {\n return caller()?.claims ?? {};\n },\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { Caller, Context, Outbound, Plugin } from \"./contract\";\nimport type { events, Pending } from \"./events\";\nimport { Refusal } from \"./answer\";\nimport { KernelFault } from \"./faults\";\nimport type { hooks } from \"./hooks\";\nimport { permissions } from \"./permissions\";\nimport type { Dialer, Narrowing, Outbox, Schedule, Storage } from \"./store\";\n\n/** Everything a context is built from. One object, so the shape is one line. */\nexport type Wiring = {\n known: ReadonlyMap<string, Plugin>;\n parsed: ReadonlyMap<string, unknown>;\n /**\n * Which transaction the running code is inside, if any.\n *\n * Per call stack rather than per process: a field would say a transaction\n * is open somewhere, never that *this* caller is the one inside it, so a\n * request emitting outside any transaction would have its event held\n * against a stranger's, and lost when that stranger rolled back.\n */\n open: AsyncLocalStorage<object>;\n config: Readonly<Record<string, unknown>>;\n bus: ReturnType<typeof events<Context>>;\n points: ReturnType<typeof hooks<Context>>;\n pending: Map<object, Pending[]>;\n\n /** What each plugin owns: one thing, living as long as the kernel does. */\n owned: Map<string, unknown>;\n db: Storage | undefined;\n\n /** Where events wait for delivery, when the project gave one. */\n outbox: Outbox | undefined;\n\n dial: Dialer | undefined;\n\n /** What the project calls the current time. */\n now: () => number;\n\n /** Where later work waits, when the project gave somewhere. */\n schedule: Schedule | undefined;\n\n /** How a declared scope becomes a condition. */\n narrow: Narrowing | undefined;\n log: (level: \"debug\" | \"info\" | \"warn\" | \"error\", plugin: string, line: string, about?: Readonly<Record<string, unknown>>) => void;\n run: (command: string, input: unknown, caller?: Caller) => Promise<void>;\n};\n\n/** Where in a transaction a context sits, if it is in one at all. */\ntype Within = {\n mark: object;\n db: unknown;\n};\n\n/**\n * What a missing dependency answers: a refusal naming what to pass.\n *\n * `used` is what the plugin called; `pass` is the option that supplies it.\n * They are rarely the same word, and saying only the first sends a reader\n * looking for an option that does not exist.\n */\nfunction absent(what: string, used: string, pass: string): never\n{\n throw new KernelFault(\n \"NOT_STARTED\",\n `A plugin used ctx.${used}, but no ${what} was given. Pass \\`${pass}\\` to createKernel, \\`${pass}: true\\` to start, or \\`${pass}: true\\` to booting in a test.`,\n );\n}\n\n/** The origin of a url, whatever its scheme, or undefined when it is not one. */\nfunction origin(url: string): string | undefined\n{\n try\n {\n const parsed = new URL(url);\n\n // `origin` is \"null\" for schemes the URL standard calls opaque, which\n // is most of them once past http: build it back from the parts, so a\n // declared redis:// host is comparable to the one being dialled.\n return parsed.origin === \"null\" || parsed.origin === \"\"\n ? `${parsed.protocol}//${parsed.host}`\n : parsed.origin;\n }\n catch\n {\n return undefined;\n }\n}\n\n/** Whether ctx.fetch can carry a call to this url at all. */\nfunction dialable(url: string): boolean\n{\n return url.toLowerCase().startsWith(\"https://\");\n}\n\n/**\n * Builds what one plugin sees, for one caller.\n *\n * Made per request rather than kept: one kernel answers every request, and a\n * context holding a caller would hand the next request the previous one.\n */\nexport function context(wiring: Wiring, plugin: string, caller?: Caller, within?: Within, headers: Readonly<Record<string, string>> = {}, acting?: string): Context\n{\n const may = permissions(() => caller);\n const seenBy = (plugin: string, inside = within): Context =>\n {\n return context(wiring, plugin, caller, inside, headers, acting);\n };\n\n /** What a listener is handed: this plugin, and nobody calling. */\n const heard = (plugin: string): Context =>\n {\n return context(wiring, plugin, undefined, undefined, {});\n };\n\n // Built lazily and once per context: a service reads ctx.caller, so one\n // made at startup would answer every request as nobody. A plugin whose\n // services are never touched builds none.\n const made = new Map<string, unknown>();\n\n const of = (name: string): unknown =>\n {\n if (made.has(name))\n {\n return made.get(name);\n }\n\n made.set(name, undefined);\n\n const services = wiring.known.get(name)?.definition.services?.(\n (name === plugin ? ctx : seenBy(name)) as never,\n );\n\n made.set(name, services);\n\n return services;\n };\n\n /**\n * What a declared scope resolves to for this caller.\n *\n * Shared by `scoped` and `stamped`, because a read and a write must agree\n * about whose rows these are: two lookups is two chances to disagree.\n */\n const scoping = (table: string): { column: string; held: string } =>\n {\n const scope = wiring.known.get(plugin)?.definition.scope;\n\n if (scope === undefined)\n {\n throw new KernelFault(\n \"UNDECLARED_SCOPE\",\n `\"${plugin}\" asked to scope \"${table}\", but declares no scope. Add one, naming the claim and which column each table carries it in.`,\n { plugin },\n );\n }\n\n const column = scope.tables[table];\n\n if (column === undefined)\n {\n throw new KernelFault(\n \"UNDECLARED_SCOPE\",\n `\"${plugin}\" asked to scope \"${table}\", which its scope does not name. Add it, or stop scoping a table nobody owns.`,\n { plugin },\n );\n }\n\n // Refused, never defaulted: a default tenant is everybody's.\n const held = caller === undefined ? acting : caller.claims[scope.claim];\n\n if (typeof held !== \"string\" || held.trim() === \"\")\n {\n throw new Refusal(\n 403,\n \"OUT_OF_SCOPE\",\n \"This request carries nothing to say whose rows it may reach.\",\n );\n }\n\n return { column, held };\n };\n\n const ctx: Context = {\n name: plugin,\n config: wiring.parsed.get(plugin) ?? wiring.config[plugin],\n\n get services(): unknown\n {\n return of(plugin);\n },\n\n caller,\n headers,\n\n now: wiring.now,\n\n log: {\n debug: (line, about) =>\n {\n wiring.log(\"debug\", plugin, line, about);\n },\n info: (line, about) =>\n {\n wiring.log(\"info\", plugin, line, about);\n },\n warn: (line, about) =>\n {\n wiring.log(\"warn\", plugin, line, about);\n },\n error: (line, about) =>\n {\n wiring.log(\"error\", plugin, line, about);\n },\n },\n\n get db(): unknown\n {\n if (within !== undefined)\n {\n return within.db;\n }\n\n return wiring.db === undefined ? absent(\"store\", \"db\", \"db\") : wiring.db.of(plugin);\n },\n\n write: <Returned,>(run: () => Promise<Returned>): Promise<Returned> =>\n {\n // Inside a transaction the ordering is already settled: the work\n // belongs to that transaction, and queueing it would wait on a\n // turn that cannot come until the transaction it is inside ends.\n if (within !== undefined || wiring.db?.write === undefined)\n {\n return run();\n }\n\n return wiring.db.write(run);\n },\n\n tx: async <Returned,>(run: (ctx: Context) => Promise<Returned>): Promise<Returned> =>\n {\n const store = wiring.db;\n\n if (store === undefined)\n {\n return absent(\"store\", \"db\", \"db\");\n }\n\n const mark = {};\n const outer = wiring.open.getStore();\n const nested = within !== undefined;\n\n wiring.pending.set(mark, []);\n\n try\n {\n // An inner tx becomes a savepoint rather than a second\n // transaction, but keeps its own buffer: work it rolled back\n // must not be announced when the outer commits.\n const returned = await wiring.open.run(mark, () =>\n store.tx(plugin, async (db) =>\n {\n const made = await run(seenBy(plugin, { mark, db }));\n\n // Written with the work, not after it: an event kept\n // once the transaction has closed is one the process\n // can still die without.\n const waiting = wiring.pending.get(mark) ?? [];\n\n if (wiring.outbox !== undefined && waiting.length > 0 && !(nested && outer !== undefined))\n {\n wiring.outbox.keep(db, waiting.map((one) => ({\n id: one.id,\n plugin: one.plugin,\n name: one.name,\n payload: one.payload,\n })));\n }\n\n return made;\n }));\n\n const announced = wiring.pending.get(mark) ?? [];\n\n if (nested && outer !== undefined)\n {\n // An inner transaction is a savepoint: the outer one may\n // still roll back, so what this announced waits on that.\n wiring.pending.get(outer)?.push(...announced);\n\n return returned;\n }\n\n // Only now: an event about work that rolled back is a lie,\n // and a listener acting on one cannot be undone.\n for (const announcement of announced)\n {\n const delivered = wiring.bus.deliver(announcement.plugin, announcement.name, announcement.payload, (to) => heard(to));\n\n // Forgotten only once something has heard it. Marking it\n // sent before that would lose exactly what the outbox\n // exists to keep.\n void delivered.then(() => wiring.outbox?.sent(announcement.id));\n }\n\n return returned;\n }\n finally\n {\n wiring.pending.delete(mark);\n }\n },\n\n // Async throughout, refusal included: a caller writing `.catch()`\n // around a call would otherwise get an uncaught error for the one\n // case it was guarding against.\n fetch: async (call: Outbound): Promise<unknown> =>\n {\n const allowed = wiring.known.get(plugin)?.definition.outbound ?? [];\n const host = origin(call.url);\n\n if (host === undefined || !allowed.includes(host))\n {\n throw new KernelFault(\n \"UNDECLARED_HOST\",\n `\"${plugin}\" called ${host ?? `\"${call.url}\"`}, which it does not declare. Add it to outbound.`,\n { plugin },\n );\n }\n\n // Declared, but not something this can carry. Said plainly,\n // because \"add it to outbound\" for a host already in outbound\n // sends the reader looking for a problem that is not there.\n if (!dialable(call.url))\n {\n throw new KernelFault(\n \"UNDECLARED_HOST\",\n `\"${plugin}\" declares ${host}, but ctx.fetch speaks https and nothing else. Reach it with its own client, opened in setup and closed in teardown.`,\n { plugin },\n );\n }\n\n return wiring.dial === undefined ? absent(\"dialer\", \"dial\", \"dial\") : wiring.dial(call);\n },\n\n events: {\n emit: (event, payload) =>\n {\n // Checked here even when it is deferred: a payload rejected after\n // a commit, from a stack with no caller in it, is one nobody\n // can trace back to what emitted it.\n const checked = wiring.bus.checked(plugin, event, payload);\n\n // Kept against whatever transaction is open, not against the\n // context this was called on. Emitting from the outer `ctx`\n // inside a `tx` is the easy mistake, and it announced work\n // that had not committed and might never.\n const mark = within?.mark ?? wiring.open.getStore();\n const waiting = mark === undefined ? undefined : wiring.pending.get(mark);\n\n if (waiting !== undefined)\n {\n waiting.push({ id: crypto.randomUUID(), plugin, name: event, payload: checked });\n\n return;\n }\n\n // On nobody's behalf, always. A listener that inherited the\n // emitter's caller would work in one process and answer as\n // nobody after a restart, because an outbox keeps a payload\n // and not a request. Whose work this was travels in the\n // payload or not at all.\n wiring.bus.deliver(plugin, event, checked, (to) => heard(to));\n },\n },\n\n hooks: {\n run: (hook, payload) =>\n {\n return wiring.points.run(plugin, hook, payload, (to) => seenBy(to));\n },\n },\n\n permissions: may,\n\n commands: {\n run: (command, input) =>\n {\n return wiring.run(command, input, caller);\n },\n\n later: (command, input, inSeconds) =>\n {\n if (wiring.schedule === undefined)\n {\n absent(\"schedule\", \"commands.later\", \"schedule\");\n }\n\n const owns = wiring.known.get(plugin)?.definition.commands ?? {};\n\n if (!(command in owns))\n {\n throw new KernelFault(\n \"UNDECLARED_COMMAND\",\n `\"${plugin}\" scheduled \"${command}\", which it does not declare. A plugin schedules only its own commands.`,\n { plugin },\n );\n }\n\n // Written by the transaction that asked, when there is one:\n // work scheduled by something that rolled back is work about\n // nothing, and it would run anyway.\n wiring.schedule.keep(within?.db, {\n id: crypto.randomUUID(),\n plugin,\n command,\n input,\n at: wiring.now() + inSeconds * 1000,\n attempts: 0,\n });\n },\n },\n\n owns: <Owned,>(owned: Owned): Owned =>\n {\n wiring.owned.set(plugin, owned);\n\n return owned;\n },\n\n owned: <Owned,>(): Owned | undefined =>\n {\n return wiring.owned.get(plugin) as Owned | undefined;\n },\n\n forScope: (claim: string): Context =>\n {\n // Only where nobody is calling. Inside a request the scope is\n // decided by who is asking, and letting a handler name another\n // is how a caller reaches rows that are not theirs.\n if (caller !== undefined)\n {\n throw new KernelFault(\n \"OUT_OF_SCOPE\",\n `\"${plugin}\" called ctx.forScope inside a request. The scope of a request is the caller's; forScope is for a listener or a scheduled command, where nobody is calling.`,\n { plugin },\n );\n }\n\n if (claim.trim() === \"\")\n {\n throw new KernelFault(\n \"OUT_OF_SCOPE\",\n `\"${plugin}\" called ctx.forScope with nothing. A scope acted for is named, or it is every scope.`,\n { plugin },\n );\n }\n\n return context(wiring, plugin, undefined, within, headers, claim);\n },\n\n stamped: (table: string): Readonly<Record<string, string>> =>\n {\n const { column, held } = scoping(table);\n\n return { [column]: held };\n },\n\n scoped: <Condition,>(table: string): Condition =>\n {\n const { column, held } = scoping(table);\n\n return (wiring.narrow === undefined\n ? absent(\"narrowing\", \"scoped\", \"narrow\")\n : wiring.narrow(table, column, held)) as Condition;\n },\n\n use: <Reached,>(name: string): Reached =>\n {\n const declared = wiring.known.get(plugin)?.definition.dependsOn ?? [];\n\n if (name !== plugin && !declared.includes(name))\n {\n throw new KernelFault(\n \"UNDECLARED_DEPENDENCY\",\n `\"${plugin}\" reached \"${name}\", which it does not depend on. Add \"${name}\" to dependsOn.`,\n { plugin },\n );\n }\n\n // The other plugin's services, against this same caller. One\n // built at startup would answer as whoever asked first.\n return of(name) as Reached;\n },\n };\n\n return ctx;\n}\n","import type { Event, Heard } from \"./contract\";\nimport { KernelFault } from \"./faults\";\n\nexport type Failure = {\n event: string;\n plugin: string;\n error: unknown;\n at: number;\n};\n\nexport type Pending = {\n /** Its own, so an outbox can mark exactly this one delivered. */\n id: string;\n\n plugin: string;\n name: string;\n payload: unknown;\n};\n\ntype Published = {\n owner: string;\n event: Event;\n};\n\n/**\n * How many listener failures are kept.\n *\n * Enough to see a pattern in what just broke, few enough that a listener\n * throwing on every event cannot exhaust the process.\n */\nconst KEPT = 100;\n\ntype Subscriber<Context> = {\n plugin: string;\n listener: Heard<Context>;\n};\n\ntype Told = (plugin: string, line: string, about: Readonly<Record<string, unknown>>) => void;\n\nexport function events<Context>(now: () => number = Date.now, told: Told = () => {})\n{\n const published = new Map<string, Published>();\n const subscribers = new Map<string, Subscriber<Context>[]>();\n const failures: Failure[] = [];\n\n /**\n * Records a listener that failed, and says so.\n *\n * Kept for a project to read, and logged as well: a failure only in a\n * list nobody polls is a failure nobody sees, and an event is the one\n * path where nothing is waiting to be told.\n *\n * Only the last few are kept. Each holds an Error, and an Error holds the\n * stack it was thrown from, so a listener failing on every event would\n * otherwise grow this list for as long as the process lives. The newest\n * are what a project reads; the oldest are what it has already seen.\n */\n function record(event: string, plugin: string, error: unknown): void\n {\n failures.push({ event, plugin, error, at: now() });\n\n if (failures.length > KEPT)\n {\n failures.splice(0, failures.length - KEPT);\n }\n\n told(plugin, `listening to \"${event}\" failed`, {\n event,\n error: error instanceof Error ? error.message : String(error),\n ...(error instanceof Error && error.stack !== undefined && { stack: error.stack }),\n });\n }\n\n function checked(plugin: string, name: string, payload: unknown): unknown\n {\n const publisher = published.get(name);\n\n if (publisher === undefined)\n {\n throw new KernelFault(\"UNDECLARED_EVENT\", `\"${plugin}\" emitted \"${name}\", which no plugin declares. Add it to emits.`, { plugin });\n }\n\n if (publisher.owner !== plugin)\n {\n throw new KernelFault(\"UNDECLARED_EVENT\", `\"${plugin}\" emitted \"${name}\", which belongs to \"${publisher.owner}\". A plugin emits only what it owns.`, { plugin, detail: { owner: publisher.owner } });\n }\n\n const parsed = publisher.event.schema.safeParse(payload);\n\n if (!parsed.success)\n {\n throw new KernelFault(\"WRONG_PAYLOAD\", `The payload for \"${name}\" does not match its schema: ${parsed.error.issues[0]?.message ?? \"it was rejected\"}.`, { plugin });\n }\n\n return parsed.data;\n }\n\n return {\n checked,\n\n declare: (owner: string, name: string, event: Event): void =>\n {\n published.set(name, { owner, event });\n },\n\n listen: (plugin: string, name: string, listener: Heard<Context>): void =>\n {\n subscribers.set(name, [...(subscribers.get(name) ?? []), { plugin, listener }]);\n },\n\n // A listener that throws is recorded and reaches neither the emitter\n // nor the ones behind it: one plugin's bug is not another's failure.\n /**\n * Calls every listener, and answers when they have all settled.\n *\n * The emitter never waits on this: it returns void from `emit`, and\n * one plugin's slow listener is not another's slow request. What does\n * wait is an outbox, which cannot forget an event until something has\n * actually heard it.\n */\n deliver: (plugin: string, name: string, payload: unknown, ctx: (plugin: string) => Context): Promise<void> =>\n {\n const heard: Promise<void>[] = [];\n\n for (const subscriber of subscribers.get(name) ?? [])\n {\n if (subscriber.plugin === plugin)\n {\n continue;\n }\n\n try\n {\n const handling = subscriber.listener.handle(payload as never, ctx(subscriber.plugin));\n\n heard.push(Promise.resolve(handling).catch((error: unknown) =>\n {\n record(name, subscriber.plugin, error);\n }));\n }\n catch (error)\n {\n record(name, subscriber.plugin, error);\n }\n }\n\n return Promise.all(heard).then(() => undefined);\n },\n\n failures: (): readonly Failure[] =>\n {\n return [...failures];\n },\n };\n}\n","import type { Hook, Joined } from \"./contract\";\nimport { KernelFault } from \"./faults\";\n\n/** What the timer answers with. An object, so no participant can return it. */\nconst LATE = Symbol(\"late\");\n\ntype Opened = {\n owner: string;\n hook: Hook;\n};\n\ntype Participating<Context> = {\n plugin: string;\n participant: Joined<Context>;\n};\n\n/**\n * How long a participant has to answer.\n *\n * A participant that throws is already a refusal; one that never answers is\n * the same thing arriving more slowly, and without this it holds the request\n * open for as long as the process lives.\n */\nconst PATIENCE = 5000;\n\nexport function hooks<Context>(patience: number = PATIENCE)\n{\n const opened = new Map<string, Opened>();\n const joined = new Map<string, Participating<Context>[]>();\n\n return {\n declare: (owner: string, name: string, hook: Hook): void =>\n {\n opened.set(name, { owner, hook });\n },\n\n participate: (plugin: string, name: string, participant: Joined<Context>): void =>\n {\n joined.set(name, [...(joined.get(name) ?? []), { plugin, participant }]);\n },\n\n run: async (plugin: string, name: string, payload: unknown, ctx: (plugin: string) => Context): Promise<string | undefined> =>\n {\n const point = opened.get(name);\n\n if (point === undefined)\n {\n throw new KernelFault(\"UNDECLARED_HOOK\", `\"${plugin}\" ran \"${name}\", which no plugin declares. Add it to hooks.`, { plugin });\n }\n\n if (point.owner !== plugin)\n {\n throw new KernelFault(\"UNDECLARED_HOOK\", `\"${plugin}\" ran \"${name}\", which belongs to \"${point.owner}\". A plugin runs only the hooks it owns.`, { plugin, detail: { owner: point.owner } });\n }\n\n const parsed = point.hook.schema.safeParse(payload);\n\n if (!parsed.success)\n {\n throw new KernelFault(\"WRONG_PAYLOAD\", `The payload for \"${name}\" does not match its schema: ${parsed.error.issues[0]?.message ?? \"it was rejected\"}.`, { plugin });\n }\n\n for (const participant of joined.get(name) ?? [])\n {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try\n {\n const answered = participant.participant.handle(parsed.data as never, ctx(participant.plugin));\n\n const refusal = await Promise.race([\n answered,\n new Promise<typeof LATE>((keep) =>\n {\n timer = setTimeout(() => keep(LATE), patience);\n }),\n ]);\n\n if (refusal === LATE)\n {\n return `\"${participant.plugin}\" did not answer in ${String(patience)}ms.`;\n }\n\n if (refusal !== undefined)\n {\n return refusal;\n }\n }\n catch (cause)\n {\n // A participant whose check crashed has not agreed to\n // anything, so a throw is a refusal, never consent.\n return `\"${participant.plugin}\" refused: ${cause instanceof Error ? cause.message : String(cause)}`;\n }\n finally\n {\n clearTimeout(timer);\n }\n }\n\n return undefined;\n },\n };\n}\n","import type { Plugin } from \"./contract\";\n\n/**\n * Dependency order: every plugin comes after the ones it depends on.\n *\n * Ties break by name, so one set always yields one order. A run that varied\n * would make what a plugin sees at setup depend on iteration order.\n */\nexport function order(known: ReadonlyMap<string, Plugin>): Plugin[]\n{\n const sorted: Plugin[] = [];\n const state = new Map<string, \"open\" | \"done\">();\n\n function walk(name: string): void\n {\n if (state.get(name) !== undefined)\n {\n return;\n }\n\n state.set(name, \"open\");\n\n const plugin = known.get(name);\n\n for (const need of [...(plugin?.definition.dependsOn ?? [])].sort())\n {\n if (known.has(need))\n {\n walk(need);\n }\n }\n\n state.set(name, \"done\");\n\n if (plugin !== undefined)\n {\n sorted.push(plugin);\n }\n }\n\n for (const name of [...known.keys()].sort())\n {\n walk(name);\n }\n\n return sorted;\n}\n","import { answer, Answered, Refusal } from \"./answer\";\nimport type { Caller, Context, Method, Route } from \"./contract\";\nimport { KernelFault } from \"./faults\";\nimport { permissions } from \"./permissions\";\n\n/** What decides whether one caller has any budget left on one route. */\nexport type Budget = {\n take: (key: string, window: { requests: number; seconds: number }) => { allowed: boolean; resetsIn: number };\n};\n\n/** One request, as it reaches the kernel. */\nexport type Incoming = {\n method: Method;\n path: string;\n input: unknown;\n caller?: Caller | undefined;\n\n /** The request's headers, lowercase. A route sees only what it declared. */\n headers?: Readonly<Record<string, string>> | undefined;\n\n /**\n * Where it came from, when nobody is signed in: an address, a key, or\n * whatever the project counts anonymous callers by. Only a rate limit\n * reads it.\n */\n from?: string | undefined;\n};\n\n/** What the kernel answers: a status, and a body already safe to send. */\nexport type Outgoing = {\n status: number;\n body: unknown;\n headers?: Readonly<Record<string, string>>;\n};\n\n/** A route the kernel holds, and who declared it. */\nexport type Mounted = {\n plugin: string;\n route: Route<Context>;\n};\n\ntype Log = (\n level: \"debug\" | \"info\" | \"warn\" | \"error\",\n plugin: string,\n line: string,\n about?: Readonly<Record<string, unknown>>,\n) => void;\n\n/** Nothing found. Said the same way whoever asked, so probing learns nothing. */\nexport const unknownRoute: Outgoing = {\n status: 404,\n body: { code: \"NOT_FOUND\", message: \"No such route.\" },\n};\n\n/** The kernel has stopped. A retry elsewhere is the only useful answer. */\nexport const notServing: Outgoing = {\n status: 503,\n body: { code: \"NOT_SERVING\", message: \"The service is shutting down.\" },\n};\n\n/**\n * Answers one request.\n *\n * The order is the whole security story, and it is deliberate:\n *\n * 1. signed in, unless the route says it is public\n * 2. permitted, against what the route declared\n * 3. parsed, so a handler only ever sees input that passed its schema\n * 4. run\n * 5. filtered, so only what the output schema names leaves\n *\n * Authentication comes before parsing so an anonymous caller cannot reach a\n * schema, and filtering comes last so a handler cannot leak by returning too\n * much.\n */\nexport async function respond(\n mounted: Mounted,\n incoming: Incoming,\n context: (plugin: string, caller?: Caller, headers?: Readonly<Record<string, string>>) => Context,\n log: Log,\n budget?: Budget,\n): Promise<Outgoing>\n{\n const { plugin, route } = mounted;\n const caller = incoming.caller;\n const may = permissions(() => caller);\n\n // An id of \"\" is nobody, not somebody. A project writing `id: row?.userId\n // ?? \"\"` would otherwise authenticate a caller with no identity, and\n // every such caller would share one rate-limit bucket besides.\n const who = caller?.id !== undefined && caller.id.trim() !== \"\" ? caller.id : undefined;\n\n try\n {\n if (route.public !== true && who === undefined)\n {\n throw new KernelFault(\"UNAUTHENTICATED\", `${route.method} ${route.path} needs a caller.`, { plugin });\n }\n\n // After identity, so one caller's flood cannot spend another's\n // budget, and before the handler, so a refused request costs nothing.\n if (route.limit !== undefined && budget !== undefined)\n {\n const verdict = budget.take(`${who ?? incoming.from ?? \"anonymous\"}:${route.method} ${route.path}`, route.limit);\n\n if (!verdict.allowed)\n {\n return {\n status: 429,\n body: { code: \"RATE_LIMITED\", message: \"Too many requests. Try again shortly.\" },\n headers: { \"retry-after\": String(verdict.resetsIn) },\n };\n }\n }\n\n const lacking = (route.requires ?? []).filter((permission) => !may.has(permission));\n\n if (lacking.length > 0)\n {\n throw new KernelFault(\n \"PERMISSION_DENIED\",\n `${route.method} ${route.path} needs ${lacking.map((permission) => `\"${permission}\"`).join(\", \")}.`,\n { plugin, detail: { lacking } },\n );\n }\n\n const parsed = route.input.safeParse(incoming.input);\n\n if (!parsed.success)\n {\n throw new Refusal(400, \"INVALID_INPUT\", \"The request is not valid.\", fields(parsed.error));\n }\n\n const returned = await route.handle(parsed.data, context(plugin, caller, declared(route, incoming.headers)));\n\n // A handler may say what status and headers its answer carries. The\n // body still passes the schema either way: what a route sends is\n // never a decision the handler alone makes.\n const carried = returned instanceof Answered ? returned : undefined;\n\n // A whitelist, not a check: what the schema does not name does not\n // leave, so a column added to a table tomorrow cannot appear in a\n // response by itself.\n const filtered = route.output.safeParse(carried === undefined ? returned : carried.body);\n\n if (!filtered.success)\n {\n log(\"error\", plugin, `${route.method} ${route.path} returned what its output schema refuses`, {\n issues: filtered.error.issues.map((issue) => `${issue.path.join(\".\")}: ${issue.message}`),\n });\n\n return { status: 500, body: { code: \"INTERNAL\", message: \"The request could not be completed.\" } };\n }\n\n if (carried !== undefined)\n {\n return { status: carried.status, body: filtered.data, headers: sendable(carried.headers, plugin, route, log) };\n }\n\n return { status: route.method === \"POST\" ? 201 : 200, body: filtered.data };\n }\n catch (cause)\n {\n const refusal = answer(cause);\n\n // A 5xx is ours and nobody saw it; a 4xx was already explained to\n // whoever caused it.\n //\n // Read off the error rather than passed whole: an Error serialises to\n // \"{}\", so a log holding one says a request failed and nothing about\n // why, which is the moment the log existed for.\n if (refusal.status >= 500)\n {\n log(\"error\", plugin, `${route.method} ${route.path} threw`, told(cause));\n }\n\n return {\n status: refusal.status,\n body: {\n code: refusal.code,\n message: refusal.message,\n ...(refusal.fields !== undefined && { fields: refusal.fields }),\n },\n };\n }\n}\n\n/** What a thrown thing says, in a shape that survives being written down. */\nfunction told(cause: unknown): Readonly<Record<string, unknown>>\n{\n if (cause instanceof Error)\n {\n return {\n error: cause.message,\n kind: cause.name,\n ...(cause.stack !== undefined && { stack: cause.stack }),\n ...(cause.cause !== undefined && { cause: told(cause.cause) }),\n };\n }\n\n return { error: String(cause) };\n}\n\n/**\n * A header a handler may never set.\n *\n * `set-cookie` decides who the caller is on their next request, which is the\n * session plugin's business and nobody else's. The rest are the kit's own\n * answer about itself, and a route overriding them turns one endpoint into\n * the hole in a policy that holds everywhere else.\n */\nconst KEPT: ReadonlySet<string> = new Set([\n \"set-cookie\",\n \"content-security-policy\",\n \"x-content-type-options\",\n \"x-frame-options\",\n \"access-control-allow-origin\",\n \"access-control-allow-credentials\",\n]);\n\n/** The headers a handler asked for, minus the ones it may not set. */\nfunction sendable(\n asked: Readonly<Record<string, string>>,\n plugin: string,\n route: Route<Context>,\n log: Log,\n): Readonly<Record<string, string>>\n{\n const sending: Record<string, string> = {};\n\n for (const [name, value] of Object.entries(asked))\n {\n const lower = name.toLowerCase();\n\n if (KEPT.has(lower))\n {\n log(\"warn\", plugin, `${route.method} ${route.path} tried to set \"${lower}\", which the kit answers for`);\n\n continue;\n }\n\n // A newline splits one header into two, and the second is whatever\n // the value's author wanted to say.\n if (/[\\r\\n]/.test(value))\n {\n log(\"warn\", plugin, `${route.method} ${route.path} tried to set \"${lower}\" to a value carrying a newline`);\n\n continue;\n }\n\n sending[lower] = value;\n }\n\n return sending;\n}\n\n/**\n * The headers a route named, and nothing else.\n *\n * A handler that could read any header could read the cookie carrying the\n * session, and anything logging its input would then be logging a credential.\n */\nfunction declared(route: Route<Context>, sent: Readonly<Record<string, string>> = {}): Readonly<Record<string, string>>\n{\n const sending: Record<string, string> = {};\n\n for (const name of route.reads ?? [])\n {\n const value = sent[name];\n\n if (value !== undefined)\n {\n sending[name] = value;\n }\n }\n\n return sending;\n}\n\n/**\n * Which fields failed, and why.\n *\n * Built only from an input schema the plugin wrote, so what it names is what\n * the caller already sent us.\n */\nfunction fields(error: { issues: readonly { path: readonly PropertyKey[]; message: string }[] }): Record<string, string>\n{\n const named: Record<string, string> = {};\n\n for (const issue of error.issues)\n {\n const at = issue.path.map((segment) => String(segment)).join(\".\");\n\n if (at !== \"\" && named[at] === undefined)\n {\n named[at] = issue.message;\n }\n }\n\n return named;\n}\n","import { KernelFault } from \"./faults\";\n\nconst PLUGIN = /^[a-z][a-z0-9-]{0,63}$/;\n\nconst NAMESPACED = /^[a-z][a-z0-9-]{0,63}(\\.[a-z][a-z0-9-]{0,63})+$/;\n\n/**\n * Names the character that broke a name, so an author sees the typo rather\n * than a regular expression.\n */\nfunction describe(value: string): string\n{\n const at = [...value].findIndex((character) => !/[a-z0-9.-]/.test(character));\n\n return at === -1 ? `\"${value}\"` : `\"${value}\" (unsupported character at position ${at + 1}: \"${value[at]}\")`;\n}\n\n/** A plugin name: lowercase, digits and hyphens, starting with a letter. */\nexport function plugin(value: string): string\n{\n if (!PLUGIN.test(value))\n {\n throw new KernelFault(\n \"INVALID_NAME\",\n `A plugin name is lowercase letters, digits and hyphens, starting with a letter, up to 64 characters. Received ${describe(value)}.`,\n { detail: { received: value } },\n );\n }\n\n return value;\n}\n\n/**\n * A namespaced name, owned by the plugin its first segment names.\n *\n * The prefix is what makes a name enough: a listener on \"auth.signed-out\"\n * knows who owns it without a lookup, and two plugins cannot claim one name.\n */\nexport function namespaced(value: string, kind: string, owner: string): string\n{\n if (!NAMESPACED.test(value))\n {\n throw new KernelFault(\n \"INVALID_NAME\",\n `A ${kind} name is dot-separated lowercase segments, such as \"${owner}.thing\". Received ${describe(value)}.`,\n { plugin: owner, detail: { received: value, kind } },\n );\n }\n\n if (!value.startsWith(`${owner}.`))\n {\n throw new KernelFault(\n \"INVALID_NAME\",\n `A ${kind} is named inside its own plugin: \"${value}\" belongs to \"${value.split(\".\")[0] ?? \"\"}\", not to \"${owner}\". Rename it to \"${owner}.${value.split(\".\").slice(1).join(\".\")}\".`,\n { plugin: owner, detail: { received: value, kind, owner } },\n );\n }\n\n return value;\n}\n\n/** Who owns a namespaced name. */\nexport function owner(value: string): string\n{\n return value.split(\".\")[0] ?? \"\";\n}\n","import type { z } from \"zod\";\n\n/**\n * Whether a schema can be trusted to whitelist what leaves.\n *\n * `safeParse` only strips what a schema does not name when the schema is an\n * object that refuses unknown keys. Everything else forwards whatever the\n * handler returned: `z.any()`, `z.unknown()`, a loose object, a catchall, a\n * record, a transform. Each of those parses a row carrying a password hash\n * without complaint and sends it.\n *\n * So the shape is checked once, at startup, rather than trusted per request.\n * A route whose output cannot filter is a route that will leak the first time\n * someone adds a column.\n */\nexport function filters(schema: z.ZodType): boolean\n{\n return whitelists(schema, 0, new Set());\n}\n\nconst OPEN: ReadonlySet<string> = new Set([\"any\", \"unknown\", \"record\", \"map\", \"custom\", \"never\", \"void\", \"transform\", \"pipe\", \"promise\", \"function\", \"file\", \"symbol\"]);\n\n/** What kind of schema this is, or \"\" for anything unreadable. */\nfunction kindOf(schema: unknown): string\n{\n if (schema === null || typeof schema !== \"object\")\n {\n return \"\";\n }\n\n return String((schema as { _zod?: { def?: { type?: unknown } } })._zod?.def?.type ?? \"\");\n}\n\nfunction whitelists(schema: unknown, depth: number, seen: Set<unknown>): boolean\n{\n // A schema deep enough to exhaust this is one nobody reviews anyway.\n if (depth > 24 || schema === null || typeof schema !== \"object\")\n {\n return false;\n }\n\n // A recursive schema reaches itself. Having judged it once is the answer:\n // whatever it holds has already been walked, and walking again never\n // returns.\n if (seen.has(schema))\n {\n return true;\n }\n\n seen.add(schema);\n\n const zod = schema as { _zod?: { def?: Record<string, unknown> } };\n const def = zod._zod?.def;\n\n if (def === undefined)\n {\n return false;\n }\n\n const kind = String(def[\"type\"] ?? \"\");\n\n if (OPEN.has(kind))\n {\n return false;\n }\n\n switch (kind)\n {\n case \"object\":\n {\n // A loose object keeps unknown keys, and a catchall names a type\n // for them: both forward what the handler happened to return.\n //\n // `z.strictObject` is the exception: its catchall is `never`, so\n // it keeps nothing. It refuses the whole answer instead of\n // stripping, which turns a new column into a 500 rather than a\n // leak, so it is safe here and a poor choice anyway.\n const catchall = def[\"catchall\"];\n\n if (catchall !== undefined && kindOf(catchall) !== \"never\")\n {\n return false;\n }\n\n const shape = def[\"shape\"];\n\n if (shape === null || typeof shape !== \"object\")\n {\n return false;\n }\n\n return Object.values(shape as Record<string, unknown>).every((field) => whitelists(field, depth + 1, seen));\n }\n\n case \"array\":\n case \"set\":\n {\n return whitelists(def[\"element\"], depth + 1, seen);\n }\n\n case \"tuple\":\n {\n const items = Array.isArray(def[\"items\"]) ? (def[\"items\"] as unknown[]) : [];\n\n return items.every((item) => whitelists(item, depth + 1, seen)) && def[\"rest\"] === undefined;\n }\n\n case \"union\":\n {\n const options = Array.isArray(def[\"options\"]) ? (def[\"options\"] as unknown[]) : [];\n\n return options.length > 0 && options.every((option) => whitelists(option, depth + 1, seen));\n }\n\n case \"intersection\":\n {\n return whitelists(def[\"left\"], depth + 1, seen) && whitelists(def[\"right\"], depth + 1, seen);\n }\n\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"readonly\":\n case \"nonoptional\":\n case \"catch\":\n {\n return whitelists(def[\"innerType\"], depth + 1, seen);\n }\n\n // A recursive shape: the schema is behind a getter, so it has to be\n // called. Depth stops the walk before the recursion does, and a tree\n // that deep is one nobody reviews anyway.\n case \"lazy\":\n {\n const getter = def[\"getter\"];\n\n if (typeof getter !== \"function\")\n {\n return false;\n }\n\n try\n {\n return whitelists((getter as () => unknown)(), depth + 1, seen);\n }\n catch\n {\n return false;\n }\n }\n\n // A leaf: it carries its own value and nothing of the caller's shape.\n default:\n {\n return true;\n }\n }\n}\n","import type { Plugin } from \"./contract\";\nimport type { KernelFault } from \"./faults\";\nimport * as names from \"./names\";\nimport { filters } from \"./output\";\n\n/** One thing wrong, and everything needed to fix it. */\nexport type Wrong = {\n code: KernelFault[\"code\"];\n plugin: string;\n message: string;\n};\n\ntype Say = (code: KernelFault[\"code\"], plugin: string, message: string) => void;\n\ntype Owned = {\n routes: Map<string, string>;\n events: Map<string, string>;\n hooks: Map<string, string>;\n commands: Map<string, string>;\n permissions: Map<string, string>;\n tables: Map<string, string>;\n};\n\n/**\n * Checks every contract, and reports everything wrong rather than the first.\n *\n * A project with four mistakes should learn all four in one run rather than\n * in four runs, each ending at a different one.\n */\nexport function validate(plugins: readonly Plugin[], config: Readonly<Record<string, unknown>>): Wrong[]\n{\n const wrong: Wrong[] = [];\n const say: Say = (code, plugin, message) =>\n {\n wrong.push({ code, plugin, message });\n };\n\n const by = new Map<string, Plugin>();\n\n for (const plugin of plugins)\n {\n if (by.has(plugin.name))\n {\n say(\"DUPLICATE_PLUGIN\", plugin.name, `Two plugins are named \"${plugin.name}\". A name is what everything else refers to, so it must be unique.`);\n\n continue;\n }\n\n by.set(plugin.name, plugin);\n }\n\n const owned: Owned = {\n routes: new Map(),\n events: new Map(),\n hooks: new Map(),\n commands: new Map(),\n permissions: new Map(),\n tables: new Map(),\n };\n\n for (const [name, plugin] of by)\n {\n declares(name, plugin, owned, say);\n }\n\n for (const [name, plugin] of by)\n {\n refers(name, plugin, by, owned, say);\n settings(name, plugin, config, say);\n }\n\n cycles(by, say);\n\n return wrong;\n}\n\n/** What a plugin declares, and whether anyone claimed it first. */\nfunction declares(name: string, plugin: Plugin, owned: Owned, say: Say): void\n{\n const claim = (kind: keyof Owned, key: string, code: KernelFault[\"code\"], label: string): void =>\n {\n const first = owned[kind].get(key);\n\n if (first !== undefined)\n {\n say(code, name, `${label} \"${key}\" is already declared by \"${first}\". Two plugins cannot own one name.`);\n\n return;\n }\n\n owned[kind].set(key, name);\n };\n\n for (const key of Object.keys(plugin.definition.permissions ?? {}))\n {\n named(name, key, \"permission\", say) && claim(\"permissions\", key, \"DUPLICATE_PERMISSION\", \"Permission\");\n }\n\n for (const key of Object.keys(plugin.definition.emits ?? {}))\n {\n named(name, key, \"event\", say) && claim(\"events\", key, \"DUPLICATE_EVENT\", \"Event\");\n }\n\n for (const key of Object.keys(plugin.definition.hooks ?? {}))\n {\n named(name, key, \"hook\", say) && claim(\"hooks\", key, \"DUPLICATE_HOOK\", \"Hook\");\n }\n\n for (const key of Object.keys(plugin.definition.commands ?? {}))\n {\n named(name, key, \"command\", say) && claim(\"commands\", key, \"DUPLICATE_COMMAND\", \"Command\");\n }\n\n // A table name is global in SQLite, so two plugins claiming one would\n // share storage while both believing it private.\n for (const key of Object.keys(plugin.definition.tables ?? {}))\n {\n claim(\"tables\", key, \"DUPLICATE_TABLE\", \"Table\");\n }\n\n for (const route of plugin.definition.routes ?? [])\n {\n path(name, route.method, route.path, owned, say);\n\n if (route.describe.trim() === \"\")\n {\n say(\"INVALID_ROUTE\", name, `Route ${route.method} \"${route.path}\" has no description. A route nobody described is one nobody can review.`);\n }\n\n // An output schema that cannot strip is not a whitelist, and the\n // route's whole promise rests on it.\n if (!filters(route.output))\n {\n say(\"INVALID_OUTPUT\", name, `Route ${route.method} \"${route.path}\" has an output schema that cannot filter what leaves. Use z.object naming every field that may be sent: it strips the rest. z.any, z.unknown, z.record, z.looseObject, a catchall and a transform all forward whatever the handler returned.`);\n }\n\n limits(name, route, say);\n reads(name, route, say);\n }\n\n const scope = plugin.definition.scope;\n\n if (scope !== undefined)\n {\n const owns = plugin.definition.tables ?? {};\n\n if (scope.claim.trim() === \"\")\n {\n say(\"UNDECLARED_SCOPE\", name, \"A scope names the claim it reads. An empty one reads nothing.\");\n }\n\n for (const table of Object.keys(scope.tables))\n {\n if (!(table in owns))\n {\n say(\"UNDECLARED_SCOPE\", name, `Scope names \"${table}\", which is not one of this plugin's tables. A plugin scopes only what it owns.`);\n }\n }\n\n if (Object.keys(scope.tables).length === 0)\n {\n say(\"UNDECLARED_SCOPE\", name, \"A scope names no table, so nothing is scoped. Name the tables that carry the claim, or remove it.\");\n }\n }\n\n for (const host of plugin.definition.outbound ?? [])\n {\n const wrong = unreachable(host);\n\n if (wrong !== undefined)\n {\n say(\"UNDECLARED_HOST\", name, wrong);\n }\n }\n\n if (!/^\\d+\\.\\d+\\.\\d+/.test(plugin.definition.version))\n {\n say(\"INVALID_NAME\", name, `Version \"${plugin.definition.version}\" is not a version. Use major.minor.patch.`);\n }\n\n if (plugin.definition.describe.trim() === \"\")\n {\n say(\"INVALID_NAME\", name, \"A plugin describes itself in one sentence. An empty description tells the next reader nothing.\");\n }\n}\n\n/**\n * A header carrying a credential, which no route may ask to read.\n *\n * A handler holding one would put it in a log the moment anyone logged its\n * input, and the framework cannot know which handler is careful.\n */\nconst SECRET: ReadonlySet<string> = new Set([\"cookie\", \"authorization\", \"proxy-authorization\", \"set-cookie\"]);\n\n/** The headers a route asks to read. */\nfunction reads(name: string, route: NonNullable<Plugin[\"definition\"][\"routes\"]>[number], say: Say): void\n{\n for (const header of route.reads ?? [])\n {\n if (header !== header.toLowerCase())\n {\n say(\"INVALID_ROUTE\", name, `Route ${route.method} \"${route.path}\" reads \"${header}\". Header names are matched lowercase.`);\n\n continue;\n }\n\n if (SECRET.has(header))\n {\n say(\"INVALID_ROUTE\", name, `Route ${route.method} \"${route.path}\" reads \"${header}\", which carries a credential. Whoever identifies the caller reads it; a handler holding it would log it.`);\n }\n }\n}\n\n/** A route's own budget, when it declares one. */\n/**\n * Which schemes a plugin may declare, and what each one means.\n *\n * Not a list of protocols the kit speaks: the kit speaks https and nothing\n * else. It is a list of what a plugin may say it talks to, so a connection\n * opened by a plugin's own client is still declared, still visible in the\n * contract, and still refused when it was never named.\n */\nconst SCHEMES: ReadonlySet<string> = new Set([\n \"https\", // an api, and what ctx.fetch dials\n \"wss\", // a socket, encrypted\n \"redis\",\n \"rediss\",\n \"postgres\",\n \"postgresql\",\n \"mysql\",\n \"mongodb\",\n \"mongodb+srv\",\n \"amqp\",\n \"amqps\",\n \"grpc\",\n \"grpcs\",\n]);\n\n/** Schemes that carry credentials in the clear, and reach beyond a network. */\nconst PLAIN: ReadonlySet<string> = new Set([\"http\", \"ws\", \"ftp\"]);\n\n/**\n * Why a declared host cannot be reached, or undefined when it can.\n *\n * A plugin declares what it talks to before it talks to it, whatever protocol\n * that is: a cache, a queue and a vector store are all things a reader of the\n * contract should see, and refusing to let them be written does not stop them\n * being used, only being declared.\n */\nfunction unreachable(host: string): string | undefined\n{\n const at = host.indexOf(\"://\");\n\n if (at === -1)\n {\n return `Outbound host \"${host}\" names no scheme. Write it as an origin, such as \"https://api.stripe.com\" or \"redis://cache.internal:6379\".`;\n }\n\n const scheme = host.slice(0, at).toLowerCase();\n const rest = host.slice(at + 3);\n\n if (PLAIN.has(scheme))\n {\n return `Outbound host \"${host}\" is not encrypted. Use \"${scheme}s://\" instead: what travels over ${scheme} travels in the clear, credentials included.`;\n }\n\n if (!SCHEMES.has(scheme))\n {\n return `Outbound host \"${host}\" uses a scheme this kit does not know. Declared hosts are one of: ${[...SCHEMES].join(\", \")}.`;\n }\n\n if (!/^[a-z0-9._-]+(:\\d+)?$/i.test(rest))\n {\n return `Outbound host \"${host}\" is not an origin. Declare the host it reaches, such as \"${scheme}://cache.internal:6379\", and no path.`;\n }\n\n return undefined;\n}\n\nfunction limits(name: string, route: NonNullable<Plugin[\"definition\"][\"routes\"]>[number], say: Say): void\n{\n const limit = route.limit;\n\n if (limit === undefined)\n {\n return;\n }\n\n if (!Number.isInteger(limit.requests) || limit.requests < 1)\n {\n say(\"INVALID_ROUTE\", name, `Route ${route.method} \"${route.path}\" declares ${limit.requests} requests per window. A budget under one refuses everything, including the caller who set it.`);\n }\n\n if (!Number.isInteger(limit.seconds) || limit.seconds < 1)\n {\n say(\"INVALID_ROUTE\", name, `Route ${route.method} \"${route.path}\" declares a window of ${limit.seconds} seconds. A window without length is one that never resets.`);\n }\n}\n\n/** One route path: how it must be written, and who already took it. */\nfunction path(name: string, method: string, given: string, owned: Owned, say: Say): void\n{\n if (!given.startsWith(\"/\"))\n {\n say(\"INVALID_ROUTE\", name, `Route path \"${given}\" must start with \"/\".`);\n\n return;\n }\n\n if (/\\s/.test(given))\n {\n say(\"INVALID_ROUTE\", name, `Route path \"${given}\" contains whitespace.`);\n\n return;\n }\n\n if (given.includes(\"//\") || (given.length > 1 && given.endsWith(\"/\")))\n {\n say(\"INVALID_ROUTE\", name, `Route path \"${given}\" has an empty segment. Two paths differing only by a slash are one route to a caller and two to a router.`);\n\n return;\n }\n\n for (const segment of given.split(\"/\").slice(1))\n {\n // A parameter is a name in code, so it reads like one: `:documentId`\n // beside `documentId` everywhere else. A literal segment is part of\n // the url, which is case-sensitive and shared with people, so it\n // stays lowercase.\n const named = segment.startsWith(\":\")\n ? /^:[a-zA-Z][a-zA-Z0-9]*$/.test(segment)\n : /^[a-z0-9][a-z0-9-]*$/.test(segment);\n\n if (!named)\n {\n say(\"INVALID_ROUTE\", name, segment.startsWith(\":\")\n ? `Route path \"${given}\" names a parameter \"${segment}\", which is not letters and digits starting with a letter.`\n : `Route path \"${given}\" has a segment \"${segment}\" outside lowercase letters, digits and hyphens.`);\n\n return;\n }\n }\n\n // A parameter is a wildcard, so two routes differing only in what they\n // named it answer the same request, and which one wins is registration\n // order.\n const shape = `${method} ${given.replace(/:[a-zA-Z0-9]+/g, \":*\")}`;\n const first = owned.routes.get(shape);\n\n if (first !== undefined)\n {\n say(\"DUPLICATE_ROUTE\", name, `Route ${method} \"${given}\" is already declared by \"${first}\". Which one answers would depend on order.`);\n\n return;\n }\n\n owned.routes.set(shape, name);\n}\n\n/** Checks one namespaced name, reporting rather than throwing. */\nfunction named(owner: string, key: string, kind: string, say: Say): boolean\n{\n try\n {\n names.namespaced(key, kind, owner);\n\n return true;\n }\n catch (cause)\n {\n say(\"INVALID_NAME\", owner, cause instanceof Error ? cause.message : String(cause));\n\n return false;\n }\n}\n\n/** What a plugin refers to: it must exist, and be reachable. */\nfunction refers(name: string, plugin: Plugin, by: ReadonlyMap<string, Plugin>, owned: Owned, say: Say): void\n{\n const declared = new Set(plugin.definition.dependsOn ?? []);\n\n /** Declared somewhere. What a listener needs, and all it needs. */\n const exists = (kind: keyof Owned, key: string, code: KernelFault[\"code\"], label: string): void =>\n {\n if (owned[kind].get(key) === undefined)\n {\n // The third answer is the one a listener usually needs and the\n // one nobody guesses: hearing does not depend, but the plugin\n // that declares the event still has to be here to declare it.\n const owner = key.split(\".\")[0] ?? \"\";\n const missing = owner !== \"\" && owner !== name && !by.has(owner)\n ? ` \"${owner}\" would declare it and was not given to createKernel: pass it too, which a test of a listener has to do.`\n : \"\";\n\n say(code, name, `${label} \"${key}\" is not declared by any plugin. Declare it, or correct the name.${missing}`);\n }\n };\n\n for (const need of declared)\n {\n if (!by.has(need))\n {\n say(\"UNKNOWN_DEPENDENCY\", name, `\"${name}\" depends on \"${need}\", which no plugin provides. Pass it to createKernel, or remove it from dependsOn.`);\n }\n }\n\n const reach = (kind: keyof Owned, key: string, code: KernelFault[\"code\"], label: string): void =>\n {\n const from = owned[kind].get(key);\n\n if (from === undefined)\n {\n say(code, name, `${label} \"${key}\" is not declared by any plugin. Declare it, or correct the name.`);\n\n return;\n }\n\n if (from !== name && !declared.has(from))\n {\n say(\"UNDECLARED_DEPENDENCY\", name, `${label} \"${key}\" belongs to \"${from}\", which \"${name}\" does not depend on. Add \"${from}\" to dependsOn.`);\n }\n };\n\n // Hearing is not depending. An event is announced to nobody in\n // particular: the emitter does not know who listens and never waits, so a\n // listener adds no edge to the graph. Requiring one made the commonest\n // real shape impossible, because two capabilities that each react to the\n // other are a cycle only on paper.\n for (const key of Object.keys(plugin.definition.listens ?? {}))\n {\n exists(\"events\", key, \"UNDECLARED_EVENT\", \"Event\");\n }\n\n // A hook is the same: the owner runs it and reads what comes back, so the\n // participant is the one being called, not the one calling.\n for (const key of Object.keys(plugin.definition.participates ?? {}))\n {\n exists(\"hooks\", key, \"UNDECLARED_HOOK\", \"Hook\");\n }\n\n for (const route of plugin.definition.routes ?? [])\n {\n for (const permission of route.requires ?? [])\n {\n reach(\"permissions\", permission, \"UNDECLARED_PERMISSION\", \"Permission\");\n }\n\n // A route open to the world that also demands a permission is two\n // intentions in one declaration, and only one of them can hold.\n if (route.public === true && (route.requires ?? []).length > 0)\n {\n say(\"INVALID_ROUTE\", name, `Route ${route.method} \"${route.path}\" is public and also requires ${(route.requires ?? []).map((one) => `\"${one}\"`).join(\", \")}. It is one or the other.`);\n }\n }\n\n for (const one of Object.values(plugin.definition.commands ?? {}))\n {\n for (const permission of one.requires ?? [])\n {\n reach(\"permissions\", permission, \"UNDECLARED_PERMISSION\", \"Permission\");\n }\n }\n}\n\n/** Config is parsed by the plugin's own schema, where it enters. */\nfunction settings(name: string, plugin: Plugin, config: Readonly<Record<string, unknown>>, say: Say): void\n{\n const schema = plugin.definition.config;\n\n if (schema === undefined)\n {\n return;\n }\n\n const answered = schema.safeParse(config[name] ?? {});\n\n if (!answered.success)\n {\n const first = answered.error.issues[0];\n const at = first === undefined || first.path.length === 0 ? \"\" : ` at \"${first.path.join(\".\")}\"`;\n\n say(\"INVALID_CONFIG\", name, `Config for \"${name}\" is invalid${at}: ${first?.message ?? \"it does not match the schema\"}.`);\n }\n}\n\n/** A cycle in dependsOn, named from where it was entered back to itself. */\nfunction cycles(by: ReadonlyMap<string, Plugin>, say: Say): void\n{\n const state = new Map<string, \"open\" | \"done\">();\n const walking: string[] = [];\n const reported = new Set<string>();\n\n function walk(name: string): void\n {\n if (state.get(name) === \"done\")\n {\n return;\n }\n\n if (state.get(name) === \"open\")\n {\n const at = walking.indexOf(name);\n const loop = [...walking.slice(at === -1 ? 0 : at), name];\n const key = [...loop].sort().join(\",\");\n\n if (!reported.has(key))\n {\n reported.add(key);\n say(\"DEPENDENCY_CYCLE\", name, `Plugins depend on each other in a loop: ${loop.join(\" -> \")}. One of them has to stop.`);\n }\n\n return;\n }\n\n state.set(name, \"open\");\n walking.push(name);\n\n for (const need of [...(by.get(name)?.definition.dependsOn ?? [])].sort())\n {\n if (by.has(need))\n {\n walk(need);\n }\n }\n\n walking.pop();\n state.set(name, \"done\");\n }\n\n for (const name of [...by.keys()].sort())\n {\n walk(name);\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { context, type Wiring } from \"./context\";\nimport type { Caller, Context, Method, Plugin, Route } from \"./contract\";\nimport { events, type Failure, type Pending } from \"./events\";\nimport { KernelFault } from \"./faults\";\nimport { hooks } from \"./hooks\";\nimport { order } from \"./order\";\nimport { permissions } from \"./permissions\";\nimport { type Budget, type Incoming, type Mounted, notServing, type Outgoing, respond, unknownRoute } from \"./request\";\nimport type { Dialer, Narrowing, Outbox, Schedule, Storage } from \"./store\";\nimport { validate } from \"./validate\";\n\n/** Where a line goes. The project decides; a plugin never writes directly. */\nexport type Log = (\n level: \"debug\" | \"info\" | \"warn\" | \"error\",\n plugin: string,\n line: string,\n about?: Readonly<Record<string, unknown>>,\n) => void;\n\n/** What a project gives the kernel. */\nexport type Options = {\n plugins: readonly Plugin[];\n config?: Readonly<Record<string, unknown>>;\n db?: Storage;\n dial?: Dialer;\n log?: Log;\n\n /**\n * What counts requests against a route's declared budget.\n *\n * Omit it and a `limit` is inert, which is why `start` says so rather\n * than letting a declared budget quietly enforce nothing.\n */\n budget?: Budget;\n\n /**\n * Where events wait between the transaction that emitted them and the\n * listener that hears them.\n *\n * Without one, an event that is emitted lives only in memory: the work\n * commits, the process stops, and nothing ever calls the listener. With\n * one, delivery is at least once, so a listener that writes must survive\n * being called twice.\n */\n outbox?: Outbox;\n\n /**\n * What the current time is, in milliseconds.\n *\n * A test pins it to make tomorrow reachable without moving the machine's\n * clock, which every other test in the process would then share.\n */\n now?: () => number;\n\n /**\n * Where work waits until it is time, and how often to look.\n *\n * Without one, `ctx.commands.later` refuses: a plugin that can ask for\n * later work in a deployment that cannot run it would be told nothing.\n */\n schedule?: Schedule;\n\n /** How often to ask the schedule what is due, in milliseconds. */\n beat?: number;\n\n /**\n * How many times a scheduled command may throw before it is abandoned.\n *\n * Eight by default, which is roughly four minutes of backing off. A job\n * that has failed that often is failing on something a retry will not\n * fix, and the line saying it gave up is worth more than the ninth try.\n */\n attempts?: number;\n\n /**\n * How a declared scope becomes a condition the store understands.\n *\n * The kernel imports no driver, so a project that declares a scope also\n * says how to narrow by it.\n */\n narrow?: Narrowing;\n\n /**\n * How long a hook participant has to answer, in milliseconds.\n *\n * A participant that never answers holds the request open, and a throw is\n * already a refusal, so silence is treated as one too.\n */\n patience?: number;\n};\n\n/** A route, and the plugin it came from. */\nexport type Registered = {\n plugin: string;\n method: Method;\n path: string;\n describe: string;\n requires: readonly string[];\n public: boolean;\n limit: { requests: number; seconds: number } | undefined;\n\n /** The request headers this route declared it reads, lowercase. */\n reads: readonly string[];\n};\n\n/** What a project holds after createKernel. */\nexport type Kernel = {\n start: () => Promise<void>;\n stop: () => Promise<void>;\n started: () => boolean;\n\n routes: () => readonly Registered[];\n handle: (incoming: Incoming) => Promise<Outgoing>;\n\n context: (plugin: string, caller?: Caller) => Context;\n events: { failures: () => readonly Failure[] };\n\n /**\n * Runs whatever the schedule says is due, once, and waits for it.\n *\n * What the beat does on a timer, asked for. A test moves its clock and\n * calls this instead of waiting a real second for an interval it does not\n * control.\n */\n due: () => Promise<void>;\n run: (command: string, input: unknown, caller?: Caller) => Promise<void>;\n};\n\nconst quiet: Log = () => {};\n\n/** The route a request lands on, and what its path segments named. */\n/**\n * One path segment, decoded, or undefined when it cannot be.\n *\n * A malformed escape makes decodeURIComponent throw, and this runs before\n * respond()'s try/catch: over HTTP the server normalises first, but a project\n * calling handle() directly would get an unhandled rejection where it asked\n * for an answer. A segment that cannot be read matches nothing.\n */\nfunction readable(given: string): string | undefined\n{\n try\n {\n return decodeURIComponent(given);\n }\n catch\n {\n return undefined;\n }\n}\n\nfunction matched(\n routes: ReadonlyMap<string, Mounted>,\n method: Method,\n path: string,\n): { mounted: Mounted; params: Readonly<Record<string, string>> } | undefined\n{\n const exact = routes.get(`${method} ${path}`);\n\n if (exact !== undefined)\n {\n return { mounted: exact, params: {} };\n }\n\n const asked = path.split(\"/\");\n\n for (const [key, mounted] of routes)\n {\n const [verb, declared] = key.split(\" \");\n\n if (verb !== method || declared === undefined)\n {\n continue;\n }\n\n const parts = declared.split(\"/\");\n\n if (parts.length !== asked.length)\n {\n continue;\n }\n\n const params: Record<string, string> = {};\n const fits = parts.every((part, at) =>\n {\n const given = asked[at] ?? \"\";\n\n if (!part.startsWith(\":\"))\n {\n return part === given;\n }\n\n const value = readable(given);\n\n if (value === undefined)\n {\n return false;\n }\n\n params[part.slice(1)] = value;\n\n return given !== \"\";\n });\n\n if (fits)\n {\n return { mounted, params };\n }\n }\n\n return undefined;\n}\n\n/** The input a route sees: what the caller passed, with the path on top. */\nfunction taken(input: unknown, params: Readonly<Record<string, string>>): unknown\n{\n if (Object.keys(params).length === 0)\n {\n return input;\n }\n\n const given = input !== null && typeof input === \"object\" && !Array.isArray(input)\n ? { ...(input as Record<string, unknown>) }\n : {};\n\n // The path wins, as it does over HTTP: a router already matched it, so a\n // body claiming otherwise is confused or deliberate.\n return { ...given, ...params };\n}\n\n/**\n * Builds a kernel from what the plugins declared.\n *\n * Nothing runs here: `start` validates first, and either brings up every\n * plugin or throws. A half-started kernel behaves according to where it\n * stopped, which is not a state anyone can reason about.\n */\nexport function createKernel(options: Options): Kernel\n{\n const config = options.config ?? {};\n const log = options.log ?? quiet;\n\n const known = new Map(options.plugins.map((one) => [one.name, one]));\n const bus = events<Context>(Date.now, (plugin, line, about) =>\n {\n log(\"error\", plugin, line, about);\n });\n const points = hooks<Context>(options.patience);\n const parsed = new Map<string, unknown>();\n const pending = new Map<object, Pending[]>();\n\n const routes = new Map<string, Mounted>();\n const commands = new Map<string, {\n plugin: string;\n requires: readonly string[];\n schema: { safeParse: (value: unknown) => { success: boolean; data?: unknown; error?: { issues: { message: string }[] } } };\n run: (input: never, ctx: Context) => void | Promise<void>;\n }>();\n\n let running = false;\n let beating: ReturnType<typeof setInterval> | undefined;\n\n /**\n * Runs what is due, one turn.\n *\n * Failures are the point rather than an afterthought: a command that\n * throws goes back with its attempt counted, so a partner that was down\n * for a minute costs a minute rather than the work.\n */\n async function due(): Promise<void>\n {\n if (options.schedule === undefined || !running)\n {\n return;\n }\n\n const clock = options.now ?? Date.now;\n const taken = await options.schedule.take(clock(), 20);\n\n for (const job of taken)\n {\n try\n {\n await run(job.command, job.input);\n await options.schedule.done(job.id);\n }\n catch (cause)\n {\n log(\"error\", job.plugin, \"a scheduled command failed\", {\n command: job.command,\n attempts: job.attempts + 1,\n error: cause instanceof Error ? cause.message : String(cause),\n });\n\n // Backing off, so a command failing on something that is\n // still broken does not spend the whole beat on itself. And\n // giving up eventually: a job retried forever is a process\n // spending itself on work nobody is waiting for any more.\n if (job.attempts + 1 >= (options.attempts ?? 8))\n {\n log(\"error\", job.plugin, \"a scheduled command gave up\", {\n command: job.command,\n attempts: job.attempts + 1,\n });\n\n await options.schedule.gaveUp(job.id);\n }\n else\n {\n await options.schedule.failed(job.id, clock() + Math.min(2 ** job.attempts, 60) * 1000);\n }\n }\n }\n }\n\n // What is still being answered. A shutdown waits for these: a request\n // that has already been accepted was promised an answer, and tearing the\n // plugins down underneath it turns that promise into a 500.\n const inFlight = new Set<Promise<unknown>>();\n let started: Plugin[] = [];\n\n const wiring: Wiring = {\n known,\n parsed,\n open: new AsyncLocalStorage<object>(),\n config,\n bus,\n points,\n pending,\n outbox: options.outbox,\n now: options.now ?? Date.now,\n schedule: options.schedule,\n narrow: options.narrow,\n owned: new Map<string, unknown>(),\n db: options.db,\n dial: options.dial,\n log,\n run: (command, input, caller) => run(command, input, caller),\n };\n\n const seenBy = (plugin: string, caller?: Caller, headers?: Readonly<Record<string, string>>): Context =>\n {\n return context(wiring, plugin, caller, undefined, headers);\n };\n\n /** Runs a command, after its permission and its schema. */\n async function run(command: string, input: unknown, caller?: Caller): Promise<void>\n {\n if (!running)\n {\n throw new KernelFault(\n \"NOT_STARTED\",\n `Command \"${command}\" was run before the kernel started. Every plugin's setup runs first, so a command called from one is too early: reach the service directly instead.`,\n );\n }\n\n const declared = commands.get(command);\n\n if (declared === undefined)\n {\n throw new KernelFault(\"UNDECLARED_COMMAND\", `Command \"${command}\" is not declared by any plugin.`);\n }\n\n const may = permissions(() => caller);\n const lacking = declared.requires.filter((permission) => !may.has(permission));\n\n if (lacking.length > 0)\n {\n // A scheduled run has no caller at all, which is not the same\n // problem as one who is short a permission: no permission can be\n // granted to nobody, so a command the schedule asks for declares\n // none. Saying only \"the caller does not have\" sends its author\n // looking for a permission to hand out.\n const scheduled = caller === undefined\n ? \" A scheduled run has no caller, so a command asked for by commands.later declares no requires.\"\n : \"\";\n\n throw new KernelFault(\n \"PERMISSION_DENIED\",\n `Command \"${command}\" needs ${lacking.map((permission) => `\"${permission}\"`).join(\", \")}, which the caller does not have.${scheduled}`,\n { plugin: declared.plugin, detail: { lacking } },\n );\n }\n\n const parsed = declared.schema.safeParse(input);\n\n if (!parsed.success)\n {\n throw new KernelFault(\n \"INVALID_PAYLOAD\",\n `The input for \"${command}\" does not match its schema: ${parsed.error?.issues[0]?.message ?? \"it was rejected\"}.`,\n { plugin: declared.plugin },\n );\n }\n\n await declared.run(parsed.data as never, seenBy(declared.plugin, caller));\n }\n\n return {\n started: () =>\n {\n return running;\n },\n\n async start(): Promise<void>\n {\n if (running)\n {\n return;\n }\n\n const wrong = validate(options.plugins, config);\n\n if (wrong.length > 0)\n {\n const lines = wrong.map((problem) => ` - [${problem.code}] ${problem.plugin}: ${problem.message}`);\n\n throw new KernelFault(\n wrong[0]?.code ?? \"INVALID_CONFIG\",\n `${wrong.length} ${wrong.length === 1 ? \"problem\" : \"problems\"} stopped the kernel from starting:\\n${lines.join(\"\\n\")}`,\n { plugin: wrong[0]?.plugin ?? \"\", detail: { wrong } },\n );\n }\n\n started = order(known);\n\n for (const plugin of started)\n {\n const schema = plugin.definition.config;\n\n if (schema !== undefined)\n {\n parsed.set(plugin.name, schema.parse(config[plugin.name] ?? {}));\n }\n }\n\n // Declared before anything is wired: a listener may name an event\n // owned by a plugin that comes later in the order.\n for (const plugin of started)\n {\n for (const [name, event] of Object.entries(plugin.definition.emits ?? {}))\n {\n bus.declare(plugin.name, name, event);\n }\n\n for (const [name, hook] of Object.entries(plugin.definition.hooks ?? {}))\n {\n points.declare(plugin.name, name, hook);\n }\n }\n\n for (const plugin of started)\n {\n for (const [name, listener] of Object.entries(plugin.definition.listens ?? {}))\n {\n bus.listen(plugin.name, name, listener);\n }\n\n for (const [name, participant] of Object.entries(plugin.definition.participates ?? {}))\n {\n points.participate(plugin.name, name, participant);\n }\n\n for (const [name, command] of Object.entries(plugin.definition.commands ?? {}))\n {\n commands.set(name, {\n plugin: plugin.name,\n requires: command.requires ?? [],\n schema: command.schema,\n run: command.run,\n });\n }\n\n for (const route of plugin.definition.routes ?? [])\n {\n routes.set(`${route.method} ${route.path}`, { plugin: plugin.name, route: route as Route<Context> });\n }\n }\n\n // A declared budget nothing enforces is worse than none: the\n // contract says the route is protected and it is not.\n if (options.budget === undefined)\n {\n const declared = [...routes.values()].filter(({ route }) => route.limit !== undefined);\n\n if (declared.length > 0)\n {\n const named = declared.map(({ plugin, route }) => `${plugin}: ${route.method} ${route.path}`);\n\n throw new KernelFault(\n \"INVALID_ROUTE\",\n `${declared.length} ${declared.length === 1 ? \"route declares a limit\" : \"routes declare limits\"} and no budget was given to createKernel, so nothing would enforce them:\\n${named.map((one) => ` - ${one}`).join(\"\\n\")}\\nPass \\`budget\\`, or remove the limits.`,\n { plugin: declared[0]?.plugin ?? \"\" },\n );\n }\n }\n\n for (const plugin of started)\n {\n await plugin.definition.setup?.(seenBy(plugin.name));\n }\n\n running = true;\n\n if (options.schedule !== undefined)\n {\n beating = setInterval(() => void due(), options.beat ?? 1000);\n\n // So a beat never holds a process open that is otherwise done.\n beating.unref?.();\n }\n\n // Anything still waiting was interrupted between its commit and\n // its delivery: the work happened, the listener never heard. It\n // is delivered now, before this kernel answers anything new.\n const interrupted = await options.outbox?.waiting() ?? [];\n\n for (const announcement of interrupted)\n {\n log(\"info\", announcement.plugin, \"delivering an event that outlived its process\", {\n event: announcement.name,\n });\n\n await bus.deliver(announcement.plugin, announcement.name, announcement.payload, (to) => seenBy(to));\n\n await options.outbox?.sent(announcement.id);\n }\n },\n\n async stop(): Promise<void>\n {\n // Stop accepting first, then wait: a request accepted after this\n // point would be one more thing to wait for, and draining would\n // never end under load.\n running = false;\n\n if (beating !== undefined)\n {\n clearInterval(beating);\n beating = undefined;\n }\n\n if (inFlight.size > 0)\n {\n log(\"info\", \"kernel\", \"waiting for requests in flight\", { count: inFlight.size });\n\n await Promise.allSettled([...inFlight]);\n }\n\n for (const plugin of [...started].reverse())\n {\n try\n {\n await plugin.definition.teardown?.(seenBy(plugin.name));\n }\n catch (cause)\n {\n log(\"error\", plugin.name, \"teardown threw\", { cause });\n }\n }\n },\n\n routes: (): readonly Registered[] =>\n [...routes.values()].map(({ plugin, route }) => ({\n plugin,\n method: route.method,\n path: route.path,\n describe: route.describe,\n requires: route.requires ?? [],\n public: route.public === true,\n limit: route.limit,\n reads: route.reads ?? [],\n })),\n\n handle: (incoming: Incoming): Promise<Outgoing> =>\n {\n // A kernel that has stopped has torn its plugins down, so an\n // answer from here would be one they never agreed to give.\n if (!running)\n {\n return Promise.resolve(notServing);\n }\n\n const found = matched(routes, incoming.method, incoming.path);\n\n if (found === undefined)\n {\n return Promise.resolve(unknownRoute);\n }\n\n // A caller may pass the declared path with its parameters in\n // `input`, as the server does, or the real one with the values in\n // it. Taking both means a test reads like the request it stands\n // for rather than like the routing table.\n const answering = respond(\n found.mounted,\n { ...incoming, input: taken(incoming.input, found.params) },\n seenBy,\n log,\n options.budget,\n );\n\n inFlight.add(answering);\n\n return answering.finally(() =>\n {\n inFlight.delete(answering);\n });\n },\n\n context: seenBy,\n\n events: { failures: bus.failures },\n\n due,\n\n run,\n };\n}\n","import type { z } from \"zod\";\n\nimport type { Command, Context, Definition, Listener, Participant, Plugin, Route } from \"./contract\";\nimport * as names from \"./names\";\n\n/**\n * Declares a plugin.\n *\n * The name is checked here rather than at start, so a typo names itself where\n * it was written instead of in a stack from somewhere else.\n *\n * `Db` is what `ctx.db` will be: the Drizzle handle over this plugin's own\n * tables. TypeScript cannot infer it, because the kernel never imports a\n * driver, so a plugin that queries names it:\n *\n * export default definePlugin.over<ItemRows>()(\"items\", { … });\n *\n * A plugin that never touches the database writes `definePlugin(name, …)` and\n * ignores all of this.\n */\nexport function definePlugin<Schema extends z.ZodType, Services = unknown, Db = unknown>(\n name: string,\n definition: Definition<Schema, Services, Db>,\n): Plugin\n{\n names.plugin(name);\n\n return { name, definition: definition as unknown as Definition };\n}\n\n/**\n * Declares a plugin whose `ctx.db` is typed.\n *\n * Curried because TypeScript takes a type argument list all or nothing: name\n * `Db` on `definePlugin` directly and you must also name `Schema`, which is\n * the config schema and infers perfectly well on its own.\n *\n * `Services` is named alongside `Db` when a route reads `ctx.services`: it is\n * inferred from what `services` returns, and a route above that key would\n * otherwise see `unknown`.\n */\ndefinePlugin.over = <Db, Services = unknown>() =>\n <Schema extends z.ZodType>(\n name: string,\n definition: Definition<Schema, Services, Db>,\n ): Plugin =>\n {\n names.plugin(name);\n\n return { name, definition: definition as unknown as Definition };\n };\n\n/**\n * Declares one route, with its input typed by its own schema.\n *\n * TypeScript settles a whole object literal's type before it looks inside an\n * array, so a route written inline hands its handler `unknown`. Declaring the\n * route through a function infers the schema first, and the handler reads its\n * fields.\n *\n * defineRoute<ItemCtx>()({\n * method: \"GET\",\n * input: z.object({ id: z.uuid() }),\n * handle: (given) => given.id, // a string, no cast\n * })\n */\nexport function defineRoute<Ctx = Context>()\n{\n return <Input extends z.ZodType>(route: Route<Ctx, Input>): Route<Ctx, Input> =>\n {\n return route;\n };\n}\n\n/**\n * Declares one listener, with its payload typed by the event's own schema.\n *\n * Pass the schema the emitting plugin declared: the kernel parses against it\n * before delivering, so what arrives has already passed.\n *\n * defineListener<ItemCtx>()(ItemMade.schema, {\n * describe: \"…\",\n * handle: (made) => made.id, // a string, no cast\n * })\n */\nexport function defineListener<Ctx = Context>()\n{\n return <Payload extends z.ZodType>(\n _schema: Payload,\n listener: Listener<Ctx, z.infer<Payload>>,\n ): Listener<Ctx, z.infer<Payload>> =>\n {\n return listener;\n };\n}\n\n/** Declares one participant, with its payload typed by the hook's schema. */\nexport function defineParticipant<Ctx = Context>()\n{\n return <Payload extends z.ZodType>(\n _schema: Payload,\n participant: Participant<Ctx, z.infer<Payload>>,\n ): Participant<Ctx, z.infer<Payload>> =>\n {\n return participant;\n };\n}\n\n/** Declares one command, with its input typed by its own schema. */\nexport function defineCommand<Ctx = Context>()\n{\n return <Input extends z.ZodType>(command: Command<Ctx, Input>): Command<Ctx, Input> =>\n {\n return command;\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type Database from \"better-sqlite3\";\n\n/** Where one plugin keeps its migrations. */\nexport type Source = {\n plugin: string;\n from: string;\n};\n\n/** One migration file, as it sits on disk. */\nexport type Step = {\n plugin: string;\n name: string;\n sql: string;\n hash: string;\n};\n\n/** What went wrong, in a sentence naming the file. */\nexport class MigrationFault extends Error\n{\n readonly plugin: string;\n\n readonly step: string | undefined;\n\n constructor(message: string, plugin: string, step?: string)\n {\n super(message);\n\n this.name = \"MigrationFault\";\n this.plugin = plugin;\n this.step = step;\n }\n}\n\nconst NAMED = /^(\\d{4})-[a-z0-9][a-z0-9-]*\\.sql$/;\n\n/** The table recording what has run. Ours, and no plugin's to read. */\nconst LEDGER = `\n CREATE TABLE IF NOT EXISTS _migrations (\n plugin TEXT NOT NULL,\n name TEXT NOT NULL,\n hash TEXT NOT NULL,\n ran_at TEXT NOT NULL,\n PRIMARY KEY (plugin, name)\n )\n`;\n\n/** What a file says, hashed so a later edit to it is visible. */\nfunction read(plugin: string, from: string, name: string): Step\n{\n const sql = readFileSync(join(from, name), \"utf8\");\n\n return { plugin, name, sql, hash: createHash(\"sha256\").update(sql).digest(\"hex\") };\n}\n\n/**\n * The migrations one plugin holds, in the order their numbers give.\n *\n * A name outside `NNNN-name.sql` is refused rather than sorted somewhere:\n * \"2-b.sql\" sorts before \"10-a.sql\" as text and after it as a number, and a\n * schema that depends on which is a schema nobody can reproduce.\n */\nexport function steps(source: Source): Step[]\n{\n let found: string[];\n\n try\n {\n found = readdirSync(source.from);\n }\n catch\n {\n throw new MigrationFault(`\"${source.plugin}\" declares migrations at \"${source.from}\", which cannot be read.`, source.plugin);\n }\n\n const sql = found.filter((name) => name.endsWith(\".sql\"));\n\n for (const name of sql)\n {\n if (!NAMED.test(name))\n {\n throw new MigrationFault(`\"${name}\" is not named NNNN-name.sql, so its place in the order is ambiguous.`, source.plugin, name);\n }\n }\n\n const numbers = new Map<string, string>();\n\n for (const name of sql)\n {\n const at = NAMED.exec(name)?.[1] ?? \"\";\n const first = numbers.get(at);\n\n if (first !== undefined)\n {\n throw new MigrationFault(`\"${name}\" and \"${first}\" share the number ${at}, so which runs first is undefined.`, source.plugin, name);\n }\n\n numbers.set(at, name);\n }\n\n return [...sql].sort().map((name) => read(source.plugin, source.from, name));\n}\n\n/**\n * Runs what has not run yet, in dependency order, each in its own transaction.\n *\n * A migration already recorded is checked against what it recorded rather\n * than skipped quietly: a file edited after it ran leaves one database with\n * the old shape and another with the new, both reporting they are current.\n */\nexport function migrate(connection: Database.Database, sources: readonly Source[]): Step[] {\n connection.exec(LEDGER);\n\n const seen = new Map<string, string>();\n\n for (const row of connection.prepare(\"SELECT plugin, name, hash FROM _migrations\").all() as { plugin: string; name: string; hash: string }[])\n {\n seen.set(`${row.plugin}/${row.name}`, row.hash);\n }\n\n const ran: Step[] = [];\n\n for (const source of sources)\n {\n for (const step of steps(source))\n {\n const before = seen.get(`${step.plugin}/${step.name}`);\n\n if (before === step.hash)\n {\n continue;\n }\n\n if (before !== undefined)\n {\n throw new MigrationFault(\n `\"${step.name}\" has changed since it ran. A migration is history: add a new one rather than editing what other databases already applied.`,\n step.plugin,\n step.name,\n );\n }\n\n // One transaction per step, so a failure leaves the ones before it\n // applied and recorded rather than half of one applied.\n const apply = connection.transaction(() =>\n {\n connection.exec(step.sql);\n connection.prepare(\"INSERT INTO _migrations (plugin, name, hash, ran_at) VALUES (?, ?, ?, ?)\")\n .run(step.plugin, step.name, step.hash, new Date().toISOString());\n });\n\n try\n {\n apply();\n }\n catch (cause)\n {\n throw new MigrationFault(\n `\"${step.name}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n step.plugin,\n step.name,\n );\n }\n\n ran.push(step);\n }\n }\n\n return ran;\n}\n","import { eq } from \"drizzle-orm\";\n\nimport type { Narrowing } from \"../../kernel/api\";\n\ntype Column = Readonly<Record<string, unknown>>;\n\n/**\n * Turns a declared scope into a condition.\n *\n * The kernel knows which table and which column, and nothing about how a\n * query is built. This knows Drizzle and nothing about tenants, so neither\n * half has to learn the other's business.\n */\nexport function narrowing(owned: Readonly<Record<string, Readonly<Record<string, unknown>>>>): Narrowing\n{\n return (table: string, column: string, value: string): unknown =>\n {\n // Table names are unique across the store, because a plugin's tables\n // live in its own namespace and the kernel checked that at startup.\n const found = Object.values(owned)\n .map((tables) => tables[table])\n .find((one) => one !== undefined) as Column | undefined;\n\n if (found === undefined)\n {\n throw new Error(`Cannot scope \"${table}\": no table of that name was given to the store.`);\n }\n\n const at = found[column];\n\n if (at === undefined)\n {\n throw new Error(`Cannot scope \"${table}\" by \"${column}\": the table declares no such column.`);\n }\n\n return eq(at as Parameters<typeof eq>[0], value);\n };\n}\n","import type Database from \"better-sqlite3\";\n\nimport type { Announcement, Outbox } from \"../../kernel/api\";\n\n/**\n * Where events wait, in the same database as the work they announce.\n *\n * That is the whole point: the row is written by the transaction that emitted\n * the event, so the two cannot disagree. An event about work that rolled back\n * rolls back with it, and work that committed leaves an event behind even if\n * the process stops before anyone hears it.\n *\n * Its table is the kit's, not a plugin's, so no contract declares it and no\n * `ctx.db` reaches it.\n */\nexport function outbox(connection: Database.Database): Outbox\n{\n connection.exec(`\n CREATE TABLE IF NOT EXISTS kit_outbox (\n id TEXT PRIMARY KEY,\n plugin TEXT NOT NULL,\n name TEXT NOT NULL,\n payload TEXT NOT NULL,\n keptAt TEXT NOT NULL\n )\n `);\n\n const insert = connection.prepare(\n \"INSERT INTO kit_outbox (id, plugin, name, payload, keptAt) VALUES (?, ?, ?, ?, ?)\",\n );\n\n const remove = connection.prepare(\"DELETE FROM kit_outbox WHERE id = ?\");\n const unsent = connection.prepare(\"SELECT id, plugin, name, payload FROM kit_outbox ORDER BY keptAt\");\n\n return {\n // Synchronous, and it must stay that way: this runs inside an open\n // transaction, and an await here would let another one interleave.\n keep: (_db: unknown, announcements: readonly Announcement[]) =>\n {\n const at = new Date().toISOString();\n\n for (const one of announcements)\n {\n insert.run(one.id, one.plugin, one.name, JSON.stringify(one.payload), at);\n }\n },\n\n sent: (id: string) =>\n {\n // A delivery can finish after the process began stopping, and\n // this runs when it does. Forgetting a delivered event matters\n // less than crashing on the way out: the event is delivered\n // either way, and what stays is redelivered next start, which\n // at-least-once already allows for.\n try\n {\n remove.run(id);\n }\n catch (cause)\n {\n if (!(cause instanceof TypeError))\n {\n throw cause;\n }\n }\n\n return Promise.resolve();\n },\n\n waiting: () =>\n {\n const rows = unsent.all() as { id: string; plugin: string; name: string; payload: string }[];\n\n return Promise.resolve(rows.map((row): Announcement => ({\n id: row.id,\n plugin: row.plugin,\n name: row.name,\n payload: JSON.parse(row.payload) as unknown,\n })));\n },\n };\n}\n","import type Database from \"better-sqlite3\";\n\nimport type { Schedule, Scheduled } from \"../../kernel/api\";\n\n/**\n * Where later work waits, in the same database as the work that asked for it.\n *\n * A job claimed by one process is not claimed by another: `take` marks and\n * reads in one statement, so two processes beating at the same moment split\n * the work rather than doubling it.\n *\n * Its table is the kit's, not a plugin's, so no contract declares it.\n */\nexport function schedule(connection: Database.Database): Schedule\n{\n connection.exec(`\n CREATE TABLE IF NOT EXISTS kit_schedule (\n id TEXT PRIMARY KEY,\n plugin TEXT NOT NULL,\n command TEXT NOT NULL,\n input TEXT NOT NULL,\n runAt INTEGER NOT NULL,\n takenAt INTEGER,\n attempts INTEGER NOT NULL DEFAULT 0\n );\n\n CREATE INDEX IF NOT EXISTS kit_schedule_due ON kit_schedule (runAt) WHERE takenAt IS NULL;\n `);\n\n const insert = connection.prepare(\n \"INSERT INTO kit_schedule (id, plugin, command, input, runAt, attempts) VALUES (?, ?, ?, ?, ?, ?)\",\n );\n\n // One statement, so the claim and the read cannot come apart: a second\n // process reaching the same row finds it already taken.\n const claim = connection.prepare(`\n UPDATE kit_schedule SET takenAt = ?\n WHERE id IN (\n SELECT id FROM kit_schedule\n WHERE takenAt IS NULL AND runAt <= ?\n ORDER BY runAt\n LIMIT ?\n )\n RETURNING id, plugin, command, input, runAt, attempts\n `);\n\n const remove = connection.prepare(\"DELETE FROM kit_schedule WHERE id = ?\");\n const again = connection.prepare(\n \"UPDATE kit_schedule SET takenAt = NULL, runAt = ?, attempts = attempts + 1 WHERE id = ?\",\n );\n\n return {\n keep: (_db: unknown, job: Scheduled) =>\n {\n insert.run(job.id, job.plugin, job.command, JSON.stringify(job.input), job.at, job.attempts);\n },\n\n take: (now: number, limit: number) =>\n {\n const rows = claim.all(now, now, limit) as {\n id: string;\n plugin: string;\n command: string;\n input: string;\n runAt: number;\n attempts: number;\n }[];\n\n return Promise.resolve(rows.map((row): Scheduled => ({\n id: row.id,\n plugin: row.plugin,\n command: row.command,\n input: JSON.parse(row.input) as unknown,\n at: row.runAt,\n attempts: row.attempts,\n })));\n },\n\n done: (id: string) =>\n {\n remove.run(id);\n\n return Promise.resolve();\n },\n\n failed: (id: string, at: number) =>\n {\n again.run(at, id);\n\n return Promise.resolve();\n },\n\n gaveUp: (id: string) =>\n {\n remove.run(id);\n\n return Promise.resolve();\n },\n };\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nimport Database from \"better-sqlite3\";\n\n/** What opening a database needs to know. */\nexport type Opening = {\n /** A path, or \":memory:\" for one that lives as long as the process. */\n file: string;\n\n /** How long a writer waits for another to finish, in milliseconds. */\n busyMs?: number;\n\n /** Whether to keep the write-ahead log. Off for :memory:, which has none. */\n wal?: boolean;\n};\n\n/**\n * Opens one connection, configured the way a server needs it.\n *\n * SQLite defaults suit a single-process script, not a server, and every one\n * of these was chosen rather than inherited:\n *\n * - WAL lets readers work while one writer writes. Without it a read blocks\n * every write, and a busy server spends its afternoon waiting.\n * - foreign_keys is OFF by default, which means a schema declaring them gets\n * no enforcement at all and nobody is told.\n * - busy_timeout turns \"database is locked\", thrown instantly, into a wait.\n * SQLite has one writer; the question is only whether the second one waits\n * or fails.\n * - NORMAL synchronous is the pairing WAL is designed for: durable across a\n * process crash, and only at risk in an OS-level power loss.\n */\nexport function connect(opening: Opening): Database.Database\n{\n const memory = opening.file === \":memory:\";\n\n // Made rather than demanded: better-sqlite3 answers a missing directory\n // with \"Cannot open database because the directory does not exist\",\n // naming neither the path nor the setting, so the first run of a fresh\n // checkout fails on something nobody chose.\n if (!memory)\n {\n mkdirSync(dirname(opening.file), { recursive: true });\n }\n\n const connection = new Database(opening.file);\n\n if (opening.wal ?? !memory)\n {\n connection.pragma(\"journal_mode = WAL\");\n connection.pragma(\"synchronous = NORMAL\");\n }\n\n connection.pragma(\"foreign_keys = ON\");\n connection.pragma(`busy_timeout = ${opening.busyMs ?? 5_000}`);\n\n return connection;\n}\n","/**\n * Runs work one at a time.\n *\n * SQLite gives us one connection, and a transaction lives on the connection\n * rather than on the call that opened it. So an async transaction that awaits\n * anything leaves the connection inside a transaction while other work runs:\n * a second request's write lands in someone else's transaction and is lost to\n * their rollback, and a second BEGIN throws outright.\n *\n * Queueing is what makes `tx` mean what it says. It costs throughput, which\n * is the trade SQLite already made for us: one writer, whatever we do.\n */\nexport function queue()\n{\n let last: Promise<unknown> = Promise.resolve();\n\n return {\n run: <Made,>(work: () => Promise<Made>): Promise<Made> =>\n {\n const mine = last.then(work, work);\n\n // The chain must not stop at a failure, and must not keep the\n // rejection alive: whoever asked already holds it.\n last = mine.catch(() => undefined);\n\n return mine;\n },\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type Database from \"better-sqlite3\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\n\nimport { queue } from \"./queue\";\n\nexport type Tables = Readonly<Record<string, unknown>>;\n\nexport type Holding = {\n connection: Database.Database;\n tables: Readonly<Record<string, Tables>>;\n};\n\nexport type Handle = ReturnType<typeof drizzle>;\n\n/**\n * One connection, and one handle per plugin over it.\n *\n * The handle carries only that plugin's tables, so a query naming another\n * plugin's table does not compile. That is a compile-time boundary, not a\n * physical one: the connection underneath is shared, and a plugin importing\n * another's table object, or reaching `$client`, gets past it. SQLite gives\n * one connection, and a connection per plugin would make a transaction across\n * two plugins impossible, which costs more than it buys.\n */\nexport function store(holding: Holding)\n{\n const handles = new Map<string, Handle>();\n const waiting = queue();\n\n /**\n * Which transaction the running code is inside, if any.\n *\n * A counter would say a transaction is open, never that *this* call is\n * the one inside it: while a transaction waits on the network, the next\n * one off the queue would read that counter, believe itself nested, and\n * open a savepoint inside a stranger's transaction.\n */\n const inside = new AsyncLocalStorage<number>();\n\n let open = true;\n let counter = 0;\n\n function of(plugin: string): Handle\n {\n if (!open)\n {\n throw new Error(`\"${plugin}\" reached the database after it was closed.`);\n }\n\n const already = handles.get(plugin);\n\n if (already !== undefined)\n {\n return already;\n }\n\n const owns = holding.tables[plugin];\n\n if (owns === undefined)\n {\n throw new Error(`\"${plugin}\" asked for a database handle but declares no tables. Add them to its contract, or stop reaching for ctx.db.`);\n }\n\n const made = drizzle(holding.connection, { schema: owns });\n\n handles.set(plugin, made);\n\n return made;\n }\n\n /**\n * One transaction, or a savepoint when one is already open.\n *\n * The savepoint's name is its own, not its depth: a name taken from a\n * shared counter is a name another call has moved by the time this one\n * releases it, and SQLite answers \"no such savepoint\" to the request that\n * did nothing wrong.\n */\n async function within<Made>(plugin: string, run: (db: unknown) => Promise<Made>): Promise<Made>\n {\n const db = of(plugin);\n const nested = inside.getStore() !== undefined;\n\n counter += 1;\n\n const at = counter;\n const name = `sp_${String(at)}`;\n\n holding.connection.exec(nested ? `SAVEPOINT ${name}` : \"BEGIN IMMEDIATE\");\n\n try\n {\n const made = await inside.run(at, () => run(db));\n\n holding.connection.exec(nested ? `RELEASE ${name}` : \"COMMIT\");\n\n return made;\n }\n catch (cause)\n {\n try\n {\n holding.connection.exec(nested ? `ROLLBACK TO ${name}; RELEASE ${name}` : \"ROLLBACK\");\n }\n catch\n {\n // Already unwound by SQLite itself. The original cause is what\n // the caller needs, never this.\n }\n\n throw cause;\n }\n }\n\n return {\n of,\n\n /**\n * Runs work in one transaction, rolled back if it throws.\n *\n * Serialised against every other transaction and every write: this is\n * async but better-sqlite3 is not, so an await inside would otherwise\n * leave the connection in a transaction while other work ran through\n * it. That work would then belong to this transaction, and vanish\n * with its rollback.\n *\n * A transaction already open on this call stack becomes a savepoint\n * rather than queueing behind itself, which would deadlock.\n */\n tx: <Made,>(plugin: string, run: (db: unknown) => Promise<Made>): Promise<Made> =>\n {\n // Already inside one on this call stack: a savepoint, and never\n // queued behind the transaction it is inside, which would wait\n // for itself.\n return inside.getStore() === undefined ? waiting.run(() => within(plugin, run)) : within(plugin, run);\n },\n\n /**\n * Runs work outside a transaction, but never during someone else's.\n *\n * better-sqlite3 is synchronous, so one statement cannot interleave\n * with another. What can interleave is a statement issued while an\n * async transaction is parked on an await: it joins that transaction\n * and is undone by its rollback, having told its caller it succeeded.\n *\n * The kernel routes every non-transactional query through here, so\n * that window does not exist. It always queues: `depth` says a\n * transaction is open somewhere, never that this caller is the one\n * inside it, and work that is genuinely inside one reaches the\n * database through the transaction's own handle instead.\n */\n write: <Made,>(run: () => Promise<Made>): Promise<Made> =>\n {\n return inside.getStore() === undefined ? waiting.run(run) : run();\n },\n\n /** Whether the running code is inside a transaction. For diagnosis. */\n inTransaction: (): boolean =>\n {\n return inside.getStore() !== undefined;\n },\n\n close: (): void =>\n {\n open = false;\n handles.clear();\n holding.connection.close();\n },\n };\n}\n","import { connect, type Opening } from \"./internal/connect\";\nimport { migrate, MigrationFault, type Source, type Step, steps } from \"./internal/migrate\";\nimport { narrowing } from \"./internal/narrow\";\nimport { outbox } from \"./internal/outbox\";\nimport { schedule } from \"./internal/schedule\";\n\nimport type { Narrowing, Outbox, Schedule } from \"../kernel/api\";\nimport { store, type Handle, type Tables } from \"./internal/store\";\n\n/** What building a store needs: where the file is, and who owns what. */\nexport type Settings = Opening & {\n tables: Readonly<Record<string, Tables>>;\n};\n\n/**\n * What a project holds after opening a database.\n *\n * Wider than the kernel's `Storage`: this one also migrates and closes, which\n * a plugin has no business doing and the kernel never asks for.\n */\n/**\n * What `start` needs of a database, whichever one it is.\n *\n * Wider than the kernel's `Storage`: this one also migrates and closes, which\n * a plugin has no business doing and the kernel never asks for. `of` answers\n * `unknown` because the kit does not know what database it was given; a\n * plugin names the shape it expects through `definePlugin.over`.\n */\nexport type Store<Handed = unknown> = {\n of: (plugin: string) => Handed;\n\n /** An outbox in this same database, when the store can hold one. */\n outbox?: () => Outbox;\n\n /** A schedule in this same database, for work asked for later. */\n schedule?: () => Schedule;\n\n /** How a declared scope becomes a condition over the tables it was given. */\n narrowing?: () => Narrowing;\n tx: <Made>(plugin: string, run: (db: unknown) => Promise<Made>) => Promise<Made>;\n write: <Made>(run: () => Promise<Made>) => Promise<Made>;\n inTransaction: () => boolean;\n migrate: (sources: readonly Source[]) => Step[];\n close: () => void;\n};\n\nexport { MigrationFault, narrowing, outbox, schedule, steps };\nexport type { Handle, Opening, Source, Step, Tables };\n\n/**\n * Opens a database and holds one handle per plugin over it.\n *\n * Built by the project rather than reached for: two stores can exist in one\n * process without seeing each other, which is what a test needs.\n */\nexport function database(settings: Settings): Store<Handle>\n{\n const connection = connect(settings);\n const made = store({ connection, tables: settings.tables });\n\n return {\n of: made.of,\n tx: made.tx,\n write: made.write,\n inTransaction: made.inTransaction,\n close: made.close,\n\n /** Runs every migration that has not run, in the order given. */\n migrate: (sources: readonly Source[]): Step[] =>\n {\n return migrate(connection, sources);\n },\n\n /**\n * Where events wait, in this same database.\n *\n * Built here rather than from a connection handed out, because an\n * outbox that wrote somewhere else would be exactly the thing it\n * exists to prevent: two places that can disagree about whether the\n * work happened.\n */\n outbox: (): Outbox =>\n {\n return outbox(connection);\n },\n\n /** Where later work waits, in this same database. */\n schedule: (): Schedule =>\n {\n return schedule(connection);\n },\n\n /** How a scope narrows a query, over the tables one plugin declared. */\n narrowing: (): Narrowing =>\n {\n return narrowing(settings.tables);\n },\n };\n}\n","import { timingSafeEqual } from \"node:crypto\";\n\n// A normal string comparison returns as soon as two bytes differ, so how long\n// it took says how much of the secret was right. Repeated a few thousand\n// times, that recovers a token one character at a time.\n//\n// The lengths are compared first and separately: that is public anyway, and\n// timingSafeEqual throws on a mismatch rather than answering false.\nexport function same(left: string, right: string): boolean\n{\n const first = Buffer.from(left, \"utf8\");\n const second = Buffer.from(right, \"utf8\");\n\n if (first.length !== second.length)\n {\n return false;\n }\n\n return timingSafeEqual(first, second);\n}\n","export type Window = {\n requests: number;\n seconds: number;\n};\n\nexport type Verdict = {\n allowed: boolean;\n remaining: number;\n resetsIn: number;\n};\n\ntype Counted = {\n hits: number;\n until: number;\n};\n\n// A fixed window rather than a sliding log: one counter per caller instead of\n// one timestamp per request, which is what keeps a flood from costing memory\n// in proportion to itself.\nexport function limiter(now: () => number = Date.now)\n{\n const counted = new Map<string, Counted>();\n\n return {\n take: (key: string, window: Window): Verdict =>\n {\n const at = now();\n const seen = counted.get(key);\n\n if (seen === undefined || seen.until <= at)\n {\n counted.set(key, { hits: 1, until: at + window.seconds * 1_000 });\n\n return { allowed: true, remaining: window.requests - 1, resetsIn: window.seconds };\n }\n\n seen.hits += 1;\n\n return {\n allowed: seen.hits <= window.requests,\n remaining: Math.max(0, window.requests - seen.hits),\n resetsIn: Math.ceil((seen.until - at) / 1_000),\n };\n },\n\n // Called on a timer by whoever holds the limiter: a map that only\n // grows is a slow leak on a public route.\n sweep: (): number =>\n {\n const at = now();\n\n let dropped = 0;\n\n for (const [key, seen] of counted)\n {\n if (seen.until <= at)\n {\n counted.delete(key);\n dropped += 1;\n }\n }\n\n return dropped;\n },\n\n size: (): number =>\n {\n return counted.size;\n },\n };\n}\n"]}