@lunora/codegen 1.0.0-alpha.15 → 1.0.0-alpha.150

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 +3140 -1043
  4. package/dist/index.d.ts +3140 -1043
  5. package/dist/index.mjs +1 -32
  6. package/dist/packem_shared/AGENTS_FILENAME-B1Abt3Gl.mjs +1 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-CtcysaKS.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-B3VZ6vTw.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER--PCtJMQc.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-DHX1qUP5.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-CKO5gtGe.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-C4UXIUyy.mjs +3 -0
  16. package/dist/packem_shared/QUEUES_FILENAME-C-pzLGy4.mjs +1 -0
  17. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DazENDSB.mjs +9 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-B1BUjuG5.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-yZc-1mxR.mjs +18 -0
  22. package/dist/packem_shared/WORKFLOWS_FILENAME-BfvqsG9Z.mjs +1 -0
  23. package/dist/packem_shared/ast-BYoSZlae.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-D5xOB07T.mjs +3 -0
  25. package/dist/packem_shared/chain-Dygm2apY.mjs +1 -0
  26. package/dist/packem_shared/classify-procedure-call-Ib2EMtFH.mjs +1 -0
  27. package/dist/packem_shared/context-property-calls-Br0sVv8E.mjs +1 -0
  28. package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
  29. package/dist/packem_shared/discoverAuthApiCalls-DoNQSgso.mjs +1 -0
  30. package/dist/packem_shared/discoverCrons-DCxl4hty.mjs +1 -0
  31. package/dist/packem_shared/discoverFunctions-CXURzTDU.mjs +1 -0
  32. package/dist/packem_shared/discoverHttpRoutes-2XhMbeh5.mjs +1 -0
  33. package/dist/packem_shared/discoverHyperdriveCalls-DTq4PKT5.mjs +1 -0
  34. package/dist/packem_shared/discoverInserts-qU5F4W4g.mjs +1 -0
  35. package/dist/packem_shared/discoverMaskProcedures-BZsC5dHd.mjs +1 -0
  36. package/dist/packem_shared/discoverMigrations-BFkJQ8Sy.mjs +1 -0
  37. package/dist/packem_shared/discoverNondeterministicCalls-B-NNzzPW.mjs +1 -0
  38. package/dist/packem_shared/discoverQueries-B4emAFn5.mjs +1 -0
  39. package/dist/packem_shared/discoverR2sqlCalls-C2GtrFnl.mjs +1 -0
  40. package/dist/packem_shared/discoverRlsMetadata-BKcUnSNr.mjs +1 -0
  41. package/dist/packem_shared/discoverRlsProcedures-fAhxiIyD.mjs +1 -0
  42. package/dist/packem_shared/discoverSandboxUsage-CJhnKA0_.mjs +1 -0
  43. package/dist/packem_shared/discoverSchema-D5XGH2wu.mjs +1 -0
  44. package/dist/packem_shared/discoverStorageRulesMetadata-C7XmORWp.mjs +1 -0
  45. package/dist/packem_shared/emit-CXfWb_pY.mjs +2302 -0
  46. package/dist/packem_shared/emitApp-DcrQNgaz.mjs +694 -0
  47. package/dist/packem_shared/exported-procedure-chains-M40rbSYM.mjs +1 -0
  48. package/dist/packem_shared/formatAdvisories-CkEu1eye.mjs +2 -0
  49. package/dist/packem_shared/index-xGhyK9J_.mjs +1 -0
  50. package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -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-Ddvo5dCs.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,694 @@
1
+ import{A as S,G as D}from"./emit-CXfWb_pY.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(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 notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,O=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],T=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],L=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:s,hasKvIntrospector:c,hasQueue:o,hasScheduler:d,hasStorage:h,hasWorkflow:u,useUmbrella:l,wantsOpenApi:p,wantsOpenRpc:b}=e,i=l?"lunorash/runtime":"@lunora/runtime",g=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&g.push("GlobalIntrospector","AdminTableResolver"),r&&g.push("FrameworkHostHandler");const f=[...n||s?["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),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...R(c),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...h?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...u?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...O(e),`import type { ${[...g].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...x(e.identity),...T(e),...n||s?['import schema from "../schema.js";']:[],...C(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},I=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 plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\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}']:[]],q=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>;"]:[]],N=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
+ }`),G=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
+ }`]:[],...N(e)],j=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
+ schema: schema as unknown as D1CtxDbOptions["schema"],
82
+ });
83
+ },
84
+ }
85
+ : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
86
+ ? {
87
+ hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
88
+ const env = rawEnv as Env;
89
+ const exec = this.hyperdriveGlobalDeclaration?.exec(env) as SqlExec | undefined;
90
+
91
+ if (!exec) {
92
+ return undefined;
93
+ }
94
+
95
+ const origin = this.hyperdriveGlobalDeclaration?.origin?.(env);
96
+ const crossShard = origin
97
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
98
+ : undefined;
99
+
100
+ return createHyperdriveGlobalCtxDb({
101
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
102
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
103
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
104
+ // See the D1 twin: one \`cdc\` switch, both changelogs.
105
+ cdc: request?.cdc ?? false,
106
+ engine: this.hyperdriveGlobalDeclaration?.engine as HyperdriveEngine,
107
+ exec,
108
+ schema: schema as unknown as SqlCtxDbOptions["schema"],
109
+ });
110
+ },
111
+ }
112
+ : {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
113
+ ? {
114
+ scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
115
+ }
116
+ : {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
117
+ ${a.join(`
118
+ `)}
119
+ `:""},B=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
120
+ options.schedulerDO = this.schedulerDeclaration.namespace(env);
121
+ }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
122
+ const source = workflowEnv as Record<string, unknown>;
123
+ const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
124
+ const apiToken = source["CLOUDFLARE_API_TOKEN"];
125
+
126
+ return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
127
+ ? createWorkflowsRestClient({ accountId, apiToken })
128
+ : undefined;
129
+ };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
130
+ const database = this.globalDeclaration.d1(env);
131
+
132
+ if (database) {
133
+ options.globalIntrospector = buildGlobalIntrospector(database);
134
+ // \`resolveTableSharding\`/\`importGlobals\` wire the admin bulk-import
135
+ // endpoint: without the former, EVERY row (including a \`.global()\`
136
+ // table's) routes to the default shard, so a global table is never
137
+ // recognised as global and the latter is never reached — the
138
+ // endpoint answers 200 with \`inserted: {}\` for a write that never
139
+ // happened. Both are mechanical over the schema this file already
140
+ // imports, so there is nothing project-specific to configure.
141
+ options.resolveTableSharding = buildTableShardingResolver();
142
+ options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
143
+ // The read/replay half of the same admin plane. Each one is the
144
+ // only reason its endpoint can see the global storage plane at
145
+ // all, and every one of them fails SILENTLY when unset — export
146
+ // and \`lunora backup create\` answer 200 having written only
147
+ // shard-local rows (an export→import round trip then restores
148
+ // cleanly minus every global row), CDC sync answers with only
149
+ // shard changes, and point-in-time apply reports
150
+ // \`globalApplied: 0\`. Nothing here is project-specific either.
151
+ options.exportGlobals = buildGlobalExporter(database);
152
+ options.syncGlobals = buildGlobalCdcSync(database);
153
+ options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
154
+ }
155
+ }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
156
+ Object.assign(options, this.buildStorageAdmin(env));
157
+ options.storage = (rawEnv: unknown) => this.resolveStorage(rawEnv as Env);
158
+ }`]:[],...e.hasKvIntrospector?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...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
159
+ // \`this.authDeclaration.namespace\` again below would be optional all over again.
160
+ const authDeclaration = this.authDeclaration;
161
+ const authNamespace = authDeclaration?.namespace;
162
+ const authD1 = authDeclaration?.d1;
163
+
164
+ if (authDeclaration && authNamespace) {
165
+ // DO-backed mode. The auth tables live inside the object and DO storage is
166
+ // unreachable from here, so better-auth runs in there and this worker talks
167
+ // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
168
+ // than more emitted code: request-path logic in generated output can only be
169
+ // typechecked, never unit-tested.
170
+ const authWiring = createDoAuthWiring({
171
+ internalSecret: authDeclaration.internalSecret?.(env),
172
+ namespace: authNamespace(env),
173
+ objectName: authDeclaration.objectName?.(env),
174
+ });
175
+
176
+ options.authHandler = authWiring.authHandler;
177
+ options.resolveIdentity = authWiring.resolveIdentity;
178
+ // The audit log lives in the object like every other auth table, so the feed
179
+ // reads through it rather than querying D1.
180
+ options.authAuditReader = authWiring.auditReader;
181
+ // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
182
+ // from the worker, which DO storage does not allow. The studio's auth pages
183
+ // therefore report "not configured" in this mode rather than silently
184
+ // returning empty data.
185
+ } else if (authDeclaration && authD1) {
186
+ options.authHandler = (request) => {
187
+ const auth = getAuth();
188
+
189
+ return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
190
+ };
191
+ options.resolveIdentity = async (request) => {
192
+ const auth = getAuth();
193
+
194
+ if (!auth) {
195
+ return null;
196
+ }
197
+
198
+ const session = await auth.api.getSession({ headers: (request as Request).headers });
199
+
200
+ if (!session?.user?.id) {
201
+ return null;
202
+ }
203
+
204
+ // \`role\` rides along so \`rls(policies, { roles })\` and \`auth.can(...)\`
205
+ // work on this wiring without a hand-written resolver. better-auth's
206
+ // \`admin()\` plugin owns that column (comma-joined for multiple roles)
207
+ // and only an administrator can write it; it is absent when the plugin
208
+ // is off, which reads as no roles.
209
+ //
210
+ // \`expiresAtMs\` is the socket credential expiry the runtime forwards
211
+ // as \`x-lunora-identity-exp\`. Without it the DO's expiry check never
212
+ // fires, so a signed-out, banned or lapsed user keeps streaming their
213
+ // RLS-scoped rows over an already-open WebSocket while every HTTP call
214
+ // is anonymous. better-auth hands back a \`Date\`; anything else means
215
+ // the adapter did not hydrate it, and omitting beats guessing.
216
+ const expiresAt = session.session.expiresAt;
217
+
218
+ return {
219
+ ...(expiresAt instanceof Date ? { expiresAtMs: expiresAt.getTime() } : {}),
220
+ role: (session.user as { role?: unknown }).role,
221
+ userId: session.user.id,
222
+ };
223
+ };
224
+ const authInstance = getAuth();
225
+
226
+ options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
227
+ options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
228
+ }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
229
+ const accessResolver = createAccessResolver(this.accessSelector(env));
230
+ const fallback = options.resolveIdentity;
231
+
232
+ options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
233
+ }`:` if (this.accessSelector) {
234
+ options.resolveIdentity = createAccessResolver(this.accessSelector(env));
235
+ }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
236
+ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
237
+ `)}
238
+ };`]:[]],W=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): 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>,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],P=e=>e.hasScheduler?`
239
+ /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until both the namespace and origin are wired. */
240
+ private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
241
+ const namespace = this.schedulerDeclaration?.namespace(env);
242
+ const origin = this.schedulerDeclaration?.origin?.(env);
243
+
244
+ return namespace && origin ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace, originUrl: origin }) : undefined;
245
+ }
246
+ `:"",$=e=>e?`
247
+ /**
248
+ * One bucket's \`Storage\`, signing under the name it is registered as.
249
+ *
250
+ * \`bucketName\` is bound into every signed URL's HMAC canonical, so a bucket
251
+ * that signs as the default's name lets a URL minted for one bucket verify
252
+ * against another sharing the secret — and multi-bucket verification fails
253
+ * outright. Hence \`"default"\` for the bare \`ctx.storage\` bucket and the
254
+ * \`buckets\` key for every other.
255
+ */
256
+ private makeStorage(env: Env, declaration: StorageDeclaration<Env>, bucket: R2BucketLike, bucketName: string): Storage {
257
+ return createStorage({
258
+ bucket,
259
+ bucketName,
260
+ publicBaseUrl: declaration.publicBaseUrl?.(env),
261
+ s3: declaration.s3?.(env),
262
+ signingSecret: declaration.signingSecret?.(env),
263
+ });
264
+ }
265
+
266
+ /** Resolve the storage capability (single or multi-bucket) for the DO side. */
267
+ private resolveStorage(env: Env): Storage | undefined {
268
+ const declaration = this.storageDeclaration;
269
+
270
+ if (!declaration) {
271
+ return undefined;
272
+ }
273
+
274
+ const defaultBucket = declaration.bucket(env);
275
+
276
+ if (!defaultBucket) {
277
+ return undefined;
278
+ }
279
+
280
+ const extraEntries = Object.entries(declaration.buckets ?? {})
281
+ .map(([name, selector]) => [name, selector(env)] as const)
282
+ .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
283
+
284
+ if (extraEntries.length === 0) {
285
+ return this.makeStorage(env, declaration, defaultBucket, "default");
286
+ }
287
+
288
+ const map: Record<string, Storage> = { default: this.makeStorage(env, declaration, defaultBucket, "default") };
289
+
290
+ for (const [name, bucket] of extraEntries) {
291
+ map[name] = this.makeStorage(env, declaration, bucket, name);
292
+ }
293
+
294
+ return createBucketStorage(map, { default: "default" });
295
+ }
296
+
297
+ /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
298
+ private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
299
+ const declaration = this.storageDeclaration;
300
+
301
+ if (!declaration) {
302
+ return {};
303
+ }
304
+
305
+ const defaultBucket = declaration.bucket(env);
306
+
307
+ if (!defaultBucket) {
308
+ return {};
309
+ }
310
+
311
+ // Held separately from the map so \`pick\`'s fallback is a plain binding:
312
+ // under \`noUncheckedIndexedAccess\` a \`Record<string, Storage>\` lookup —
313
+ // including \`buckets.default\` — widens to \`Storage | undefined\`, which
314
+ // would not satisfy \`pick\`'s declared \`Storage\` return.
315
+ const fallbackStorage = this.makeStorage(env, declaration, defaultBucket, "default");
316
+ const buckets: Record<string, Storage> = { default: fallbackStorage };
317
+
318
+ for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
319
+ const bucket = selector(env);
320
+
321
+ if (bucket) {
322
+ buckets[name] = this.makeStorage(env, declaration, bucket, name);
323
+ }
324
+ }
325
+
326
+ const pick = (name?: string): Storage => buckets[name !== undefined && name !== "" ? name : "default"] ?? fallbackStorage;
327
+ const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
328
+
329
+ return {
330
+ storageBuckets: Object.keys(buckets),
331
+ storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
332
+ storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
333
+ storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
334
+ storageSignedUrl: hasSigning
335
+ ? (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT" }) =>
336
+ pick(opts?.bucket).getSignedUrl(key, { contentType: opts?.contentType, expiresInSeconds: opts?.expiresInSeconds, method: opts?.method })
337
+ : undefined,
338
+ storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
339
+ };
340
+ }
341
+ `:"",H=e=>e?`
342
+ /**
343
+ * 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\`).
344
+ *
345
+ * Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
346
+ * last-known write, when supplied) so reads observe it — read-your-writes
347
+ * across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
348
+ * produced by each write so the caller (the generated DO) can record it via
349
+ * \`setOutboundBookmark\` and echo \`x-d1-bookmark\` on the response.
350
+ *
351
+ * Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
352
+ * (storage-object resets, isolate memory evictions, dropped connections) does
353
+ * not surface on every \`.global()\` read. Only statements that are provably
354
+ * read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
355
+ * optimistic-concurrency check issues through \`all\` — pass straight through,
356
+ * because a transient error never says whether the write applied.
357
+ */
358
+ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
359
+ // Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
360
+ // below so a hand-rolled test double that omits it keeps working via
361
+ // \`prepare()\` straight on the raw binding — today's behaviour. With no
362
+ // inbound bookmark, \`"first-unconstrained"\` is the documented no-op
363
+ // equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
364
+ const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
365
+ const target = session ?? database;
366
+ const batchFn = target.batch;
367
+
368
+ return retryingExec({
369
+ all: async (sql, parameters) => {
370
+ const result = await target
371
+ .prepare(sql)
372
+ .bind(...parameters)
373
+ .all<Record<string, unknown>>();
374
+
375
+ // \`all\` carries writes, not just reads: D1 runs
376
+ // \`UPDATE/DELETE … RETURNING\` through it exactly like \`.run()\`, and
377
+ // that is precisely what \`@lunora/sql-store\` issues for its
378
+ // optimistic-concurrency compare-and-swap — so \`patch\`, \`replace\`
379
+ // and \`delete\` all land here and nowhere else. Without this the
380
+ // bookmark those writes produced was never reported, and the next
381
+ // read could pin a replica that has not seen them: read-your-writes
382
+ // lost on the exact path the bookmark exists for. Reporting it after
383
+ // a plain \`SELECT\` too is harmless and correct — the session's
384
+ // bookmark only ever moves forward, and \`setOutboundBookmark\` takes
385
+ // the last value.
386
+ onBookmark?.(session?.getBookmark() ?? undefined);
387
+
388
+ return result.results;
389
+ },
390
+ // D1's own \`batch\` runs the whole array as one atomic SQLite
391
+ // transaction. Guarded because \`batch\` is optional in the structural
392
+ // type (test doubles may omit it) — real D1 always has it; a double
393
+ // without it still works through the store's sequential fallback.
394
+ // Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
395
+ // directly so TS can narrow the captured \`batchFn\` across the closure
396
+ // boundary (a property-access narrowing like
397
+ // \`hasBatch = typeof target.batch === "function"\` does not survive
398
+ // into a nested arrow function); \`.call\` still binds \`this\` to
399
+ // \`target\`, so the real workerd \`D1Database\`/session doesn't throw
400
+ // \`TypeError: Illegal invocation\` the way a detached
401
+ // \`const fn = target.batch; fn(...)\` capture would.
402
+ batch: batchFn
403
+ ? async (statements) => {
404
+ await batchFn.call(
405
+ target,
406
+ statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
407
+ );
408
+ onBookmark?.(session?.getBookmark() ?? undefined);
409
+ }
410
+ : undefined,
411
+ run: async (sql, parameters) => {
412
+ await target
413
+ .prepare(sql)
414
+ .bind(...parameters)
415
+ .run();
416
+ onBookmark?.(session?.getBookmark() ?? undefined);
417
+ },
418
+ });
419
+ };
420
+
421
+ /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
422
+ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
423
+ const exec = buildExec(database);
424
+
425
+ return {
426
+ facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
427
+ listTables: () => listGlobalTables(exec, schema as never),
428
+ readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
429
+ };
430
+ };
431
+
432
+ /**
433
+ * \`resolveTableSharding\` for the admin bulk-import endpoint: a lookup over each
434
+ * table's declared \`shardMode\` (\`defineTable(...).global()\` / \`.shardBy(field)\`
435
+ * already record exactly this shape on the table) — mechanical, nothing to
436
+ * configure per project. \`undefined\` for a table the schema doesn't declare, so
437
+ * the import endpoint's own unknown-table handling still applies.
438
+ */
439
+ const buildTableShardingResolver = (): AdminTableResolver => (table) => {
440
+ const declared = (schema as unknown as D1CtxDbOptions["schema"]).tables[table];
441
+
442
+ return declared?.shardMode ? { mode: declared.shardMode } : undefined;
443
+ };
444
+
445
+ /**
446
+ * \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
447
+ * through the same D1 writer \`.global()\` reads/writes already use, via
448
+ * \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
449
+ * twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
450
+ * shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
451
+ *
452
+ * Passes each row's own \`line\` through rather than dropping it: the caller
453
+ * (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
454
+ * physical source line, and global rows are typically interspersed with
455
+ * shard-local ones it filtered out before calling here — a single
456
+ * \`startLine\` plus positional counting would mis-attribute every row after
457
+ * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
458
+ * falls back to the position-derived count otherwise.
459
+ */
460
+ const buildGlobalImporter =
461
+ (database: D1DatabaseLike, cdc: boolean) =>
462
+ (request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
463
+ const exec = buildExec(database);
464
+ // Same reason the PITR applier carries it: a bulk import that skips the
465
+ // changelog restores rows no downstream consumer is ever told about.
466
+ const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
467
+
468
+ return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
469
+ exec,
470
+ rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
471
+ startLine: request.startLine,
472
+ });
473
+ };
474
+
475
+ /**
476
+ * \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
477
+ * which drains the same stream): the read twin of {@link buildGlobalImporter},
478
+ * over the same D1 handle. \`@lunora/d1\`'s \`exportGlobalRows\` keyset-paginates
479
+ * each table and provisions the schema's global tables first, so a table that
480
+ * was never written exports as empty instead of throwing \`no such table\`.
481
+ *
482
+ * \`tables\` is forwarded as-is: the runtime passes an empty array for "every
483
+ * table" (its \`tables === undefined\` case), which is exactly what
484
+ * \`selectGlobalTables\` reads an empty allowlist as.
485
+ */
486
+ const buildGlobalExporter =
487
+ (database: D1DatabaseLike) =>
488
+ (request: { tables: ReadonlyArray<string> }) =>
489
+ exportGlobalRows(buildExec(database), schema as unknown as D1CtxDbOptions["schema"], { tables: request.tables });
490
+
491
+ /**
492
+ * \`syncGlobals\` for the admin CDC sync + warehouse-connector endpoints: pages
493
+ * the global \`__cdc_log\` past \`sinceSeq\`, the global-plane twin of the shard's
494
+ * \`runShardCdcSync\`.
495
+ *
496
+ * Probes \`sqlite_master\` first, exactly as the shard twin does. The changelog
497
+ * table is only created when the global writer runs with CDC enabled, so on
498
+ * every other app a straight read would throw \`no such table: __cdc_log\` and
499
+ * turn "nothing has changed yet" into a 500. Absent log ⇒ an empty page that
500
+ * leaves the caller's cursor where it was.
501
+ */
502
+ const buildGlobalCdcSync =
503
+ (database: D1DatabaseLike) =>
504
+ async (request: { limit?: number; sinceSeq: number }): Promise<{ changes: ReadonlyArray<Record<string, unknown>>; cursor: number }> => {
505
+ const exec = buildExec(database);
506
+ const present = await exec.all(\`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\`, ["__cdc_log"]);
507
+
508
+ if (present.length === 0) {
509
+ return { changes: [], cursor: request.sinceSeq };
510
+ }
511
+
512
+ const page = await readD1CdcChanges(exec, { limit: request.limit, sinceSeq: request.sinceSeq });
513
+
514
+ // \`as unknown as\`, because \`CdcChange\` is an interface and interfaces carry
515
+ // no implicit index signature — the shapes are otherwise identical.
516
+ return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
517
+ };
518
+
519
+ /**
520
+ * \`applyGlobals\` for the admin point-in-time-recovery apply endpoint: replays a
521
+ * batch of global CDC changes through the same D1 writer \`.global()\` writes go
522
+ * through, and reports how many were replayed.
523
+ *
524
+ * \`applyCdcChanges\` is order-sensitive and idempotent per row (insert, falling
525
+ * back to replace on conflict), so the batch is handed over untouched — the
526
+ * caller already emits it in commit order. The changes arrive as plain parsed
527
+ * JSON off the wire, hence the cast to the replayer's own change shape.
528
+ *
529
+ * The writer carries the app's own \`cdc\` setting, so a replay APPENDS to the
530
+ * global changelog like any other write. Built without it the restored rows
531
+ * reach the tables and nothing else: a warehouse connector's cursor walks past a
532
+ * range that has no entries and its mirror silently diverges from the database,
533
+ * with nothing on either side able to notice — and every live \`.global()\` shape
534
+ * misses the restore until the next unconditional resync.
535
+ */
536
+ const buildGlobalCdcApplier =
537
+ (database: D1DatabaseLike, cdc: boolean) =>
538
+ async (request: { changes: ReadonlyArray<Record<string, unknown>> }): Promise<number> => {
539
+ const writer = createD1CtxDb({ cdc, exec: buildExec(database), schema: schema as unknown as D1CtxDbOptions["schema"] });
540
+
541
+ await applyCdcChanges(writer, request.changes as unknown as Parameters<typeof applyCdcChanges>[1]);
542
+
543
+ return request.changes.length;
544
+ };
545
+ `:"",U=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),F=e=>{const{hasAuth:t}=e,a=I(e),r=B(e),n=t?` let auth: LunoraAuth | null = null;
546
+ `:"",s=t?`
547
+ const ensureAuth = async (env: Env): Promise<void> => {
548
+ if (!this.authDeclaration || auth) {
549
+ return;
550
+ }
551
+
552
+ const d1 = this.authDeclaration.d1;
553
+
554
+ // DO-backed mode builds no instance here: better-auth runs inside the
555
+ // object, which materialises its own schema (the Kysely migrator below is
556
+ // dialect-bound and cannot target DO storage).
557
+ if (!d1) {
558
+ return;
559
+ }
560
+
561
+ auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
562
+ // Apply the better-auth schema lazily on first request (raw-D1 Kysely
563
+ // migrator). For production run the migrate command ahead of deploy.
564
+ await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
565
+ };
566
+ `:"",c=t?`
567
+ await ensureAuth(env);`:"",o=t?"() => auth":"() => null",d=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",h=e.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
568
+ host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${o})) : createWorker(this.buildWorkerOptions(env, ${o}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${o}));`,u=e.hasFramework?"host?: FrameworkHostHandler":"",l=e.emailAgents??[],p=l.length>0?` composed.email = dispatchAgentEmail([
569
+ ${l.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
570
+ `)}
571
+ ]);
572
+
573
+ `:"",b=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
574
+ public build(): ComposedApp {
575
+ return this.assemble();
576
+ }${e.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`${D}${L(e).join(`
577
+ `)}
578
+
579
+ /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
580
+ type Selector<Env, T> = (env: Env) => T | undefined;
581
+ ${m(e)?"\n/** The generated `createShardDO` config — the long-tail `.ai()` / `.kv()` / … methods pass straight through to it. */\ntype ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;\n":""}
582
+ ${a.join(`
583
+
584
+ `)}${a.length>0?`
585
+
586
+ `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
587
+ interface ComposedApp extends LunoraWorker {
588
+ /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
589
+ email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
590
+ /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
591
+ ShardDO: ReturnType<typeof createShardDO>;
592
+ }
593
+
594
+ /**
595
+ * Fluent worker-composition builder. Records each capability declaration, then
596
+ * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
597
+ * worker-side \`createWorker\` options — constructing the worker lazily on the
598
+ * first request so per-isolate singletons are built once.
599
+ */
600
+ class AppBuilder<Env extends object> {
601
+ ${q(e).join(`
602
+ `)}
603
+
604
+ private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
605
+
606
+ ${G(e).join(`
607
+
608
+ `)}
609
+
610
+ ${b}
611
+
612
+ /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
613
+ private assemble(${u}): ComposedApp {
614
+ const ShardDO = createShardDO({${j(e)}});
615
+
616
+ // Per-isolate singletons: the worker (and auth instance) are expensive to
617
+ // build, so the first request constructs them and every later request on
618
+ // the same isolate reuses them.
619
+ let worker: LunoraWorker | null = null;
620
+ ${n}${s}
621
+ ${h}
622
+
623
+ const composed: ComposedApp = {
624
+ ShardDO,
625
+ fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
626
+ const env = rawEnv as Env;${c}
627
+ worker ??= buildWorker(env);
628
+
629
+ return worker.fetch(request, rawEnv, context);
630
+ },
631
+ scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
632
+ worker ??= buildWorker(rawEnv as Env);
633
+
634
+ return worker.scheduled(controller, rawEnv, context);
635
+ },
636
+ serverQuery: (request, rawEnv, reference, args, options) => {
637
+ worker ??= buildWorker(rawEnv as Env);
638
+
639
+ return worker.serverQuery(request, rawEnv, reference, args, options);
640
+ },${e.hasQueue?`
641
+ queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
642
+ worker ??= buildWorker(rawEnv as Env);
643
+
644
+ return worker.queue?.(batch, rawEnv, context);
645
+ },`:""}
646
+ };
647
+
648
+ ${p} if (this.emailHandler) {
649
+ const handler = this.emailHandler;
650
+
651
+ composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
652
+ }
653
+
654
+ return composed;
655
+ }
656
+ ${P(e)}${$(e.hasStorage)}
657
+ /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
658
+ private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
659
+ const options: WorkerOptions = {
660
+ ${W(e).join(`
661
+ `)}
662
+ };
663
+
664
+ if (this.adminToken) {
665
+ options.adminToken = this.adminToken(env);
666
+ }
667
+
668
+ ${r.join(`
669
+
670
+ `)}${r.length>0?`
671
+
672
+ `:""} for (const fn of this.extendFns) {
673
+ Object.assign(options, fn(env, { ...options }));
674
+ }
675
+
676
+ return options;
677
+ }
678
+ }
679
+ ${H(e.hasGlobal)}
680
+ /**
681
+ * Start composing the app. Chain the capability methods, then \`.build()\`.
682
+ *
683
+ * \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
684
+ * — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
685
+ * what any app with its own bindings declares — is NOT assignable to an index
686
+ * signature, so the stricter bound forced every real app to write
687
+ * \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
688
+ * through the selectors you pass it, so the looser bound costs nothing.
689
+ */
690
+ const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
691
+
692
+ export { AppBuilder, defineApp };
693
+ export type { ${U(e)} };
694
+ `};export{F as emitApp};