@lunora/codegen 1.0.0-alpha.13 → 1.0.0-alpha.130

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 (80) hide show
  1. package/LICENSE.md +6 -0
  2. package/dist/index.d.mts +3010 -1005
  3. package/dist/index.d.ts +3010 -1005
  4. package/dist/index.mjs +1 -31
  5. package/dist/packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs +1 -0
  6. package/dist/packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs +1 -0
  7. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  8. package/dist/packem_shared/DEFAULT_TARGET-CrhWLUK7.mjs +1 -0
  9. package/dist/packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs +1 -0
  10. package/dist/packem_shared/GENERATED_HEADER-NWWDWOX4.mjs +1 -0
  11. package/dist/packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs +1 -0
  12. package/dist/packem_shared/MUTATORS_FILENAME-DJerSBO-.mjs +1 -0
  13. package/dist/packem_shared/NOTIFY_FILENAME-CPg7zlsb.mjs +1 -0
  14. package/dist/packem_shared/OPENRPC_VERSION-6XrIwoNr.mjs +3 -0
  15. package/dist/packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs +1 -0
  16. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME--CCXsODJ.mjs +9 -0
  17. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CftvRWB8.mjs +2 -0
  18. package/dist/packem_shared/SDK_LANGUAGES-CFyux-74.mjs +371 -0
  19. package/dist/packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs +1 -0
  20. package/dist/packem_shared/SchemaSnapshotParseError-D2h88OHU.mjs +16 -0
  21. package/dist/packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs +1 -0
  22. package/dist/packem_shared/buildOpenApiDocument-DDvSUMD9.mjs +3 -0
  23. package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
  24. package/dist/packem_shared/discover-ast-D33zP-NZ.mjs +1 -0
  25. package/dist/packem_shared/discover-queries-Dfj_0WJG.mjs +1 -0
  26. package/dist/packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs +1 -0
  27. package/dist/packem_shared/discoverCrons-BUJO2ipU.mjs +1 -0
  28. package/dist/packem_shared/discoverFunctions-CYHtspcp.mjs +1 -0
  29. package/dist/packem_shared/discoverHttpRoutes-BkwEwmK0.mjs +1 -0
  30. package/dist/packem_shared/discoverInserts-YX8AmrzL.mjs +1 -0
  31. package/dist/packem_shared/discoverMaskProcedures-DExWLcsu.mjs +1 -0
  32. package/dist/packem_shared/discoverMigrations-4Jjf5DJE.mjs +1 -0
  33. package/dist/packem_shared/discoverNondeterministicCalls-xRw6-4OU.mjs +1 -0
  34. package/dist/packem_shared/discoverQueries-C5S9tFoD.mjs +1 -0
  35. package/dist/packem_shared/discoverR2sqlCalls-Ciq0-bVB.mjs +1 -0
  36. package/dist/packem_shared/discoverRlsMetadata-Bnn3zDlc.mjs +1 -0
  37. package/dist/packem_shared/discoverSandboxUsage-L0lV17de.mjs +1 -0
  38. package/dist/packem_shared/discoverSchema-gJ93Xjpx.mjs +1 -0
  39. package/dist/packem_shared/discoverStorageRulesMetadata-DYAgRSL6.mjs +1 -0
  40. package/dist/packem_shared/emit-GW3Jf9w0.mjs +2268 -0
  41. package/dist/packem_shared/emitApp-D-mz_p6P.mjs +646 -0
  42. package/dist/packem_shared/formatAdvisories-CkEu1eye.mjs +2 -0
  43. package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -0
  44. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  45. package/dist/packem_shared/parse-validator-C5ycrhR3.mjs +1 -0
  46. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  47. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  48. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  49. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  50. package/package.json +12 -7
  51. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  52. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  53. package/dist/packem_shared/GENERATED_HEADER-BEA7oWGC.mjs +0 -2841
  54. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  55. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  56. package/dist/packem_shared/OPENRPC_VERSION-CQ3f8YQ-.mjs +0 -60
  57. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  58. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BXtduJFE.mjs +0 -954
  59. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  60. package/dist/packem_shared/WORKFLOWS_FILENAME-D62dcBGg.mjs +0 -84
  61. package/dist/packem_shared/buildOpenApiDocument-699G4RP4.mjs +0 -183
  62. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  63. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  64. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  65. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  66. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  67. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  68. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  69. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  70. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  71. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  72. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  73. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  74. package/dist/packem_shared/discoverSchema-BnWHHJ4T.mjs +0 -822
  75. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  76. package/dist/packem_shared/emitApp-DiK0QSBn.mjs +0 -617
  77. package/dist/packem_shared/formatAdvisories-8NIv1k0I.mjs +0 -69
  78. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  79. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  80. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,646 @@
1
+ import{A as S,G as D}from"./emit-GW3Jf9w0.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]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=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:o,hasKv:c,hasQueue:s,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 w=[...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";']:[],...R(t,a),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(c),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...h?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...u?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...O(e),`import type { ${[...g].toSorted((f,y)=>f.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${w} } from "${i}";`,"",...A(e.identity),...T(e),...n||o?['import schema from "../schema.js";']:[],...C(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['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";']},q=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. */
2
+ interface StorageDeclaration<Env> {
3
+ /** The default R2 bucket binding (the bare \`ctx.storage\`). */
4
+ bucket: Selector<Env, R2BucketLike>;
5
+ /** Extra named buckets, reached via \`ctx.storage.bucket("name")\` and the studio's bucket picker. */
6
+ buckets?: Record<string, Selector<Env, R2BucketLike>>;
7
+ /** Public base URL signed/public object URLs resolve against. */
8
+ publicBaseUrl?: Selector<Env, string>;
9
+ /** HMAC secret for signed URLs. */
10
+ signingSecret?: Selector<Env, string>;
11
+ }`]:[],...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}']:[]],I=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = 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} */
12
+ public ${t}(factory: NonNullable<ShardConfig["${a}"]>): this {
13
+ this.shardExtras.${a} = factory;
14
+
15
+ return this;
16
+ }`),N=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. */
17
+ public admin(selector: Selector<Env, string>): this {
18
+ this.adminToken = selector;
19
+
20
+ return this;
21
+ }`," /**\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 }",...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. */
22
+ public global(declaration: GlobalDeclaration<Env>): this {
23
+ this.globalDeclaration = declaration;
24
+
25
+ return this;
26
+ }`]:[],...e.hasHyperdriveGlobal?[` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
27
+ public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
28
+ this.hyperdriveGlobalDeclaration = declaration;
29
+
30
+ return this;
31
+ }`]:[],` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
32
+ public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
33
+ this.emailHandler = handler;
34
+
35
+ return this;
36
+ }`," /** 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. */
37
+ public route(key: string, handler: Route): this {
38
+ this.routeMap[key] = handler;
39
+
40
+ return this;
41
+ }`,...e.hasScheduler?[` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
42
+ public scheduler(declaration: SchedulerDeclaration<Env>): this {
43
+ this.schedulerDeclaration = declaration;
44
+
45
+ return this;
46
+ }`]:[],` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
47
+ public shard(selector: Selector<Env, ShardNamespaceLike>): this {
48
+ this.shardSelector = selector;
49
+
50
+ return this;
51
+ }`,...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
52
+ public storage(declaration: StorageDeclaration<Env>): this {
53
+ this.storageDeclaration = declaration;
54
+
55
+ return this;
56
+ }`]:[],...G(e)],j=e=>{const t=r=>e.hasScheduler?`
57
+ ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${r}["scheduler"] } : {}),`:"",a=[" cdc: this.cdcEnabled,",...e.hasGlobal?[` ...(this.globalDeclaration
58
+ ? {
59
+ d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
60
+ const env = rawEnv as Env;
61
+ const database = this.globalDeclaration?.d1(env);
62
+
63
+ if (!database) {
64
+ return undefined;
65
+ }
66
+
67
+ const origin = this.globalDeclaration?.origin?.(env);
68
+ const crossShard = origin
69
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
70
+ : undefined;
71
+
72
+ return createD1CtxDb({
73
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("D1CtxDbOptions")}
74
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
75
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
76
+ // Forwarded from the shard's own \`cdc\` config, so ONE
77
+ // switch governs both changelogs. Built without it, the
78
+ // global \`__cdc_log\` is never written and the shape
79
+ // poll's changed-tables fast path is unreachable.
80
+ cdc: request?.cdc ?? false,
81
+ exec: buildExec(database, request?.bookmark, request?.onBookmark),
82
+ schema: schema as unknown as D1CtxDbOptions["schema"],
83
+ });
84
+ },
85
+ }
86
+ : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
87
+ ? {
88
+ hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
89
+ const env = rawEnv as Env;
90
+ const exec = this.hyperdriveGlobalDeclaration?.exec(env) as SqlExec | undefined;
91
+
92
+ if (!exec) {
93
+ return undefined;
94
+ }
95
+
96
+ const origin = this.hyperdriveGlobalDeclaration?.origin?.(env);
97
+ const crossShard = origin
98
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
99
+ : undefined;
100
+
101
+ return createHyperdriveGlobalCtxDb({
102
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
103
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
104
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
105
+ // See the D1 twin: one \`cdc\` switch, both changelogs.
106
+ cdc: request?.cdc ?? false,
107
+ engine: this.hyperdriveGlobalDeclaration?.engine as HyperdriveEngine,
108
+ exec,
109
+ schema: schema as unknown as SqlCtxDbOptions["schema"],
110
+ });
111
+ },
112
+ }
113
+ : {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
114
+ ? {
115
+ scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
116
+ }
117
+ : {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
118
+ ${a.join(`
119
+ `)}
120
+ `:""},B=e=>[...e.hasScheduler?[` if (this.schedulerDeclaration) {
121
+ options.schedulerDO = this.schedulerDeclaration.namespace(env);
122
+ }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
123
+ const source = workflowEnv as Record<string, unknown>;
124
+ const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
125
+ const apiToken = source["CLOUDFLARE_API_TOKEN"];
126
+
127
+ return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
128
+ ? createWorkflowsRestClient({ accountId, apiToken })
129
+ : undefined;
130
+ };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
131
+ const database = this.globalDeclaration.d1(env);
132
+
133
+ if (database) {
134
+ options.d1 = database;
135
+ options.globalIntrospector = buildGlobalIntrospector(database);
136
+ // \`resolveTableSharding\`/\`importGlobals\` wire the admin bulk-import
137
+ // endpoint: without the former, EVERY row (including a \`.global()\`
138
+ // table's) routes to the default shard, so a global table is never
139
+ // recognised as global and the latter is never reached — the
140
+ // endpoint answers 200 with \`inserted: {}\` for a write that never
141
+ // happened. Both are mechanical over the schema this file already
142
+ // imports, so there is nothing project-specific to configure.
143
+ options.resolveTableSharding = buildTableShardingResolver();
144
+ options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
145
+ // The read/replay half of the same admin plane. Each one is the
146
+ // only reason its endpoint can see the global storage plane at
147
+ // all, and every one of them fails SILENTLY when unset — export
148
+ // and \`lunora backup create\` answer 200 having written only
149
+ // shard-local rows (an export→import round trip then restores
150
+ // cleanly minus every global row), CDC sync answers with only
151
+ // shard changes, and point-in-time apply reports
152
+ // \`globalApplied: 0\`. Nothing here is project-specific either.
153
+ options.exportGlobals = buildGlobalExporter(database);
154
+ options.syncGlobals = buildGlobalCdcSync(database);
155
+ options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
156
+ }
157
+ }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
158
+ Object.assign(options, this.buildStorageAdmin(env));
159
+ options.storage = (rawEnv: unknown) => this.resolveStorage(rawEnv as Env);
160
+ }`]:[],...e.hasKv?[" 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
161
+ // \`this.authDeclaration.namespace\` again below would be optional all over again.
162
+ const authDeclaration = this.authDeclaration;
163
+ const authNamespace = authDeclaration?.namespace;
164
+ const authD1 = authDeclaration?.d1;
165
+
166
+ if (authDeclaration && authNamespace) {
167
+ // DO-backed mode. The auth tables live inside the object and DO storage is
168
+ // unreachable from here, so better-auth runs in there and this worker talks
169
+ // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
170
+ // than more emitted code: request-path logic in generated output can only be
171
+ // typechecked, never unit-tested.
172
+ const authWiring = createDoAuthWiring({
173
+ internalSecret: authDeclaration.internalSecret?.(env),
174
+ namespace: authNamespace(env),
175
+ objectName: authDeclaration.objectName?.(env),
176
+ });
177
+
178
+ options.authHandler = authWiring.authHandler;
179
+ options.resolveIdentity = authWiring.resolveIdentity;
180
+ // The audit log lives in the object like every other auth table, so the feed
181
+ // reads through it rather than querying D1.
182
+ options.authAuditReader = authWiring.auditReader;
183
+ // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
184
+ // from the worker, which DO storage does not allow. The studio's auth pages
185
+ // therefore report "not configured" in this mode rather than silently
186
+ // returning empty data.
187
+ } else if (authDeclaration && authD1) {
188
+ options.authHandler = (request) => {
189
+ const auth = getAuth();
190
+
191
+ return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
192
+ };
193
+ options.resolveIdentity = async (request) => {
194
+ const auth = getAuth();
195
+
196
+ if (!auth) {
197
+ return null;
198
+ }
199
+
200
+ const session = await auth.api.getSession({ headers: (request as Request).headers });
201
+
202
+ return session?.user?.id ? { userId: session.user.id } : null;
203
+ };
204
+ const authInstance = getAuth();
205
+
206
+ options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
207
+ options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
208
+ }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
209
+ const accessResolver = createAccessResolver(this.accessSelector(env));
210
+ const fallback = options.resolveIdentity;
211
+
212
+ options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
213
+ }`:` if (this.accessSelector) {
214
+ options.resolveIdentity = createAccessResolver(this.accessSelector(env));
215
+ }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
216
+ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
217
+ `)}
218
+ };`]:[]],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),"],$=e=>e.hasScheduler?`
219
+ /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until both the namespace and origin are wired. */
220
+ private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
221
+ const namespace = this.schedulerDeclaration?.namespace(env);
222
+ const origin = this.schedulerDeclaration?.origin?.(env);
223
+
224
+ return namespace && origin ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace, originUrl: origin }) : undefined;
225
+ }
226
+ `:"",P=e=>e?`
227
+ /** Resolve the storage capability (single or multi-bucket) for the DO side. */
228
+ private resolveStorage(env: Env): Storage | undefined {
229
+ const declaration = this.storageDeclaration;
230
+
231
+ if (!declaration) {
232
+ return undefined;
233
+ }
234
+
235
+ const defaultBucket = declaration.bucket(env);
236
+
237
+ if (!defaultBucket) {
238
+ return undefined;
239
+ }
240
+
241
+ const make = (bucket: R2BucketLike): Storage =>
242
+ createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
243
+ const extraEntries = Object.entries(declaration.buckets ?? {})
244
+ .map(([name, selector]) => [name, selector(env)] as const)
245
+ .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
246
+
247
+ if (extraEntries.length === 0) {
248
+ return make(defaultBucket);
249
+ }
250
+
251
+ const map: Record<string, Storage> = { default: make(defaultBucket) };
252
+
253
+ for (const [name, bucket] of extraEntries) {
254
+ map[name] = make(bucket);
255
+ }
256
+
257
+ return createBucketStorage(map, { default: "default" });
258
+ }
259
+
260
+ /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
261
+ private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
262
+ const declaration = this.storageDeclaration;
263
+
264
+ if (!declaration) {
265
+ return {};
266
+ }
267
+
268
+ const defaultBucket = declaration.bucket(env);
269
+
270
+ if (!defaultBucket) {
271
+ return {};
272
+ }
273
+
274
+ const make = (bucket: R2BucketLike): Storage =>
275
+ createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
276
+ // Held separately from the map so \`pick\`'s fallback is a plain binding:
277
+ // under \`noUncheckedIndexedAccess\` a \`Record<string, Storage>\` lookup —
278
+ // including \`buckets.default\` — widens to \`Storage | undefined\`, which
279
+ // would not satisfy \`pick\`'s declared \`Storage\` return.
280
+ const fallbackStorage = make(defaultBucket);
281
+ const buckets: Record<string, Storage> = { default: fallbackStorage };
282
+
283
+ for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
284
+ const bucket = selector(env);
285
+
286
+ if (bucket) {
287
+ buckets[name] = make(bucket);
288
+ }
289
+ }
290
+
291
+ const pick = (name?: string): Storage => buckets[name !== undefined && name !== "" ? name : "default"] ?? fallbackStorage;
292
+ const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
293
+
294
+ return {
295
+ storageBuckets: Object.keys(buckets),
296
+ storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
297
+ storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
298
+ storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
299
+ storageSignedUrl: hasSigning
300
+ ? (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT" }) =>
301
+ pick(opts?.bucket).getSignedUrl(key, { contentType: opts?.contentType, expiresInSeconds: opts?.expiresInSeconds, method: opts?.method })
302
+ : undefined,
303
+ storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
304
+ };
305
+ }
306
+ `:"",H=e=>e?`
307
+ /**
308
+ * 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\`).
309
+ *
310
+ * Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
311
+ * last-known write, when supplied) so reads observe it — read-your-writes
312
+ * across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
313
+ * produced by each write so the caller (the generated DO) can record it via
314
+ * \`setOutboundBookmark\` and echo \`x-d1-bookmark\` on the response.
315
+ *
316
+ * Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
317
+ * (storage-object resets, isolate memory evictions, dropped connections) does
318
+ * not surface on every \`.global()\` read. Only statements that are provably
319
+ * read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
320
+ * optimistic-concurrency check issues through \`all\` — pass straight through,
321
+ * because a transient error never says whether the write applied.
322
+ */
323
+ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
324
+ // Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
325
+ // below so a hand-rolled test double that omits it keeps working via
326
+ // \`prepare()\` straight on the raw binding — today's behaviour. With no
327
+ // inbound bookmark, \`"first-unconstrained"\` is the documented no-op
328
+ // equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
329
+ const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
330
+ const target = session ?? database;
331
+ const batchFn = target.batch;
332
+
333
+ return retryingExec({
334
+ all: async (sql, parameters) => {
335
+ const result = await target
336
+ .prepare(sql)
337
+ .bind(...parameters)
338
+ .all<Record<string, unknown>>();
339
+
340
+ return result.results;
341
+ },
342
+ // D1's own \`batch\` runs the whole array as one atomic SQLite
343
+ // transaction. Guarded because \`batch\` is optional in the structural
344
+ // type (test doubles may omit it) — real D1 always has it; a double
345
+ // without it still works through the store's sequential fallback.
346
+ // Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
347
+ // directly so TS can narrow the captured \`batchFn\` across the closure
348
+ // boundary (a property-access narrowing like
349
+ // \`hasBatch = typeof target.batch === "function"\` does not survive
350
+ // into a nested arrow function); \`.call\` still binds \`this\` to
351
+ // \`target\`, so the real workerd \`D1Database\`/session doesn't throw
352
+ // \`TypeError: Illegal invocation\` the way a detached
353
+ // \`const fn = target.batch; fn(...)\` capture would.
354
+ batch: batchFn
355
+ ? async (statements) => {
356
+ await batchFn.call(
357
+ target,
358
+ statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
359
+ );
360
+ onBookmark?.(session?.getBookmark() ?? undefined);
361
+ }
362
+ : undefined,
363
+ run: async (sql, parameters) => {
364
+ await target
365
+ .prepare(sql)
366
+ .bind(...parameters)
367
+ .run();
368
+ onBookmark?.(session?.getBookmark() ?? undefined);
369
+ },
370
+ });
371
+ };
372
+
373
+ /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
374
+ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
375
+ const exec = buildExec(database);
376
+
377
+ return {
378
+ facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
379
+ listTables: () => listGlobalTables(exec, schema as never),
380
+ readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
381
+ };
382
+ };
383
+
384
+ /**
385
+ * \`resolveTableSharding\` for the admin bulk-import endpoint: a lookup over each
386
+ * table's declared \`shardMode\` (\`defineTable(...).global()\` / \`.shardBy(field)\`
387
+ * already record exactly this shape on the table) — mechanical, nothing to
388
+ * configure per project. \`undefined\` for a table the schema doesn't declare, so
389
+ * the import endpoint's own unknown-table handling still applies.
390
+ */
391
+ const buildTableShardingResolver = (): AdminTableResolver => (table) => {
392
+ const declared = (schema as unknown as D1CtxDbOptions["schema"]).tables[table];
393
+
394
+ return declared?.shardMode ? { mode: declared.shardMode } : undefined;
395
+ };
396
+
397
+ /**
398
+ * \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
399
+ * through the same D1 writer \`.global()\` reads/writes already use, via
400
+ * \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
401
+ * twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
402
+ * shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
403
+ *
404
+ * Passes each row's own \`line\` through rather than dropping it: the caller
405
+ * (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
406
+ * physical source line, and global rows are typically interspersed with
407
+ * shard-local ones it filtered out before calling here — a single
408
+ * \`startLine\` plus positional counting would mis-attribute every row after
409
+ * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
410
+ * falls back to the position-derived count otherwise.
411
+ */
412
+ const buildGlobalImporter =
413
+ (database: D1DatabaseLike, cdc: boolean) =>
414
+ (request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
415
+ const exec = buildExec(database);
416
+ // Same reason the PITR applier carries it: a bulk import that skips the
417
+ // changelog restores rows no downstream consumer is ever told about.
418
+ const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
419
+
420
+ return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
421
+ exec,
422
+ rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
423
+ startLine: request.startLine,
424
+ });
425
+ };
426
+
427
+ /**
428
+ * \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
429
+ * which drains the same stream): the read twin of {@link buildGlobalImporter},
430
+ * over the same D1 handle. \`@lunora/d1\`'s \`exportGlobalRows\` keyset-paginates
431
+ * each table and provisions the schema's global tables first, so a table that
432
+ * was never written exports as empty instead of throwing \`no such table\`.
433
+ *
434
+ * \`tables\` is forwarded as-is: the runtime passes an empty array for "every
435
+ * table" (its \`tables === undefined\` case), which is exactly what
436
+ * \`selectGlobalTables\` reads an empty allowlist as.
437
+ */
438
+ const buildGlobalExporter =
439
+ (database: D1DatabaseLike) =>
440
+ (request: { tables: ReadonlyArray<string> }) =>
441
+ exportGlobalRows(buildExec(database), schema as unknown as D1CtxDbOptions["schema"], { tables: request.tables });
442
+
443
+ /**
444
+ * \`syncGlobals\` for the admin CDC sync + warehouse-connector endpoints: pages
445
+ * the global \`__cdc_log\` past \`sinceSeq\`, the global-plane twin of the shard's
446
+ * \`runShardCdcSync\`.
447
+ *
448
+ * Probes \`sqlite_master\` first, exactly as the shard twin does. The changelog
449
+ * table is only created when the global writer runs with CDC enabled, so on
450
+ * every other app a straight read would throw \`no such table: __cdc_log\` and
451
+ * turn "nothing has changed yet" into a 500. Absent log ⇒ an empty page that
452
+ * leaves the caller's cursor where it was.
453
+ */
454
+ const buildGlobalCdcSync =
455
+ (database: D1DatabaseLike) =>
456
+ async (request: { limit?: number; sinceSeq: number }): Promise<{ changes: ReadonlyArray<Record<string, unknown>>; cursor: number }> => {
457
+ const exec = buildExec(database);
458
+ const present = await exec.all(\`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\`, ["__cdc_log"]);
459
+
460
+ if (present.length === 0) {
461
+ return { changes: [], cursor: request.sinceSeq };
462
+ }
463
+
464
+ const page = await readD1CdcChanges(exec, { limit: request.limit, sinceSeq: request.sinceSeq });
465
+
466
+ // \`as unknown as\`, because \`CdcChange\` is an interface and interfaces carry
467
+ // no implicit index signature — the shapes are otherwise identical.
468
+ return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
469
+ };
470
+
471
+ /**
472
+ * \`applyGlobals\` for the admin point-in-time-recovery apply endpoint: replays a
473
+ * batch of global CDC changes through the same D1 writer \`.global()\` writes go
474
+ * through, and reports how many were replayed.
475
+ *
476
+ * \`applyCdcChanges\` is order-sensitive and idempotent per row (insert, falling
477
+ * back to replace on conflict), so the batch is handed over untouched — the
478
+ * caller already emits it in commit order. The changes arrive as plain parsed
479
+ * JSON off the wire, hence the cast to the replayer's own change shape.
480
+ *
481
+ * The writer carries the app's own \`cdc\` setting, so a replay APPENDS to the
482
+ * global changelog like any other write. Built without it the restored rows
483
+ * reach the tables and nothing else: a warehouse connector's cursor walks past a
484
+ * range that has no entries and its mirror silently diverges from the database,
485
+ * with nothing on either side able to notice — and every live \`.global()\` shape
486
+ * misses the restore until the next unconditional resync.
487
+ */
488
+ const buildGlobalCdcApplier =
489
+ (database: D1DatabaseLike, cdc: boolean) =>
490
+ async (request: { changes: ReadonlyArray<Record<string, unknown>> }): Promise<number> => {
491
+ const writer = createD1CtxDb({ cdc, exec: buildExec(database), schema: schema as unknown as D1CtxDbOptions["schema"] });
492
+
493
+ await applyCdcChanges(writer, request.changes as unknown as Parameters<typeof applyCdcChanges>[1]);
494
+
495
+ return request.changes.length;
496
+ };
497
+ `:"",_=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=q(e),r=B(e),n=t?` let auth: LunoraAuth | null = null;
498
+ `:"",o=t?`
499
+ const ensureAuth = async (env: Env): Promise<void> => {
500
+ if (!this.authDeclaration || auth) {
501
+ return;
502
+ }
503
+
504
+ const d1 = this.authDeclaration.d1;
505
+
506
+ // DO-backed mode builds no instance here: better-auth runs inside the
507
+ // object, which materialises its own schema (the Kysely migrator below is
508
+ // dialect-bound and cannot target DO storage).
509
+ if (!d1) {
510
+ return;
511
+ }
512
+
513
+ auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
514
+ // Apply the better-auth schema lazily on first request (raw-D1 Kysely
515
+ // migrator). For production run the migrate command ahead of deploy.
516
+ await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
517
+ };
518
+ `:"",c=t?`
519
+ await ensureAuth(env);`:"",s=t?"() => auth":"() => null",d=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",h=e.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
520
+ host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,u=e.hasFramework?"host?: FrameworkHostHandler":"",l=e.emailAgents??[],p=l.length>0?` composed.email = dispatchAgentEmail([
521
+ ${l.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
522
+ `)}
523
+ ]);
524
+
525
+ `:"",b=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
526
+ public build(): ComposedApp {
527
+ return this.assemble();
528
+ }${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(`
529
+ `)}
530
+
531
+ /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
532
+ type Selector<Env, T> = (env: Env) => T | undefined;
533
+ ${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":""}
534
+ ${a.join(`
535
+
536
+ `)}${a.length>0?`
537
+
538
+ `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
539
+ interface ComposedApp extends LunoraWorker {
540
+ /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
541
+ email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
542
+ /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
543
+ ShardDO: ReturnType<typeof createShardDO>;
544
+ }
545
+
546
+ /**
547
+ * Fluent worker-composition builder. Records each capability declaration, then
548
+ * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
549
+ * worker-side \`createWorker\` options — constructing the worker lazily on the
550
+ * first request so per-isolate singletons are built once.
551
+ */
552
+ class AppBuilder<Env extends object> {
553
+ ${I(e).join(`
554
+ `)}
555
+
556
+ private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
557
+
558
+ ${N(e).join(`
559
+
560
+ `)}
561
+
562
+ ${b}
563
+
564
+ /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
565
+ private assemble(${u}): ComposedApp {
566
+ const ShardDO = createShardDO({${j(e)}});
567
+
568
+ // Per-isolate singletons: the worker (and auth instance) are expensive to
569
+ // build, so the first request constructs them and every later request on
570
+ // the same isolate reuses them.
571
+ let worker: LunoraWorker | null = null;
572
+ ${n}${o}
573
+ ${h}
574
+
575
+ const composed: ComposedApp = {
576
+ ShardDO,
577
+ fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
578
+ const env = rawEnv as Env;${c}
579
+ worker ??= buildWorker(env);
580
+
581
+ return worker.fetch(request, rawEnv, context);
582
+ },
583
+ scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
584
+ worker ??= buildWorker(rawEnv as Env);
585
+
586
+ return worker.scheduled(controller, rawEnv, context);
587
+ },
588
+ serverQuery: (request, rawEnv, reference, args, options) => {
589
+ worker ??= buildWorker(rawEnv as Env);
590
+
591
+ return worker.serverQuery(request, rawEnv, reference, args, options);
592
+ },${e.hasQueue?`
593
+ queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
594
+ worker ??= buildWorker(rawEnv as Env);
595
+
596
+ return worker.queue?.(batch, rawEnv, context);
597
+ },`:""}
598
+ };
599
+
600
+ ${p} if (this.emailHandler) {
601
+ const handler = this.emailHandler;
602
+
603
+ composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
604
+ }
605
+
606
+ return composed;
607
+ }
608
+ ${$(e)}${P(e.hasStorage)}
609
+ /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
610
+ private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
611
+ const options: WorkerOptions = {
612
+ ${W(e).join(`
613
+ `)}
614
+ };
615
+
616
+ if (this.adminToken) {
617
+ options.adminToken = this.adminToken(env);
618
+ }
619
+
620
+ ${r.join(`
621
+
622
+ `)}${r.length>0?`
623
+
624
+ `:""} for (const fn of this.extendFns) {
625
+ Object.assign(options, fn(env, { ...options }));
626
+ }
627
+
628
+ return options;
629
+ }
630
+ }
631
+ ${H(e.hasGlobal)}
632
+ /**
633
+ * Start composing the app. Chain the capability methods, then \`.build()\`.
634
+ *
635
+ * \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
636
+ * — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
637
+ * what any app with its own bindings declares — is NOT assignable to an index
638
+ * signature, so the stricter bound forced every real app to write
639
+ * \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
640
+ * through the selectors you pass it, so the looser bound costs nothing.
641
+ */
642
+ const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
643
+
644
+ export { AppBuilder, defineApp };
645
+ export type { ${_(e)} };
646
+ `};export{F as emitApp};