@lunora/codegen 1.0.0-alpha.16 → 1.0.0-alpha.161

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +3190 -1055
  4. package/dist/index.d.ts +3190 -1055
  5. package/dist/index.mjs +1 -32
  6. package/dist/packem_shared/AGENTS_FILENAME-CRdh_pOr.mjs +1 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-BssQL6eI.mjs +1 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_TARGET-lPq34YeN.mjs +1 -0
  10. package/dist/packem_shared/FLAGS_FILENAME-Bn_wWM4d.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER-zxE5ds4T.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-CW7-uASH.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-DHX1qUP5.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-BH0djo6F.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-BgLkvCYK.mjs +3 -0
  16. package/dist/packem_shared/QUEUES_FILENAME-CIfuMMG3.mjs +1 -0
  17. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DqFQB0lY.mjs +9 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs +2 -0
  19. package/dist/packem_shared/SDK_LANGUAGES-CFyux-74.mjs +371 -0
  20. package/dist/packem_shared/SHAPES_FILENAME-DhZ3JkkH.mjs +1 -0
  21. package/dist/packem_shared/SchemaSnapshotParseError-yrVM8bTa.mjs +18 -0
  22. package/dist/packem_shared/WORKFLOWS_FILENAME-CSqONfHS.mjs +1 -0
  23. package/dist/packem_shared/buildOpenApiDocument-qYjkmRTX.mjs +3 -0
  24. package/dist/packem_shared/chain-DboeOxBl.mjs +1 -0
  25. package/dist/packem_shared/classify-procedure-call-CRm5Etni.mjs +1 -0
  26. package/dist/packem_shared/context-property-calls-CBUh7oAY.mjs +1 -0
  27. package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
  28. package/dist/packem_shared/discoverAuthApiCalls-B5Qmjmyk.mjs +1 -0
  29. package/dist/packem_shared/discoverCrons-c0ig327z.mjs +1 -0
  30. package/dist/packem_shared/discoverFunctions-DeuEs6Ce.mjs +1 -0
  31. package/dist/packem_shared/discoverHttpRoutes-zWSSyyOj.mjs +1 -0
  32. package/dist/packem_shared/discoverHyperdriveCalls-C6kV2CPz.mjs +1 -0
  33. package/dist/packem_shared/discoverInserts-BB7o_8pU.mjs +1 -0
  34. package/dist/packem_shared/discoverMaskProcedures-CNqwOwXv.mjs +1 -0
  35. package/dist/packem_shared/discoverMigrations-CQjGLKW-.mjs +1 -0
  36. package/dist/packem_shared/discoverNondeterministicCalls-B07wjsd2.mjs +1 -0
  37. package/dist/packem_shared/discoverQueries-Dz2vDpE9.mjs +1 -0
  38. package/dist/packem_shared/discoverR2sqlCalls-CuHe5smg.mjs +1 -0
  39. package/dist/packem_shared/discoverRlsMetadata-CXWVNLk4.mjs +1 -0
  40. package/dist/packem_shared/discoverRlsProcedures-DXdr9YHi.mjs +1 -0
  41. package/dist/packem_shared/discoverSandboxUsage-BJHLHZR_.mjs +1 -0
  42. package/dist/packem_shared/discoverSchema-C4znXEB-.mjs +1 -0
  43. package/dist/packem_shared/discoverStorageRulesMetadata-CUa2Dtb4.mjs +1 -0
  44. package/dist/packem_shared/emit-BNdsZPcd.mjs +2470 -0
  45. package/dist/packem_shared/emitApp-x-gjOrYL.mjs +755 -0
  46. package/dist/packem_shared/exported-procedure-chains-Cmt3Pr92.mjs +1 -0
  47. package/dist/packem_shared/formatAdvisories-CkEu1eye.mjs +2 -0
  48. package/dist/packem_shared/index-BsVoa-4F.mjs +1 -0
  49. package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -0
  50. package/dist/packem_shared/listLunoraSourceFiles-BvqYMy81.mjs +1 -0
  51. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  52. package/dist/packem_shared/parse-validator-CMV0eq2a.mjs +1 -0
  53. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  54. package/dist/packem_shared/queries-D8DheHbi.mjs +1 -0
  55. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  56. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  57. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  58. package/dist/packem_shared/unwrap-handler-return-CmIWbykC.mjs +1 -0
  59. package/package.json +16 -7
  60. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  61. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  62. package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
  63. package/dist/packem_shared/GENERATED_HEADER-CkZUgM4_.mjs +0 -2944
  64. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  65. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  66. package/dist/packem_shared/OPENRPC_VERSION-VINwUAxf.mjs +0 -60
  67. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  68. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DsBxQ5C_.mjs +0 -963
  69. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  70. package/dist/packem_shared/WORKFLOWS_FILENAME-D62dcBGg.mjs +0 -84
  71. package/dist/packem_shared/buildOpenApiDocument-BSoDzIn8.mjs +0 -183
  72. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  73. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  74. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  75. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  76. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  77. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  78. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  79. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  80. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  81. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  82. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  83. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  84. package/dist/packem_shared/discoverSchema-BnWHHJ4T.mjs +0 -822
  85. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  86. package/dist/packem_shared/emitApp-DGmlt5fq.mjs +0 -617
  87. package/dist/packem_shared/formatAdvisories-8NIv1k0I.mjs +0 -69
  88. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  89. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  90. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,755 @@
1
+ import{A as S,G as E}from"./emit-BNdsZPcd.mjs";const D=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[D(t),e.method,e.configKey,e.doc]),m=e=>v.some(([t])=>e[t]),x=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],A=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],R=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],C=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],O=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],T=e=>e?['import notifyConfig from "../notify.js";']:[],f=e=>(e.emailAgents?.length??0)>0,I=e=>f(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>f(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],q=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:o,hasKvIntrospector:h,hasQueue:c,hasScheduler:i,hasStorage:u,hasWorkflow:p,useUmbrella:b,wantsOpenApi:l,wantsOpenRpc:g}=e,d=b?"lunorash/runtime":"@lunora/runtime",s=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];c&&s.push("TriggerTrace"),n&&s.push("GlobalIntrospector","AdminTableResolver"),r&&s.push("FrameworkHostHandler");const k=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...A(t,a),...O(n),...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...R(h),...C(e.hasVectors===!0),...i?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...p?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...I(e),`import type { ${[...s].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${d}";`,`import { ${k} } from "${d}";`,"",...x(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...T(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...c?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...l?['import { openApiSpec } from "./openapi.js";']:[],...g?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},N=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;"," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],G=e=>v.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
2
+ public ${t}(factory: NonNullable<ShardConfig["${a}"]>): this {
3
+ this.shardExtras.${a} = factory;
4
+
5
+ return this;
6
+ }`),B=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
7
+ public admin(selector: Selector<Env, string>): this {
8
+ this.adminToken = selector;
9
+
10
+ return this;
11
+ }`," /**\n * Opt into change-data-capture: every write records a post-image to `__cdc_log` — on this shard AND, when the app has `.global()` tables, on the global backend. Backs streaming export, replay-PITR, and the `.global()` half of `defineShape` replication (whose poll tick asks the global changelog which tables moved). Off by default: it costs a changelog row per write, which an app using none of the above should not pay.\n *\n * REQUIRED for a shard-local `defineShape`: those replicate out of `__cdc_log`, and a `shape_subscribe` is refused with `SHAPE_REQUIRES_CDC` without it.\n *\n * It also changes how fresh a `.global()` shape is against writes made OUTSIDE `ctx.db` — an admin import, a PITR replay, an external ETL job, or a predicate over wall clock. With CDC off the poll re-reads every shape every 2s. With it on the poll asks the global changelog which tables moved and skips the rest, so a change the changelog never saw waits for the 30s unconditional resync instead. Writes through `ctx.db` are unaffected: they append, so the poll sees them on the next tick either way.\n */\n public cdc(enabled = true): this {\n this.cdcEnabled = enabled;\n\n return this;\n }",` /**
12
+ * Enable the per-shard reactive query cache: query results are memoized by \`(functionPath, args, identity)\` and invalidated by the ctx-db write hooks BEFORE the subscription broadcast, so a subscriber re-running its query always observes the post-write state.
13
+ *
14
+ * Off by default (every dispatch re-runs its handler). Pass an options object to tune the caps: \`maxEntries\` (default 1000) and \`maxBytes\` (default 4 MiB); either accepts \`Number.POSITIVE_INFINITY\` to disable that cap.
15
+ */
16
+ public reactiveCache(config: boolean | { maxBytes?: number; maxEntries?: number } = true): this {
17
+ this.reactiveCacheConfig = config;
18
+
19
+ return this;
20
+ }`,...e.hasAuth?[' /** Wire better-auth — the builder lazily builds the instance, runs `ensureMigrated`, and dispatches `/api/auth/*` inside the worker (instrumented for the auth-failure SLO). Pass `d1` for the D1-backed default, or `namespace` + `internalSecret` to host the auth tables in a Durable Object (what `@better-auth/scim` needs). */\n public auth(declaration: AuthDeclaration<Env>): this {\n // Reject the ambiguous and the empty shapes here rather than at the first\n // request: with neither storage set, auth would silently never answer, and\n // with both it is unclear which one owns the tables.\n if (declaration.d1 && declaration.namespace) {\n throw new Error(".auth(): pass either `d1` or `namespace`, not both — they are two different homes for the same tables.");\n }\n\n if (!declaration.d1 && !declaration.namespace) {\n throw new Error(".auth(): needs `d1` (D1-backed) or `namespace` (Durable-Object-backed) to know where the auth tables live.");\n }\n\n if (declaration.namespace && !declaration.internalSecret) {\n throw new Error(\n ".auth(): `namespace` requires `internalSecret` — the auth DO binding is reachable from any worker bound to it, so identity resolution is gated on a shared secret and would otherwise fail closed on every request.",\n );\n }\n\n this.authDeclaration = declaration;\n\n return this;\n }']:[]," /** Escape hatch — merge raw `WorkerOptions` (anything not yet sugared) over the derived options at build time. The second `derived` argument is a snapshot of the options assembled so far (after `.auth(...)` etc.), so you can compose rather than clobber — e.g. wrap `derived.resolveIdentity` instead of replacing it. */\n public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {\n this.extendFns.push(fn);\n\n return this;\n }",...e.hasGlobal?[` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
21
+ public global(declaration: GlobalDeclaration<Env>): this {
22
+ this.globalDeclaration = declaration;
23
+
24
+ return this;
25
+ }`]:[],...e.hasHyperdriveGlobal?[` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
26
+ public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
27
+ this.hyperdriveGlobalDeclaration = declaration;
28
+
29
+ return this;
30
+ }`]:[],` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
31
+ public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
32
+ this.emailHandler = handler;
33
+
34
+ return this;
35
+ }`," /** Mount a whole HTTP app (`httpRouter()` from `@lunora/server`, or anything with a `fetch`) ahead of Lunora's own routes. Use this for a multi-endpoint hono app with its own CORS + error handling; `.route()` is for one-off endpoints. */\n public httpRouter(app: HttpRouterLike): this {\n this.httpRouterApp = app;\n\n return this;\n }",` /** Mount a custom HTTP route (e.g. an asset-serving or test endpoint). Key is \`"METHOD path"\`, \`"path"\`, or a path prefix matched by the runtime. */
36
+ public route(key: string, handler: Route): this {
37
+ this.routeMap[key] = handler;
38
+
39
+ return this;
40
+ }`,...e.hasScheduler?[` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
41
+ public scheduler(declaration: SchedulerDeclaration<Env>): this {
42
+ this.schedulerDeclaration = declaration;
43
+
44
+ return this;
45
+ }`]:[],` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
46
+ public shard(selector: Selector<Env, ShardNamespaceLike>): this {
47
+ this.shardSelector = selector;
48
+
49
+ return this;
50
+ }`,...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
51
+ public storage(declaration: StorageDeclaration<Env>): this {
52
+ this.storageDeclaration = declaration;
53
+
54
+ return this;
55
+ }`]:[],...G(e)],W=e=>{const t=r=>e.hasScheduler?`
56
+ ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${r}["scheduler"] } : {}),`:"",a=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,",...e.hasGlobal?[` ...(this.globalDeclaration
57
+ ? {
58
+ d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
59
+ const env = rawEnv as Env;
60
+ const database = this.globalDeclaration?.d1(env);
61
+
62
+ if (!database) {
63
+ return undefined;
64
+ }
65
+
66
+ const origin = this.globalDeclaration?.origin?.(env);
67
+ const crossShard = origin
68
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
69
+ : undefined;
70
+
71
+ return createD1CtxDb({
72
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("D1CtxDbOptions")}
73
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
74
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
75
+ // Forwarded from the shard's own \`cdc\` config, so ONE
76
+ // switch governs both changelogs. Built without it, the
77
+ // global \`__cdc_log\` is never written and the shape
78
+ // poll's changed-tables fast path is unreachable.
79
+ cdc: request?.cdc ?? false,
80
+ exec: buildExec(database, request?.bookmark, request?.onBookmark),
81
+ // The binding outlives this per-request writer, so the
82
+ // provisioning sweep runs once per isolate rather than
83
+ // once per request. See \`SqlCtxDbOptions.provisionScope\`.
84
+ provisionScope: database,
85
+ schema: schema as unknown as D1CtxDbOptions["schema"],
86
+ });
87
+ },
88
+ }
89
+ : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
90
+ ? {
91
+ hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
92
+ const env = rawEnv as Env;
93
+ const declaration = this.hyperdriveGlobalDeclaration;
94
+ const exec = declaration?.exec(env) as SqlExec | undefined;
95
+
96
+ if (!declaration || !exec) {
97
+ return undefined;
98
+ }
99
+
100
+ const origin = declaration.origin?.(env);
101
+ const crossShard = origin
102
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
103
+ : undefined;
104
+
105
+ return createHyperdriveGlobalCtxDb({
106
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
107
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
108
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
109
+ // See the D1 twin: one \`cdc\` switch, both changelogs.
110
+ cdc: request?.cdc ?? false,
111
+ engine: declaration.engine as HyperdriveEngine,
112
+ exec,
113
+ // The DECLARATION, not \`exec\` — \`exec(env)\` is a user
114
+ // callback that builds a fresh client per call, so scoping
115
+ // to its result would key the memo on a new object every
116
+ // request and never share anything. The declaration is
117
+ // built once and names one database.
118
+ provisionScope: declaration,
119
+ schema: schema as unknown as SqlCtxDbOptions["schema"],
120
+ });
121
+ },
122
+ }
123
+ : {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
124
+ ? {
125
+ scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
126
+ }
127
+ : {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
128
+ ${a.join(`
129
+ `)}
130
+ `:""},P=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
131
+ options.schedulerDO = this.schedulerDeclaration.namespace(env);
132
+ }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
133
+ const source = workflowEnv as Record<string, unknown>;
134
+ const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
135
+ const apiToken = source["CLOUDFLARE_API_TOKEN"];
136
+
137
+ return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
138
+ ? createWorkflowsRestClient({ accountId, apiToken })
139
+ : undefined;
140
+ };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
141
+ const database = this.globalDeclaration.d1(env);
142
+
143
+ if (database) {
144
+ options.globalIntrospector = buildGlobalIntrospector(database);
145
+ // \`resolveTableSharding\`/\`importGlobals\` wire the admin bulk-import
146
+ // endpoint: without the former, EVERY row (including a \`.global()\`
147
+ // table's) routes to the default shard, so a global table is never
148
+ // recognised as global and the latter is never reached — the
149
+ // endpoint answers 200 with \`inserted: {}\` for a write that never
150
+ // happened. Both are mechanical over the schema this file already
151
+ // imports, so there is nothing project-specific to configure.
152
+ options.resolveTableSharding = buildTableShardingResolver();
153
+ options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
154
+ // The read/replay half of the same admin plane. Each one is the
155
+ // only reason its endpoint can see the global storage plane at
156
+ // all, and every one of them fails SILENTLY when unset — export
157
+ // and \`lunora backup create\` answer 200 having written only
158
+ // shard-local rows (an export→import round trip then restores
159
+ // cleanly minus every global row), CDC sync answers with only
160
+ // shard changes, and point-in-time apply reports
161
+ // \`globalApplied: 0\`. Nothing here is project-specific either.
162
+ options.exportGlobals = buildGlobalExporter(database);
163
+ options.syncGlobals = buildGlobalCdcSync(database);
164
+ options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
165
+ }
166
+ }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
167
+ Object.assign(options, this.buildStorageAdmin(env));
168
+ options.storage = (rawEnv: unknown) => this.resolveStorage(rawEnv as Env);
169
+ }`]:[],...e.hasKvIntrospector?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasVectors===!0?[` if (this.shardExtras.vectors) {
170
+ options.vectorIntrospector = createVectorAdminIntrospector({
171
+ indexes: this.shardExtras.vectors(env as unknown as Record<string, unknown>),
172
+ registry: LUNORA_VECTOR_INDEXES,
173
+ });
174
+ } else {
175
+ // Emitted only when the schema declares an index, so reaching here
176
+ // means the app declared one and never bound it. The studio's
177
+ // Vectors tab is on (its flag is the same index count) and every
178
+ // request to it would answer VECTORS_NOT_CONFIGURED, while
179
+ // \`ctx.vectors\` is the throwing stub — so this is already broken,
180
+ // just later and less legibly. Same shape as \`.auth()\`'s guards.
181
+ throw new Error(
182
+ ".vectors(): the schema declares vector index(es) but no binding map was chained. Pass \`.vectors((env) => ({ <indexName>: env.<BINDING> }))\` so \`ctx.vectors\` resolves and the studio's Vectors tab can list them.",
183
+ );
184
+ }`]:[],...e.hasNotify?[" options.notifySubscriptionStore = notifyConfig.store ? notifyConfig.store(env as Record<string, unknown>) : undefined;"]:[]," options.logArchive = resolveLogArchiveFromEnv(env);",...e.hasAuth?[` // Captured before the branch so the narrowing survives — reading
185
+ // \`this.authDeclaration.namespace\` again below would be optional all over again.
186
+ const authDeclaration = this.authDeclaration;
187
+ const authNamespace = authDeclaration?.namespace;
188
+ const authD1 = authDeclaration?.d1;
189
+
190
+ if (authDeclaration && authNamespace) {
191
+ // DO-backed mode. The auth tables live inside the object and DO storage is
192
+ // unreachable from here, so better-auth runs in there and this worker talks
193
+ // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
194
+ // than more emitted code: request-path logic in generated output can only be
195
+ // typechecked, never unit-tested.
196
+ const authWiring = createDoAuthWiring({
197
+ internalSecret: authDeclaration.internalSecret?.(env),
198
+ namespace: authNamespace(env),
199
+ objectName: authDeclaration.objectName?.(env),
200
+ });
201
+
202
+ options.authHandler = authWiring.authHandler;
203
+ options.resolveIdentity = authWiring.resolveIdentity;
204
+ // The audit log lives in the object like every other auth table, so the feed
205
+ // reads through it rather than querying D1.
206
+ options.authAuditReader = authWiring.auditReader;
207
+ // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
208
+ // from the worker, which DO storage does not allow. The studio's auth pages
209
+ // therefore report "not configured" in this mode rather than silently
210
+ // returning empty data.
211
+ } else if (authDeclaration && authD1) {
212
+ options.authHandler = (request) => {
213
+ const auth = getAuth();
214
+
215
+ return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
216
+ };
217
+ options.resolveIdentity = async (request) => {
218
+ const auth = getAuth();
219
+
220
+ if (!auth) {
221
+ return null;
222
+ }
223
+
224
+ const session = await auth.api.getSession({ headers: (request as Request).headers });
225
+
226
+ if (!session?.user?.id) {
227
+ return null;
228
+ }
229
+
230
+ // \`role\` rides along so \`rls(policies, { roles })\` and \`auth.can(...)\`
231
+ // work on this wiring without a hand-written resolver. better-auth's
232
+ // \`admin()\` plugin owns that column (comma-joined for multiple roles)
233
+ // and only an administrator can write it; it is absent when the plugin
234
+ // is off, which reads as no roles.
235
+ //
236
+ // \`expiresAtMs\` is the socket credential expiry the runtime forwards
237
+ // as \`x-lunora-identity-exp\`. Without it the DO's expiry check never
238
+ // fires, so a signed-out, banned or lapsed user keeps streaming their
239
+ // RLS-scoped rows over an already-open WebSocket while every HTTP call
240
+ // is anonymous. better-auth hands back a \`Date\`; anything else means
241
+ // the adapter did not hydrate it, and omitting beats guessing.
242
+ const expiresAt = session.session.expiresAt;
243
+ // \`email\` and \`name\` are the claims \`ctx.auth.getIdentity()\` is
244
+ // documented to carry ("email, name, roles, custom claims"). Without
245
+ // them the documented \`me\` query — \`identity?.email\` — resolves
246
+ // \`undefined\` on the built-in wiring. Empty strings are dropped so an
247
+ // absent claim reads as absent rather than as "".
248
+ const user = session.user as { email?: unknown; name?: unknown; role?: unknown };
249
+
250
+ return {
251
+ ...(typeof user.email === "string" && user.email.length > 0 ? { email: user.email } : {}),
252
+ ...(expiresAt instanceof Date ? { expiresAtMs: expiresAt.getTime() } : {}),
253
+ ...(typeof user.name === "string" && user.name.length > 0 ? { name: user.name } : {}),
254
+ role: user.role,
255
+ userId: session.user.id,
256
+ };
257
+ };
258
+ const authInstance = getAuth();
259
+
260
+ options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
261
+ options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
262
+ }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
263
+ const accessResolver = createAccessResolver(this.accessSelector(env));
264
+ const fallback = options.resolveIdentity;
265
+
266
+ options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
267
+ }`:` if (this.accessSelector) {
268
+ options.resolveIdentity = createAccessResolver(this.accessSelector(env));
269
+ }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
270
+ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
271
+ `)}
272
+ };`]:[]],_=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],$=e=>e.hasScheduler?`
273
+ /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
274
+ private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
275
+ const namespace = this.schedulerDeclaration?.namespace(env);
276
+
277
+ return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
278
+ }
279
+ `:"",H=e=>e?`
280
+ /**
281
+ * One bucket's \`Storage\`, signing under the name it is registered as.
282
+ *
283
+ * \`bucketName\` is bound into every signed URL's HMAC canonical, so a bucket
284
+ * that signs as the default's name lets a URL minted for one bucket verify
285
+ * against another sharing the secret — and multi-bucket verification fails
286
+ * outright. Hence \`"default"\` for the bare \`ctx.storage\` bucket and the
287
+ * \`buckets\` key for every other.
288
+ */
289
+ private makeStorage(env: Env, declaration: StorageDeclaration<Env>, bucket: R2BucketLike, bucketName: string): Storage {
290
+ return createStorage({
291
+ bucket,
292
+ bucketName,
293
+ publicBaseUrl: declaration.publicBaseUrl?.(env),
294
+ s3: declaration.s3?.(env),
295
+ signingSecret: declaration.signingSecret?.(env),
296
+ });
297
+ }
298
+
299
+ /** Resolve the storage capability (single or multi-bucket) for the DO side. */
300
+ private resolveStorage(env: Env): Storage | undefined {
301
+ const declaration = this.storageDeclaration;
302
+
303
+ if (!declaration) {
304
+ return undefined;
305
+ }
306
+
307
+ const defaultBucket = declaration.bucket(env);
308
+
309
+ if (!defaultBucket) {
310
+ return undefined;
311
+ }
312
+
313
+ const extraEntries = Object.entries(declaration.buckets ?? {})
314
+ .map(([name, selector]) => [name, selector(env)] as const)
315
+ .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
316
+
317
+ if (extraEntries.length === 0) {
318
+ return this.makeStorage(env, declaration, defaultBucket, "default");
319
+ }
320
+
321
+ const map: Record<string, Storage> = { default: this.makeStorage(env, declaration, defaultBucket, "default") };
322
+
323
+ for (const [name, bucket] of extraEntries) {
324
+ map[name] = this.makeStorage(env, declaration, bucket, name);
325
+ }
326
+
327
+ return createBucketStorage(map, { default: "default" });
328
+ }
329
+
330
+ /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
331
+ private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
332
+ const declaration = this.storageDeclaration;
333
+
334
+ if (!declaration) {
335
+ return {};
336
+ }
337
+
338
+ const defaultBucket = declaration.bucket(env);
339
+
340
+ if (!defaultBucket) {
341
+ return {};
342
+ }
343
+
344
+ // Held separately from the map so \`pick\`'s fallback is a plain binding:
345
+ // under \`noUncheckedIndexedAccess\` a \`Record<string, Storage>\` lookup —
346
+ // including \`buckets.default\` — widens to \`Storage | undefined\`, which
347
+ // would not satisfy \`pick\`'s declared \`Storage\` return.
348
+ const fallbackStorage = this.makeStorage(env, declaration, defaultBucket, "default");
349
+ const buckets: Record<string, Storage> = { default: fallbackStorage };
350
+
351
+ for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
352
+ const bucket = selector(env);
353
+
354
+ if (bucket) {
355
+ buckets[name] = this.makeStorage(env, declaration, bucket, name);
356
+ }
357
+ }
358
+
359
+ // \`Object.hasOwn\`, not a bare lookup: \`buckets\` is a plain object, so a
360
+ // prototype key (\`?bucket=constructor\`, \`__proto__\`, \`toString\`) resolves
361
+ // to an inherited Object.prototype member, \`??\` never engages, and the
362
+ // caller gets a method-less value instead of the default bucket.
363
+ const pick = (name?: string): Storage => {
364
+ const wanted = name !== undefined && name !== "" ? name : "default";
365
+
366
+ return (Object.hasOwn(buckets, wanted) ? buckets[wanted] : undefined) ?? fallbackStorage;
367
+ };
368
+ const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
369
+
370
+ return {
371
+ storageBuckets: Object.keys(buckets),
372
+ storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
373
+ storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
374
+ storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
375
+ storageSignedUrl: hasSigning
376
+ ? (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT" }) =>
377
+ pick(opts?.bucket).getSignedUrl(key, { contentType: opts?.contentType, expiresInSeconds: opts?.expiresInSeconds, method: opts?.method })
378
+ : undefined,
379
+ storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
380
+ };
381
+ }
382
+ `:"",U=e=>e?`
383
+ /**
384
+ * Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
385
+ *
386
+ * Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
387
+ * last-known write, when supplied) so reads observe it — read-your-writes
388
+ * across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
389
+ * produced by each write so the caller (the generated DO) can record it via
390
+ * \`setOutboundBookmark\` and echo \`x-d1-bookmark\` on the response.
391
+ *
392
+ * Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
393
+ * (storage-object resets, isolate memory evictions, dropped connections) does
394
+ * not surface on every \`.global()\` read. Only statements that are provably
395
+ * read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
396
+ * optimistic-concurrency check issues through \`all\` — pass straight through,
397
+ * because a transient error never says whether the write applied.
398
+ */
399
+ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
400
+ // Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
401
+ // below so a hand-rolled test double that omits it keeps working via
402
+ // \`prepare()\` straight on the raw binding — today's behaviour. With no
403
+ // inbound bookmark, \`"first-unconstrained"\` is the documented no-op
404
+ // equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
405
+ const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
406
+ const target = session ?? database;
407
+ const batchFn = target.batch;
408
+
409
+ return retryingExec({
410
+ all: async (sql, parameters) => {
411
+ const result = await target
412
+ .prepare(sql)
413
+ .bind(...parameters)
414
+ .all<Record<string, unknown>>();
415
+
416
+ // \`all\` carries writes, not just reads: D1 runs
417
+ // \`UPDATE/DELETE … RETURNING\` through it exactly like \`.run()\`, and
418
+ // that is precisely what \`@lunora/sql-store\` issues for its
419
+ // optimistic-concurrency compare-and-swap — so \`patch\`, \`replace\`
420
+ // and \`delete\` all land here and nowhere else. Without this the
421
+ // bookmark those writes produced was never reported, and the next
422
+ // read could pin a replica that has not seen them: read-your-writes
423
+ // lost on the exact path the bookmark exists for. Reporting it after
424
+ // a plain \`SELECT\` too is harmless and correct — the session's
425
+ // bookmark only ever moves forward, and \`setOutboundBookmark\` takes
426
+ // the last value.
427
+ onBookmark?.(session?.getBookmark() ?? undefined);
428
+
429
+ return result.results;
430
+ },
431
+ // D1's own \`batch\` runs the whole array as one atomic SQLite
432
+ // transaction. Guarded because \`batch\` is optional in the structural
433
+ // type (test doubles may omit it) — real D1 always has it; a double
434
+ // without it still works through the store's sequential fallback.
435
+ // Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
436
+ // directly so TS can narrow the captured \`batchFn\` across the closure
437
+ // boundary (a property-access narrowing like
438
+ // \`hasBatch = typeof target.batch === "function"\` does not survive
439
+ // into a nested arrow function); \`.call\` still binds \`this\` to
440
+ // \`target\`, so the real workerd \`D1Database\`/session doesn't throw
441
+ // \`TypeError: Illegal invocation\` the way a detached
442
+ // \`const fn = target.batch; fn(...)\` capture would.
443
+ batch: batchFn
444
+ ? async (statements) => {
445
+ await batchFn.call(
446
+ target,
447
+ statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
448
+ );
449
+ onBookmark?.(session?.getBookmark() ?? undefined);
450
+ }
451
+ : undefined,
452
+ run: async (sql, parameters) => {
453
+ await target
454
+ .prepare(sql)
455
+ .bind(...parameters)
456
+ .run();
457
+ onBookmark?.(session?.getBookmark() ?? undefined);
458
+ },
459
+ });
460
+ };
461
+
462
+ /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
463
+ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
464
+ const exec = buildExec(database);
465
+
466
+ return {
467
+ facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
468
+ listTables: () => listGlobalTables(exec, schema as never),
469
+ readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
470
+ };
471
+ };
472
+
473
+ /**
474
+ * \`resolveTableSharding\` for the admin bulk-import endpoint: a lookup over each
475
+ * table's declared \`shardMode\` (\`defineTable(...).global()\` / \`.shardBy(field)\`
476
+ * already record exactly this shape on the table) — mechanical, nothing to
477
+ * configure per project. \`undefined\` for a table the schema doesn't declare, so
478
+ * the import endpoint's own unknown-table handling still applies.
479
+ */
480
+ const buildTableShardingResolver = (): AdminTableResolver => (table) => {
481
+ const declared = (schema as unknown as D1CtxDbOptions["schema"]).tables[table];
482
+
483
+ return declared?.shardMode ? { mode: declared.shardMode } : undefined;
484
+ };
485
+
486
+ /**
487
+ * \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
488
+ * through the same D1 writer \`.global()\` reads/writes already use, via
489
+ * \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
490
+ * twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
491
+ * shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
492
+ *
493
+ * Passes each row's own \`line\` through rather than dropping it: the caller
494
+ * (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
495
+ * physical source line, and global rows are typically interspersed with
496
+ * shard-local ones it filtered out before calling here — a single
497
+ * \`startLine\` plus positional counting would mis-attribute every row after
498
+ * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
499
+ * falls back to the position-derived count otherwise.
500
+ */
501
+ const buildGlobalImporter =
502
+ (database: D1DatabaseLike, cdc: boolean) =>
503
+ (request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
504
+ const exec = buildExec(database);
505
+ // Same reason the PITR applier carries it: a bulk import that skips the
506
+ // changelog restores rows no downstream consumer is ever told about.
507
+ const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
508
+
509
+ return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
510
+ exec,
511
+ rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
512
+ startLine: request.startLine,
513
+ });
514
+ };
515
+
516
+ /**
517
+ * \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
518
+ * which drains the same stream): the read twin of {@link buildGlobalImporter},
519
+ * over the same D1 handle. \`@lunora/d1\`'s \`exportGlobalRows\` keyset-paginates
520
+ * each table and provisions the schema's global tables first, so a table that
521
+ * was never written exports as empty instead of throwing \`no such table\`.
522
+ *
523
+ * \`tables\` is forwarded as-is: the runtime passes an empty array for "every
524
+ * table" (its \`tables === undefined\` case), which is exactly what
525
+ * \`selectGlobalTables\` reads an empty allowlist as.
526
+ */
527
+ const buildGlobalExporter =
528
+ (database: D1DatabaseLike) =>
529
+ (request: { tables: ReadonlyArray<string> }) =>
530
+ exportGlobalRows(buildExec(database), schema as unknown as D1CtxDbOptions["schema"], { tables: request.tables });
531
+
532
+ /**
533
+ * \`syncGlobals\` for the admin CDC sync + warehouse-connector endpoints: pages
534
+ * the global \`__cdc_log\` past \`sinceSeq\`, the global-plane twin of the shard's
535
+ * \`runShardCdcSync\`.
536
+ *
537
+ * Probes \`sqlite_master\` first, exactly as the shard twin does. The changelog
538
+ * table is only created when the global writer runs with CDC enabled, so on
539
+ * every other app a straight read would throw \`no such table: __cdc_log\` and
540
+ * turn "nothing has changed yet" into a 500. Absent log ⇒ an empty page that
541
+ * leaves the caller's cursor where it was.
542
+ */
543
+ const buildGlobalCdcSync =
544
+ (database: D1DatabaseLike) =>
545
+ async (request: { limit?: number; sinceSeq: number }): Promise<{ changes: ReadonlyArray<Record<string, unknown>>; cursor: number }> => {
546
+ const exec = buildExec(database);
547
+ const present = await exec.all(\`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\`, ["__cdc_log"]);
548
+
549
+ if (present.length === 0) {
550
+ return { changes: [], cursor: request.sinceSeq };
551
+ }
552
+
553
+ const page = await readD1CdcChanges(exec, { limit: request.limit, sinceSeq: request.sinceSeq });
554
+
555
+ // \`as unknown as\`, because \`CdcChange\` is an interface and interfaces carry
556
+ // no implicit index signature — the shapes are otherwise identical.
557
+ return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
558
+ };
559
+
560
+ /**
561
+ * \`applyGlobals\` for the admin point-in-time-recovery apply endpoint: replays a
562
+ * batch of global CDC changes through the same D1 writer \`.global()\` writes go
563
+ * through, and reports how many were replayed.
564
+ *
565
+ * \`applyCdcChanges\` is order-sensitive and idempotent per row (insert, falling
566
+ * back to replace on conflict), so the batch is handed over untouched — the
567
+ * caller already emits it in commit order. The changes arrive as plain parsed
568
+ * JSON off the wire, hence the cast to the replayer's own change shape.
569
+ *
570
+ * The writer carries the app's own \`cdc\` setting, so a replay APPENDS to the
571
+ * global changelog like any other write. Built without it the restored rows
572
+ * reach the tables and nothing else: a warehouse connector's cursor walks past a
573
+ * range that has no entries and its mirror silently diverges from the database,
574
+ * with nothing on either side able to notice — and every live \`.global()\` shape
575
+ * misses the restore until the next unconditional resync.
576
+ */
577
+ const buildGlobalCdcApplier =
578
+ (database: D1DatabaseLike, cdc: boolean) =>
579
+ async (request: { changes: ReadonlyArray<Record<string, unknown>> }): Promise<number> => {
580
+ const writer = createD1CtxDb({ cdc, exec: buildExec(database), schema: schema as unknown as D1CtxDbOptions["schema"] });
581
+
582
+ await applyCdcChanges(writer, request.changes as unknown as Parameters<typeof applyCdcChanges>[1]);
583
+
584
+ return request.changes.length;
585
+ };
586
+ `:"",F=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),Q=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=N(t),n=P(t),o=a?` let auth: LunoraAuth | null = null;
587
+ let authInit: Promise<void> | null = null;
588
+ `:"",h=a?`
589
+ const initAuth = async (env: Env): Promise<void> => {
590
+ if (!this.authDeclaration) {
591
+ return;
592
+ }
593
+
594
+ const d1 = this.authDeclaration.d1;
595
+
596
+ // DO-backed mode builds no instance here: better-auth runs inside the
597
+ // object, which materialises its own schema (the Kysely migrator below is
598
+ // dialect-bound and cannot target DO storage).
599
+ if (!d1) {
600
+ return;
601
+ }
602
+
603
+ // Apply the better-auth schema lazily on first request (raw-D1 Kysely
604
+ // migrator). For production run the migrate command ahead of deploy.
605
+ // The migration instance takes the RAW binding: better-auth migrates
606
+ // only through Kysely and rejects the adapter the request instance uses.
607
+ await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
608
+ // Assigned after the schema exists, never before. Assigning first is
609
+ // what let a concurrent request see a non-null \`auth\` and serve
610
+ // \`/api/auth/*\` against tables the migrator had not created yet —
611
+ // \`no such table: rateLimit\`, from the isolate that was mid-migration.
612
+ auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
613
+ };
614
+
615
+ // Single-flighted on the PROMISE, not on \`auth\`. Every \`fetch\` awaits this
616
+ // and the body above is async, so a per-isolate cold start runs it once
617
+ // rather than once per concurrent request — better-auth's migrator emits a
618
+ // bare \`CREATE TABLE\` (no IF NOT EXISTS), so a second concurrent run on a
619
+ // fresh database fails with \`table user already exists\` and, because this is
620
+ // awaited ahead of the router, 500s every route. Evicted on failure so a
621
+ // transient error retries instead of being replayed forever.
622
+ const ensureAuth = (env: Env): Promise<void> =>
623
+ (authInit ??= initAuth(env).catch((error: unknown) => {
624
+ authInit = null;
625
+ throw error;
626
+ }));
627
+ `:"",c=a?`
628
+ await ensureAuth(env);`:"",i=a?"() => auth":"() => null",u=a?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",p=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
629
+ host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${i})) : createWorker(this.buildWorkerOptions(env, ${i}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${i}));`,b=t.hasFramework?"host?: FrameworkHostHandler":"",l=t.emailAgents??[],g=l.length>0?` composed.email = dispatchAgentEmail([
630
+ ${l.map(s=>` { agent: lunoraAgentDefinitions.${s.exportName}, binding: ${JSON.stringify(s.bindingName)} },`).join(`
631
+ `)}
632
+ ]);
633
+
634
+ `:"",d=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
635
+ public build(): ComposedApp {
636
+ return this.assemble();
637
+ }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${E}${q(t).join(`
638
+ `)}
639
+
640
+ /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
641
+ type Selector<Env, T> = (env: Env) => T | undefined;
642
+ ${m(t)?"\n/** The generated `createShardDO` config — the long-tail `.ai()` / `.kv()` / … methods pass straight through to it. */\ntype ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;\n":""}
643
+ ${r.join(`
644
+
645
+ `)}${r.length>0?`
646
+
647
+ `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
648
+ interface ComposedApp extends LunoraWorker {
649
+ /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
650
+ email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
651
+ /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
652
+ ShardDO: ReturnType<typeof createShardDO>;
653
+ }
654
+
655
+ /**
656
+ * Fluent worker-composition builder. Records each capability declaration, then
657
+ * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
658
+ * worker-side \`createWorker\` options — constructing the worker lazily on the
659
+ * first request so per-isolate singletons are built once.
660
+ */
661
+ class AppBuilder<Env extends object> {
662
+ ${j(t).join(`
663
+ `)}
664
+
665
+ private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
666
+
667
+ ${B(t).join(`
668
+
669
+ `)}
670
+
671
+ ${d}
672
+
673
+ /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
674
+ private assemble(${b}): ComposedApp {
675
+ const ShardDO = createShardDO({${W(t)}});
676
+
677
+ // Per-isolate singletons: the worker (and auth instance) are expensive to
678
+ // build, so the first request constructs them and every later request on
679
+ // the same isolate reuses them.
680
+ let worker: LunoraWorker | null = null;
681
+ ${o}${h}
682
+ ${p}
683
+
684
+ const composed: ComposedApp = {
685
+ ShardDO,
686
+ fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
687
+ const env = rawEnv as Env;${c}
688
+ worker ??= buildWorker(env);
689
+
690
+ return worker.fetch(request, rawEnv, context);
691
+ },
692
+ scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
693
+ worker ??= buildWorker(rawEnv as Env);
694
+
695
+ return worker.scheduled(controller, rawEnv, context);
696
+ },
697
+ serverQuery: (request, rawEnv, reference, args, options) => {
698
+ worker ??= buildWorker(rawEnv as Env);
699
+
700
+ return worker.serverQuery(request, rawEnv, reference, args, options);
701
+ },${t.hasQueue?`
702
+ queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
703
+ worker ??= buildWorker(rawEnv as Env);
704
+
705
+ return worker.queue?.(batch, rawEnv, context);
706
+ },`:""}
707
+ };
708
+
709
+ ${g} if (this.emailHandler) {
710
+ const handler = this.emailHandler;
711
+
712
+ composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
713
+ }
714
+
715
+ return composed;
716
+ }
717
+ ${$(t)}${H(t.hasStorage)}
718
+ /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
719
+ private buildWorkerOptions(env: Env, ${u}): WorkerOptions {
720
+ const options: WorkerOptions = {
721
+ ${_(t).join(`
722
+ `)}
723
+ };
724
+
725
+ if (this.adminToken) {
726
+ options.adminToken = this.adminToken(env);
727
+ }
728
+
729
+ ${n.join(`
730
+
731
+ `)}${n.length>0?`
732
+
733
+ `:""} for (const fn of this.extendFns) {
734
+ Object.assign(options, fn(env, { ...options }));
735
+ }
736
+
737
+ return options;
738
+ }
739
+ }
740
+ ${U(t.hasGlobal)}
741
+ /**
742
+ * Start composing the app. Chain the capability methods, then \`.build()\`.
743
+ *
744
+ * \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
745
+ * — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
746
+ * what any app with its own bindings declares — is NOT assignable to an index
747
+ * signature, so the stricter bound forced every real app to write
748
+ * \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
749
+ * through the selectors you pass it, so the looser bound costs nothing.
750
+ */
751
+ const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
752
+
753
+ export { AppBuilder, defineApp };
754
+ export type { ${F(t)} };
755
+ `};export{Q as emitApp};