@lunora/codegen 0.0.0 → 1.0.0-alpha.2

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 (34) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +117 -9
  3. package/__assets__/package-og.svg +14 -0
  4. package/dist/index.d.mts +1473 -0
  5. package/dist/index.d.ts +1473 -0
  6. package/dist/index.mjs +28 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-0K-pjNb8.mjs +224 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-54jWDxA9.mjs +22 -0
  9. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +61 -0
  10. package/dist/packem_shared/buildOpenApiDocument-yHVN66Xd.mjs +183 -0
  11. package/dist/packem_shared/buildOpenRpcDocument-BZGY1-jT.mjs +60 -0
  12. package/dist/packem_shared/buildSchemaSnapshot-DzLDbWk3.mjs +233 -0
  13. package/dist/packem_shared/createCodegenProject-DGJm0_Pk.mjs +895 -0
  14. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +13 -0
  15. package/dist/packem_shared/discoverAuthApiCalls-C35R6z0T.mjs +62 -0
  16. package/dist/packem_shared/discoverCrons-BL6iGuJ3.mjs +254 -0
  17. package/dist/packem_shared/discoverFunctions-DEgAcRuD.mjs +460 -0
  18. package/dist/packem_shared/discoverHttpRoutes-C978pBiG.mjs +131 -0
  19. package/dist/packem_shared/discoverInserts-CRQdXvHO.mjs +39 -0
  20. package/dist/packem_shared/discoverMaskProcedures-B64zA740.mjs +217 -0
  21. package/dist/packem_shared/discoverMigrations-Doj_-BAA.mjs +91 -0
  22. package/dist/packem_shared/discoverNondeterministicCalls-4KiPQxQU.mjs +122 -0
  23. package/dist/packem_shared/discoverQueries-BkIi0dBD.mjs +62 -0
  24. package/dist/packem_shared/discoverRlsMetadata-DpRB1HMe.mjs +280 -0
  25. package/dist/packem_shared/discoverSchema-BBulgGbH.mjs +542 -0
  26. package/dist/packem_shared/discoverStorageRulesMetadata-DAqJUxUv.mjs +97 -0
  27. package/dist/packem_shared/discoverWorkflows-DRDQdhfq.mjs +84 -0
  28. package/dist/packem_shared/emitApi-hRVC-kE7.mjs +2426 -0
  29. package/dist/packem_shared/emitApp-CzZ6GbrD.mjs +593 -0
  30. package/dist/packem_shared/lintSchema-DicbOHvH.mjs +68 -0
  31. package/dist/packem_shared/parse-validator-tuQtHrsr.mjs +132 -0
  32. package/dist/packem_shared/paths-BRd6JHuF.mjs +11 -0
  33. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +57 -0
  34. package/package.json +45 -17
@@ -0,0 +1,2426 @@
1
+ import { s as sanitizeNamespace } from './paths-BRd6JHuF.mjs';
2
+
3
+ const GENERATED_HEADER = "// GENERATED by @lunora/codegen — do not edit.\n// Run `lunora codegen` to regenerate.\n\n";
4
+ const baseSpecifiers = (useUmbrella = false) => useUmbrella ? {
5
+ client: "lunorash/client",
6
+ do: "lunorash/do",
7
+ server: "lunorash/server",
8
+ serverDataModel: "lunorash/server/data-model",
9
+ serverDrizzle: "lunorash/server/drizzle",
10
+ serverTypes: "lunorash/server/types"
11
+ } : {
12
+ client: "@lunora/client",
13
+ do: "@lunora/do",
14
+ server: "@lunora/server",
15
+ serverDataModel: "@lunora/server/data-model",
16
+ serverDrizzle: "@lunora/server/drizzle",
17
+ serverTypes: "@lunora/server/types"
18
+ };
19
+ const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/u;
20
+ const LITERAL_VALUE_RE = /^(?:"[^"\\]*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u;
21
+ const IMPORT_PATH_RE = /^[\w./-]+$/u;
22
+ const assertIdentifier = (value, context) => {
23
+ if (!IDENTIFIER_RE.test(value)) {
24
+ throw new Error(`@lunora/codegen: ${context} is not a valid JS identifier: ${JSON.stringify(value)}`);
25
+ }
26
+ };
27
+ const renderPropertyKey = (fieldName) => IDENTIFIER_RE.test(fieldName) ? fieldName : JSON.stringify(fieldName);
28
+ const SCALAR_TYPE_BY_KIND = {
29
+ any: "unknown",
30
+ bigint: "bigint",
31
+ boolean: "boolean",
32
+ bytes: "ArrayBuffer",
33
+ // Epoch-millisecond numbers; the distinction is semantic only.
34
+ date: "number",
35
+ // v.from() wraps an external Standard Schema validator whose output type is
36
+ // not statically recoverable at codegen time — emit `unknown` so the
37
+ // generated api types still compile without depending on the library.
38
+ from: "unknown",
39
+ null: "null",
40
+ number: "number",
41
+ // The key of a stored R2 object — a string; the distinction is semantic only.
42
+ storage: "string",
43
+ string: "string",
44
+ timestamp: "number"
45
+ };
46
+ const literalToType = (value) => {
47
+ if (value === void 0) {
48
+ return "unknown";
49
+ }
50
+ if (!LITERAL_VALUE_RE.test(value)) {
51
+ throw new Error(`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(value)}`);
52
+ }
53
+ return value;
54
+ };
55
+ const validatorToType = (validator) => {
56
+ const scalar = SCALAR_TYPE_BY_KIND[validator.kind];
57
+ if (scalar !== void 0) {
58
+ return scalar;
59
+ }
60
+ switch (validator.kind) {
61
+ case "array": {
62
+ return `Array<${validator.inner ? validatorToType(validator.inner) : "unknown"}>`;
63
+ }
64
+ case "id": {
65
+ const tableName = validator.tableName ?? "_unknown_";
66
+ assertIdentifier(tableName, "v.id() table name");
67
+ return `Id<"${tableName}">`;
68
+ }
69
+ case "literal": {
70
+ return literalToType(validator.literalValue);
71
+ }
72
+ case "object": {
73
+ if (!validator.shape) {
74
+ return "Record<string, unknown>";
75
+ }
76
+ const fields = Object.entries(validator.shape).map(([key, child]) => `${renderPropertyKey(key)}: ${validatorToType(child)}`).join("; ");
77
+ return `{ ${fields} }`;
78
+ }
79
+ case "optional": {
80
+ return `${validator.inner ? validatorToType(validator.inner) : "unknown"} | undefined`;
81
+ }
82
+ case "record": {
83
+ const key = validator.keyType ? validatorToType(validator.keyType) : "string";
84
+ const value = validator.valueType ? validatorToType(validator.valueType) : "unknown";
85
+ return `Record<${key}, ${value}>`;
86
+ }
87
+ case "union": {
88
+ return validator.members && validator.members.length > 0 ? validator.members.map((member) => validatorToType(member)).join(" | ") : "never";
89
+ }
90
+ default: {
91
+ return "unknown";
92
+ }
93
+ }
94
+ };
95
+ const renderArgsType = (args) => {
96
+ const entries = Object.entries(args);
97
+ if (entries.length === 0) {
98
+ return "{}";
99
+ }
100
+ return `{ ${entries.map(([key, validator]) => {
101
+ const propertyKey = renderPropertyKey(key);
102
+ if (validator.kind === "optional") {
103
+ const inner = validator.inner ? validatorToType(validator.inner) : "unknown";
104
+ return `${propertyKey}?: ${inner}`;
105
+ }
106
+ return `${propertyKey}: ${validatorToType(validator)}`;
107
+ }).join("; ")} }`;
108
+ };
109
+ const isOptionalOnInsert = (validator) => validator.kind === "optional" || Boolean(validator.column?.hasDefault);
110
+ const renderInsertInterface = (table) => {
111
+ assertIdentifier(table.name, "table name");
112
+ const fields = Object.entries(table.shape).map(([fieldName, validator]) => {
113
+ const inner = validator.kind === "optional" && validator.inner ? validator.inner : validator;
114
+ const type = validatorToType(inner);
115
+ const propertyKey = renderPropertyKey(fieldName);
116
+ return isOptionalOnInsert(validator) ? ` ${propertyKey}?: ${type};` : ` ${propertyKey}: ${type};`;
117
+ }).join("\n");
118
+ const body = fields ? `
119
+ ${fields}
120
+ ` : "";
121
+ return `export interface Insert_${table.name} {
122
+ _id?: Id<"${table.name}">;
123
+ _creationTime?: number;${body}}`;
124
+ };
125
+ const emitDataModel = (schema, useUmbrella = false) => {
126
+ const base = baseSpecifiers(useUmbrella);
127
+ for (const table of schema.tables) {
128
+ assertIdentifier(table.name, "table name");
129
+ }
130
+ const tableNames = schema.tables.map((table) => `"${table.name}"`).join(" | ") || "never";
131
+ const documents = schema.tables.map((table) => {
132
+ const fields = Object.entries(table.shape).map(([fieldName, validator]) => {
133
+ const propertyKey = renderPropertyKey(fieldName);
134
+ if (validator.kind === "optional") {
135
+ const inner = validator.inner ? validatorToType(validator.inner) : "unknown";
136
+ return ` ${propertyKey}?: ${inner};`;
137
+ }
138
+ return ` ${propertyKey}: ${validatorToType(validator)};`;
139
+ }).join("\n");
140
+ const body = fields ? `
141
+ ${fields}
142
+ ` : "";
143
+ return `export interface Doc_${table.name} {
144
+ _id: Id<"${table.name}">;
145
+ _creationTime: number;${body}}`;
146
+ }).join("\n\n");
147
+ const documentMap = schema.tables.map((table) => ` ${table.name}: Doc_${table.name};`).join("\n");
148
+ const indexNamesByTable = schema.tables.map((table) => {
149
+ const names = table.indexes.map((index) => JSON.stringify(index.name)).join(" | ");
150
+ return ` ${table.name}: ${names || "never"};`;
151
+ }).join("\n");
152
+ const searchIndexNamesByTable = schema.tables.map((table) => {
153
+ const names = table.shardMode === "global" ? "" : table.searchIndexes.map((index) => JSON.stringify(index.name)).join(" | ");
154
+ return ` ${table.name}: ${names || "never"};`;
155
+ }).join("\n");
156
+ const rankIndexNamesByTable = schema.tables.map((table) => {
157
+ const names = table.rankIndexes.map((index) => JSON.stringify(index.name)).join(" | ");
158
+ return ` ${table.name}: ${names || "never"};`;
159
+ }).join("\n");
160
+ const vectorIndexNames = schema.vectorIndexes.map((index) => JSON.stringify(index.name)).join(" | ") || "never";
161
+ const insertInterfaces = schema.tables.map((table) => renderInsertInterface(table)).join("\n\n");
162
+ const insertMap = schema.tables.map((table) => ` ${table.name}: Insert_${table.name};`).join("\n");
163
+ const relationsMap = schema.tables.map((table) => {
164
+ const entries = table.relations.map((relation) => {
165
+ assertIdentifier(relation.table, "relation target table");
166
+ return ` ${renderPropertyKey(relation.name)}: ${relation.kind === "one" ? "OneRelation" : "ManyRelation"}<"${relation.table}">;`;
167
+ }).join("\n");
168
+ return entries ? ` ${table.name}: {
169
+ ${entries}
170
+ };` : ` ${table.name}: {};`;
171
+ }).join("\n");
172
+ return `${GENERATED_HEADER}import type {
173
+ DatabaseReaderFacade as DatabaseReaderFacadeOf,
174
+ DatabaseWriterFacade as DatabaseWriterFacadeOf,
175
+ LoadWith as LoadWithOf,
176
+ TableReaderFacade as TableReaderFacadeOf,
177
+ TableWriterFacade as TableWriterFacadeOf,
178
+ WithArg as WithArgOf,
179
+ } from "${base.serverDataModel}";
180
+
181
+ export type {
182
+ AggregateOp,
183
+ GroupByEntry,
184
+ OrderBy,
185
+ QueryArgs,
186
+ QueryPage,
187
+ RankPage,
188
+ RankResult,
189
+ RestrictableQueryOptions,
190
+ RestrictableQueryOptionsOf,
191
+ SearchFilterBuilder,
192
+ SearchReader,
193
+ TableAggregateOptions,
194
+ TableAggregateOptionsOf,
195
+ TableGroupByOptions,
196
+ TableGroupByOptionsOf,
197
+ TableRankOptions,
198
+ TableRankPageOptions,
199
+ Where,
200
+ WhereOf,
201
+ WhereOperators,
202
+ } from "${base.serverDataModel}";
203
+
204
+ export type TableName = ${tableNames};
205
+
206
+ export type Id<TName extends string> = string & { readonly __table: TName };
207
+
208
+ ${documents}
209
+
210
+ export interface DataModel {
211
+ ${documentMap}
212
+ }
213
+
214
+ export type Doc<T extends keyof DataModel> = DataModel[T];
215
+
216
+ /**
217
+ * Per-table index name union. \`never\` for tables without secondary indexes.
218
+ * Used by \`TableReader.withIndex()\` to constrain callers to declared names.
219
+ */
220
+ export interface IndexNamesByTable {
221
+ ${indexNamesByTable}
222
+ }
223
+
224
+ export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
225
+
226
+ /** Per-table search-index name union. \`never\` for tables without searchIndex. */
227
+ export interface SearchIndexNamesByTable {
228
+ ${searchIndexNamesByTable}
229
+ }
230
+
231
+ export type SearchIndexName<T extends keyof DataModel> = SearchIndexNamesByTable[T];
232
+
233
+ /** Per-table rank-index name union. \`never\` for tables without a rankIndex. */
234
+ export interface RankIndexNamesByTable {
235
+ ${rankIndexNamesByTable}
236
+ }
237
+
238
+ export type RankIndexName<T extends keyof DataModel> = RankIndexNamesByTable[T];
239
+
240
+ /** Union of declared vector index names. \`never\` when none are declared. */
241
+ export type VectorIndexName = ${vectorIndexNames};
242
+
243
+ ${insertInterfaces}
244
+
245
+ /** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
246
+ export interface InsertModel {
247
+ ${insertMap}
248
+ }
249
+
250
+ export type Insert<T extends keyof DataModel> = InsertModel[T];
251
+
252
+ /**
253
+ * Phantom relation descriptors. They carry the relation kind and target table
254
+ * as type parameters only — there is no runtime value — so the \`with\` argument
255
+ * and its return type can be inferred from {@link Relations}.
256
+ */
257
+ export interface OneRelation<Target extends keyof DataModel> {
258
+ readonly __relationKind: "one";
259
+ readonly __target: Target;
260
+ }
261
+
262
+ export interface ManyRelation<Target extends keyof DataModel> {
263
+ readonly __relationKind: "many";
264
+ readonly __target: Target;
265
+ }
266
+
267
+ /** Per-table relation map keyed by accessor name. \`{}\` for tables with none. */
268
+ export interface Relations {
269
+ ${relationsMap}
270
+ }
271
+
272
+ /** The \`with\` argument for table \`T\` — see \`@lunora/server/data-model\`. */
273
+ export type WithArg<T extends keyof DataModel> = WithArgOf<DataModel, Relations, T>;
274
+
275
+ /** \`Doc<T>\` narrowed to exactly the relations requested in the with-arg \`W\`. */
276
+ export type LoadWith<T extends keyof DataModel, W> = LoadWithOf<DataModel, Relations, T, W>;
277
+
278
+ /** Read-only typed table accessor exposed on \`QueryCtx.db.<table>\`. */
279
+ export type TableReaderFacade<T extends keyof DataModel> = TableReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T>;
280
+
281
+ /** Read-write typed table accessor exposed on \`MutationCtx.db.<table>\` / \`ActionCtx.db.<table>\`. */
282
+ export type TableWriterFacade<T extends keyof DataModel> = TableWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T>;
283
+
284
+ /** Per-table read facade — \`ctx.db.<table>\` on a \`QueryCtx\`. */
285
+ export type DatabaseReaderFacade = DatabaseReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable>;
286
+
287
+ /** Per-table read-write facade — \`ctx.db.<table>\` on a \`MutationCtx\` / \`ActionCtx\`. */
288
+ export type DatabaseWriterFacade = DatabaseWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable>;
289
+
290
+ /** Insert builder returned by \`ctx.orm.insert(table)\`. */
291
+ export interface OrmInsertBuilder<T extends keyof DataModel> {
292
+ values: (values: Insert<T>) => Promise<Id<T>>;
293
+ }
294
+
295
+ /** Replace builder returned by \`ctx.orm.replace(table, id)\` — swaps the whole document. */
296
+ export interface OrmReplaceBuilder<T extends keyof DataModel> {
297
+ with: (values: Insert<T>) => Promise<void>;
298
+ }
299
+
300
+ /** Update builder returned by \`ctx.orm.update(table, id)\` — patches the named fields. */
301
+ export interface OrmUpdateBuilder<T extends keyof DataModel> {
302
+ set: (values: Partial<Insert<T>>) => Promise<void>;
303
+ }
304
+
305
+ /** Read-only ORM surface — \`ctx.orm\` on a \`QueryCtx\`. Mirrors \`ctx.db\` reads under a kitcn-style \`query\` namespace. */
306
+ export interface OrmReader {
307
+ query: DatabaseReaderFacade;
308
+ }
309
+
310
+ /** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
311
+ export interface OrmWriter extends OrmReader {
312
+ delete: <T extends keyof DataModel>(table: T, id: Id<T>) => Promise<void>;
313
+ insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
314
+ replace: <T extends keyof DataModel>(table: T, id: Id<T>) => OrmReplaceBuilder<T>;
315
+ update: <T extends keyof DataModel>(table: T, id: Id<T>) => OrmUpdateBuilder<T>;
316
+ }
317
+ `;
318
+ };
319
+ const GENERATED_IMPORT_RE = /import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu;
320
+ const GENERATED_PREFIX_RE = /^(?:\.\.?\/)*_generated\//u;
321
+ const relocateGeneratedImports = (returnType) => returnType.replaceAll(GENERATED_IMPORT_RE, (_match, spec) => {
322
+ const stripped = spec.replace(GENERATED_PREFIX_RE, "./");
323
+ return `import("${stripped}")`;
324
+ });
325
+ const referencedDataModelImports = (body) => ["Doc", "Id"].filter((name) => new RegExp(String.raw`\b${name}<`, "u").test(body));
326
+ const renderApiBody = (functions) => {
327
+ const namespaces = /* @__PURE__ */ new Map();
328
+ for (const definition of functions) {
329
+ const list = namespaces.get(definition.filePath) ?? [];
330
+ list.push(definition);
331
+ namespaces.set(definition.filePath, list);
332
+ }
333
+ const renderNamespace = ([file, list]) => {
334
+ const members = list.map((definition) => {
335
+ const argsType = renderArgsType(definition.args);
336
+ const returnType = relocateGeneratedImports(definition.returnType);
337
+ return ` ${definition.exportName}: FunctionReference<"${definition.kind}", ${argsType}, ${returnType}>;`;
338
+ }).join("\n");
339
+ return ` ${renderPropertyKey(sanitizeNamespace(file))}: {
340
+ ${members}
341
+ };`;
342
+ };
343
+ return [...namespaces.entries()].toSorted(([a], [b]) => a.localeCompare(b)).map((entry) => renderNamespace(entry)).join("\n");
344
+ };
345
+ const renderWorkflowsRef = (workflows) => {
346
+ if (workflows.length === 0) {
347
+ return { block: "", importLine: "" };
348
+ }
349
+ const sorted = [...workflows].toSorted((a, b) => a.exportName.localeCompare(b.exportName));
350
+ const refMembers = sorted.map((workflow) => ` ${workflow.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${workflow.exportName}>>;`).join("\n");
351
+ const objectMembers = sorted.map(
352
+ (workflow) => ` ${workflow.exportName}: { isLunoraWorkflow: true, binding: ${JSON.stringify(workflow.bindingName)}, name: ${JSON.stringify(workflow.exportName)} },`
353
+ ).join("\n");
354
+ const block = `
355
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
356
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;
357
+
358
+ /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
359
+ export interface WorkflowReference<Params = Record<string, unknown>> {
360
+ readonly isLunoraWorkflow: true;
361
+ readonly __params?: Params;
362
+ readonly binding: string;
363
+ readonly name: string;
364
+ }
365
+
366
+ /** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
367
+ export interface WorkflowsRef {
368
+ ${refMembers}
369
+ }
370
+
371
+ export const workflows: WorkflowsRef = {
372
+ ${objectMembers}
373
+ };
374
+ `;
375
+ return { block, importLine: `import type * as lunoraWorkflowDefinitions from "../workflows.js";
376
+ ` };
377
+ };
378
+ const emitApi = (functions, workflows = [], useUmbrella = false) => {
379
+ const base = baseSpecifiers(useUmbrella);
380
+ const publicFunctions = functions.filter((definition) => definition.visibility !== "internal");
381
+ const internalFunctions = functions.filter((definition) => definition.visibility === "internal");
382
+ const publicBody = renderApiBody(publicFunctions);
383
+ const internalBody = renderApiBody(internalFunctions);
384
+ const combinedBody = `${publicBody}
385
+ ${internalBody}`;
386
+ const dataModelImports = referencedDataModelImports(combinedBody);
387
+ const dataModelImportLine = dataModelImports.length > 0 ? `
388
+ import type { ${dataModelImports.join(", ")} } from "./dataModel.js";
389
+ ` : "";
390
+ const apiBlock = publicBody ? `
391
+ ${publicBody}
392
+ ` : "";
393
+ const internalBlock = internalBody ? `
394
+ ${internalBody}
395
+ ` : "";
396
+ const workflowsRef = renderWorkflowsRef(workflows);
397
+ return `${GENERATED_HEADER}import { anyApi } from "${base.serverTypes}";
398
+ import type { FunctionReference } from "${base.client}";
399
+ ${workflowsRef.importLine}${dataModelImportLine}
400
+ export interface ApiTypes {${apiBlock}}
401
+
402
+ export const api = anyApi as unknown as ApiTypes;
403
+
404
+ /** Internal functions — callable only server-side via \`ctx.run*\`, never from a client. */
405
+ export interface InternalApiTypes {${internalBlock}}
406
+
407
+ export const internal = anyApi as unknown as InternalApiTypes;
408
+ ${workflowsRef.block}`;
409
+ };
410
+ const emitSeed = (enabled) => {
411
+ if (!enabled) {
412
+ return "";
413
+ }
414
+ return `${GENERATED_HEADER}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
415
+ import type { SeedClient, SeedClientOptions } from "@lunora/seed";
416
+
417
+ import schema from "../schema.js";
418
+ import type { InsertModel } from "./dataModel.js";
419
+
420
+ /**
421
+ * Schema-aware seed client with this project's \`InsertModel\` and runtime schema
422
+ * pre-bound. Each table is a method; call it with a count, a range, explicit
423
+ * partial rows, or per-field overrides. Foreign keys connect to rows seeded
424
+ * earlier in the run, and FK-parent tables are seeded automatically.
425
+ * @example
426
+ * const seed = createSeedClient({ seed: 1 });
427
+ * const { users } = await seed.users(5);
428
+ * const { posts } = await seed.posts((x) => x([10, 20]));
429
+ */
430
+ export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
431
+ `;
432
+ };
433
+ const moduleAlias = (filePath, index) => `lunora_${sanitizeNamespace(filePath)}_${String(index)}`;
434
+ const CALL_REGISTERED_HELPER = `const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
435
+ const registered = LUNORA_FUNCTIONS[functionPath];
436
+
437
+ if (!registered) {
438
+ throw Object.assign(new Error(\`function not registered: \${functionPath}\`), {
439
+ name: "LunoraError",
440
+ code: "FUNCTION_NOT_FOUND",
441
+ status: 404,
442
+ });
443
+ }
444
+
445
+ return (await registered.handler(context, args ?? {})) as R;
446
+ };`;
447
+ const renderFunctionRegistry = (functions, migrations) => {
448
+ const aliasByPath = /* @__PURE__ */ new Map();
449
+ const registerPath = (filePath) => {
450
+ if (!aliasByPath.has(filePath)) {
451
+ aliasByPath.set(filePath, moduleAlias(filePath, aliasByPath.size));
452
+ }
453
+ };
454
+ for (const definition of functions) {
455
+ registerPath(definition.filePath);
456
+ }
457
+ for (const migration of migrations) {
458
+ registerPath(migration.filePath);
459
+ }
460
+ const importLines = [...aliasByPath.entries()].map(([filePath, alias]) => {
461
+ if (!IMPORT_PATH_RE.test(filePath)) {
462
+ throw new Error(`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(filePath)}`);
463
+ }
464
+ return `import * as ${alias} from "../${filePath}.js";`;
465
+ }).join("\n");
466
+ const dispatchEntries = functions.map(
467
+ (definition) => ` "${sanitizeNamespace(definition.filePath)}:${definition.exportName}": ${aliasByPath.get(definition.filePath) ?? ""}.${definition.exportName} as unknown as RegisteredLunoraFunction,`
468
+ ).join("\n");
469
+ const migrationEntries = migrations.map(
470
+ (migration) => ` ${JSON.stringify(migration.id)}: ${aliasByPath.get(migration.filePath) ?? ""}.${migration.exportName} as unknown as RegisteredDataMigration,`
471
+ ).join("\n");
472
+ return {
473
+ dispatchBody: dispatchEntries.length > 0 ? `
474
+ ${dispatchEntries}
475
+ ` : "",
476
+ importBlock: importLines.length > 0 ? `${importLines}
477
+
478
+ ` : "",
479
+ migrationBody: migrationEntries.length > 0 ? `
480
+ ${migrationEntries}
481
+ ` : ""
482
+ };
483
+ };
484
+ const renderCaller = (functions) => {
485
+ const namespaces = /* @__PURE__ */ new Map();
486
+ for (const definition of functions) {
487
+ const list = namespaces.get(definition.filePath) ?? [];
488
+ list.push(definition);
489
+ namespaces.set(definition.filePath, list);
490
+ }
491
+ const ordered = [...namespaces.entries()].toSorted(([a], [b]) => a.localeCompare(b));
492
+ const types = ordered.map(([file, list]) => {
493
+ const members = list.map((definition) => {
494
+ const argsType = renderArgsType(definition.args);
495
+ const optional = argsType === "{}" ? "?" : "";
496
+ const returnType = relocateGeneratedImports(definition.returnType);
497
+ if (definition.kind === "stream") {
498
+ return ` ${definition.exportName}: (args${optional}: ${argsType}) => Promise<AsyncIterable<${returnType}>>;`;
499
+ }
500
+ return ` ${definition.exportName}: (args${optional}: ${argsType}) => Promise<${returnType}>;`;
501
+ }).join("\n");
502
+ return ` ${renderPropertyKey(sanitizeNamespace(file))}: {
503
+ ${members}
504
+ };`;
505
+ }).join("\n");
506
+ const implementation = ordered.map(([file, list]) => {
507
+ const namespace = sanitizeNamespace(file);
508
+ const leaves = list.map((definition) => ` ${definition.exportName}: (args) => callRegistered(context, "${namespace}:${definition.exportName}", args),`).join("\n");
509
+ return ` ${renderPropertyKey(namespace)}: {
510
+ ${leaves}
511
+ },`;
512
+ }).join("\n");
513
+ return { implementation, types };
514
+ };
515
+ const buildStorageBucketNames = (schema, ruleBuckets = []) => {
516
+ const named = /* @__PURE__ */ new Set();
517
+ for (const table of schema.tables) {
518
+ for (const validator of Object.values(table.shape)) {
519
+ const resolved = validator.kind === "optional" && validator.inner ? validator.inner : validator;
520
+ if (resolved.kind === "storage" && typeof resolved.bucket === "string" && resolved.bucket !== "") {
521
+ named.add(resolved.bucket);
522
+ }
523
+ }
524
+ }
525
+ for (const bucket of ruleBuckets) {
526
+ if (bucket !== "" && bucket !== "default") {
527
+ named.add(bucket);
528
+ }
529
+ }
530
+ return ["default", ...[...named].toSorted((a, b) => a.localeCompare(b))];
531
+ };
532
+ const emitServer = ({
533
+ containers = [],
534
+ hasAi = false,
535
+ hasAnalytics = false,
536
+ hasBrowser = false,
537
+ hasHyperdrive = false,
538
+ hasImages = false,
539
+ hasKv = false,
540
+ hasPayments = false,
541
+ hasPipelines = false,
542
+ schema,
543
+ storageRuleBuckets = [],
544
+ useUmbrella = false,
545
+ workflows = []
546
+ } = {}) => {
547
+ const base = baseSpecifiers(useUmbrella);
548
+ const storageBucketUnion = buildStorageBucketNames(schema ?? { tables: []}, storageRuleBuckets).map((name) => JSON.stringify(name)).join(" | ");
549
+ const aiTypeImport = hasAi ? `import type { LunoraAi } from "@lunora/ai";
550
+ ` : "";
551
+ const aiActionField = hasAi ? `
552
+ readonly ai: LunoraAi;` : "";
553
+ const paymentsTypeImport = hasPayments ? `import type { LunoraPayment } from "@lunora/payment";
554
+ ` : "";
555
+ const paymentsActionField = hasPayments ? `
556
+ readonly payments: LunoraPayment;` : "";
557
+ const containersTypeImport = containers.length > 0 ? `import type { ContainerAccessor } from "@lunora/container";
558
+ ` : "";
559
+ const containersActionField = containers.length > 0 ? `
560
+ readonly containers: {${containers.map((container) => `
561
+ readonly ${container.exportName}: ContainerAccessor;`).join("")}
562
+ };` : "";
563
+ const envBindingFields = [
564
+ ...hasAi ? [` /** Workers AI binding (the conventional \`env.AI\`), narrowing \`ctx.ai\`. */
565
+ readonly AI?: unknown;`] : [],
566
+ ...containers.map((container) => {
567
+ assertIdentifier(container.bindingName, `container binding "${container.bindingName}"`);
568
+ return ` /** Durable Object namespace for the \`${container.exportName}\` container. */
569
+ readonly ${container.bindingName}?: unknown;`;
570
+ }),
571
+ ...workflows.map((workflow) => {
572
+ assertIdentifier(workflow.bindingName, `workflow binding "${workflow.bindingName}"`);
573
+ return ` /** Workflow binding for the \`${workflow.exportName}\` workflow. */
574
+ readonly ${workflow.bindingName}?: unknown;`;
575
+ })
576
+ ].join("\n");
577
+ const envBlock = `
578
+
579
+ /**
580
+ * This project's Cloudflare bindings, as far as codegen can discover them from
581
+ * \`lunora/\` source — the container/workflow Durable Object namespaces and the
582
+ * conventional Workers AI binding. Bindings the config layer reconciles from
583
+ * user-named wrangler config (R2/KV/D1/\`services\`/queues/…) aren't statically
584
+ * visible here, so the open index signature keeps them reachable (cast at the
585
+ * use site). Service bindings (\`env.<SERVICE>.fetch(...)\` / RPC stubs) live
586
+ * under this signature too — Lunora can't type a third-party worker's RPC
587
+ * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
588
+ */
589
+ export interface CloudflareBindings {
590
+ readonly [binding: string]: unknown;${envBindingFields ? `
591
+ ${envBindingFields}` : ""}
592
+ }
593
+
594
+ /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
595
+ export type Env = CloudflareBindings;`;
596
+ const kvContextField = hasKv ? `
597
+ readonly kv: import("@lunora/kv").Kv;` : "";
598
+ const hyperdriveActionField = hasHyperdrive ? `
599
+ /**
600
+ * External database access via Hyperdrive. Non-deterministic — available only in actions. Writes here are NOT tracked by Lunora live queries; subscriptions will not re-run on external DB changes.
601
+ */
602
+ readonly sql: import("@lunora/hyperdrive").SqlClient;` : "";
603
+ const browserActionField = hasBrowser ? `
604
+ /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
605
+ readonly browser: import("@lunora/browser").Browser;` : "";
606
+ const imagesActionField = hasImages ? `
607
+ /** Cloudflare Images transforms (resize/format/optimize). Non-deterministic — available only in actions. */
608
+ readonly images: import("@lunora/images").Images;` : "";
609
+ const analyticsContextField = hasAnalytics ? `
610
+ /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
611
+ readonly analytics: import("@lunora/analytics").AnalyticsClient;` : "";
612
+ const pipelinesActionField = hasPipelines ? `
613
+ /** Pipelines ingestion sink (durable, R2-backed). Fire-and-forget and batched; do not read it back in-handler. */
614
+ readonly pipelines: import("@lunora/pipelines").PipelineClient;` : "";
615
+ const hasWorkflows = workflows.length > 0;
616
+ const workflowsTypeImport = hasWorkflows ? `import type { WorkflowHandle } from "@lunora/workflow";
617
+ import type * as lunoraWorkflowDefinitions from "../workflows.js";
618
+ ` : "";
619
+ const workflowsTypeBlock = hasWorkflows ? `
620
+
621
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
622
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
623
+ ? unknown extends Params
624
+ ? Record<string, unknown>
625
+ : NonNullable<Params>
626
+ : Record<string, unknown>;
627
+
628
+ /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
629
+ export interface LunoraWorkflows {
630
+ ${workflows.map((workflow) => ` get(name: ${JSON.stringify(workflow.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${workflow.exportName}>>;`).join("\n")}
631
+ }` : "";
632
+ const workflowsOmit = hasWorkflows ? ` | "workflows"` : "";
633
+ const workflowsContextField = hasWorkflows ? `
634
+ readonly workflows: LunoraWorkflows;` : "";
635
+ const server = `${GENERATED_HEADER}import { createPolicyDsl, initLunora, v as vBase } from "${base.server}";
636
+ import type {
637
+ ActionBuilder,
638
+ ActionCtx as ActionCtxBase,
639
+ ColumnValidator,
640
+ DatabaseReader,
641
+ DatabaseWriter,
642
+ EmptyArgs,
643
+ InternalActionBuilder,
644
+ InternalMutationBuilder,
645
+ InternalQueryBuilder,
646
+ MutationBuilder,
647
+ MutationCtx as MutationCtxBase,
648
+ QueryBuilder,
649
+ QueryCtx as QueryCtxBase,
650
+ ReadOnlyStorage,
651
+ Storage as StorageBase,
652
+ TableReader,
653
+ } from "${base.server}";
654
+
655
+ import type { DataModel, DatabaseReaderFacade, DatabaseWriterFacade, Doc, Id as IdOfTable, OrmReader, OrmWriter, Relations, TableName } from "./dataModel.js";
656
+ ${aiTypeImport}${paymentsTypeImport}${containersTypeImport}${workflowsTypeImport}
657
+ export type { DataModel, Doc, Id, TableName } from "./dataModel.js";
658
+
659
+ /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
660
+ export type StorageBucketName = ${storageBucketUnion};${envBlock}${workflowsTypeBlock}
661
+
662
+ /**
663
+ * Project-typed contexts. The base contexts from \`@lunora/server\` are
664
+ * untyped against the schema; here \`db\` is widened to the generated per-table
665
+ * facade (\`ctx.db.<table>.findMany(...)\`) while keeping the legacy structural
666
+ * \`db.get\`/\`db.query\` surface for back-compat, and \`storage\` is narrowed so
667
+ * \`ctx.storage.bucket(name)\` autocompletes the declared buckets.
668
+ */
669
+ /**
670
+ * The Convex-style fluent reader \`ctx.db.query(table)\`, bound to this schema:
671
+ * a table-name literal narrows the row type, so \`.collect()\` / \`.first()\` /
672
+ * \`.take()\` (and the \`.withIndex()\` / \`.filter()\` / \`.order()\` chain) resolve
673
+ * as \`Doc<table>\` with no \`as unknown as Doc<...>\` casts. The per-table accessor
674
+ * \`ctx.db.<table>\` stays available alongside it via the facade.
675
+ *
676
+ * Intersected with the wide \`(string) => TableReader\` signature so the bound
677
+ * \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
678
+ * call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
679
+ */
680
+ type TypedTableQuery = (<T extends TableName>(table: T) => TableReader<Doc<T>>) & ((table: string) => TableReader);
681
+
682
+ /**
683
+ * The point read \`ctx.db.get(id)\`, bound to this schema: an \`Id<"table">\`
684
+ * carries its table name, so the resolved document is typed \`Doc<table>\` (or
685
+ * \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
686
+ */
687
+ type TypedTableGet = <T extends TableName>(id: IdOfTable<T>) => Promise<Doc<T> | null>;
688
+
689
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"> {
690
+ readonly db: Omit<DatabaseReader, "query" | "get"> & DatabaseReaderFacade & { query: TypedTableQuery; get: TypedTableGet };
691
+ readonly orm: OrmReader;
692
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${kvContextField}${analyticsContextField}
693
+ }
694
+
695
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${workflowsOmit}> {
696
+ readonly db: Omit<DatabaseWriter, "query" | "get"> & DatabaseWriterFacade & { query: TypedTableQuery; get: TypedTableGet };
697
+ readonly orm: OrmWriter;
698
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${kvContextField}${analyticsContextField}${workflowsContextField}
699
+ }
700
+
701
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${workflowsOmit}> {
702
+ readonly db: Omit<DatabaseWriter, "query" | "get"> & DatabaseWriterFacade & { query: TypedTableQuery; get: TypedTableGet };
703
+ readonly orm: OrmWriter;
704
+ readonly storage: StorageBase<StorageBucketName>;${aiActionField}${paymentsActionField}${containersActionField}${kvContextField}${hyperdriveActionField}${browserActionField}${imagesActionField}${analyticsContextField}${pipelinesActionField}${workflowsContextField}
705
+ }
706
+
707
+ /**
708
+ * Procedure builders bound to this project's typed contexts. Chain
709
+ * \`.input({...})\` to declare args, \`.use(middleware)\` for rate limiting / RLS /
710
+ * masking (each middleware may refine \`ctx\`), then the terminal
711
+ * \`.query()\` / \`.mutation()\` / \`.action()\` with a \`({ ctx, args }) => ...\`
712
+ * handler. \`.output(validator)\` and (queries) \`.stream()\` are also available.
713
+ */
714
+ const lunoraBuilders = initLunora.dataModel<DataModel>().create();
715
+
716
+ /** \`query\` builder bound to this project's typed {@link QueryCtx}. */
717
+ export const query = lunoraBuilders.query as unknown as QueryBuilder<QueryCtx, EmptyArgs>;
718
+
719
+ /** \`mutation\` builder bound to this project's typed {@link MutationCtx}. */
720
+ export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder<MutationCtx, EmptyArgs>;
721
+
722
+ /** \`action\` builder bound to this project's typed {@link ActionCtx}. */
723
+ export const action = lunoraBuilders.action as unknown as ActionBuilder<ActionCtx, EmptyArgs>;
724
+
725
+ /** \`internalQuery\` builder bound to this project's typed {@link QueryCtx} — never exposed on \`api\`. */
726
+ export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder<QueryCtx, EmptyArgs>;
727
+
728
+ /** \`internalMutation\` builder bound to this project's typed {@link MutationCtx} — never exposed on \`api\`. */
729
+ export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder<MutationCtx, EmptyArgs>;
730
+
731
+ /** \`internalAction\` builder bound to this project's typed {@link ActionCtx} — never exposed on \`api\`. */
732
+ export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder<ActionCtx, EmptyArgs>;
733
+
734
+ /**
735
+ * \`definePolicy\` bound to THIS schema's {@link DataModel} + {@link Relations}.
736
+ * Import it from here (\`./_generated/server\`) instead of \`@lunora/server\` to get
737
+ * a relation-aware RLS authoring surface: \`table\` autocompletes to a real table
738
+ * name and the \`when\` predicate type-checks against the table's columns **and**
739
+ * its declared relations — \`{ author: { is: {...} } }\`, \`{ posts: { some: {...} } }\`,
740
+ * etc. (the \`@lunora/do\` pre-resolver resolves relation predicates on reads).
741
+ * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
742
+ * so the \`rls()\` chain discovers a policy authored either way the same.
743
+ */
744
+ export const definePolicy = createPolicyDsl<DataModel, Relations>();
745
+
746
+ /**
747
+ * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
748
+ * table names — so the argument autocompletes and returns a precise
749
+ * \`Id<"table">\`. Identical to \`@lunora/server\`'s \`v\` at runtime; the only
750
+ * difference is the tightened \`id\` type.
751
+ *
752
+ * Import \`v\` from here (\`./_generated/server\`) in your queries/mutations/actions
753
+ * to get table-name autocomplete. \`lunora/schema.ts\` can't use it — it is the
754
+ * file that defines the table names, so they aren't known yet there; pass the
755
+ * names as string literals and the generated \`Id<"table">\` types still catch a
756
+ * typo wherever the id is used.
757
+ */
758
+ export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
759
+ id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
760
+ };
761
+ `;
762
+ return server;
763
+ };
764
+ const renderLifecycleManifest = (functions) => {
765
+ const manifest = { connect: [], disconnect: [] };
766
+ for (const definition of functions) {
767
+ if (!definition.lifecycle) {
768
+ continue;
769
+ }
770
+ manifest[definition.lifecycle].push(`${sanitizeNamespace(definition.filePath)}:${definition.exportName}`);
771
+ }
772
+ return manifest;
773
+ };
774
+ const emitFunctions = (functions, migrations = []) => {
775
+ const hasFunctions = functions.length > 0;
776
+ const { dispatchBody, importBlock, migrationBody } = renderFunctionRegistry(functions, migrations);
777
+ const lifecycleHooks = renderLifecycleManifest(functions);
778
+ const caller = renderCaller(functions);
779
+ const callerTypes = caller.types ? `
780
+ ${caller.types}
781
+ ` : "";
782
+ const callerImpl = caller.implementation ? `
783
+ ${caller.implementation}
784
+ ` : "";
785
+ const callerDataModelImports = referencedDataModelImports(caller.types);
786
+ const dataModelImport = callerDataModelImports.length > 0 ? `import type { ${callerDataModelImports.join(", ")} } from "./dataModel.js";
787
+ ` : "";
788
+ const callerParameter = hasFunctions ? "context" : "_context";
789
+ const callRegisteredHelper = hasFunctions ? `${CALL_REGISTERED_HELPER}
790
+
791
+ ` : "";
792
+ return `${GENERATED_HEADER}${importBlock}import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
793
+ ${dataModelImport}
794
+ /**
795
+ * Single registered function, narrowed to the shape \`handleRpc\` needs.
796
+ * The real argument validators / return types are checked elsewhere — at
797
+ * the dispatch site we erase to \`unknown\` so a single map can host every
798
+ * registered function.
799
+ */
800
+ export interface RegisteredLunoraFunction {
801
+ kind: "action" | "mutation" | "query" | "stream";
802
+ args: Record<string, unknown>;
803
+ /**
804
+ * For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
805
+ * For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
806
+ * \`AbortSignal\` as a third argument — the runtime drives it frame-by-frame.
807
+ */
808
+ handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
809
+ /** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
810
+ visibility?: "internal" | "public";
811
+ }
812
+
813
+ /**
814
+ * Static dispatch table. The key matches the \`__lunoraRef\` the client
815
+ * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
816
+ */
817
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${dispatchBody}};
818
+
819
+ /**
820
+ * Connection-lifecycle manifest: the function paths the generated ShardDO
821
+ * dispatches when a client's WebSocket connects (\`connect\`) or disconnects
822
+ * (\`disconnect\`). Each path also resolves through {@link LUNORA_FUNCTIONS}; the
823
+ * DO runs every hook under the socket's verified identity via system dispatch.
824
+ */
825
+ export const LUNORA_LIFECYCLE_HOOKS: { connect: readonly string[]; disconnect: readonly string[] } = {
826
+ connect: [${lifecycleHooks.connect.map((path) => JSON.stringify(path)).join(", ")}],
827
+ disconnect: [${lifecycleHooks.disconnect.map((path) => JSON.stringify(path)).join(", ")}],
828
+ };
829
+
830
+ /**
831
+ * Resolve and invoke a registered function from an external caller. Throws a
832
+ * LunoraError-shaped object (404) when the path is unknown — the runtime's
833
+ * structural error mapper turns that into the right HTTP status. Internal
834
+ * functions are treated as not-found so their existence never leaks to clients.
835
+ */
836
+ export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
837
+ const registered = LUNORA_FUNCTIONS[functionPath];
838
+
839
+ if (!registered || registered.visibility === "internal") {
840
+ throw Object.assign(new Error(\`function not registered: \${functionPath}\`), {
841
+ name: "LunoraError",
842
+ code: "FUNCTION_NOT_FOUND",
843
+ status: 404,
844
+ });
845
+ }
846
+
847
+ return registered.handler(context, args);
848
+ };
849
+
850
+ /**
851
+ * A handler context accepted by {@link createCaller}. The runtime context the
852
+ * shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
853
+ */
854
+ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
855
+
856
+ /**
857
+ * Typed, in-process server-to-server caller. Every registered function — public
858
+ * *and* internal — is reachable; each call dispatches against the same shard
859
+ * with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
860
+ * \`runAction\` but without re-stating the function path.
861
+ */
862
+ export interface Caller {${callerTypes}}
863
+
864
+ ${callRegisteredHelper}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
865
+ export const createCaller = (${callerParameter}: CallerCtx): Caller => ({${callerImpl}});
866
+
867
+ /**
868
+ * Single registered data migration, narrowed to the shape the per-shard runner
869
+ * consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
870
+ * validation lives in \`defineMigration\`.
871
+ */
872
+ export interface RegisteredDataMigration {
873
+ batchSize?: number;
874
+ down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
875
+ id: string;
876
+ table: string;
877
+ up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
878
+ }
879
+
880
+ /**
881
+ * Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
882
+ * shard DO's admin RPC and the CLI resolve migrations to run through this map.
883
+ */
884
+ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${migrationBody}};
885
+ `;
886
+ };
887
+ const buildTableReferences = (schema) => {
888
+ const references = {};
889
+ for (const table of schema.tables) {
890
+ const fields = {};
891
+ for (const [field, validator] of Object.entries(table.shape)) {
892
+ const resolved = validator.kind === "optional" && validator.inner ? validator.inner : validator;
893
+ if (resolved.kind === "id" && resolved.tableName !== void 0) {
894
+ fields[field] = resolved.tableName;
895
+ }
896
+ }
897
+ if (Object.keys(fields).length > 0) {
898
+ references[table.name] = fields;
899
+ }
900
+ }
901
+ return references;
902
+ };
903
+ const buildStorageColumns = (schema) => {
904
+ const byTable = {};
905
+ for (const table of schema.tables) {
906
+ const fields = [];
907
+ for (const [field, validator] of Object.entries(table.shape)) {
908
+ const resolved = validator.kind === "optional" && validator.inner ? validator.inner : validator;
909
+ if (resolved.kind === "storage") {
910
+ fields.push(field);
911
+ }
912
+ }
913
+ if (fields.length > 0) {
914
+ byTable[table.name] = fields;
915
+ }
916
+ }
917
+ return byTable;
918
+ };
919
+ const buildTableIndexes = (schema) => {
920
+ const byTable = {};
921
+ for (const table of schema.tables) {
922
+ const entries = [
923
+ ...table.indexes.map((index) => {
924
+ return { fields: [...index.fields], name: index.name, type: "index", ...index.unique === true ? { unique: true } : {} };
925
+ }),
926
+ ...table.searchIndexes.map((index) => {
927
+ return { fields: [index.field, ...index.filterFields ?? []], name: index.name, type: "search" };
928
+ }),
929
+ ...table.rankIndexes.map((index) => {
930
+ return { fields: index.sortBy.map((key) => key.field), name: index.name, type: "rank" };
931
+ }),
932
+ ...table.vectorIndexes.map((index) => {
933
+ return { fields: index.field === void 0 ? [] : [index.field], name: index.name, type: "vector" };
934
+ })
935
+ ];
936
+ if (entries.length > 0) {
937
+ byTable[table.name] = entries;
938
+ }
939
+ }
940
+ return byTable;
941
+ };
942
+ const buildTableColumns = (schema) => {
943
+ const byTable = {};
944
+ for (const table of schema.tables) {
945
+ const columns = [
946
+ { name: "_id", optional: false, pk: true, type: "id" },
947
+ { name: "_creationTime", optional: false, type: "number" }
948
+ ];
949
+ for (const [field, validator] of Object.entries(table.shape)) {
950
+ const optional = validator.kind === "optional" || Boolean(validator.column?.hasDefault);
951
+ const resolved = validator.kind === "optional" && validator.inner ? validator.inner : validator;
952
+ const column = { name: field, optional, type: resolved.kind };
953
+ if (resolved.kind === "id" && resolved.tableName !== void 0) {
954
+ column.ref = resolved.tableName;
955
+ }
956
+ if (resolved.kind === "storage") {
957
+ column.isStorage = true;
958
+ }
959
+ columns.push(column);
960
+ }
961
+ byTable[table.name] = columns;
962
+ }
963
+ return byTable;
964
+ };
965
+ const emitRelationFanout = (hasGlobalTables) => {
966
+ if (!hasGlobalTables) {
967
+ return { importFragment: "", override: "" };
968
+ }
969
+ return {
970
+ importFragment: "serveRelationFanout, ",
971
+ override: `
972
+ protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
973
+ this.ensureMigrated();
974
+
975
+ const { db } = this.buildCtx({ functionPath }) as { db: DatabaseWriterLike };
976
+
977
+ return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
978
+ }
979
+ `
980
+ };
981
+ };
982
+ const emitAiFragments = (hasAi) => {
983
+ if (!hasAi) {
984
+ return { build: "", configField: "", contextField: "", stub: "" };
985
+ }
986
+ const aiMissing = `throw new Error("ctx.ai: no AI binding found. Add an \\\`ai\\\` binding (env.AI) to wrangler.jsonc, or pass \\\`ai\\\` to createShardDO().");`;
987
+ return {
988
+ // Build ctx.ai from the resolved Workers AI binding (a `config.ai` thunk
989
+ // override, else `env.AI`). createAi is provider-agnostic — a model-id
990
+ // string resolves Workers AI, any AI SDK model object passes through — so
991
+ // a handler is never locked to Workers AI. Falls back to `aiStub`.
992
+ build: `
993
+ const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
994
+ const ai: LunoraAi = aiBinding ? createAi({ binding: aiBinding as AiBindingLike }) : aiStub;
995
+ `,
996
+ // Optional override for the Workers AI binding. When omitted, ctx.ai is
997
+ // built from `env.AI` (the conventional binding the config layer
998
+ // auto-reconciles); the thunk lets a caller point it elsewhere or inject
999
+ // a double in tests.
1000
+ configField: `
1001
+ ai?: (env: Record<string, unknown>) => AiBindingLike;`,
1002
+ contextField: `
1003
+ ai,`,
1004
+ stub: `
1005
+ const aiStub: LunoraAi = {
1006
+ embeddingModel: () => {
1007
+ ${aiMissing}
1008
+ },
1009
+ model: () => {
1010
+ ${aiMissing}
1011
+ },
1012
+ run: async () => {
1013
+ ${aiMissing}
1014
+ },
1015
+ // workersai is a callable-with-properties; a bare throwing arrow isn't
1016
+ // structurally assignable, so cast it. Never invoked (the stub throws first).
1017
+ workersai: (() => {
1018
+ ${aiMissing}
1019
+ }) as unknown as LunoraAi["workersai"],
1020
+ };
1021
+ `
1022
+ };
1023
+ };
1024
+ const EMPTY_HELPER_FRAGMENTS = { build: "", configField: "", contextField: "", importLines: [], stub: "" };
1025
+ const emitKvFragments = (hasKv) => {
1026
+ if (!hasKv) {
1027
+ return EMPTY_HELPER_FRAGMENTS;
1028
+ }
1029
+ const kvMissing = `throw new Error("ctx.kv: no KV binding found. Add a \\\`kv_namespaces\\\` binding (env.KV) to wrangler.jsonc, or pass \\\`kv\\\` to createShardDO().");`;
1030
+ return {
1031
+ build: `
1032
+ const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
1033
+ const kv: Kv = kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub;
1034
+ `,
1035
+ configField: `
1036
+ kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,
1037
+ contextField: `
1038
+ kv,`,
1039
+ importLines: [`import type { Kv, KVNamespaceLike } from "@lunora/kv";`, `import { createKv } from "@lunora/kv";`],
1040
+ stub: `
1041
+ const kvStub: Kv = {
1042
+ delete: async () => {
1043
+ ${kvMissing}
1044
+ },
1045
+ get: async () => {
1046
+ ${kvMissing}
1047
+ },
1048
+ getRaw: async () => {
1049
+ ${kvMissing}
1050
+ },
1051
+ getWithMetadata: async () => {
1052
+ ${kvMissing}
1053
+ },
1054
+ list: async () => {
1055
+ ${kvMissing}
1056
+ },
1057
+ put: async () => {
1058
+ ${kvMissing}
1059
+ },
1060
+ };
1061
+ `
1062
+ };
1063
+ };
1064
+ const emitAnalyticsFragments = (hasAnalytics) => {
1065
+ if (!hasAnalytics) {
1066
+ return EMPTY_HELPER_FRAGMENTS;
1067
+ }
1068
+ const analyticsMissing = `throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\\`analytics_engine_datasets\\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\\`analytics\\\` to createShardDO().");`;
1069
+ return {
1070
+ build: `
1071
+ const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
1072
+ const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
1073
+ `,
1074
+ configField: `
1075
+ analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,
1076
+ contextField: `
1077
+ analytics,`,
1078
+ importLines: [
1079
+ `import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/analytics";`,
1080
+ `import { createAnalytics } from "@lunora/analytics";`
1081
+ ],
1082
+ stub: `
1083
+ const analyticsStub: AnalyticsClient = {
1084
+ track: () => {
1085
+ ${analyticsMissing}
1086
+ },
1087
+ writeDataPoint: () => {
1088
+ ${analyticsMissing}
1089
+ },
1090
+ };
1091
+ `
1092
+ };
1093
+ };
1094
+ const emitImagesFragments = (hasImages) => {
1095
+ if (!hasImages) {
1096
+ return EMPTY_HELPER_FRAGMENTS;
1097
+ }
1098
+ const imagesMissing = `throw new Error("ctx.images: no Images binding found. Add an \\\`images\\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\\`images\\\` to createShardDO().");`;
1099
+ return {
1100
+ build: `
1101
+ const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
1102
+ const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
1103
+ `,
1104
+ configField: `
1105
+ images?: (env: Record<string, unknown>) => ImagesBindingLike;`,
1106
+ // ActionCtx-only: woven onto the action ctx object, never query/mutation.
1107
+ contextField: `
1108
+ images,`,
1109
+ importLines: [`import type { Images, ImagesBindingLike } from "@lunora/images";`, `import { createImages } from "@lunora/images";`],
1110
+ stub: `
1111
+ const imagesStub: Images = {
1112
+ info: async () => {
1113
+ ${imagesMissing}
1114
+ },
1115
+ transform: async () => {
1116
+ ${imagesMissing}
1117
+ },
1118
+ };
1119
+ `
1120
+ };
1121
+ };
1122
+ const emitHyperdriveFragments = (hasHyperdrive) => {
1123
+ if (!hasHyperdrive) {
1124
+ return EMPTY_HELPER_FRAGMENTS;
1125
+ }
1126
+ const sqlMissing = `throw new Error("ctx.sql: provide a \\\`sql\\\` config thunk that builds a SqlClient from your driver, e.g. \\\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\\`.");`;
1127
+ return {
1128
+ build: `
1129
+ const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
1130
+ `,
1131
+ configField: `
1132
+ sql?: (env: Record<string, unknown>) => SqlClient;`,
1133
+ // ActionCtx-only: woven onto the action ctx object, never query/mutation.
1134
+ contextField: `
1135
+ sql,`,
1136
+ importLines: [`import type { SqlClient } from "@lunora/hyperdrive";`],
1137
+ stub: `
1138
+ const sqlStub: SqlClient = {
1139
+ query: async () => {
1140
+ ${sqlMissing}
1141
+ },
1142
+ };
1143
+ `
1144
+ };
1145
+ };
1146
+ const emitBrowserFragments = (hasBrowser) => {
1147
+ if (!hasBrowser) {
1148
+ return EMPTY_HELPER_FRAGMENTS;
1149
+ }
1150
+ const browserMissing = `throw new Error("ctx.browser: provide a \\\`browser\\\` config thunk, e.g. \\\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\\` with \\\`import { launch } from '@cloudflare/playwright'\\\`.");`;
1151
+ return {
1152
+ build: `
1153
+ const browser: Browser = config.browser ? config.browser(env) : browserStub;
1154
+ `,
1155
+ configField: `
1156
+ browser?: (env: Record<string, unknown>) => Browser;`,
1157
+ // ActionCtx-only: woven onto the action ctx object, never query/mutation.
1158
+ contextField: `
1159
+ browser,`,
1160
+ // Type-only import: the generated build never calls `createBrowser`
1161
+ // (the `config.browser` thunk owns construction, injecting the optional
1162
+ // `@cloudflare/playwright` peer the worker stays free of), so only the
1163
+ // `Browser` type is referenced here.
1164
+ importLines: [`import type { Browser } from "@lunora/browser";`],
1165
+ stub: `
1166
+ const browserStub: Browser = {
1167
+ content: async () => {
1168
+ ${browserMissing}
1169
+ },
1170
+ launch: async () => {
1171
+ ${browserMissing}
1172
+ },
1173
+ pdf: async () => {
1174
+ ${browserMissing}
1175
+ },
1176
+ scrape: async () => {
1177
+ ${browserMissing}
1178
+ },
1179
+ screenshot: async () => {
1180
+ ${browserMissing}
1181
+ },
1182
+ };
1183
+ `
1184
+ };
1185
+ };
1186
+ const emitContainers = (containers) => {
1187
+ if (containers.length === 0) {
1188
+ return "";
1189
+ }
1190
+ const classes = containers.map((container) => {
1191
+ assertIdentifier(container.exportName, `container export "${container.exportName}"`);
1192
+ assertIdentifier(container.className, `container class "${container.className}"`);
1193
+ return `/** Container DO for the \`${container.exportName}\` definition (binding \`${container.bindingName}\`). */
1194
+ export class ${container.className} extends LunoraContainer {
1195
+ public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1196
+ super(ctx, env, ${container.exportName}, "${container.exportName}");
1197
+ }
1198
+ }
1199
+ `;
1200
+ }).join("\n");
1201
+ const imports = containers.map((container) => container.exportName).join(", ");
1202
+ return `${GENERATED_HEADER}/**
1203
+ * Container-enabled Durable Object classes for the containers declared in
1204
+ * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
1205
+ * requires each \`containers[].class_name\` to be exported by the worker:
1206
+ *
1207
+ * \`export * from "./lunora/_generated/containers.js";\`
1208
+ */
1209
+ import LunoraContainer from "@lunora/container/do";
1210
+
1211
+ import { ${imports} } from "../containers.js";
1212
+
1213
+ ${classes}`;
1214
+ };
1215
+ const emitContainerFragments = (containers) => {
1216
+ if (containers.length === 0) {
1217
+ return { build: "", contextField: "", importLines: [], specs: "" };
1218
+ }
1219
+ for (const container of containers) {
1220
+ assertIdentifier(container.exportName, `container export "${container.exportName}"`);
1221
+ assertIdentifier(container.bindingName, `container binding "${container.bindingName}"`);
1222
+ }
1223
+ const specEntries = containers.map((container) => {
1224
+ const maxInstances = container.maxInstances === void 0 ? "" : `, maxInstances: ${String(container.maxInstances)}`;
1225
+ return ` { binding: "${container.bindingName}", exportName: "${container.exportName}"${maxInstances} },`;
1226
+ }).join("\n");
1227
+ return {
1228
+ build: `
1229
+ const containers = createContainerContext(env, LUNORA_CONTAINERS);
1230
+ `,
1231
+ contextField: `
1232
+ containers,`,
1233
+ importLines: [`import type { ContainerBindingSpec } from "@lunora/container";`, `import { createContainerContext } from "@lunora/container";`],
1234
+ // eslint-disable-next-line no-secrets/no-secrets -- the emitted readonly-array type annotation is dense generated TS, not a credential
1235
+ specs: `
1236
+ /** Wiring specs for \`ctx.containers\` (codegen-derived from \`lunora/containers.ts\`). */
1237
+ const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
1238
+ ${specEntries}
1239
+ ];
1240
+ `
1241
+ };
1242
+ };
1243
+ const emitWorkflows = (workflows) => {
1244
+ if (workflows.length === 0) {
1245
+ return "";
1246
+ }
1247
+ const classes = workflows.map((workflow) => {
1248
+ assertIdentifier(workflow.exportName, `workflow export "${workflow.exportName}"`);
1249
+ assertIdentifier(workflow.className, `workflow class "${workflow.className}"`);
1250
+ return `/** WorkflowEntrypoint for the \`${workflow.exportName}\` definition (binding \`${workflow.bindingName}\`). */
1251
+ export class ${workflow.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${workflow.exportName}>, WorkflowOutputOf<typeof ${workflow.exportName}>> {
1252
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1253
+ super(ctx, env, ${workflow.exportName}, "${workflow.exportName}");
1254
+ }
1255
+ }
1256
+ `;
1257
+ }).join("\n");
1258
+ const imports = workflows.map((workflow) => workflow.exportName).join(", ");
1259
+ return `${GENERATED_HEADER}/**
1260
+ * WorkflowEntrypoint classes for the workflows declared in
1261
+ * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
1262
+ * requires each \`workflows[].class_name\` to be exported by the worker:
1263
+ *
1264
+ * \`export * from "./lunora/_generated/workflows.js";\`
1265
+ */
1266
+ import LunoraWorkflow from "@lunora/workflow/do";
1267
+
1268
+ import { ${imports} } from "../workflows.js";
1269
+
1270
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`), so each entrypoint keeps the authored \`ctx.params\` type. */
1271
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
1272
+ ? unknown extends Params
1273
+ ? Record<string, unknown>
1274
+ : NonNullable<Params>
1275
+ : Record<string, unknown>;
1276
+
1277
+ /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
1278
+ type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
1279
+
1280
+ ${classes}`;
1281
+ };
1282
+ const emitWorkflowFragments = (workflows) => {
1283
+ if (workflows.length === 0) {
1284
+ return { build: "", contextField: "", importLines: [], specs: "" };
1285
+ }
1286
+ for (const workflow of workflows) {
1287
+ assertIdentifier(workflow.exportName, `workflow export "${workflow.exportName}"`);
1288
+ assertIdentifier(workflow.bindingName, `workflow binding "${workflow.bindingName}"`);
1289
+ }
1290
+ const specEntries = workflows.map((workflow) => ` { binding: "${workflow.bindingName}", exportName: "${workflow.exportName}" },`).join("\n");
1291
+ return {
1292
+ build: `
1293
+ const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
1294
+ `,
1295
+ contextField: `
1296
+ workflows,`,
1297
+ importLines: [`import type { WorkflowBindingSpec } from "@lunora/workflow";`, `import { createWorkflowContext } from "@lunora/workflow";`],
1298
+ // eslint-disable-next-line no-secrets/no-secrets -- the emitted readonly-array type annotation is dense generated TS, not a credential
1299
+ specs: `
1300
+ /** Wiring specs for \`ctx.workflows\` (codegen-derived from \`lunora/workflows.ts\`). */
1301
+ const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
1302
+ ${specEntries}
1303
+ ];
1304
+ `
1305
+ };
1306
+ };
1307
+ const emitWorkflowsMetadataFragments = (workflows) => {
1308
+ if (workflows.length === 0) {
1309
+ return { constant: "", override: "" };
1310
+ }
1311
+ const metadata = {
1312
+ workflows: workflows.map((workflow) => {
1313
+ return {
1314
+ binding: workflow.bindingName,
1315
+ className: workflow.className,
1316
+ exportName: workflow.exportName,
1317
+ name: workflow.name
1318
+ };
1319
+ })
1320
+ };
1321
+ return {
1322
+ constant: `
1323
+ /** Read-only declared-workflow metadata (discovered from \`lunora/workflows.ts\`) served via \`__lunora_admin__:listWorkflows\` for the studio's workflows view. */
1324
+ const LUNORA_WORKFLOWS_INFO: WorkflowsResult = ${JSON.stringify(metadata, void 0, 4)};
1325
+ `,
1326
+ override: `
1327
+ protected override workflowsMetadata(): WorkflowsResult {
1328
+ return LUNORA_WORKFLOWS_INFO;
1329
+ }
1330
+ `
1331
+ };
1332
+ };
1333
+ const emitPaymentFragments = (hasPayments) => {
1334
+ if (!hasPayments) {
1335
+ return { build: "", configField: "", contextField: "", imports: [], stub: "" };
1336
+ }
1337
+ const missing = `throw new Error("ctx.payments: no payment configured. Pass \\\`payment\\\` to createShardDO().");`;
1338
+ return {
1339
+ imports: [
1340
+ `import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";`,
1341
+ `import { paymentsFromContext } from "@lunora/payment";`
1342
+ ],
1343
+ // Built after `db` (the store rides ctx.db) and `userId` (the default authorizer ties a
1344
+ // referenceId to the caller). The adapter — which carries provider secrets — comes from
1345
+ // the `config.payment` thunk over env. Falls back to `paymentStub`.
1346
+ build: `
1347
+ const payments: LunoraPayment = config.payment
1348
+ ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
1349
+ : paymentStub;
1350
+ `,
1351
+ configField: `
1352
+ payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,
1353
+ contextField: `
1354
+ payments,`,
1355
+ stub: `
1356
+ const paymentStub: LunoraPayment = {
1357
+ attach: () => {
1358
+ ${missing}
1359
+ },
1360
+ cancelSubscription: () => {
1361
+ ${missing}
1362
+ },
1363
+ check: () => {
1364
+ ${missing}
1365
+ },
1366
+ createCheckout: () => {
1367
+ ${missing}
1368
+ },
1369
+ createPortalSession: () => {
1370
+ ${missing}
1371
+ },
1372
+ handleWebhook: () => {
1373
+ ${missing}
1374
+ },
1375
+ listBalances: () => {
1376
+ ${missing}
1377
+ },
1378
+ listSubscriptions: () => {
1379
+ ${missing}
1380
+ },
1381
+ track: () => {
1382
+ ${missing}
1383
+ },
1384
+ } as unknown as LunoraPayment;
1385
+ `
1386
+ };
1387
+ };
1388
+ const buildDoTypeImports = (hasVectors, hasWorkflows) => [
1389
+ "AdvisoryFinding",
1390
+ "DatabaseWriterLike",
1391
+ "DataMigrationLike",
1392
+ "LogSink",
1393
+ "MaskPoliciesResult",
1394
+ "MigrationRunResult",
1395
+ "RunShardApplyCdcArgs",
1396
+ "RunShardMigrationArgs",
1397
+ "RlsPoliciesResult",
1398
+ "RunShardRankBeforeArgs",
1399
+ "RunShardRankPageArgs",
1400
+ "RunShardWriteArgs",
1401
+ "RunShardWriteResult",
1402
+ "SchedulerLike",
1403
+ "SchemaLike",
1404
+ "ShardDOState",
1405
+ "ShardRankPageResult",
1406
+ "SqlExec",
1407
+ "StorageRulesResult",
1408
+ "StudioFeaturesResult",
1409
+ "SystemReaderStorageLike",
1410
+ ...hasWorkflows ? ["WorkflowsResult"] : [],
1411
+ ...hasVectors ? ["WriteHook"] : []
1412
+ ];
1413
+ const emitShard = ({
1414
+ advisories = [],
1415
+ containers = [],
1416
+ hasAi = false,
1417
+ hasAnalytics = false,
1418
+ hasBrowser = false,
1419
+ hasHyperdrive = false,
1420
+ hasImages = false,
1421
+ hasKv = false,
1422
+ hasPayments = false,
1423
+ maskMetadata,
1424
+ rlsMetadata,
1425
+ schema,
1426
+ storageRules,
1427
+ studioFeatures,
1428
+ useUmbrella = false,
1429
+ workflows = []
1430
+ }) => {
1431
+ const base = baseSpecifiers(useUmbrella);
1432
+ const { build: aiBuild, configField: aiConfigField, contextField: aiContextField, stub: aiStub } = emitAiFragments(hasAi);
1433
+ const kvFragments = emitKvFragments(hasKv);
1434
+ const analyticsFragments = emitAnalyticsFragments(hasAnalytics);
1435
+ const imagesFragments = emitImagesFragments(hasImages);
1436
+ const hyperdriveFragments = emitHyperdriveFragments(hasHyperdrive);
1437
+ const browserFragments = emitBrowserFragments(hasBrowser);
1438
+ const {
1439
+ build: containersBuild,
1440
+ contextField: containersContextField,
1441
+ importLines: containerImportLines,
1442
+ specs: containerSpecs
1443
+ } = emitContainerFragments(containers);
1444
+ const {
1445
+ build: workflowsBuild,
1446
+ contextField: workflowsContextField,
1447
+ importLines: workflowImportLines,
1448
+ specs: workflowSpecs
1449
+ } = emitWorkflowFragments(workflows);
1450
+ const {
1451
+ build: paymentsBuild,
1452
+ configField: paymentsConfigField,
1453
+ contextField: paymentsContextField,
1454
+ imports: paymentsImports,
1455
+ stub: paymentStub
1456
+ } = emitPaymentFragments(hasPayments);
1457
+ const advisoryData = advisories;
1458
+ const rlsData = rlsMetadata ?? { policies: [], roles: [] };
1459
+ const maskData = maskMetadata ?? { columns: [] };
1460
+ const storageRulesData = storageRules ?? { rules: [] };
1461
+ const studioFeaturesData = studioFeatures ?? {
1462
+ mail: false,
1463
+ payments: false,
1464
+ scheduler: false,
1465
+ storage: false,
1466
+ vectors: false,
1467
+ workflows: false
1468
+ };
1469
+ const { constant: workflowsMetadataConst, override: workflowsMetadataOverride } = emitWorkflowsMetadataFragments(workflows);
1470
+ const hasVectors = schema.vectorIndexes.length > 0;
1471
+ const hasGlobalTables = schema.tables.some((table) => table.shardMode === "global");
1472
+ const hasHyperdriveGlobal = schema.tables.some((table) => table.shardMode === "global" && table.globalBackend === "hyperdrive");
1473
+ const hasD1Global = schema.tables.some((table) => table.shardMode === "global" && table.globalBackend !== "hyperdrive");
1474
+ if (hasD1Global && hasHyperdriveGlobal) {
1475
+ throw new Error(
1476
+ 'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.'
1477
+ );
1478
+ }
1479
+ const hasTables = schema.tables.length > 0;
1480
+ const tableReferences = buildTableReferences(schema);
1481
+ const tableIndexes = buildTableIndexes(schema);
1482
+ const tableColumns = buildTableColumns(schema);
1483
+ const storageColumns = buildStorageColumns(schema);
1484
+ const doTypeImports = buildDoTypeImports(hasVectors, workflows.length > 0);
1485
+ const relationFanout = emitRelationFanout(hasGlobalTables);
1486
+ const importLines = [
1487
+ `import type { ${doTypeImports.join(", ")} } from "${base.do}";`,
1488
+ `import { applyCdcChanges, createShardCtxDb, runDataMigration, runShardMigrations, ${relationFanout.importFragment}ShardDO as ShardDOBase } from "${base.do}";`,
1489
+ // `asBucketStorage` (the bucket-aware `ctx.storage` wrapper) lives in
1490
+ // `@lunora/server`, the single source — imported here rather than stamped
1491
+ // inline into every generated shard.
1492
+ `import { asBucketStorage } from "${base.server}";`
1493
+ ];
1494
+ if (hasTables) {
1495
+ importLines.push(`import { bindOrm, bindTableFacade } from "${base.server}";`);
1496
+ }
1497
+ if (hasVectors) {
1498
+ importLines.push(
1499
+ `import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/vectors";`,
1500
+ `import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/vectors";`
1501
+ );
1502
+ }
1503
+ if (hasAi) {
1504
+ importLines.push(`import type { AiBindingLike, LunoraAi } from "@lunora/ai";`, `import { createAi } from "@lunora/ai";`);
1505
+ }
1506
+ importLines.push(
1507
+ ...kvFragments.importLines,
1508
+ ...analyticsFragments.importLines,
1509
+ ...imagesFragments.importLines,
1510
+ ...hyperdriveFragments.importLines,
1511
+ ...browserFragments.importLines,
1512
+ ...containerImportLines,
1513
+ ...workflowImportLines,
1514
+ ...paymentsImports,
1515
+ ``,
1516
+ `import schema from "../schema.js";`,
1517
+ `import { LUNORA_FUNCTIONS, LUNORA_LIFECYCLE_HOOKS, LUNORA_MIGRATIONS } from "./functions.js";`
1518
+ );
1519
+ const vectorsConfigField = hasVectors ? `
1520
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;` : "";
1521
+ const d1ConfigField = hasD1Global ? `
1522
+ d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;` : "";
1523
+ const hyperdriveGlobalConfigField = hasHyperdriveGlobal ? `
1524
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;` : "";
1525
+ const globalDatabaseStub = hasGlobalTables ? `
1526
+ const globalDbStub: DatabaseWriterLike = {
1527
+ aggregate: async () => {
1528
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1529
+ },
1530
+ count: async () => {
1531
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1532
+ },
1533
+ delete: async () => {
1534
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1535
+ },
1536
+ findFirst: async () => {
1537
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1538
+ },
1539
+ findFirstOrThrow: async () => {
1540
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1541
+ },
1542
+ findMany: async () => {
1543
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1544
+ },
1545
+ get: async () => {
1546
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1547
+ },
1548
+ groupBy: async () => {
1549
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1550
+ },
1551
+ insert: async () => {
1552
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1553
+ },
1554
+ normalizeId: () => {
1555
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1556
+ },
1557
+ patch: async () => {
1558
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1559
+ },
1560
+ query: () => {
1561
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1562
+ },
1563
+ rank: async () => {
1564
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1565
+ },
1566
+ rankPage: async () => {
1567
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1568
+ },
1569
+ replace: async () => {
1570
+ throw new Error("ctx.db.<globalTable>: no global backend configured. Pass \`d1\` or \`hyperdriveGlobal\` to createShardDO().");
1571
+ },
1572
+ };
1573
+ ` : "";
1574
+ const vectorsStub = hasVectors ? `
1575
+ const vectorsStub: VectorSearchLike = {
1576
+ deleteByIds: async () => {
1577
+ throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
1578
+ },
1579
+ getByIds: async () => {
1580
+ throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
1581
+ },
1582
+ query: async () => {
1583
+ throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
1584
+ },
1585
+ upsert: async () => {
1586
+ throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
1587
+ },
1588
+ upsertNow: async () => {
1589
+ throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
1590
+ },
1591
+ };
1592
+ ` : "";
1593
+ const vectorsBuild = hasVectors ? `
1594
+ let vectors: VectorSearchLike;
1595
+ let onWrite: WriteHook | undefined;
1596
+
1597
+ if (config.vectors) {
1598
+ const lunora = createVectors({ indexes: config.vectors(env) });
1599
+
1600
+ vectors = createContextVectors(lunora);
1601
+ onWrite = createVectorSyncHook({ schema: schema as unknown as VectorSchemaLike, vectors });
1602
+ } else {
1603
+ vectors = vectorsStub;
1604
+ onWrite = undefined;
1605
+ }
1606
+ ` : "";
1607
+ const globalDatabaseField = hasGlobalTables ? "\n globalDb," : "";
1608
+ const authField = "\n auth: { identity: identity ?? null, userId: userId ?? null },";
1609
+ const databaseOptions = hasVectors ? `{${authField}
1610
+ broadcast: (delta) => {
1611
+ this.recordChangedTable(delta.table);
1612
+ },
1613
+ cdc: config.cdc ?? false,
1614
+ enforceRls: true,
1615
+ onIndexUse: this.getCtxDbIndexUseHook(),
1616
+ onRead: options.onRead ?? this.getCtxDbReadHook(),
1617
+ onWrite,
1618
+ scheduler,
1619
+ schema: schema as unknown as SchemaLike,
1620
+ sql: this.sql as SqlExec,
1621
+ storage,${globalDatabaseField}
1622
+ }` : `{${authField}
1623
+ broadcast: (delta) => {
1624
+ this.recordChangedTable(delta.table);
1625
+ },
1626
+ cdc: config.cdc ?? false,
1627
+ enforceRls: true,
1628
+ onIndexUse: this.getCtxDbIndexUseHook(),
1629
+ onRead: options.onRead ?? this.getCtxDbReadHook(),
1630
+ scheduler,
1631
+ schema: schema as unknown as SchemaLike,
1632
+ sql: this.sql as SqlExec,
1633
+ storage,${globalDatabaseField}
1634
+ }`;
1635
+ const vectorsContextField = hasVectors ? `
1636
+ vectors,` : "";
1637
+ const ormContextField = hasTables ? `
1638
+ orm: bindOrm(facade),` : "";
1639
+ const bindTableHelper = "";
1640
+ const globalDatabaseThunk = hasHyperdriveGlobal ? "config.hyperdriveGlobal" : "config.d1";
1641
+ const globalDatabaseLine = hasGlobalTables ? ` const globalDb: DatabaseWriterLike = ${globalDatabaseThunk}?.(env, { identity, userId }) ?? globalDbStub;
1642
+ ` : "";
1643
+ const facadeBlock = hasTables ? `
1644
+ const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1645
+ ${schema.tables.map(
1646
+ // Always bind through `db` (the shard ctx-db) — even for `.global()`
1647
+ // tables. `createShardCtxDb` routes global ops to the D1 `globalDb`
1648
+ // internally AND stamps the read-dependency / change-broadcast hooks that
1649
+ // drive live subscriptions; binding a global facade straight to `globalDb`
1650
+ // would skip those, so a `ctx.db.<global>` read/write would never refresh
1651
+ // a subscriber of that table.
1652
+ (table) => ` facade[${JSON.stringify(table.name)}] = bindTableFacade(db, ${JSON.stringify(table.name)});`
1653
+ ).join("\n")}
1654
+ ` : "";
1655
+ const everyContextBuild = `${kvFragments.build}${analyticsFragments.build}`;
1656
+ const everyContextField = `${kvFragments.contextField}${analyticsFragments.contextField}`;
1657
+ const actionOnlyHasAny = hasImages || hasHyperdrive || hasBrowser;
1658
+ const actionOnlyBlock = actionOnlyHasAny ? `
1659
+ // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1660
+ // and attached only for an \`action\` so query/mutation ctx never carry them.
1661
+ if (isAction) {
1662
+ ${imagesFragments.build}${hyperdriveFragments.build}${browserFragments.build}${[
1663
+ ...hasImages ? [" ctx.images = images;"] : [],
1664
+ ...hasHyperdrive ? [" ctx.sql = sql;"] : [],
1665
+ ...hasBrowser ? [" ctx.browser = browser;"] : []
1666
+ ].join("\n")}
1667
+ }
1668
+ ` : "";
1669
+ const isActionLine = actionOnlyHasAny ? ` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1670
+ ` : "";
1671
+ return `${GENERATED_HEADER}${importLines.join("\n")}
1672
+
1673
+ type FunctionKind = "action" | "mutation" | "query";
1674
+
1675
+ interface FunctionReference {
1676
+ __lunoraRef: string;
1677
+ }
1678
+
1679
+ /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1680
+ const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(tableReferences, void 0, 4)};
1681
+
1682
+ /** Declared indexes per table (secondary, search, rank, vector) for the schema viewer. */
1683
+ const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(tableIndexes, void 0, 4)};
1684
+
1685
+ /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1686
+ const LUNORA_TABLE_COLUMNS: Record<string, Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }>> = ${JSON.stringify(tableColumns, void 0, 4)};
1687
+
1688
+ /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1689
+ const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(storageColumns, void 0, 4)};
1690
+
1691
+ /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1692
+ const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(advisoryData, void 0, 4)};
1693
+
1694
+ /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1695
+ const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(rlsData, void 0, 4)};
1696
+
1697
+ /** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
1698
+ const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(maskData, void 0, 4)};
1699
+
1700
+ /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1701
+ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(storageRulesData, void 0, 4)};
1702
+
1703
+ /** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
1704
+ const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(studioFeaturesData, void 0, 4)};
1705
+ ${workflowsMetadataConst}${containerSpecs}${workflowSpecs}
1706
+ export interface ShardDOConfig {
1707
+ /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1708
+ cdc?: boolean;
1709
+ /** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
1710
+ observability?: (env: Record<string, unknown>) => LogSink | undefined;
1711
+ scheduler?: (env: Record<string, unknown>) => unknown;
1712
+ storage?: (env: Record<string, unknown>) => unknown;${vectorsConfigField}${aiConfigField}${kvFragments.configField}${analyticsFragments.configField}${imagesFragments.configField}${hyperdriveFragments.configField}${browserFragments.configField}${paymentsConfigField}${d1ConfigField}${hyperdriveGlobalConfigField}
1713
+ }
1714
+
1715
+ const schedulerStub = {
1716
+ cancel: async () => {
1717
+ throw new Error("ctx.scheduler: no scheduler configured. Pass \`scheduler\` to createShardDO().");
1718
+ },
1719
+ runAfter: async () => {
1720
+ throw new Error("ctx.scheduler: no scheduler configured. Pass \`scheduler\` to createShardDO().");
1721
+ },
1722
+ runAt: async () => {
1723
+ throw new Error("ctx.scheduler: no scheduler configured. Pass \`scheduler\` to createShardDO().");
1724
+ },
1725
+ };
1726
+
1727
+ const storageStub = {
1728
+ delete: async () => {
1729
+ throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
1730
+ },
1731
+ download: async () => {
1732
+ throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
1733
+ },
1734
+ getMetadata: async () => {
1735
+ throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
1736
+ },
1737
+ getSignedUrl: async () => {
1738
+ throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
1739
+ },
1740
+ getUrl: () => {
1741
+ throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
1742
+ },
1743
+ list: async () => {
1744
+ throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
1745
+ },
1746
+ upload: async () => {
1747
+ throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
1748
+ },
1749
+ };
1750
+ ${globalDatabaseStub}${vectorsStub}${aiStub}${kvFragments.stub}${analyticsFragments.stub}${imagesFragments.stub}${hyperdriveFragments.stub}${browserFragments.stub}${paymentStub}${bindTableHelper}
1751
+ // Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
1752
+ // referencing call fails loudly with a clear error instead of overflowing the
1753
+ // stack. Tracked across the awaited handler chain (one DO invocation is
1754
+ // single-threaded), so the counter reflects true nesting depth.
1755
+ const MAX_RUN_DEPTH = 32;
1756
+ let runDepth = 0;
1757
+
1758
+ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: Record<string, unknown>, ctx: unknown): Promise<unknown> => {
1759
+ const registered = LUNORA_FUNCTIONS[functionPath];
1760
+
1761
+ if (!registered) {
1762
+ throw new Error(\`unknown function: \${functionPath}\`);
1763
+ }
1764
+
1765
+ if (registered.kind !== expected) {
1766
+ throw new Error(\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: "\${functionPath}" is registered as a \${registered.kind}, not a \${expected}\`);
1767
+ }
1768
+
1769
+ if (runDepth >= MAX_RUN_DEPTH) {
1770
+ throw Object.assign(new Error(\`ctx.run*: composition depth limit (\${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation\`), {
1771
+ name: "LunoraError",
1772
+ code: "RUN_DEPTH_EXCEEDED",
1773
+ status: 500,
1774
+ });
1775
+ }
1776
+
1777
+ runDepth += 1;
1778
+
1779
+ try {
1780
+ return await registered.handler(ctx, args);
1781
+ } finally {
1782
+ runDepth -= 1;
1783
+ }
1784
+ };
1785
+
1786
+ /**
1787
+ * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1788
+ * from the worker entry so wrangler binds it by name.
1789
+ */
1790
+ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1791
+ class extends ShardDOBase {
1792
+ private migrated = false;
1793
+
1794
+ public override async handleRpc(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
1795
+ const registered = LUNORA_FUNCTIONS[functionPath];
1796
+
1797
+ // Internal functions are reachable server-side only: via \`ctx.run*\`
1798
+ // composition, or a trusted system dispatch (scheduler/cron, marked by
1799
+ // \`isSystemDispatch()\`). A client RPC never carries that flag, so its
1800
+ // internals stay not-found and never leak across the external boundary.
1801
+ if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) {
1802
+ throw Object.assign(new Error(\`function not registered: \${functionPath}\`), {
1803
+ name: "LunoraError",
1804
+ code: "FUNCTION_NOT_FOUND",
1805
+ status: 404,
1806
+ });
1807
+ }
1808
+
1809
+ this.ensureMigrated();
1810
+
1811
+ const ctx = this.buildCtx({ functionPath });
1812
+
1813
+ // A mutation's writes must commit all-or-nothing: wrap its dispatch in
1814
+ // the DO's BEGIN/COMMIT span so any throw (a validator, an RLS denial,
1815
+ // an OCC conflict, a failed row mid-\`insertMany\`/\`patchMany\`) rolls
1816
+ // back every write the mutation made. Queries are read-only and actions
1817
+ // do external I/O that can't be rolled back, so both dispatch directly.
1818
+ // \`ctx.run*\` composition runs inside this span (it never re-enters
1819
+ // handleRpc); runInTransaction's own guard rejects accidental nesting.
1820
+ if (registered.kind === "mutation") {
1821
+ return this.runInTransaction(() => registered.handler(ctx, args));
1822
+ }
1823
+
1824
+ return registered.handler(ctx, args);
1825
+ }
1826
+ ${relationFanout.override}
1827
+ protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<{ result: unknown; tables: Set<string> } | null> {
1828
+ const registered = LUNORA_FUNCTIONS[functionPath];
1829
+
1830
+ if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
1831
+ return null;
1832
+ }
1833
+
1834
+ this.ensureMigrated();
1835
+
1836
+ const tables = new Set<string>();
1837
+ // Identity is threaded EXPLICITLY from the (deferred/interleaved)
1838
+ // subscription caller — never read from the shared per-request field
1839
+ // here — so a concurrent RPC can't leak its identity into this re-run.
1840
+ const ctx = this.buildCtx({ functionPath, identity, onRead: (table) => tables.add(table) });
1841
+ const result = await registered.handler(ctx, args);
1842
+
1843
+ return { result, tables };
1844
+ }
1845
+
1846
+ protected override executeStream(functionPath: string, args: Record<string, unknown>): null | { iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
1847
+ const registered = LUNORA_FUNCTIONS[functionPath];
1848
+
1849
+ if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
1850
+ return null;
1851
+ }
1852
+
1853
+ this.ensureMigrated();
1854
+
1855
+ return {
1856
+ iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
1857
+ };
1858
+ }
1859
+
1860
+ protected override lifecycleHookPaths(event: "connect" | "disconnect"): readonly string[] {
1861
+ return LUNORA_LIFECYCLE_HOOKS[event];
1862
+ }
1863
+
1864
+ protected override tableRefs(table: string): Record<string, string> | undefined {
1865
+ return LUNORA_TABLE_REFS[table];
1866
+ }
1867
+
1868
+ protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "index" | "rank" | "search" | "vector"; unique?: boolean }> {
1869
+ return LUNORA_TABLE_INDEXES[table] ?? [];
1870
+ }
1871
+
1872
+ protected override tableColumns(table: string): Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }> {
1873
+ return LUNORA_TABLE_COLUMNS[table] ?? [];
1874
+ }
1875
+
1876
+ protected override storageColumns(): Record<string, string[]> {
1877
+ return LUNORA_STORAGE_COLUMNS;
1878
+ }
1879
+
1880
+ protected override rlsMetadata(): RlsPoliciesResult {
1881
+ return LUNORA_RLS_METADATA;
1882
+ }
1883
+
1884
+ protected override maskMetadata(): MaskPoliciesResult {
1885
+ return LUNORA_MASK_METADATA;
1886
+ }
1887
+
1888
+ protected override storageRulesMetadata(): StorageRulesResult {
1889
+ return LUNORA_STORAGE_RULES;
1890
+ }
1891
+
1892
+ protected override studioFeatures(): StudioFeaturesResult {
1893
+ return LUNORA_STUDIO_FEATURES;
1894
+ }
1895
+ ${workflowsMetadataOverride}
1896
+ protected override advisories(): AdvisoryFinding[] {
1897
+ return LUNORA_ADVISORIES;
1898
+ }
1899
+
1900
+ protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
1901
+ const migration = LUNORA_MIGRATIONS[args.id];
1902
+
1903
+ if (!migration) {
1904
+ throw Object.assign(new Error(\`data migration "\${args.id}" is not registered\`), {
1905
+ name: "LunoraError",
1906
+ code: "MIGRATION_NOT_FOUND",
1907
+ status: 404,
1908
+ });
1909
+ }
1910
+
1911
+ this.ensureMigrated();
1912
+
1913
+ const env = (this.env ?? {}) as Record<string, unknown>;
1914
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1915
+ const writer = createShardCtxDb({
1916
+ broadcast: (delta) => {
1917
+ this.recordChangedTable(delta.table);
1918
+ },
1919
+ cdc: config.cdc ?? false,
1920
+ scheduler,
1921
+ schema: schema as unknown as SchemaLike,
1922
+ sql: this.sql as SqlExec,
1923
+ });
1924
+
1925
+ return runDataMigration({
1926
+ batchSize: args.batchSize,
1927
+ direction: args.direction,
1928
+ dryRun: args.dryRun,
1929
+ maxBatches: args.maxBatches,
1930
+ migration: migration as unknown as DataMigrationLike,
1931
+ // Flush after each batch so live migrationStatus subscribers see
1932
+ // progress mid-run (the base method records the reserved state
1933
+ // table the raw-SQL progress write is invisible to the tracker).
1934
+ onBatch: () => this.flushMigrationProgress(),
1935
+ sql: this.sql as SqlExec,
1936
+ writer,
1937
+ });
1938
+ }
1939
+
1940
+ protected override async runShardWrite(args: RunShardWriteArgs): Promise<RunShardWriteResult> {
1941
+ const definition = (schema as unknown as SchemaLike).tables[args.table];
1942
+
1943
+ if (!definition) {
1944
+ throw Object.assign(new Error(\`unknown table: \${args.table}\`), { name: "LunoraError", code: "UNKNOWN_TABLE", status: 404 });
1945
+ }
1946
+
1947
+ // \`.global()\` tables live in D1, not this DO's SQLite — editing them
1948
+ // here would corrupt nothing but would fail confusingly, so reject up
1949
+ // front with a clear code the studio can surface.
1950
+ if (definition.shardMode?.kind === "global") {
1951
+ throw Object.assign(new Error(\`table "\${args.table}" is global; edit it through D1, not the shard\`), {
1952
+ name: "LunoraError",
1953
+ code: "GLOBAL_TABLE_NOT_EDITABLE",
1954
+ status: 400,
1955
+ });
1956
+ }
1957
+
1958
+ this.ensureMigrated();
1959
+
1960
+ const env = (this.env ?? {}) as Record<string, unknown>;
1961
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1962
+ const writer = createShardCtxDb({
1963
+ broadcast: (delta) => {
1964
+ this.recordChangedTable(delta.table);
1965
+ },
1966
+ cdc: config.cdc ?? false,
1967
+ scheduler,
1968
+ schema: schema as unknown as SchemaLike,
1969
+ sql: this.sql as SqlExec,
1970
+ });
1971
+
1972
+ if (args.op === "insert") {
1973
+ const id = await writer.insert(args.table, args.doc ?? {});
1974
+
1975
+ return { id, op: "insert" };
1976
+ }
1977
+
1978
+ if (args.op === "delete") {
1979
+ await writer.delete(args.id ?? "");
1980
+
1981
+ return { id: args.id ?? null, op: "delete" };
1982
+ }
1983
+
1984
+ if (args.op === "replace") {
1985
+ await writer.replace(args.id ?? "", args.doc ?? {});
1986
+
1987
+ return { id: args.id ?? null, op: "replace" };
1988
+ }
1989
+
1990
+ await writer.patch(args.id ?? "", args.doc ?? {});
1991
+
1992
+ return { id: args.id ?? null, op: "patch" };
1993
+ }
1994
+
1995
+ protected override async deleteRowThroughWriter(table: string, id: string): Promise<void> {
1996
+ const definition = (schema as unknown as SchemaLike).tables[table];
1997
+
1998
+ if (!definition) {
1999
+ throw Object.assign(new Error(\`unknown table: \${table}\`), { name: "LunoraError", code: "UNKNOWN_TABLE", status: 404 });
2000
+ }
2001
+
2002
+ // \`.global()\` tables live in D1, not this DO's SQLite — the same
2003
+ // guard \`runShardWrite\` applies to single-row edits.
2004
+ if (definition.shardMode?.kind === "global") {
2005
+ throw Object.assign(new Error(\`table "\${table}" is global; edit it through D1, not the shard\`), {
2006
+ name: "LunoraError",
2007
+ code: "GLOBAL_TABLE_NOT_EDITABLE",
2008
+ status: 400,
2009
+ });
2010
+ }
2011
+
2012
+ this.ensureMigrated();
2013
+
2014
+ const env = (this.env ?? {}) as Record<string, unknown>;
2015
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
2016
+ const writer = createShardCtxDb({
2017
+ broadcast: (delta) => {
2018
+ this.recordChangedTable(delta.table);
2019
+ },
2020
+ cdc: config.cdc ?? false,
2021
+ scheduler,
2022
+ schema: schema as unknown as SchemaLike,
2023
+ sql: this.sql as SqlExec,
2024
+ });
2025
+
2026
+ // Routes through the writer (not raw SQL) so FTS / aggregate / rank
2027
+ // shadow tables stay in sync and \`onDelete\` cascades fire — the
2028
+ // bounded loop lives in the base \`runShardBulkDelete\`.
2029
+ await writer.delete(id);
2030
+ }
2031
+
2032
+ protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
2033
+ this.ensureMigrated();
2034
+
2035
+ const env = (this.env ?? {}) as Record<string, unknown>;
2036
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
2037
+ const writer = createShardCtxDb({
2038
+ broadcast: (delta) => {
2039
+ this.recordChangedTable(delta.table);
2040
+ },
2041
+ cdc: config.cdc ?? false,
2042
+ scheduler,
2043
+ schema: schema as unknown as SchemaLike,
2044
+ sql: this.sql as SqlExec,
2045
+ });
2046
+
2047
+ // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2048
+ // but the shard writer from \`createShardCtxDb\` always defines it.
2049
+ if (!writer.rankBefore) {
2050
+ throw Object.assign(new Error("rankBefore is unavailable on the shard writer"), { name: "LunoraError", code: "NOT_IMPLEMENTED", status: 500 });
2051
+ }
2052
+
2053
+ return writer.rankBefore(args.table, args.index, {
2054
+ partitionKey: args.partitionKey,
2055
+ rowId: args.rowId,
2056
+ sortValues: args.sortValues,
2057
+ });
2058
+ }
2059
+
2060
+ protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
2061
+ this.ensureMigrated();
2062
+
2063
+ const env = (this.env ?? {}) as Record<string, unknown>;
2064
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
2065
+ const writer = createShardCtxDb({
2066
+ broadcast: (delta) => {
2067
+ this.recordChangedTable(delta.table);
2068
+ },
2069
+ cdc: config.cdc ?? false,
2070
+ scheduler,
2071
+ schema: schema as unknown as SchemaLike,
2072
+ sql: this.sql as SqlExec,
2073
+ });
2074
+
2075
+ // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2076
+ // but the shard writer from \`createShardCtxDb\` always defines it. The sort
2077
+ // directions live in the schema's rankIndex, so the shard reads them itself;
2078
+ // \`args.directions\` is only the coordinator's comparator hint and isn't forwarded.
2079
+ if (!writer.rankPageRows) {
2080
+ throw Object.assign(new Error("rankPage is unavailable on the shard writer"), { name: "LunoraError", code: "NOT_IMPLEMENTED", status: 500 });
2081
+ }
2082
+
2083
+ return writer.rankPageRows(args.table, args.index, {
2084
+ after: args.after,
2085
+ cursor: args.cursor,
2086
+ partitionKey: args.partitionKey,
2087
+ take: args.take,
2088
+ });
2089
+ }
2090
+
2091
+ protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
2092
+ this.ensureMigrated();
2093
+
2094
+ const env = (this.env ?? {}) as Record<string, unknown>;
2095
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
2096
+ const writer = createShardCtxDb({
2097
+ broadcast: (delta) => {
2098
+ this.recordChangedTable(delta.table);
2099
+ },
2100
+ cdc: config.cdc ?? false,
2101
+ scheduler,
2102
+ schema: schema as unknown as SchemaLike,
2103
+ sql: this.sql as SqlExec,
2104
+ });
2105
+
2106
+ await applyCdcChanges(writer, args.changes);
2107
+
2108
+ return { applied: args.changes.length };
2109
+ }
2110
+
2111
+ protected override ensureMigrated(): void {
2112
+ if (this.migrated) {
2113
+ return;
2114
+ }
2115
+
2116
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false });
2117
+ this.migrated = true;
2118
+ }
2119
+
2120
+ private buildCtx(options: { functionPath?: string; identity?: { identity?: Record<string, unknown>; userId?: string }; onRead?: (table: string) => void } = {}): unknown {
2121
+ const env = (this.env ?? {}) as Record<string, unknown>;
2122
+ // When the caller threads an explicit identity (subscription seed /
2123
+ // refresh — both run in deferred/interleaved contexts), use it by
2124
+ // value and NEVER read the shared per-request identity field, which a
2125
+ // concurrent RPC may have re-set. Otherwise (the synchronous RPC
2126
+ // dispatch path) fall back to the per-request fields as before.
2127
+ const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
2128
+ const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
2129
+ ${vectorsBuild}${aiBuild}${everyContextBuild}${containersBuild}${workflowsBuild}
2130
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
2131
+ // Build the storage adapter once and share it between \`ctx.storage\`
2132
+ // and \`ctx.db.system._storage\` so both read the same R2 binding. The
2133
+ // \`storageStub\` fallback satisfies SystemReaderStorageLike structurally
2134
+ // (its \`list\`/\`getMetadata\` throw the "no storage configured" error).
2135
+ const storage = asBucketStorage(config.storage?.(env) ?? storageStub) as unknown as SystemReaderStorageLike;
2136
+ ${globalDatabaseLine} const db: DatabaseWriterLike = createShardCtxDb(${databaseOptions});
2137
+ ${facadeBlock}${paymentsBuild}
2138
+ // \`ctx.log\`: each call is captured + attributed to the executing
2139
+ // function and routed to the optional \`observability\` sink. The DO base
2140
+ // also buffers it (studio Logs panel) and emits a structured console
2141
+ // event the dev-server formats in the terminal.
2142
+ const observability = config.observability?.(env);
2143
+ const logFunctionPath = options.functionPath ?? "";
2144
+ const log = {
2145
+ debug: (...args: unknown[]) => { this.recordUserLog(logFunctionPath, "debug", args, observability); },
2146
+ error: (...args: unknown[]) => { this.recordUserLog(logFunctionPath, "error", args, observability); },
2147
+ info: (...args: unknown[]) => { this.recordUserLog(logFunctionPath, "info", args, observability); },
2148
+ log: (...args: unknown[]) => { this.recordUserLog(logFunctionPath, "log", args, observability); },
2149
+ warn: (...args: unknown[]) => { this.recordUserLog(logFunctionPath, "warn", args, observability); },
2150
+ };
2151
+
2152
+ const ctx: Record<string, unknown> = {
2153
+ auth: {
2154
+ getIdentity: async () => identity ?? null,
2155
+ userId: userId ?? null,
2156
+ },
2157
+ db,
2158
+ fetch: globalThis.fetch.bind(globalThis),
2159
+ ip: this.getCurrentIp(),
2160
+ log,${ormContextField}
2161
+ scheduler,
2162
+ storage,${vectorsContextField}${aiContextField}${everyContextField}${paymentsContextField}${containersContextField}${workflowsContextField}
2163
+ };
2164
+ ${isActionLine}${actionOnlyBlock}
2165
+ ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
2166
+ ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
2167
+ ctx.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("query", reference.__lunoraRef, fnArgs, ctx);
2168
+
2169
+ return ctx;
2170
+ }
2171
+ };
2172
+ `;
2173
+ };
2174
+ const validatorToDrizzleColumn = (validator) => {
2175
+ switch (validator.kind) {
2176
+ case "array":
2177
+ case "object":
2178
+ case "record":
2179
+ case "union": {
2180
+ return {
2181
+ builder: "text",
2182
+ mode: "json",
2183
+ notNull: true,
2184
+ typeAnnotation: validatorToType(validator)
2185
+ };
2186
+ }
2187
+ case "bigint": {
2188
+ return { builder: "blob", mode: "bigint", notNull: true };
2189
+ }
2190
+ case "boolean": {
2191
+ return { builder: "integer", mode: "boolean", notNull: true };
2192
+ }
2193
+ case "bytes": {
2194
+ return { builder: "blob", mode: "buffer", notNull: true };
2195
+ }
2196
+ case "date":
2197
+ case "timestamp": {
2198
+ return { builder: "integer", notNull: true };
2199
+ }
2200
+ case "id": {
2201
+ return { builder: "text", notNull: true };
2202
+ }
2203
+ case "literal": {
2204
+ const value = validator.literalValue ?? "";
2205
+ if (value.startsWith('"') || value.startsWith("'")) {
2206
+ return { builder: "text", notNull: true };
2207
+ }
2208
+ if (value === "true" || value === "false") {
2209
+ return { builder: "integer", mode: "boolean", notNull: true };
2210
+ }
2211
+ if (value === "null") {
2212
+ return { builder: "text", notNull: true };
2213
+ }
2214
+ return { builder: "real", notNull: true };
2215
+ }
2216
+ case "null": {
2217
+ return { builder: "text", notNull: true };
2218
+ }
2219
+ case "number": {
2220
+ return { builder: "real", notNull: true };
2221
+ }
2222
+ case "optional": {
2223
+ const inner = validator.inner ? validatorToDrizzleColumn(validator.inner) : { builder: "text", notNull: false };
2224
+ return { ...inner, notNull: false };
2225
+ }
2226
+ case "storage":
2227
+ case "string": {
2228
+ return { builder: "text", notNull: true };
2229
+ }
2230
+ default: {
2231
+ return { builder: "text", notNull: true };
2232
+ }
2233
+ }
2234
+ };
2235
+ const renderDrizzleColumn = (name, validator, knownTables) => {
2236
+ assertIdentifier(name, "drizzle column name");
2237
+ const column = validatorToDrizzleColumn(validator);
2238
+ const isOptional = validator.kind === "optional";
2239
+ const innerValidator = isOptional && validator.inner ? validator.inner : validator;
2240
+ const modeArgument = column.mode ? `, { mode: "${column.mode}" }` : "";
2241
+ let expression = `${column.builder}("${name}"${modeArgument})`;
2242
+ if (column.typeAnnotation) {
2243
+ expression += `.$type<${column.typeAnnotation}>()`;
2244
+ }
2245
+ if (innerValidator.kind === "id" && innerValidator.tableName && knownTables.has(innerValidator.tableName)) {
2246
+ expression += `.references(() => ${innerValidator.tableName}._id)`;
2247
+ }
2248
+ if (column.notNull) {
2249
+ expression += ".notNull()";
2250
+ }
2251
+ return expression;
2252
+ };
2253
+ const renderIndexEntry = (index) => {
2254
+ assertIdentifier(index.name, "drizzle index name");
2255
+ const constructor = index.unique ? "uniqueIndex" : "index";
2256
+ const fields = index.fields.map((field) => {
2257
+ assertIdentifier(field, "drizzle index field");
2258
+ return `t.${field}`;
2259
+ }).join(", ");
2260
+ return ` ${index.name}: ${constructor}("${index.name}").on(${fields}),`;
2261
+ };
2262
+ const renderDrizzleTable = (table, knownTables) => {
2263
+ assertIdentifier(table.name, "table name");
2264
+ const columns = [
2265
+ ` _id: text("_id").primaryKey(),`,
2266
+ ` _creationTime: integer("_creationTime").notNull(),`,
2267
+ ...Object.entries(table.shape).map(([fieldName, validator]) => ` ${fieldName}: ${renderDrizzleColumn(fieldName, validator, knownTables)},`)
2268
+ ].join("\n");
2269
+ const indexBody = table.indexes.length > 0 ? `, (t) => ({
2270
+ ${table.indexes.map((index) => renderIndexEntry(index)).join("\n")}
2271
+ })` : "";
2272
+ return `export const ${table.name} = sqliteTable("${table.name}", {
2273
+ ${columns}
2274
+ }${indexBody});`;
2275
+ };
2276
+ const usedImports = (tables) => {
2277
+ const columns = /* @__PURE__ */ new Set();
2278
+ const indexes = /* @__PURE__ */ new Set();
2279
+ columns.add("text");
2280
+ columns.add("integer");
2281
+ columns.add("sqliteTable");
2282
+ for (const table of tables) {
2283
+ for (const validator of Object.values(table.shape)) {
2284
+ const column = validatorToDrizzleColumn(validator);
2285
+ columns.add(column.builder);
2286
+ }
2287
+ for (const index of table.indexes) {
2288
+ indexes.add(index.unique ? "uniqueIndex" : "index");
2289
+ }
2290
+ }
2291
+ return { columns: [...columns].toSorted((a, b) => a.localeCompare(b)), indexes: [...indexes].toSorted((a, b) => a.localeCompare(b)) };
2292
+ };
2293
+ const renderDrizzleFile = (tables, useUmbrella = false) => {
2294
+ if (tables.length === 0) {
2295
+ return `${GENERATED_HEADER}export {};
2296
+ `;
2297
+ }
2298
+ const base = baseSpecifiers(useUmbrella);
2299
+ const { columns, indexes } = usedImports(tables);
2300
+ const importParts = [...indexes, ...columns].toSorted((a, b) => a.localeCompare(b));
2301
+ const knownTables = new Set(tables.map((table) => table.name));
2302
+ const tableBlocks = tables.map((table) => renderDrizzleTable(table, knownTables)).join("\n\n");
2303
+ return `${GENERATED_HEADER}import { ${importParts.join(", ")} } from "${base.serverDrizzle}";
2304
+
2305
+ ${tableBlocks}
2306
+ `;
2307
+ };
2308
+ const emitDrizzleSchema = (schema, useUmbrella = false) => {
2309
+ const globalTables = schema.tables.filter((table) => table.shardMode === "global");
2310
+ const shardTables = schema.tables.filter((table) => table.shardMode !== "global");
2311
+ return {
2312
+ global: renderDrizzleFile(globalTables, useUmbrella),
2313
+ shard: renderDrizzleFile(shardTables, useUmbrella)
2314
+ };
2315
+ };
2316
+ const emitCrons = (crons) => {
2317
+ const triggers = [];
2318
+ const byExpression = /* @__PURE__ */ new Map();
2319
+ for (const cron of crons) {
2320
+ const existing = byExpression.get(cron.cron);
2321
+ if (existing) {
2322
+ existing.push(cron);
2323
+ } else {
2324
+ byExpression.set(cron.cron, [cron]);
2325
+ triggers.push(cron.cron);
2326
+ }
2327
+ }
2328
+ const triggerEntries = triggers.map((expression) => ` ${JSON.stringify(expression)},`).join("\n");
2329
+ const triggerBody = triggerEntries.length > 0 ? `
2330
+ ${triggerEntries}
2331
+ ` : "";
2332
+ const mapEntries = [...byExpression.entries()].map(([expression, jobs]) => {
2333
+ const jobEntries = jobs.map((job) => {
2334
+ const targetField = job.workflow ? `workflow: ${JSON.stringify(job.workflow.binding)}` : `functionPath: ${JSON.stringify(job.functionPath)}`;
2335
+ return ` { name: ${JSON.stringify(job.name)}, ${targetField}, args: ${JSON.stringify(job.args)} },`;
2336
+ }).join("\n");
2337
+ return ` ${JSON.stringify(expression)}: [
2338
+ ${jobEntries}
2339
+ ],`;
2340
+ }).join("\n");
2341
+ const mapBody = mapEntries.length > 0 ? `
2342
+ ${mapEntries}
2343
+ ` : "";
2344
+ return `${GENERATED_HEADER}/**
2345
+ * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
2346
+ * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
2347
+ * shard; \`workflow\` is a \`WORKFLOW_*\` binding name whose durable workflow is
2348
+ * started fresh per fire. \`args\` are forwarded verbatim (a workflow's become
2349
+ * its \`params\`).
2350
+ */
2351
+ export interface LunoraCronJob {
2352
+ args: Record<string, unknown>;
2353
+ functionPath?: string;
2354
+ name: string;
2355
+ workflow?: string;
2356
+ }
2357
+
2358
+ /**
2359
+ * Deduplicated cron schedules — mirror of wrangler's \`triggers.crons\`. The
2360
+ * Lunora vite plugin keeps \`wrangler.jsonc\` in sync with this array.
2361
+ */
2362
+ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${triggerBody}];
2363
+
2364
+ /**
2365
+ * Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
2366
+ * looks up \`event.cron\` here and dispatches every job in the list.
2367
+ */
2368
+ export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${mapBody}};
2369
+ `;
2370
+ };
2371
+ const emitVectors = (vectorIndexes) => {
2372
+ const entries = [...vectorIndexes].toSorted((a, b) => a.name.localeCompare(b.name)).map((index) => {
2373
+ const parts = [`name: ${JSON.stringify(index.name)}`, `table: ${JSON.stringify(index.table)}`];
2374
+ if (index.field !== void 0) {
2375
+ parts.push(`field: ${JSON.stringify(index.field)}`);
2376
+ }
2377
+ if (index.dimensions !== void 0) {
2378
+ parts.push(`dimensions: ${JSON.stringify(index.dimensions)}`);
2379
+ }
2380
+ if (index.metric !== void 0) {
2381
+ parts.push(`metric: ${JSON.stringify(index.metric)}`);
2382
+ }
2383
+ if (index.metadata !== void 0) {
2384
+ parts.push(`metadata: ${JSON.stringify(index.metadata)}`);
2385
+ }
2386
+ return ` { ${parts.join(", ")} },`;
2387
+ }).join("\n");
2388
+ const body = entries.length > 0 ? `
2389
+ ${entries}
2390
+ ` : "";
2391
+ return `${GENERATED_HEADER}/**
2392
+ * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
2393
+ * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
2394
+ * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
2395
+ * mirrored into Vectorize for filtering.
2396
+ */
2397
+ export interface LunoraVectorIndex {
2398
+ dimensions?: number;
2399
+ field?: string;
2400
+ metadata?: ReadonlyArray<string>;
2401
+ metric?: "cosine" | "dot-product" | "euclidean";
2402
+ name: string;
2403
+ table: string;
2404
+ }
2405
+
2406
+ /**
2407
+ * Static registry of every vector index in the schema, sorted by name.
2408
+ * Vectorize cannot enumerate indexes at runtime, so the worker passes this to
2409
+ * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2410
+ */
2411
+ export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${body}];
2412
+ `;
2413
+ };
2414
+ const emitWranglerCronTriggers = (crons) => {
2415
+ const seen = /* @__PURE__ */ new Set();
2416
+ const triggers = [];
2417
+ for (const cron of crons) {
2418
+ if (!seen.has(cron.cron)) {
2419
+ seen.add(cron.cron);
2420
+ triggers.push(cron.cron);
2421
+ }
2422
+ }
2423
+ return triggers;
2424
+ };
2425
+
2426
+ export { GENERATED_HEADER, buildStorageColumns, emitApi, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitSeed, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers };