@lunora/codegen 1.0.0-alpha.34 → 1.0.0-alpha.341

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 (124) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.mts +4336 -2185
  3. package/dist/index.d.ts +4336 -2185
  4. package/dist/index.mjs +1 -35
  5. package/dist/packem_shared/AGENTS_FILENAME-isdHqPIt.mjs +1 -0
  6. package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-mK4cZpcz.mjs +1 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs +1 -0
  10. package/dist/packem_shared/FLAGS_FILENAME-BQk3SX8D.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER-BXK9A_wP.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-CIAJQeKB.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-Cy9h3EVW.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-9to_l_Kh.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-l4HD4osw.mjs +3 -0
  16. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
  17. package/dist/packem_shared/QUEUES_FILENAME-Civ-7SiI.mjs +1 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DC18IFFl.mjs +31 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs +2 -0
  20. package/dist/packem_shared/SHAPES_FILENAME-DVJbfDZ8.mjs +1 -0
  21. package/dist/packem_shared/SchemaSnapshotParseError-H9eQX4ui.mjs +18 -0
  22. package/dist/packem_shared/WORKFLOWS_FILENAME-kXq07aGl.mjs +1 -0
  23. package/dist/packem_shared/attribution-CG8-kUcl.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-DWdj2jvW.mjs +3 -0
  25. package/dist/packem_shared/capabilitiesUsedBy-C-7D7vlH.mjs +1 -0
  26. package/dist/packem_shared/chain-74gjwZMP.mjs +1 -0
  27. package/dist/packem_shared/classify-procedure-call-BkaeM9Ej.mjs +1 -0
  28. package/dist/packem_shared/context-property-calls-dFjpeIlP.mjs +1 -0
  29. package/dist/packem_shared/context-root-CNR6TAsP.mjs +1 -0
  30. package/dist/packem_shared/createCodegenProject-R4so-yTU.mjs +1 -0
  31. package/dist/packem_shared/database-calls-UPlhi3Ks.mjs +1 -0
  32. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  33. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  34. package/dist/packem_shared/discoverAuthApiCalls-CScPrUD-.mjs +1 -0
  35. package/dist/packem_shared/discoverCrons-B1_NUt19.mjs +1 -0
  36. package/dist/packem_shared/discoverFunctions-DkPOc8b9.mjs +1 -0
  37. package/dist/packem_shared/discoverHttpRoutes-DCDgDIYv.mjs +1 -0
  38. package/dist/packem_shared/discoverHyperdriveCalls-CL-d0IVo.mjs +1 -0
  39. package/dist/packem_shared/discoverInserts-BcoTjXqI.mjs +1 -0
  40. package/dist/packem_shared/discoverMaskProcedures-Bw-BOIbA.mjs +1 -0
  41. package/dist/packem_shared/discoverMigrations-BWxx8Wv9.mjs +1 -0
  42. package/dist/packem_shared/discoverNondeterministicCalls-3INW8oqs.mjs +1 -0
  43. package/dist/packem_shared/discoverQueries-CxQRVuIV.mjs +1 -0
  44. package/dist/packem_shared/discoverR2sqlCalls-B4oeTYEM.mjs +1 -0
  45. package/dist/packem_shared/discoverRlsMetadata-D0B4nCmG.mjs +1 -0
  46. package/dist/packem_shared/discoverRlsProcedures-Cl6UKT7L.mjs +1 -0
  47. package/dist/packem_shared/discoverSandboxUsage--Z1vx7GM.mjs +1 -0
  48. package/dist/packem_shared/discoverSchema-Cwt-DQgh.mjs +1 -0
  49. package/dist/packem_shared/discoverStorageRulesMetadata-CitX6ziW.mjs +1 -0
  50. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  51. package/dist/packem_shared/emitAgents--VDKoet4.mjs +1 -0
  52. package/dist/packem_shared/emitApi-zynTVppI.mjs +147 -0
  53. package/dist/packem_shared/emitApp-BL16wvE9.mjs +986 -0
  54. package/dist/packem_shared/emitCrons-lc-hnJYn.mjs +96 -0
  55. package/dist/packem_shared/emitDataModel-CuFqq97x.mjs +114 -0
  56. package/dist/packem_shared/emitDrizzleSchema-bct1OuH5.mjs +15 -0
  57. package/dist/packem_shared/emitFunctions-D7mopPiT.mjs +506 -0
  58. package/dist/packem_shared/emitServer-CGUhLmlG.mjs +1 -0
  59. package/dist/packem_shared/emitShard-hzuG9fUo.mjs +1 -0
  60. package/dist/packem_shared/exported-procedure-chains-D1WlRfqJ.mjs +1 -0
  61. package/dist/packem_shared/fingerprintSchemaSources-BKXkgkj4.mjs +1 -0
  62. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
  63. package/dist/packem_shared/handler-reference-CClSR4bi.mjs +1 -0
  64. package/dist/packem_shared/index-CN8FVvr-.mjs +1 -0
  65. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  66. package/dist/packem_shared/isTestPath-C3QumE88.mjs +1 -0
  67. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  68. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  69. package/dist/packem_shared/loadProjectConfig-B7RmxIeD.mjs +1 -0
  70. package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
  71. package/dist/packem_shared/modules-l-Db0C4S.mjs +1 -0
  72. package/dist/packem_shared/parse-validator-iVTounLK.mjs +1 -0
  73. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  74. package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
  75. package/dist/packem_shared/qualifiers-Bl5fSmav.mjs +1 -0
  76. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  77. package/dist/packem_shared/readServiceBindings-BA49C6aN.mjs +1 -0
  78. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  79. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  80. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  81. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  82. package/dist/packem_shared/server-B6VhYK7m.mjs +368 -0
  83. package/dist/packem_shared/shard-CBG10DT5.mjs +1776 -0
  84. package/dist/packem_shared/shard-runtime-ByYXjCKY.mjs +333 -0
  85. package/dist/packem_shared/shared-8vTRkL2-.mjs +13 -0
  86. package/dist/packem_shared/unwrap-handler-return-CGdJGvGh.mjs +1 -0
  87. package/dist/sdk/index.d.mts +288 -0
  88. package/dist/sdk/index.d.ts +288 -0
  89. package/dist/sdk/index.mjs +372 -0
  90. package/package.json +21 -8
  91. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  92. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  93. package/dist/packem_shared/FLAGS_FILENAME-BjpS5w08.mjs +0 -139
  94. package/dist/packem_shared/GENERATED_HEADER-CLwPlCQe.mjs +0 -3
  95. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  96. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  97. package/dist/packem_shared/OPENRPC_VERSION-4YIeMkOI.mjs +0 -60
  98. package/dist/packem_shared/QUEUES_FILENAME-BF0iUmx7.mjs +0 -119
  99. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DnD-_HwA.mjs +0 -3425
  100. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  101. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  102. package/dist/packem_shared/WORKFLOWS_FILENAME-CCC_42o3.mjs +0 -124
  103. package/dist/packem_shared/buildOpenApiDocument-bp1pYSV6.mjs +0 -183
  104. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  105. package/dist/packem_shared/discoverAuthApiCalls-URDoTADN.mjs +0 -62
  106. package/dist/packem_shared/discoverCrons-DdZOeroL.mjs +0 -257
  107. package/dist/packem_shared/discoverFunctions-BJdF7lRs.mjs +0 -514
  108. package/dist/packem_shared/discoverHttpRoutes-CcwP-Rkr.mjs +0 -131
  109. package/dist/packem_shared/discoverInserts-BpFhM32L.mjs +0 -61
  110. package/dist/packem_shared/discoverMaskProcedures-DT-v8wvj.mjs +0 -273
  111. package/dist/packem_shared/discoverMigrations-cG1idBVM.mjs +0 -97
  112. package/dist/packem_shared/discoverNondeterministicCalls-CEOjmfk4.mjs +0 -122
  113. package/dist/packem_shared/discoverQueries-DeVBQVAG.mjs +0 -62
  114. package/dist/packem_shared/discoverR2sqlCalls-CWCAU-xJ.mjs +0 -80
  115. package/dist/packem_shared/discoverRlsMetadata-BL0oukaK.mjs +0 -280
  116. package/dist/packem_shared/discoverSchema-CeXJWVKV.mjs +0 -874
  117. package/dist/packem_shared/discoverStorageRulesMetadata-CFHByjIl.mjs +0 -97
  118. package/dist/packem_shared/emit-CBwEvCXQ.mjs +0 -3451
  119. package/dist/packem_shared/emitApp-nQ2oC-8G.mjs +0 -668
  120. package/dist/packem_shared/formatAdvisories-DLIqHq5l.mjs +0 -114
  121. package/dist/packem_shared/parse-validator-D6zI2i85.mjs +0 -134
  122. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  123. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  124. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -1,668 +0,0 @@
1
- import { A as APP_METHOD_CAPABILITIES, G as GENERATED_HEADER } from './emit-CBwEvCXQ.mjs';
2
-
3
- const hasFlagKey = (key) => `has${key.charAt(0).toUpperCase()}${key.slice(1)}`;
4
- const LONG_TAIL = APP_METHOD_CAPABILITIES.map(
5
- ({ appMethod, key }) => [hasFlagKey(key), appMethod.method, appMethod.configKey, appMethod.doc]
6
- );
7
- const hasAnyLongTail = (options) => LONG_TAIL.some(([flag]) => options[flag]);
8
- const buildIdentityImports = (identity) => identity ? [`import * as lunoraIdentityContract from "../identity.js";`] : [];
9
- const buildAccessImports = (hasAccess, hasAuth) => hasAccess ? [
10
- `import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";`,
11
- `import { createAccessResolver${hasAuth ? ", composeResolvers" : ""} } from "@lunora/cloudflare-access";`
12
- ] : [];
13
- const buildKvImports = (hasKv) => hasKv ? [`import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";`] : [];
14
- const buildImportLines = (options) => {
15
- const {
16
- hasAccess,
17
- hasAuth,
18
- hasFramework,
19
- hasGlobal,
20
- hasHyperdriveGlobal,
21
- hasKv,
22
- hasQueue,
23
- hasScheduler,
24
- hasStorage,
25
- hasWorkflow,
26
- useUmbrella,
27
- wantsOpenApi,
28
- wantsOpenRpc
29
- } = options;
30
- const runtimeModule = useUmbrella ? "lunorash/runtime" : "@lunora/runtime";
31
- const runtimeTypeImports = ["ExecutionContextLike", "LunoraWorker", "Route", "ScheduledControllerLike", "ShardNamespaceLike", "WorkerOptions"];
32
- if (hasGlobal) {
33
- runtimeTypeImports.push("GlobalIntrospector");
34
- }
35
- if (hasFramework) {
36
- runtimeTypeImports.push("FrameworkHostHandler");
37
- }
38
- const runtimeValueImports = [
39
- ...hasGlobal || hasHyperdriveGlobal ? ["createCrossShardRelationCapabilities"] : [],
40
- "createWorker",
41
- ...hasFramework ? ["withFrameworkWorker"] : []
42
- ].join(", ");
43
- return [
44
- ...hasAuth ? [
45
- `import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";`,
46
- `import { createAuth, createAuthAdmin, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";`
47
- ] : [],
48
- ...buildAccessImports(hasAccess, hasAuth),
49
- ...hasGlobal ? [
50
- `import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";`,
51
- `import { createD1CtxDb, facetGlobalColumn, listGlobalTables, readGlobalTablePage } from "@lunora/d1";`
52
- ] : [],
53
- ...hasHyperdriveGlobal ? [
54
- `import type { HyperdriveEngine } from "@lunora/hyperdrive/global";`,
55
- `import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";`,
56
- `import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";`
57
- ] : [],
58
- ...buildKvImports(hasKv),
59
- ...hasScheduler ? [`import type { DurableObjectNamespaceLike } from "@lunora/scheduler";`, `import { createScheduler } from "@lunora/scheduler";`] : [],
60
- ...hasStorage ? [`import type { R2BucketLike, Storage } from "@lunora/storage";`, `import { createBucketStorage, createStorage } from "@lunora/storage";`] : [],
61
- ...hasWorkflow ? [`import { createWorkflowsRestClient } from "@lunora/workflow";`] : [],
62
- `import type { ${[...runtimeTypeImports].toSorted((a, b) => a.localeCompare(b)).join(", ")} } from "${runtimeModule}";`,
63
- `import { ${runtimeValueImports} } from "${runtimeModule}";`,
64
- ``,
65
- ...buildIdentityImports(options.identity),
66
- ...hasGlobal || hasHyperdriveGlobal ? [`import schema from "../schema.js";`] : [],
67
- `import { LUNORA_CRONS } from "./crons.js";`,
68
- `import { LUNORA_FUNCTIONS } from "./functions.js";`,
69
- ...hasQueue ? [
70
- `import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";`,
71
- `import { LUNORA_QUEUE_REGISTRY } from "./queues.js";`
72
- ] : [],
73
- ...wantsOpenApi ? [`import { openApiSpec } from "./openapi.js";`] : [],
74
- ...wantsOpenRpc ? [`import { openRpcSpec } from "./openrpc.js";`] : [],
75
- `import { createShardDO } from "./shard.js";`
76
- ];
77
- };
78
- const buildDeclarationBlocks = (options) => [
79
- ...options.hasStorage ? [
80
- `/** \`.storage(...)\` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs \`ctx.storage\` AND the studio file browser. */
81
- interface StorageDeclaration<Env> {
82
- /** The default R2 bucket binding (the bare \`ctx.storage\`). */
83
- bucket: Selector<Env, R2BucketLike>;
84
- /** Extra named buckets, reached via \`ctx.storage.bucket("name")\` and the studio's bucket picker. */
85
- buckets?: Record<string, Selector<Env, R2BucketLike>>;
86
- /** Public base URL signed/public object URLs resolve against. */
87
- publicBaseUrl?: Selector<Env, string>;
88
- /** HMAC secret for signed URLs. */
89
- signingSecret?: Selector<Env, string>;
90
- }`
91
- ] : [],
92
- ...options.hasScheduler ? [
93
- `/** \`.scheduler(...)\` declaration — the \`SchedulerDO\` namespace plus the worker origin its callbacks dispatch back to. Backs \`ctx.scheduler\` AND the studio's scheduled-jobs view. */
94
- interface SchedulerDeclaration<Env> {
95
- /** The \`SchedulerDO\` namespace binding (typically \`env.SCHEDULER\`). */
96
- namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;
97
- /** The worker origin the \`SchedulerDO\` dispatches HTTP job callbacks back to. */
98
- origin?: Selector<Env, string>;
99
- }`
100
- ] : [],
101
- ...options.hasGlobal ? [
102
- `/** \`.global(...)\` declaration — the D1 binding backing \`.global()\` tables. Backs cross-tenant \`ctx.db\` reads/writes AND the studio's global data browser. */
103
- interface GlobalDeclaration<Env> {
104
- /** The D1 binding (typically \`env.DB\`). */
105
- d1: Selector<Env, D1DatabaseLike>;
106
- /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */
107
- origin?: Selector<Env, string>;
108
- }`
109
- ] : [],
110
- ...options.hasHyperdriveGlobal ? [
111
- `/** \`.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. */
112
- interface HyperdriveGlobalDeclaration<Env> {
113
- /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */
114
- engine: HyperdriveEngine;
115
- /** Build the \`SqlExec\` from \`env\` — e.g. \`buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))\`. Cache the driver on the DO instance; rebuild lazily after hibernation. */
116
- exec: (env: Env) => SqlExec;
117
- /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */
118
- origin?: Selector<Env, string>;
119
- }`
120
- ] : [],
121
- ...options.hasAuth ? [
122
- `/** \`.auth(...)\` declaration — better-auth options plus the D1 binding its SQL adapter reads. The builder owns the lazy build + \`ensureMigrated\` dance and wires \`authHandler\` / \`resolveIdentity\` / \`authAdmin\`. */
123
- interface AuthDeclaration<Env> {
124
- /** The D1 binding the auth SQL adapter is wired over (via \`lunoraD1Adapter\`). */
125
- d1: Selector<Env, unknown>;
126
- /** Build the better-auth options from \`env\` (secret, plugins, email/password, …). */
127
- options: (env: Env) => LunoraAuthOptions;
128
- }`
129
- ] : []
130
- ];
131
- const buildFieldLines = (options) => [
132
- ...options.hasAccess ? [` private accessSelector?: Selector<Env, CreateAccessResolverOptions>;`] : [],
133
- ` private adminToken?: Selector<Env, string>;`,
134
- ...options.hasAuth ? [` private authDeclaration?: AuthDeclaration<Env>;`] : [],
135
- ` private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];`,
136
- ...options.hasGlobal ? [` private globalDeclaration?: GlobalDeclaration<Env>;`] : [],
137
- ...options.hasHyperdriveGlobal ? [` private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;`] : [],
138
- ` private readonly routeMap: Record<string, Route> = {};`,
139
- ...options.hasScheduler ? [` private schedulerDeclaration?: SchedulerDeclaration<Env>;`] : [],
140
- ...hasAnyLongTail(options) ? [` private readonly shardExtras: Partial<ShardConfig> = {};`] : [],
141
- ` private shardSelector?: Selector<Env, ShardNamespaceLike>;`,
142
- ...options.hasStorage ? [` private storageDeclaration?: StorageDeclaration<Env>;`] : []
143
- ];
144
- const buildLongTailMethods = (options) => LONG_TAIL.filter(([flag]) => options[flag]).map(
145
- ([, name, key, document_]) => ` /** ${document_} */
146
- public ${name}(factory: NonNullable<ShardConfig["${key}"]>): this {
147
- this.shardExtras.${key} = factory;
148
-
149
- return this;
150
- }`
151
- );
152
- const buildMethodBlocks = (options) => [
153
- ...options.hasAccess ? [
154
- ` /** Wire Cloudflare Access (Zero Trust) — verifies the \`Cf-Access-Jwt-Assertion\` JWT and feeds the identity into \`ctx.auth\` / RLS via \`resolveIdentity\`. When \`.auth(...)\` is also configured, Access is composed ahead of it (Access wins when its JWT is present; everyone else falls through to the app session). */
155
- public access(selector: Selector<Env, CreateAccessResolverOptions>): this {
156
- this.accessSelector = selector;
157
-
158
- return this;
159
- }`
160
- ] : [],
161
- ` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
162
- public admin(selector: Selector<Env, string>): this {
163
- this.adminToken = selector;
164
-
165
- return this;
166
- }`,
167
- ...options.hasAuth ? [
168
- ` /** Wire better-auth — the builder lazily builds the instance, runs \`ensureMigrated\`, and dispatches \`/api/auth/*\` inside the worker (instrumented for the auth-failure SLO). */
169
- public auth(declaration: AuthDeclaration<Env>): this {
170
- this.authDeclaration = declaration;
171
-
172
- return this;
173
- }`
174
- ] : [],
175
- ` /** 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. */
176
- public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {
177
- this.extendFns.push(fn);
178
-
179
- return this;
180
- }`,
181
- ...options.hasGlobal ? [
182
- ` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
183
- public global(declaration: GlobalDeclaration<Env>): this {
184
- this.globalDeclaration = declaration;
185
-
186
- return this;
187
- }`
188
- ] : [],
189
- ...options.hasHyperdriveGlobal ? [
190
- ` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
191
- public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
192
- this.hyperdriveGlobalDeclaration = declaration;
193
-
194
- return this;
195
- }`
196
- ] : [],
197
- ` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
198
- public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
199
- this.emailHandler = handler;
200
-
201
- return this;
202
- }`,
203
- ` /** 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. */
204
- public route(key: string, handler: Route): this {
205
- this.routeMap[key] = handler;
206
-
207
- return this;
208
- }`,
209
- ...options.hasScheduler ? [
210
- ` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
211
- public scheduler(declaration: SchedulerDeclaration<Env>): this {
212
- this.schedulerDeclaration = declaration;
213
-
214
- return this;
215
- }`
216
- ] : [],
217
- ` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
218
- public shard(selector: Selector<Env, ShardNamespaceLike>): this {
219
- this.shardSelector = selector;
220
-
221
- return this;
222
- }`,
223
- ...options.hasStorage ? [
224
- ` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
225
- public storage(declaration: StorageDeclaration<Env>): this {
226
- this.storageDeclaration = declaration;
227
-
228
- return this;
229
- }`
230
- ] : [],
231
- ...buildLongTailMethods(options)
232
- ];
233
- const buildShardFactoryBody = (options) => {
234
- const entries = [
235
- ...options.hasGlobal ? [
236
- ` ...(this.globalDeclaration
237
- ? {
238
- d1: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
239
- const env = rawEnv as Env;
240
- const database = this.globalDeclaration?.d1(env);
241
-
242
- if (!database) {
243
- return undefined;
244
- }
245
-
246
- const origin = this.globalDeclaration?.origin?.(env);
247
- const crossShard = origin
248
- ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
249
- : undefined;
250
-
251
- return createD1CtxDb({
252
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
253
- auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
254
- exec: buildExec(database),
255
- schema: schema as unknown as D1CtxDbOptions["schema"],
256
- });
257
- },
258
- }
259
- : {}),`
260
- ] : [],
261
- ...options.hasHyperdriveGlobal ? [
262
- ` ...(this.hyperdriveGlobalDeclaration
263
- ? {
264
- hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
265
- const env = rawEnv as Env;
266
- const exec = this.hyperdriveGlobalDeclaration?.exec(env) as SqlExec | undefined;
267
-
268
- if (!exec) {
269
- return undefined;
270
- }
271
-
272
- const origin = this.hyperdriveGlobalDeclaration?.origin?.(env);
273
- const crossShard = origin
274
- ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
275
- : undefined;
276
-
277
- return createHyperdriveGlobalCtxDb({
278
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
279
- auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
280
- engine: this.hyperdriveGlobalDeclaration?.engine as HyperdriveEngine,
281
- exec,
282
- schema: schema as unknown as SqlCtxDbOptions["schema"],
283
- });
284
- },
285
- }
286
- : {}),`
287
- ] : [],
288
- ...options.hasScheduler ? [
289
- ` ...(this.schedulerDeclaration
290
- ? {
291
- scheduler: (rawEnv: Record<string, unknown>) => {
292
- const env = rawEnv as Env;
293
- const namespace = this.schedulerDeclaration?.namespace(env);
294
- const origin = this.schedulerDeclaration?.origin?.(env);
295
-
296
- return namespace && origin ? createScheduler({${options.jurisdiction ? ` jurisdiction: ${JSON.stringify(options.jurisdiction)},` : ""} namespace, originUrl: origin }) : undefined;
297
- },
298
- }
299
- : {}),`
300
- ] : [],
301
- ...options.hasStorage ? [` ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),`] : [],
302
- ...hasAnyLongTail(options) ? [` ...this.shardExtras,`] : []
303
- ];
304
- return entries.length > 0 ? `
305
- ${entries.join("\n")}
306
- ` : "";
307
- };
308
- const buildWorkerOptionLines = (options) => [
309
- ...options.hasScheduler ? [
310
- ` if (this.schedulerDeclaration) {
311
- options.schedulerDO = this.schedulerDeclaration.namespace(env);
312
- }`
313
- ] : [],
314
- ...options.hasWorkflow ? [
315
- // Resolve the Workflows REST client from the request env so the studio's
316
- // \`/_lunora/admin/workflows*\` proxy can read instance/step state; returns
317
- // undefined (→ "not configured") until the CF account id + API token are set.
318
- ` options.workflowsClient = (workflowEnv) => {
319
- const source = workflowEnv as Record<string, unknown>;
320
- const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
321
- const apiToken = source["CLOUDFLARE_API_TOKEN"];
322
-
323
- return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
324
- ? createWorkflowsRestClient({ accountId, apiToken })
325
- : undefined;
326
- };`
327
- ] : [],
328
- ...options.hasGlobal ? [
329
- ` if (this.globalDeclaration) {
330
- const database = this.globalDeclaration.d1(env);
331
-
332
- if (database) {
333
- options.d1 = database;
334
- options.globalIntrospector = buildGlobalIntrospector(database);
335
- }
336
- }`
337
- ] : [],
338
- ...options.hasStorage ? [
339
- ` if (this.storageDeclaration) {
340
- Object.assign(options, this.buildStorageAdmin(env));
341
- }`
342
- ] : [],
343
- // The studio's KV browser is wired zero-config: `createKvIntrospectorFromEnv`
344
- // scans `env` for every bound Workers KV namespace, so each `kv_namespaces`
345
- // entry in wrangler.jsonc appears under its binding name (any name, any count)
346
- // with no manual `createKvIntrospector` call. A deployment with no KV binding
347
- // yields an empty namespace list rather than crashing.
348
- ...options.hasKv ? [` options.kvIntrospector = createKvIntrospectorFromEnv(env);`] : [],
349
- ...options.hasAuth ? [
350
- ` if (this.authDeclaration) {
351
- options.authHandler = (request) => {
352
- const auth = getAuth();
353
-
354
- return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
355
- };
356
- options.resolveIdentity = async (request) => {
357
- const auth = getAuth();
358
-
359
- if (!auth) {
360
- return null;
361
- }
362
-
363
- const session = await auth.api.getSession({ headers: (request as Request).headers });
364
-
365
- return session?.user?.id ? { userId: session.user.id } : null;
366
- };
367
- const authInstance = getAuth();
368
-
369
- options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
370
- }`
371
- ] : [],
372
- // Cloudflare Access — runs AFTER the auth block so it can compose ahead of
373
- // the better-auth resolver rather than clobber it. With `.auth()` present,
374
- // a request carrying a verified Access JWT is authenticated by Access and
375
- // everyone else falls through to the app session; without it, Access is the
376
- // sole resolver.
377
- ...options.hasAccess ? [
378
- options.hasAuth ? ` if (this.accessSelector) {
379
- const accessResolver = createAccessResolver(this.accessSelector(env));
380
- const fallback = options.resolveIdentity;
381
-
382
- options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
383
- }` : ` if (this.accessSelector) {
384
- options.resolveIdentity = createAccessResolver(this.accessSelector(env));
385
- }`
386
- ] : []
387
- ];
388
- const buildBaseWorkerOptions = (options) => [
389
- ` cronJobs: LUNORA_CRONS,`,
390
- ` functions: LUNORA_FUNCTIONS,`,
391
- // The declared `defineIdentity(...)` contract — wires the runtime trust
392
- // boundary so `wrapResolverWithContract` validates every resolved identity
393
- // against it before it becomes `ctx.auth`. Emitted only when the app declares
394
- // a contract, so apps without one keep unchanged output.
395
- ...options.identity ? [` identity: lunoraIdentityContract.${options.identity.exportName},`] : [],
396
- // Schema `.jurisdiction("…")` pins every DO the worker reaches to the
397
- // Cloudflare data-residency region. Emitted only when declared, so apps
398
- // without it keep the un-pinned global namespace (and unchanged output).
399
- ...options.jurisdiction ? [` jurisdiction: ${JSON.stringify(options.jurisdiction)},`] : [],
400
- ...options.wantsOpenApi ? [` openApiSpec,`] : [],
401
- ...options.wantsOpenRpc ? [` openRpcSpec,`] : [],
402
- // The push-consumer handler backing the worker's `queue(batch, …)` entry:
403
- // routes each delivered batch to its `defineQueue` handler. Built from
404
- // `@lunora/queue` here (keeping the runtime decoupled) and wired only when the
405
- // app declares push queues in `lunora/queues.ts`. In a dev environment (or with
406
- // `LUNORA_QUEUE_CAPTURE`), every consumed message is recorded into the studio's
407
- // Queues log via the root shard's `recordQueueMessage` admin RPC.
408
- ...options.hasQueue ? [
409
- ` queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike): Promise<void> =>`,
410
- ` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {`,
411
- ` capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)`,
412
- ` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${options.jurisdiction ? `, { jurisdiction: ${JSON.stringify(options.jurisdiction)} }` : ""})`,
413
- ` : undefined,`,
414
- ` env: queueEnv as Record<string, unknown>,`,
415
- ` }),`
416
- ] : [],
417
- ` routes: this.routeMap,`,
418
- ` shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),`
419
- ];
420
- const buildStorageHelpers = (hasStorage) => hasStorage ? `
421
- /** Resolve the storage capability (single or multi-bucket) for the DO side. */
422
- private resolveStorage(env: Env): Storage | undefined {
423
- const declaration = this.storageDeclaration;
424
-
425
- if (!declaration) {
426
- return undefined;
427
- }
428
-
429
- const defaultBucket = declaration.bucket(env);
430
-
431
- if (!defaultBucket) {
432
- return undefined;
433
- }
434
-
435
- const make = (bucket: R2BucketLike): Storage =>
436
- createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
437
- const extraEntries = Object.entries(declaration.buckets ?? {})
438
- .map(([name, selector]) => [name, selector(env)] as const)
439
- .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
440
-
441
- if (extraEntries.length === 0) {
442
- return make(defaultBucket);
443
- }
444
-
445
- const map: Record<string, Storage> = { default: make(defaultBucket) };
446
-
447
- for (const [name, bucket] of extraEntries) {
448
- map[name] = make(bucket);
449
- }
450
-
451
- return createBucketStorage(map, { default: "default" });
452
- }
453
-
454
- /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
455
- private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
456
- const declaration = this.storageDeclaration;
457
-
458
- if (!declaration) {
459
- return {};
460
- }
461
-
462
- const defaultBucket = declaration.bucket(env);
463
-
464
- if (!defaultBucket) {
465
- return {};
466
- }
467
-
468
- const make = (bucket: R2BucketLike): Storage =>
469
- createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
470
- const buckets: Record<string, Storage> = { default: make(defaultBucket) };
471
-
472
- for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
473
- const bucket = selector(env);
474
-
475
- if (bucket) {
476
- buckets[name] = make(bucket);
477
- }
478
- }
479
-
480
- const pick = (name?: string): Storage => buckets[name !== undefined && name !== "" ? name : "default"] ?? buckets.default;
481
- const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
482
-
483
- return {
484
- storageBuckets: Object.keys(buckets),
485
- storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
486
- storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
487
- storageSignedUrl: hasSigning
488
- ? (key: string, opts?: { bucket?: string; expiresInSeconds?: number }) => pick(opts?.bucket).getSignedUrl(key, { expiresInSeconds: opts?.expiresInSeconds })
489
- : undefined,
490
- storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string }) => pick(opts?.bucket).upload(key, body, opts),
491
- };
492
- }
493
- ` : "";
494
- const buildGlobalHelpers = (hasGlobal) => hasGlobal ? `
495
- /** Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`). */
496
- const buildExec = (database: D1DatabaseLike): D1Exec => ({
497
- all: async (sql, parameters) => {
498
- const result = await database
499
- .prepare(sql)
500
- .bind(...parameters)
501
- .all<Record<string, unknown>>();
502
-
503
- return result.results;
504
- },
505
- run: async (sql, parameters) => {
506
- await database
507
- .prepare(sql)
508
- .bind(...parameters)
509
- .run();
510
- },
511
- });
512
-
513
- /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
514
- const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
515
- const exec = buildExec(database);
516
-
517
- return {
518
- facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
519
- listTables: () => listGlobalTables(exec, schema as never),
520
- readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
521
- };
522
- };
523
- ` : "";
524
- const buildExportedTypes = (options) => [
525
- ...options.hasAuth ? ["AuthDeclaration"] : [],
526
- "ComposedApp",
527
- ...options.hasGlobal ? ["GlobalDeclaration"] : [],
528
- ...options.hasScheduler ? ["SchedulerDeclaration"] : [],
529
- "Selector",
530
- ...options.hasStorage ? ["StorageDeclaration"] : []
531
- ].toSorted((a, b) => a.localeCompare(b)).join(", ");
532
- const emitApp = (options) => {
533
- const { hasAuth } = options;
534
- const declarationBlocks = buildDeclarationBlocks(options);
535
- const workerOptionLines = buildWorkerOptionLines(options);
536
- const authState = hasAuth ? ` let auth: LunoraAuth | null = null;
537
- ` : "";
538
- const ensureAuthBlock = hasAuth ? `
539
- const ensureAuth = async (env: Env): Promise<void> => {
540
- if (!this.authDeclaration || auth) {
541
- return;
542
- }
543
-
544
- auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(this.authDeclaration.d1(env) as never) });
545
- // Apply the better-auth schema lazily on first request (raw-D1 Kysely
546
- // migrator). For production run the migrate command ahead of deploy.
547
- await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: this.authDeclaration.d1(env) as never }));
548
- };
549
- ` : "";
550
- const ensureAuthCall = hasAuth ? `
551
- await ensureAuth(env);` : "";
552
- const getAuthArgument = hasAuth ? `() => auth` : `() => null`;
553
- const getAuthParameter = hasAuth ? `getAuth: () => LunoraAuth | null` : `_getAuth: () => null`;
554
- const buildWorkerLine = options.hasFramework ? ` const buildWorker = (env: Env): LunoraWorker =>
555
- host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${getAuthArgument})) : createWorker(this.buildWorkerOptions(env, ${getAuthArgument}));` : ` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${getAuthArgument}));`;
556
- const assembleParameter = options.hasFramework ? `host?: FrameworkHostHandler` : ``;
557
- const buildTerminals = ` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
558
- public build(): ComposedApp {
559
- return this.assemble();
560
- }${options.hasFramework ? `
561
-
562
- /** 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\`). */
563
- public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {
564
- return this.assemble(host);
565
- }` : ``}`;
566
- return `${GENERATED_HEADER}${buildImportLines(options).join("\n")}
567
-
568
- /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
569
- type Selector<Env, T> = (env: Env) => T | undefined;
570
- ${hasAnyLongTail(options) ? `
571
- /** The generated \`createShardDO\` config — the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
572
- type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
573
- ` : ""}
574
- ${declarationBlocks.join("\n\n")}${declarationBlocks.length > 0 ? "\n\n" : ""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
575
- interface ComposedApp extends LunoraWorker {
576
- /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
577
- email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
578
- /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
579
- ShardDO: ReturnType<typeof createShardDO>;
580
- }
581
-
582
- /**
583
- * Fluent worker-composition builder. Records each capability declaration, then
584
- * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
585
- * worker-side \`createWorker\` options — constructing the worker lazily on the
586
- * first request so per-isolate singletons are built once.
587
- */
588
- class AppBuilder<Env extends Record<string, unknown>> {
589
- ${buildFieldLines(options).join("\n")}
590
-
591
- private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
592
-
593
- ${buildMethodBlocks(options).join("\n\n")}
594
-
595
- ${buildTerminals}
596
-
597
- /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
598
- private assemble(${assembleParameter}): ComposedApp {
599
- const ShardDO = createShardDO({${buildShardFactoryBody(options)}});
600
-
601
- // Per-isolate singletons: the worker (and auth instance) are expensive to
602
- // build, so the first request constructs them and every later request on
603
- // the same isolate reuses them.
604
- let worker: LunoraWorker | null = null;
605
- ${authState}${ensureAuthBlock}
606
- ${buildWorkerLine}
607
-
608
- const composed: ComposedApp = {
609
- ShardDO,
610
- fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
611
- const env = rawEnv as Env;${ensureAuthCall}
612
- worker ??= buildWorker(env);
613
-
614
- return worker.fetch(request, rawEnv, context);
615
- },
616
- scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
617
- worker ??= buildWorker(rawEnv as Env);
618
-
619
- return worker.scheduled(controller, rawEnv, context);
620
- },
621
- serverQuery: (request, rawEnv, reference, args, options) => {
622
- worker ??= buildWorker(rawEnv as Env);
623
-
624
- return worker.serverQuery(request, rawEnv, reference, args, options);
625
- },${options.hasQueue ? `
626
- queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
627
- worker ??= buildWorker(rawEnv as Env);
628
-
629
- return worker.queue?.(batch, rawEnv, context);
630
- },` : ""}
631
- };
632
-
633
- if (this.emailHandler) {
634
- const handler = this.emailHandler;
635
-
636
- composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
637
- }
638
-
639
- return composed;
640
- }
641
- ${buildStorageHelpers(options.hasStorage)}
642
- /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
643
- private buildWorkerOptions(env: Env, ${getAuthParameter}): WorkerOptions {
644
- const options: WorkerOptions = {
645
- ${buildBaseWorkerOptions(options).join("\n")}
646
- };
647
-
648
- if (this.adminToken) {
649
- options.adminToken = this.adminToken(env);
650
- }
651
-
652
- ${workerOptionLines.join("\n\n")}${workerOptionLines.length > 0 ? "\n\n" : ""} for (const fn of this.extendFns) {
653
- Object.assign(options, fn(env, { ...options }));
654
- }
655
-
656
- return options;
657
- }
658
- }
659
- ${buildGlobalHelpers(options.hasGlobal)}
660
- /** Start composing the app. Chain the capability methods, then \`.build()\`. */
661
- const defineApp = <Env extends Record<string, unknown>>(): AppBuilder<Env> => new AppBuilder<Env>();
662
-
663
- export { AppBuilder, defineApp };
664
- export type { ${buildExportedTypes(options)} };
665
- `;
666
- };
667
-
668
- export { emitApp };