@lunora/codegen 1.0.0-alpha.24 → 1.0.0-alpha.241

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 (111) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +3390 -1179
  4. package/dist/index.d.ts +3390 -1179
  5. package/dist/index.mjs +1 -34
  6. package/dist/packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs +1 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs +1 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_TARGET-DCpDuuUM.mjs +1 -0
  10. package/dist/packem_shared/FLAGS_FILENAME-BedPDCsR.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER-DSXl0YM2.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-Cl6P9WGv.mjs +3 -0
  16. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  17. package/dist/packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs +1 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CtkD-vQu.mjs +9 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  20. package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
  21. package/dist/packem_shared/SHAPES_FILENAME-zJgzynXR.mjs +1 -0
  22. package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
  23. package/dist/packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-nYvBhjxu.mjs +3 -0
  25. package/dist/packem_shared/capabilities-DJJWVEtk.mjs +18 -0
  26. package/dist/packem_shared/chain-H2N_uKgj.mjs +1 -0
  27. package/dist/packem_shared/classify-procedure-call-BztLe76A.mjs +1 -0
  28. package/dist/packem_shared/context-property-calls-CjDzLU8p.mjs +1 -0
  29. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  30. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  31. package/dist/packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs +1 -0
  32. package/dist/packem_shared/discoverCrons-MfKw7IFf.mjs +1 -0
  33. package/dist/packem_shared/discoverFunctions-BsmX-sEq.mjs +1 -0
  34. package/dist/packem_shared/discoverHttpRoutes-BcXI9CNt.mjs +1 -0
  35. package/dist/packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs +1 -0
  36. package/dist/packem_shared/discoverInserts-CFJ3IVeI.mjs +1 -0
  37. package/dist/packem_shared/discoverMaskProcedures-CV_Cc2_g.mjs +1 -0
  38. package/dist/packem_shared/discoverMigrations-DbrHwcGE.mjs +1 -0
  39. package/dist/packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs +1 -0
  40. package/dist/packem_shared/discoverQueries-C7y8i_Ga.mjs +1 -0
  41. package/dist/packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs +1 -0
  42. package/dist/packem_shared/discoverRlsMetadata-CPmAGL0W.mjs +1 -0
  43. package/dist/packem_shared/discoverRlsProcedures-BO4qC77y.mjs +1 -0
  44. package/dist/packem_shared/discoverSandboxUsage-CrjZ6yNg.mjs +1 -0
  45. package/dist/packem_shared/discoverSchema-D8DBDHEg.mjs +1 -0
  46. package/dist/packem_shared/discoverStorageRulesMetadata-D8VYflWt.mjs +1 -0
  47. package/dist/packem_shared/emitAgents-CoNw0AKK.mjs +1 -0
  48. package/dist/packem_shared/emitApi-CJ9ziZnP.mjs +154 -0
  49. package/dist/packem_shared/emitApp-CgXCWBms.mjs +844 -0
  50. package/dist/packem_shared/emitCrons-BP2xBXDJ.mjs +83 -0
  51. package/dist/packem_shared/emitDataModel-D3WuEZ4b.mjs +113 -0
  52. package/dist/packem_shared/emitDrizzleSchema-Cv0HtLR3.mjs +15 -0
  53. package/dist/packem_shared/emitFunctions-BqAz1ssY.mjs +249 -0
  54. package/dist/packem_shared/emitServer-BEo_fCY8.mjs +365 -0
  55. package/dist/packem_shared/emitShard-DFgzghbs.mjs +1 -0
  56. package/dist/packem_shared/exported-procedure-chains-CmCDiPBV.mjs +1 -0
  57. package/dist/packem_shared/fingerprintSchemaSources-L3nGKDQt.mjs +1 -0
  58. package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
  59. package/dist/packem_shared/index-BoaHhVtM.mjs +1 -0
  60. package/dist/packem_shared/ir-BgM8A3XV.mjs +1 -0
  61. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  62. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  63. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  64. package/dist/packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs +1 -0
  65. package/dist/packem_shared/loadProjectConfig-CKsFNgn3.mjs +1 -0
  66. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  67. package/dist/packem_shared/parse-validator-C94Yiabo.mjs +1 -0
  68. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  69. package/dist/packem_shared/qualifiers-BhOL15WZ.mjs +1 -0
  70. package/dist/packem_shared/queries-B-f4jO-x.mjs +1 -0
  71. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  72. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  73. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  74. package/dist/packem_shared/shard-BaHiawkc.mjs +1435 -0
  75. package/dist/packem_shared/shard-runtime-B5SUfdZB.mjs +318 -0
  76. package/dist/packem_shared/shared-DjUziztz.mjs +9 -0
  77. package/dist/packem_shared/unwrap-handler-return-CoV_GK33.mjs +1 -0
  78. package/package.json +16 -7
  79. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  80. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  81. package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
  82. package/dist/packem_shared/GENERATED_HEADER-DUkXYD5R.mjs +0 -3260
  83. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  84. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  85. package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
  86. package/dist/packem_shared/OPENRPC_VERSION-CjBUaolx.mjs +0 -60
  87. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  88. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BUcGCXi3.mjs +0 -1130
  89. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  90. package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
  91. package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
  92. package/dist/packem_shared/buildOpenApiDocument-WxYTLh11.mjs +0 -183
  93. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  94. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  95. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  96. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  97. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  98. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  99. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  100. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  101. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  102. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  103. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  104. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  105. package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
  106. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  107. package/dist/packem_shared/emitApp-DD0i1ks0.mjs +0 -666
  108. package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
  109. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  110. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  111. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,844 @@
1
+ import{A as w}from"./capabilities-DJJWVEtk.mjs";import{i as k}from"./ir-BgM8A3XV.mjs";import{G as S}from"./shared-DjUziztz.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,g=w.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>g.some(([t])=>e[t]),D=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";']:[],A=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],C=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],v=e=>(e.emailAgents?.length??0)>0,T=e=>v(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],N=e=>v(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],d=e=>e.tables.some(t=>k(t)),I=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],s=[...r||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,h)=>c.localeCompare(h)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},L=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:h,wantsOpenRpc:u}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...C(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(i),...A(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...T(e),...I(e),"",...D(e.identity),...N(e),...a||n?['import schema from "../schema.js";']:[],...O(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";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...u?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.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. */\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. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," 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> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],G=e=>g.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
2
+ public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
3
+ this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
4
+
5
+ return this;
6
+ }`),B=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
7
+ public admin(selector: Selector<Env, string>): this {
8
+ this.adminToken = selector;
9
+
10
+ return this;
11
+ }`," /**\n * Opt into change-data-capture: every write records a post-image to `__cdc_log` — on this shard AND, when the app has `.global()` tables, on the global backend. Backs streaming export, replay-PITR, and the `.global()` half of `defineShape` replication (whose poll tick asks the global changelog which tables moved). Off by default: it costs a changelog row per write, which an app using none of the above should not pay.\n *\n * REQUIRED for a shard-local `defineShape`: those replicate out of `__cdc_log`, and a `shape_subscribe` is refused with `SHAPE_REQUIRES_CDC` without it.\n *\n * It also changes how fresh a `.global()` shape is against writes made OUTSIDE `ctx.db` — an admin import, a PITR replay, an external ETL job, or a predicate over wall clock. With CDC off the poll re-reads every shape every 2s. With it on the poll asks the global changelog which tables moved and skips the rest, so a change the changelog never saw waits for the 30s unconditional resync instead. Writes through `ctx.db` are unaffected: they append, so the poll sees them on the next tick either way.\n */\n public cdc(enabled = true): this {\n this.cdcEnabled = enabled;\n\n return this;\n }",` /**
12
+ * Enable the per-shard reactive query cache: query results are memoized by \`(functionPath, args, identity)\` and invalidated by the ctx-db write hooks BEFORE the subscription broadcast, so a subscriber re-running its query always observes the post-write state.
13
+ *
14
+ * Off by default (every dispatch re-runs its handler). Pass an options object to tune the caps: \`maxEntries\` (default 1000) and \`maxBytes\` (default 4 MiB); either accepts \`Number.POSITIVE_INFINITY\` to disable that cap.
15
+ */
16
+ public reactiveCache(config: boolean | { maxBytes?: number; maxEntries?: number } = true): this {
17
+ this.reactiveCacheConfig = config;
18
+
19
+ return this;
20
+ }`,` /** Ceiling on the join keys ONE relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
21
+ public maxRelationKeys(limit: NonNullable<ShardConfig["maxRelationKeys"]>): this {
22
+ this.maxRelationKeysLimit = limit;
23
+
24
+ return this;
25
+ }`," /**\n * Route the shard's `ctx.log` lines, `ctx.trace` spans and `ctx.metrics` measurements to a telemetry sink.\n *\n * The DO half of observability: without it every in-handler signal stays in the shard's local ring buffer (the studio Logs panel) and reaches no collector. The worker half — one `onRpc` event per dispatched RPC — is a `createWorker` option; pass the SAME sink to both via `.extend((env) => ({ observability: sink(env) }))` to correlate them.\n */\n public observability(selector: NonNullable<ShardConfig[\"observability\"]>): this {\n this.observabilitySink = selector;\n\n return this;\n }",' /** Resolution policy for a relation-crossing `where` whose child is co-located in this shard: `"auto"` (cost-based, the engine default), `"always"` (inline correlated EXISTS) or `"never"` (universal semijoin). All three return identical rows. */\n public relationExistsPushDown(mode: NonNullable<ShardConfig["relationExistsPushDown"]>): this {\n this.relationExistsPushDownMode = mode;\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. */
26
+ public global(declaration: GlobalDeclaration<Env>): this {
27
+ this.globalDeclaration = declaration;
28
+
29
+ return this;
30
+ }`]:[],...e.hasHyperdriveGlobal?[` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
31
+ public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
32
+ this.hyperdriveGlobalDeclaration = declaration;
33
+
34
+ return this;
35
+ }`]:[],` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
36
+ public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
37
+ this.emailHandler = handler;
38
+
39
+ return this;
40
+ }`," /** 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. */
41
+ public route(key: string, handler: Route): this {
42
+ this.routeMap[key] = handler;
43
+
44
+ return this;
45
+ }`,...e.hasScheduler?[` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
46
+ public scheduler(declaration: SchedulerDeclaration<Env>): this {
47
+ this.schedulerDeclaration = declaration;
48
+
49
+ return this;
50
+ }`]:[],` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
51
+ public shard(selector: Selector<Env, ShardNamespaceLike>): this {
52
+ this.shardSelector = selector;
53
+
54
+ return this;
55
+ }`,...d(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
56
+ public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
57
+ this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
58
+
59
+ return this;
60
+ }`]:[],...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
61
+ public storage(declaration: StorageDeclaration<Env>): this {
62
+ this.storageDeclaration = declaration;
63
+
64
+ return this;
65
+ }`]:[],...G(e)],P=e=>{const t=a=>e.hasScheduler?`
66
+ ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",r=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),"," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
67
+ ? {
68
+ d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
69
+ const env = rawEnv as Env;
70
+ const database = this.globalDeclaration?.d1(env);
71
+
72
+ if (!database) {
73
+ return undefined;
74
+ }
75
+
76
+ const origin = this.globalDeclaration?.origin?.(env);
77
+ const crossShard = origin
78
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
79
+ : undefined;
80
+
81
+ return createD1CtxDb({
82
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("D1CtxDbOptions")}
83
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
84
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
85
+ // Forwarded from the shard's own \`cdc\` config, so ONE
86
+ // switch governs both changelogs. Built without it, the
87
+ // global \`__cdc_log\` is never written and the shape
88
+ // poll's changed-tables fast path is unreachable.
89
+ cdc: request?.cdc ?? false,
90
+ exec: buildExec(database, request?.bookmark, request?.onBookmark),
91
+ // The binding outlives this per-request writer, so the
92
+ // provisioning sweep runs once per isolate rather than
93
+ // once per request. See \`SqlCtxDbOptions.provisionScope\`.
94
+ provisionScope: database,
95
+ schema: schema as unknown as D1CtxDbOptions["schema"],
96
+ });
97
+ },
98
+ }
99
+ : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
100
+ ? {
101
+ hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
102
+ const env = rawEnv as Env;
103
+ const declaration = this.hyperdriveGlobalDeclaration;
104
+ const exec = declaration?.exec(env) as SqlExec | undefined;
105
+
106
+ if (!declaration || !exec) {
107
+ return undefined;
108
+ }
109
+
110
+ const origin = declaration.origin?.(env);
111
+ const crossShard = origin
112
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
113
+ : undefined;
114
+
115
+ return createHyperdriveGlobalCtxDb({
116
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
117
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
118
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
119
+ // See the D1 twin: one \`cdc\` switch, both changelogs.
120
+ cdc: request?.cdc ?? false,
121
+ engine: declaration.engine as HyperdriveEngine,
122
+ exec,
123
+ // The DECLARATION, not \`exec\` — \`exec(env)\` is a user
124
+ // callback that builds a fresh client per call, so scoping
125
+ // to its result would key the memo on a new object every
126
+ // request and never share anything. The declaration is
127
+ // built once and names one database.
128
+ provisionScope: declaration,
129
+ schema: schema as unknown as SqlCtxDbOptions["schema"],
130
+ });
131
+ },
132
+ }
133
+ : {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
134
+ ? {
135
+ scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
136
+ }
137
+ : {}),`]:[],...d(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
138
+ ${r.join(`
139
+ `)}
140
+ `:""},W=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
141
+ // The schema's jurisdiction pins the auth object like every other DO.
142
+ jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",_=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,$=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
143
+ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${_(t.shardMode)}],`).join(`
144
+ `)}
145
+ ]);
146
+
147
+ options.listSchemaTables = () => [...tableSharding.keys()];
148
+ options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...d(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
149
+
150
+ if (shardRegistry) {
151
+ options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}namespace: shardRegistry }) });
152
+ }`]:[]],H=e=>[...$(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
153
+ options.schedulerDO = this.schedulerDeclaration.namespace(env);
154
+ }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
155
+ const source = workflowEnv as Record<string, unknown>;
156
+ const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
157
+ const apiToken = source["CLOUDFLARE_API_TOKEN"];
158
+
159
+ return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
160
+ ? createWorkflowsRestClient({ accountId, apiToken })
161
+ : undefined;
162
+ };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
163
+ const database = this.globalDeclaration.d1(env);
164
+
165
+ if (database) {
166
+ options.globalIntrospector = buildGlobalIntrospector(database);
167
+ // \`importGlobals\` wires the admin bulk-import endpoint's global
168
+ // plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
169
+ // land here, and without it they are reported, not written.
170
+ options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
171
+ // The read/replay half of the same admin plane. Each one is the
172
+ // only reason its endpoint can see the global storage plane at
173
+ // all, and every one of them fails SILENTLY when unset — export
174
+ // and \`lunora backup create\` answer 200 having written only
175
+ // shard-local rows (an export→import round trip then restores
176
+ // cleanly minus every global row), CDC sync answers with only
177
+ // shard changes, and point-in-time apply reports
178
+ // \`globalApplied: 0\`. Nothing here is project-specific either.
179
+ options.exportGlobals = buildGlobalExporter(database);
180
+ options.syncGlobals = buildGlobalCdcSync(database);
181
+ options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
182
+ }
183
+ }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
184
+ Object.assign(options, this.buildStorageAdmin(env));
185
+ options.storage = (rawEnv: unknown, origin?: string) => this.resolveStorage(rawEnv as Env, origin);
186
+ }`]:[],...e.hasKvIntrospector?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasVectors===!0?[` if (this.shardExtras.vectors) {
187
+ options.vectorIntrospector = createVectorAdminIntrospector({
188
+ indexes: this.shardExtras.vectors(env as unknown as Record<string, unknown>),
189
+ registry: LUNORA_VECTOR_INDEXES,
190
+ });
191
+ } else {
192
+ // Emitted only when the schema declares an index, so reaching here
193
+ // means the app declared one and never bound it. The studio's
194
+ // Vectors tab is on (its flag is the same index count) and every
195
+ // request to it would answer VECTORS_NOT_CONFIGURED, while
196
+ // \`ctx.vectors\` is the throwing stub — so this is already broken,
197
+ // just later and less legibly. Same shape as \`.auth()\`'s guards.
198
+ throw new Error(
199
+ ".vectors(): the schema declares vector index(es) but no binding map was chained. Pass \`.vectors((env) => ({ <indexName>: env.<BINDING> }))\` so \`ctx.vectors\` resolves and the studio's Vectors tab can list them.",
200
+ );
201
+ }`]:[],...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
202
+ // \`this.authDeclaration.namespace\` again below would be optional all over again.
203
+ const authDeclaration = this.authDeclaration;
204
+ const authNamespace = authDeclaration?.namespace;
205
+ const authD1 = authDeclaration?.d1;
206
+
207
+ if (authDeclaration && authNamespace) {
208
+ // DO-backed mode. The auth tables live inside the object and DO storage is
209
+ // unreachable from here, so better-auth runs in there and this worker talks
210
+ // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
211
+ // than more emitted code: request-path logic in generated output can only be
212
+ // typechecked, never unit-tested.
213
+ const authWiring = createDoAuthWiring({
214
+ internalSecret: authDeclaration.internalSecret?.(env),${W(e)}
215
+ namespace: authNamespace(env),
216
+ objectName: authDeclaration.objectName?.(env),
217
+ });
218
+
219
+ options.authHandler = authWiring.authHandler;
220
+ options.resolveIdentity = authWiring.resolveIdentity;
221
+ // The audit log lives in the object like every other auth table, so the feed
222
+ // reads through it rather than querying D1.
223
+ options.authAuditReader = authWiring.auditReader;
224
+ // Set only once auth is pinned to a jurisdiction: copies the users left in the
225
+ // un-pinned object across (\`__lunora_admin__:copyAuthToJurisdiction\`).
226
+ options.authJurisdictionMove = authWiring.jurisdictionMove;
227
+ // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
228
+ // from the worker, which DO storage does not allow. The studio's auth pages
229
+ // therefore report "not configured" in this mode rather than silently
230
+ // returning empty data.
231
+ } else if (authDeclaration && authD1) {
232
+ options.authHandler = (request) => {
233
+ const auth = getAuth();
234
+
235
+ return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
236
+ };
237
+ options.resolveIdentity = async (request) => {
238
+ const auth = getAuth();
239
+
240
+ if (!auth) {
241
+ return null;
242
+ }
243
+
244
+ const session = await auth.api.getSession({ headers: (request as Request).headers });
245
+
246
+ if (!session?.user?.id) {
247
+ return null;
248
+ }
249
+
250
+ // \`role\` rides along so \`rls(policies, { roles })\` and \`auth.can(...)\`
251
+ // work on this wiring without a hand-written resolver. better-auth's
252
+ // \`admin()\` plugin owns that column (comma-joined for multiple roles)
253
+ // and only an administrator can write it; it is absent when the plugin
254
+ // is off, which reads as no roles.
255
+ //
256
+ // \`expiresAtMs\` is the socket credential expiry the runtime forwards
257
+ // as \`x-lunora-identity-exp\`. Without it the DO's expiry check never
258
+ // fires, so a signed-out, banned or lapsed user keeps streaming their
259
+ // RLS-scoped rows over an already-open WebSocket while every HTTP call
260
+ // is anonymous. better-auth hands back a \`Date\`; anything else means
261
+ // the adapter did not hydrate it, and omitting beats guessing.
262
+ const expiresAt = session.session.expiresAt;
263
+ // \`email\` and \`name\` are the claims \`ctx.auth.getIdentity()\` is
264
+ // documented to carry ("email, name, roles, custom claims"). Without
265
+ // them the documented \`me\` query — \`identity?.email\` — resolves
266
+ // \`undefined\` on the built-in wiring. Empty strings are dropped so an
267
+ // absent claim reads as absent rather than as "".
268
+ const user = session.user as { email?: unknown; name?: unknown; role?: unknown };
269
+
270
+ return {
271
+ ...(typeof user.email === "string" && user.email.length > 0 ? { email: user.email } : {}),
272
+ ...(expiresAt instanceof Date ? { expiresAtMs: expiresAt.getTime() } : {}),
273
+ ...(typeof user.name === "string" && user.name.length > 0 ? { name: user.name } : {}),
274
+ role: user.role,
275
+ userId: session.user.id,
276
+ };
277
+ };
278
+ const authInstance = getAuth();
279
+
280
+ options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
281
+ options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
282
+ }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
283
+ const accessResolver = createAccessResolver(this.accessSelector(env));
284
+ const fallback = options.resolveIdentity;
285
+
286
+ options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
287
+ }`:` if (this.accessSelector) {
288
+ options.resolveIdentity = createAccessResolver(this.accessSelector(env));
289
+ }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
290
+ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
291
+ `)}
292
+ };`]:[]],U=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],F=e=>e.hasScheduler?`
293
+ /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
294
+ private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
295
+ const namespace = this.schedulerDeclaration?.namespace(env);
296
+
297
+ return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
298
+ }
299
+ `:"",M=e=>e?`
300
+ /**
301
+ * One bucket's \`Storage\`, signing under the name it is registered as.
302
+ *
303
+ * \`bucketName\` is bound into every signed URL's HMAC canonical, so a bucket
304
+ * that signs as the default's name lets a URL minted for one bucket verify
305
+ * against another sharing the secret — and multi-bucket verification fails
306
+ * outright. Hence \`"default"\` for the bare \`ctx.storage\` bucket and the
307
+ * \`buckets\` key for every other.
308
+ *
309
+ * \`origin\` is the request's own origin, the base when no \`publicBaseUrl\` is
310
+ * declared.
311
+ */
312
+ private makeStorage(env: Env, declaration: StorageDeclaration<Env>, bucket: R2BucketLike, bucketName: string, origin?: string): Storage {
313
+ return createStorage({
314
+ bucket,
315
+ bucketName,
316
+ publicBaseUrl: declaration.publicBaseUrl?.(env) ?? origin,
317
+ s3: declaration.s3?.(env),
318
+ signingSecret: declaration.signingSecret?.(env),
319
+ });
320
+ }
321
+
322
+ /** Resolve the storage capability (single or multi-bucket) for the DO side. */
323
+ private resolveStorage(env: Env, origin?: string): Storage | undefined {
324
+ const declaration = this.storageDeclaration;
325
+
326
+ if (!declaration) {
327
+ return undefined;
328
+ }
329
+
330
+ const defaultBucket = declaration.bucket(env);
331
+
332
+ if (!defaultBucket) {
333
+ return undefined;
334
+ }
335
+
336
+ const extraEntries = Object.entries(declaration.buckets ?? {})
337
+ .map(([name, selector]) => [name, selector(env)] as const)
338
+ .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
339
+
340
+ if (extraEntries.length === 0) {
341
+ return this.makeStorage(env, declaration, defaultBucket, "default", origin);
342
+ }
343
+
344
+ const map: Record<string, Storage> = { default: this.makeStorage(env, declaration, defaultBucket, "default", origin) };
345
+
346
+ for (const [name, bucket] of extraEntries) {
347
+ map[name] = this.makeStorage(env, declaration, bucket, name, origin);
348
+ }
349
+
350
+ return createBucketStorage(map, { default: "default" });
351
+ }
352
+
353
+ /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
354
+ private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
355
+ const declaration = this.storageDeclaration;
356
+
357
+ if (!declaration) {
358
+ return {};
359
+ }
360
+
361
+ const defaultBucket = declaration.bucket(env);
362
+
363
+ if (!defaultBucket) {
364
+ return {};
365
+ }
366
+
367
+ const bindings: Record<string, R2BucketLike> = { default: defaultBucket };
368
+
369
+ for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
370
+ const bucket = selector(env);
371
+
372
+ if (bucket) {
373
+ bindings[name] = bucket;
374
+ }
375
+ }
376
+
377
+ // \`Object.hasOwn\`, not a bare lookup: \`bindings\` is a plain object, so a
378
+ // prototype key (\`?bucket=constructor\`, \`__proto__\`, \`toString\`) resolves
379
+ // to an inherited Object.prototype member instead of the default bucket.
380
+ //
381
+ // \`origin\` is the base when no \`publicBaseUrl\` is declared: the origin the
382
+ // admin request reached the worker on, which the signed-URL route hands
383
+ // over and then verifies. Only the secret gates signing.
384
+ const pick = (name?: string, origin?: string): Storage => {
385
+ const wanted = name !== undefined && name !== "" ? name : "default";
386
+ const bucketName = Object.hasOwn(bindings, wanted) ? wanted : "default";
387
+
388
+ return this.makeStorage(env, declaration, bindings[bucketName] ?? defaultBucket, bucketName, origin);
389
+ };
390
+ const hasSigning = Boolean(declaration.signingSecret?.(env));
391
+
392
+ return {
393
+ storageBuckets: Object.keys(bindings),
394
+ storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
395
+ storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
396
+ storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
397
+ storageSignedUrl: hasSigning
398
+ ? (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT"; origin?: string }) =>
399
+ pick(opts?.bucket, opts?.origin).getSignedUrl(key, { contentType: opts?.contentType, expiresInSeconds: opts?.expiresInSeconds, method: opts?.method })
400
+ : undefined,
401
+ storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
402
+ };
403
+ }
404
+ `:"",Q=e=>e?`
405
+ /**
406
+ * 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\`).
407
+ *
408
+ * Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
409
+ * last-known write, when supplied) so reads observe it — read-your-writes
410
+ * across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
411
+ * produced by each write so the caller (the generated DO) can record it on the
412
+ * dispatch's bookmark sink and echo \`x-d1-bookmark\` on the response.
413
+ *
414
+ * Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
415
+ * (storage-object resets, isolate memory evictions, dropped connections) does
416
+ * not surface on every \`.global()\` read. Only statements that are provably
417
+ * read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
418
+ * optimistic-concurrency check issues through \`all\` — pass straight through,
419
+ * because a transient error never says whether the write applied.
420
+ *
421
+ * Every read and write also records D1's own \`meta\` accounting (\`rows_read\` /
422
+ * \`rows_written\` / \`duration\`) against a low-cardinality \`verb:table\` tag.
423
+ * Rows READ is rows SCANNED, not returned, so this is the number that explains
424
+ * a D1 bill and the one a missing index inflates without anything being
425
+ * deployed; the dashboard's own metric is per-database and can't name the query.
426
+ * The emit is best-effort — instrumentation must never fail a served query.
427
+ */
428
+ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
429
+ // Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
430
+ // below so a hand-rolled test double that omits it keeps working via
431
+ // \`prepare()\` straight on the raw binding — today's behaviour. With no
432
+ // inbound bookmark, \`"first-unconstrained"\` is the documented no-op
433
+ // equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
434
+ const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
435
+ const target = session ?? database;
436
+ const batchFn = target.batch;
437
+ const meter = (sql: string, meta: Record<string, unknown> | undefined): void => {
438
+ try {
439
+ emitD1QueryCost(sql, meta);
440
+ } catch {
441
+ // Best-effort: never let cost accounting fail the query it measures.
442
+ }
443
+ };
444
+
445
+ return retryingExec({
446
+ all: async (sql, parameters) => {
447
+ const result = await target
448
+ .prepare(sql)
449
+ .bind(...parameters)
450
+ .all<Record<string, unknown>>();
451
+
452
+ // \`all\` carries writes, not just reads: D1 runs
453
+ // \`UPDATE/DELETE … RETURNING\` through it exactly like \`.run()\`, and
454
+ // that is precisely what \`@lunora/sql-store\` issues for its
455
+ // optimistic-concurrency compare-and-swap — so \`patch\`, \`replace\`
456
+ // and \`delete\` all land here and nowhere else. Without this the
457
+ // bookmark those writes produced was never reported, and the next
458
+ // read could pin a replica that has not seen them: read-your-writes
459
+ // lost on the exact path the bookmark exists for. Reporting it after
460
+ // a plain \`SELECT\` too is harmless and correct — the session's
461
+ // bookmark only ever moves forward, and the sink takes the last
462
+ // value.
463
+ onBookmark?.(session?.getBookmark() ?? undefined);
464
+ meter(sql, result.meta);
465
+
466
+ return result.results;
467
+ },
468
+ // D1's own \`batch\` runs the whole array as one atomic SQLite
469
+ // transaction. Guarded because \`batch\` is optional in the structural
470
+ // type (test doubles may omit it) — real D1 always has it; a double
471
+ // without it still works through the store's sequential fallback.
472
+ // Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
473
+ // directly so TS can narrow the captured \`batchFn\` across the closure
474
+ // boundary (a property-access narrowing like
475
+ // \`hasBatch = typeof target.batch === "function"\` does not survive
476
+ // into a nested arrow function); \`.call\` still binds \`this\` to
477
+ // \`target\`, so the real workerd \`D1Database\`/session doesn't throw
478
+ // \`TypeError: Illegal invocation\` the way a detached
479
+ // \`const fn = target.batch; fn(...)\` capture would.
480
+ batch: batchFn
481
+ ? async (statements) => {
482
+ const results = await batchFn.call(
483
+ target,
484
+ statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
485
+ );
486
+
487
+ // Meter each leg. D1 returns one result per statement, in
488
+ // order, each with its own \`meta\` — and a batch is where the
489
+ // expensive writes live (\`@lunora/sql-store\` runs its
490
+ // backfills through here), so discarding it left exactly the
491
+ // statements worth costing unaccounted. Guarded on the array
492
+ // because \`batch\` is optional in the structural type and a
493
+ // test double may resolve to anything.
494
+ if (Array.isArray(results)) {
495
+ for (const [index, statement] of statements.entries()) {
496
+ meter(statement.sql, (results[index] as { meta?: Record<string, unknown> } | undefined)?.meta);
497
+ }
498
+ }
499
+
500
+ onBookmark?.(session?.getBookmark() ?? undefined);
501
+ }
502
+ : undefined,
503
+ run: async (sql, parameters) => {
504
+ const result = await target
505
+ .prepare(sql)
506
+ .bind(...parameters)
507
+ .run();
508
+
509
+ meter(sql, result.meta);
510
+ onBookmark?.(session?.getBookmark() ?? undefined);
511
+ },
512
+ });
513
+ };
514
+
515
+ /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
516
+ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
517
+ const exec = buildExec(database);
518
+
519
+ return {
520
+ facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
521
+ listTables: () => listGlobalTables(exec, schema as never),
522
+ readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
523
+ };
524
+ };
525
+
526
+ /**
527
+ * \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
528
+ * through the same D1 writer \`.global()\` reads/writes already use, via
529
+ * \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
530
+ * twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
531
+ * shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
532
+ *
533
+ * Passes each row's own \`line\` through rather than dropping it: the caller
534
+ * (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
535
+ * physical source line, and global rows are typically interspersed with
536
+ * shard-local ones it filtered out before calling here — a single
537
+ * \`startLine\` plus positional counting would mis-attribute every row after
538
+ * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
539
+ * falls back to the position-derived count otherwise.
540
+ */
541
+ const buildGlobalImporter =
542
+ (database: D1DatabaseLike, cdc: boolean) =>
543
+ (request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
544
+ const exec = buildExec(database);
545
+ // Same reason the PITR applier carries it: a bulk import that skips the
546
+ // changelog restores rows no downstream consumer is ever told about.
547
+ const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
548
+
549
+ return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
550
+ exec,
551
+ rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
552
+ startLine: request.startLine,
553
+ });
554
+ };
555
+
556
+ /**
557
+ * \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
558
+ * which drains the same stream): the read twin of {@link buildGlobalImporter},
559
+ * over the same D1 handle. \`@lunora/d1\`'s \`exportGlobalRows\` keyset-paginates
560
+ * each table and provisions the schema's global tables first, so a table that
561
+ * was never written exports as empty instead of throwing \`no such table\`.
562
+ *
563
+ * \`tables\` is forwarded as-is: the runtime passes an empty array for "every
564
+ * table" (its \`tables === undefined\` case), which is exactly what
565
+ * \`selectGlobalTables\` reads an empty allowlist as.
566
+ */
567
+ const buildGlobalExporter =
568
+ (database: D1DatabaseLike) =>
569
+ (request: { tables: ReadonlyArray<string> }) =>
570
+ exportGlobalRows(buildExec(database), schema as unknown as D1CtxDbOptions["schema"], { tables: request.tables });
571
+
572
+ /**
573
+ * \`syncGlobals\` for the admin CDC sync + warehouse-connector endpoints: pages
574
+ * the global \`__cdc_log\` past \`sinceSeq\`, the global-plane twin of the shard's
575
+ * \`runShardCdcSync\`.
576
+ *
577
+ * Probes \`sqlite_master\` first, exactly as the shard twin does. The changelog
578
+ * table is only created when the global writer runs with CDC enabled, so on
579
+ * every other app a straight read would throw \`no such table: __cdc_log\` and
580
+ * turn "nothing has changed yet" into a 500. Absent log ⇒ an empty page that
581
+ * leaves the caller's cursor where it was.
582
+ */
583
+ const buildGlobalCdcSync =
584
+ (database: D1DatabaseLike) =>
585
+ async (request: { limit?: number; sinceSeq: number }): Promise<{ changes: ReadonlyArray<Record<string, unknown>>; cursor: number }> => {
586
+ const exec = buildExec(database);
587
+ const present = await exec.all(\`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\`, ["__cdc_log"]);
588
+
589
+ if (present.length === 0) {
590
+ return { changes: [], cursor: request.sinceSeq };
591
+ }
592
+
593
+ const page = await readD1CdcChanges(exec, { limit: request.limit, sinceSeq: request.sinceSeq });
594
+
595
+ // \`as unknown as\`, because \`CdcChange\` is an interface and interfaces carry
596
+ // no implicit index signature — the shapes are otherwise identical.
597
+ return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
598
+ };
599
+
600
+ /**
601
+ * \`applyGlobals\` for the admin point-in-time-recovery apply endpoint: replays a
602
+ * batch of global CDC changes through the same D1 writer \`.global()\` writes go
603
+ * through, and reports how many were replayed.
604
+ *
605
+ * \`applyCdcChanges\` is order-sensitive and idempotent per row (insert, falling
606
+ * back to replace on conflict), so the batch is handed over untouched — the
607
+ * caller already emits it in commit order. The changes arrive as plain parsed
608
+ * JSON off the wire, hence the cast to the replayer's own change shape.
609
+ *
610
+ * The writer carries the app's own \`cdc\` setting, so a replay APPENDS to the
611
+ * global changelog like any other write. Built without it the restored rows
612
+ * reach the tables and nothing else: a warehouse connector's cursor walks past a
613
+ * range that has no entries and its mirror silently diverges from the database,
614
+ * with nothing on either side able to notice — and every live \`.global()\` shape
615
+ * misses the restore until the next unconditional resync.
616
+ */
617
+ const buildGlobalCdcApplier =
618
+ (database: D1DatabaseLike, cdc: boolean) =>
619
+ async (request: { changes: ReadonlyArray<Record<string, unknown>> }): Promise<number> => {
620
+ const writer = createD1CtxDb({ cdc, exec: buildExec(database), schema: schema as unknown as D1CtxDbOptions["schema"] });
621
+
622
+ await applyCdcChanges(writer, request.changes as unknown as Parameters<typeof applyCdcChanges>[1]);
623
+
624
+ return request.changes.length;
625
+ };
626
+ `:"",K=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),Y=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:r}=t,a=q(t),n=H(t),i=r?` let auth: LunoraAuth | null = null;
627
+ let authInit: Promise<void> | null = null;
628
+ `:"",o=r?`
629
+ const initAuth = async (env: Env): Promise<void> => {
630
+ if (!this.authDeclaration) {
631
+ return;
632
+ }
633
+
634
+ const d1 = this.authDeclaration.d1;
635
+
636
+ // DO-backed mode builds no instance here: better-auth runs inside the
637
+ // object, which materialises its own schema (the Kysely migrator below is
638
+ // dialect-bound and cannot target DO storage).
639
+ if (!d1) {
640
+ return;
641
+ }
642
+
643
+ // Apply the better-auth schema lazily on first request (raw-D1 Kysely
644
+ // migrator). For production run the migrate command ahead of deploy.
645
+ // The migration instance takes the RAW binding: better-auth migrates
646
+ // only through Kysely and rejects the adapter the request instance uses.
647
+ //
648
+ // CONSTRUCTED BEFORE THE MIGRATION, ASSIGNED AFTER IT. Both halves matter:
649
+ // building it first gives \`ensureMigrated\`'s schema-check invalidation a
650
+ // registered check to invalidate, and assigning it only afterwards keeps a
651
+ // concurrent request from serving \`/api/auth/*\` against tables the
652
+ // migrator has not created yet. See \`emit-app.ts\` in @lunora/codegen for
653
+ // the full reasoning.
654
+ //
655
+ // On a first boot against an unmigrated database this means better-auth's
656
+ // eager schema check runs BEFORE the migration, so one
657
+ // "the auth tables do not match…" line on a cold start is expected.
658
+ const requestAuth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
659
+
660
+ await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
661
+
662
+ auth = requestAuth;
663
+ };
664
+
665
+ // Single-flighted on the PROMISE, not on \`auth\`. Every \`fetch\` awaits this
666
+ // and the body above is async, so a per-isolate cold start runs it once
667
+ // rather than once per concurrent request — better-auth's migrator emits a
668
+ // bare \`CREATE TABLE\` (no IF NOT EXISTS), so a second concurrent run on a
669
+ // fresh database fails with \`table user already exists\` and, because this is
670
+ // awaited ahead of the router, 500s every route. Evicted on failure so a
671
+ // transient error retries instead of being replayed forever.
672
+ const ensureAuth = (env: Env): Promise<void> =>
673
+ (authInit ??= initAuth(env).catch((error: unknown) => {
674
+ authInit = null;
675
+ throw error;
676
+ }));
677
+ `:"",l=r?`
678
+ await ensureAuth(env);`:"",s=r?"() => auth":"() => null",c=r?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",h=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
679
+ 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=t.hasFramework?"host?: FrameworkHostHandler":"",p=t.emailAgents??[],y=p.length>0?` composed.email = dispatchAgentEmail([
680
+ ${p.map(b=>` { agent: lunoraAgentDefinitions.${b.exportName}, binding: ${JSON.stringify(b.bindingName)} },`).join(`
681
+ `)}
682
+ ]);
683
+
684
+ `:"",f=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
685
+ public build(): ComposedApp {
686
+ return this.assemble();
687
+ }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${S}${L(t).join(`
688
+ `)}
689
+
690
+ /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
691
+ type Selector<Env, T> = (env: Env) => T | undefined;
692
+
693
+ /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
694
+ type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
695
+ ${t.jurisdiction?`
696
+ // Module scope, so every isolate loading this script (the worker and each Durable
697
+ // Object class it exports) knows the schema's jurisdiction before a request runs.
698
+ // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
699
+ declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
700
+ `:""}
701
+ ${a.join(`
702
+
703
+ `)}${a.length>0?`
704
+
705
+ `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
706
+ interface ComposedApp extends LunoraWorker {
707
+ /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
708
+ email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
709
+ /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
710
+ ShardDO: ReturnType<typeof createShardDO>;
711
+ }
712
+
713
+ /**
714
+ * Fluent worker-composition builder. Records each capability declaration, then
715
+ * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
716
+ * worker-side \`createWorker\` options — constructing the worker lazily on the
717
+ * first request so per-isolate singletons are built once.
718
+ */
719
+ class AppBuilder<Env extends object> {
720
+ ${j(t).join(`
721
+ `)}
722
+
723
+ private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
724
+
725
+ ${B(t).join(`
726
+
727
+ `)}
728
+
729
+ ${f}
730
+
731
+ /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
732
+ private assemble(${u}): ComposedApp {
733
+ const ShardDO = createShardDO({${P(t)}});
734
+
735
+ // Per-isolate singletons: the worker (and auth instance) are expensive to
736
+ // build, so the first request constructs them and every later request on
737
+ // the same isolate reuses them.
738
+ let worker: LunoraWorker | null = null;
739
+ ${i}${o}
740
+ ${h}
741
+
742
+ const composed: ComposedApp = {
743
+ ShardDO,
744
+ fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
745
+ const env = rawEnv as Env;${l}
746
+ worker ??= buildWorker(env);
747
+
748
+ return worker.fetch(request, rawEnv, context);
749
+ },
750
+ scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
751
+ worker ??= buildWorker(rawEnv as Env);
752
+
753
+ return worker.scheduled(controller, rawEnv, context);
754
+ },
755
+ serverQuery: (request, rawEnv, reference, args, options) => {
756
+ worker ??= buildWorker(rawEnv as Env);
757
+
758
+ return worker.serverQuery(request, rawEnv, reference, args, options);
759
+ },${t.hasQueue||t.hasFramework?`
760
+ queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
761
+ worker ??= buildWorker(rawEnv as Env);
762
+
763
+ return worker.queue?.(batch, rawEnv, context);
764
+ },`:""}
765
+ };
766
+
767
+ ${y} if (this.emailHandler) {
768
+ const handler = this.emailHandler;
769
+
770
+ composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
771
+ }
772
+ ${t.hasFramework?`
773
+ // A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
774
+ // does). Nothing in Lunora serves one, so when the app registered no handler
775
+ // of its own the host's is the only one there is — forward to it rather than
776
+ // dropping the entry.
777
+ if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
778
+ composed.email = (message, rawEnv, context) => {
779
+ worker ??= buildWorker(rawEnv as Env);
780
+
781
+ return worker.email?.(message, rawEnv, context) ?? Promise.resolve();
782
+ };
783
+ }
784
+ `:""}
785
+ return composed;
786
+ }
787
+ ${F(t)}${M(t.hasStorage)}
788
+ /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
789
+ private buildWorkerOptions(env: Env, ${c}): WorkerOptions {
790
+ const options: WorkerOptions = {
791
+ ${U(t).join(`
792
+ `)}
793
+ };
794
+
795
+ if (this.adminToken) {
796
+ options.adminToken = this.adminToken(env);
797
+ }
798
+
799
+ ${n.join(`
800
+
801
+ `)}${n.length>0?`
802
+
803
+ `:""} for (const fn of this.extendFns) {
804
+ Object.assign(options, fn(env, { ...options }));
805
+ }
806
+
807
+ return options;
808
+ }
809
+ }
810
+ ${Q(t.hasGlobal)}
811
+ /**
812
+ * Shape of the project's root \`lunora.config.*\`.
813
+ *
814
+ * Declared HERE, not in a package, so the \`app\` hook is typed against THIS
815
+ * project's builder with no annotation to keep in step — and so the config file
816
+ * needs only a type-only import, which is erased. That matters: the hook is
817
+ * bundled into the worker, and a runtime import in that file ships with it.
818
+ */
819
+ interface LunoraConfig<Env extends object = object> {
820
+ /** Codegen's static advisor. \`minSeverity\` is the lowest level it reports and writes into \`_generated/shard.ts\`; an \`"error"\` is never dropped, so the gate that fails codegen stays on. A literal, for the same reason as \`target\`. */
821
+ advisor?: { minSeverity?: "error" | "info" | "warn" };
822
+ /** Receives this project's \`defineApp()\` builder and returns it — where a Vite-first app makes the builder calls its generated entry cannot derive. */
823
+ app?: (app: AppBuilder<Env>) => AppBuilder<Env>;
824
+ /** Opt into remote-binding dev without \`--remote\` or \`LUNORA_REMOTE\` on every run. A literal, for the same reason as \`target\`. */
825
+ remote?: boolean;
826
+ /** Deploy target id — \`lunora deploy\`/\`verify\` read it when no \`--target\` is passed. Must be a literal: \`runCodegen\` resolves it synchronously by PARSING this file, so a computed value is not seen — \`lunora verify\` reports \`platform_unreadable_target\` rather than defaulting in silence. */
827
+ target?: string;
828
+ }
829
+
830
+ /**
831
+ * Start composing the app. Chain the capability methods, then \`.build()\`.
832
+ *
833
+ * \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
834
+ * — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
835
+ * what any app with its own bindings declares — is NOT assignable to an index
836
+ * signature, so the stricter bound forced every real app to write
837
+ * \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
838
+ * through the selectors you pass it, so the looser bound costs nothing.
839
+ */
840
+ const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
841
+
842
+ export { AppBuilder, defineApp };
843
+ export type { ${K(t)} };
844
+ `};export{Y as emitApp};