@lunora/codegen 1.0.0-alpha.324 → 1.0.0-alpha.326

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 (35) hide show
  1. package/dist/index.d.mts +25 -11
  2. package/dist/index.d.ts +25 -11
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/DEFAULT_TARGET-BbWiB-rs.mjs +1 -0
  5. package/dist/packem_shared/{NOTIFY_FILENAME-bAt7J3cs.mjs → NOTIFY_FILENAME-DiYZjYts.mjs} +1 -1
  6. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-WbrlAts0.mjs +11 -0
  7. package/dist/packem_shared/chain-DYBhMcDK.mjs +1 -0
  8. package/dist/packem_shared/classify-procedure-call-DUBO9bqm.mjs +1 -0
  9. package/dist/packem_shared/{context-property-calls-Cn3upNgZ.mjs → context-property-calls-eO5eiVZG.mjs} +1 -1
  10. package/dist/packem_shared/{context-root-BdxINX-T.mjs → context-root-D-pTjHtx.mjs} +1 -1
  11. package/dist/packem_shared/{database-calls-BKozZUEW.mjs → database-calls-DJgmh0Kv.mjs} +1 -1
  12. package/dist/packem_shared/discoverFunctions-CIJja4zp.mjs +1 -0
  13. package/dist/packem_shared/discoverHyperdriveCalls-DVIQ0i_e.mjs +1 -0
  14. package/dist/packem_shared/{discoverInserts-BjxXCACZ.mjs → discoverInserts-CednbRCq.mjs} +1 -1
  15. package/dist/packem_shared/discoverMaskProcedures-B4k9BS0s.mjs +1 -0
  16. package/dist/packem_shared/{discoverNondeterministicCalls-DvhyKM-f.mjs → discoverNondeterministicCalls-B6FUSWes.mjs} +1 -1
  17. package/dist/packem_shared/{discoverQueries-C8E7TeRT.mjs → discoverQueries-BezURxvr.mjs} +1 -1
  18. package/dist/packem_shared/discoverR2sqlCalls-B9Q6xfi6.mjs +1 -0
  19. package/dist/packem_shared/{discoverRlsMetadata-QRsWRQbM.mjs → discoverRlsMetadata-DCgP2H39.mjs} +1 -1
  20. package/dist/packem_shared/{discoverRlsProcedures-Du7ITNTQ.mjs → discoverRlsProcedures-Os1lrVX_.mjs} +1 -1
  21. package/dist/packem_shared/{discoverStorageRulesMetadata-ClzKLdCV.mjs → discoverStorageRulesMetadata-BTD9Vs5X.mjs} +1 -1
  22. package/dist/packem_shared/{emitFunctions-CuZzKaU4.mjs → emitFunctions-Cg0JxGpk.mjs} +130 -76
  23. package/dist/packem_shared/{emitShard-BF--3qQv.mjs → emitShard-Ba8hJ_G8.mjs} +1 -1
  24. package/dist/packem_shared/{exported-procedure-chains-BNBUkXui.mjs → exported-procedure-chains-DOFtzPZn.mjs} +1 -1
  25. package/dist/packem_shared/{index-JnqBWRYO.mjs → index-iWQbulvu.mjs} +1 -1
  26. package/dist/packem_shared/{shard-ceGu_Fps.mjs → shard-BtImwCVL.mjs} +95 -92
  27. package/package.json +9 -9
  28. package/dist/packem_shared/DEFAULT_TARGET-DXhxbij-.mjs +0 -1
  29. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CXmfa4xx.mjs +0 -11
  30. package/dist/packem_shared/chain-Cm6BMT8g.mjs +0 -1
  31. package/dist/packem_shared/classify-procedure-call-DVxdUhZt.mjs +0 -1
  32. package/dist/packem_shared/discoverFunctions-CZgLhsMn.mjs +0 -1
  33. package/dist/packem_shared/discoverHyperdriveCalls-DV4IglLE.mjs +0 -1
  34. package/dist/packem_shared/discoverMaskProcedures-DE-8CDen.mjs +0 -1
  35. package/dist/packem_shared/discoverR2sqlCalls-DVcfMO6-.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{LunoraError as Nt}from"@lunora/errors";import{serializeSchemaSnapshot as Mt,hashSchemaSnapshot as $t}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as qt,isD1GlobalTable as Ft}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Ut}from"./json-data-Chfs2Cz5.mjs";import{r as I,e as Bt,a as jt,b as Wt,c as Ht,d as Vt,f as Kt,g as Gt,h as Qt,i as Jt,j as zt,k as Yt,l as Xt,m as Zt,n as er,o as tr,p as rr,q as nr}from"./shard-runtime-BpoCV-aM.mjs";import{u as J,i as ar,G as sr,d as or}from"./shared-DnCokNcE.mjs";import{p as ir}from"./platform-8oj7iXQy.mjs";import{i as dr}from"./schema-BgM8A3XV.mjs";const h=(n,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${e}); })()`,oe=["categories","description","facing","level","remediation","title"],cr=n=>{const e={};return{advisoryRows:n.map(a=>{let r=e[a.name];return r||(r=Object.fromEntries(oe.filter(s=>s in a).map(s=>[s,a[s]])),e[a.name]=r),Object.fromEntries(Object.entries(a).filter(([s,d])=>!oe.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},lr=` /**
1
+ import{LunoraError as $t}from"@lunora/errors";import{serializeSchemaSnapshot as qt,hashSchemaSnapshot as Ft}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Ut,isD1GlobalTable as Bt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as jt}from"./json-data-Chfs2Cz5.mjs";import{r as L,e as Wt,a as Ht,b as Vt,c as Kt,d as Gt,f as Qt,g as Jt,h as zt,i as Yt,j as Xt,k as Zt,l as er,m as tr,n as rr,o as nr,p as ar,q as sr}from"./shard-runtime-BpoCV-aM.mjs";import{u as z,i as or,G as ir,d as dr}from"./shared-DnCokNcE.mjs";import{p as cr}from"./platform-8oj7iXQy.mjs";import{i as lr}from"./schema-BgM8A3XV.mjs";const h=(n,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${e}); })()`,oe=["categories","description","facing","level","remediation","title"],ur=n=>{const e={};return{advisoryRows:n.map(a=>{let r=e[a.name];return r||(r=Object.fromEntries(oe.filter(s=>s in a).map(s=>[s,a[s]])),e[a.name]=r),Object.fromEntries(Object.entries(a).filter(([s,d])=>!oe.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},hr=` /**
2
2
  * The bare writer every admin/maintenance entry point writes through.
3
3
  *
4
4
  * Admin and maintenance writes go through the SAME reactive-cache hooks as a
@@ -30,7 +30,7 @@ import{LunoraError as Nt}from"@lunora/errors";import{serializeSchemaSnapshot as
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,g=(n="")=>` const writer = this.adminWriter(${n});`,ur=`${lr}
33
+ }`,m=(n="")=>` const writer = this.adminWriter(${n});`,pr=`${hr}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -47,7 +47,7 @@ import{LunoraError as Nt}from"@lunora/errors";import{serializeSchemaSnapshot as
47
47
  throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
48
48
  }
49
49
 
50
- ${g()}
50
+ ${m()}
51
51
 
52
52
  return runDataMigration({
53
53
  ...(args.batchSize === undefined ? {} : { batchSize: args.batchSize }),
@@ -80,7 +80,7 @@ ${g()}
80
80
 
81
81
  this.ensureMigrated();
82
82
 
83
- ${g("headroom ?? this.transactionHeadroom()")}
83
+ ${m("headroom ?? this.transactionHeadroom()")}
84
84
 
85
85
  if (args.op === "insert") {
86
86
  const id = await writer.insert(args.table, args.doc ?? {});
@@ -135,7 +135,7 @@ ${g("headroom ?? this.transactionHeadroom()")}
135
135
  protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
136
136
  this.ensureMigrated();
137
137
 
138
- ${g()}
138
+ ${m()}
139
139
 
140
140
  const rows: ExportRow[] = [];
141
141
 
@@ -152,7 +152,7 @@ ${g()}
152
152
  protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
153
153
  this.ensureMigrated();
154
154
 
155
- ${g()}
155
+ ${m()}
156
156
 
157
157
  // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
158
158
  // database's \`_id\`s carry across verbatim and every foreign key
@@ -163,7 +163,7 @@ ${g()}
163
163
  protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
164
164
  this.ensureMigrated();
165
165
 
166
- ${g()}
166
+ ${m()}
167
167
 
168
168
  // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
169
169
  // but the shard writer from \`createShardCtxDb\` always defines it.
@@ -181,7 +181,7 @@ ${g()}
181
181
  protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
182
182
  this.ensureMigrated();
183
183
 
184
- ${g()}
184
+ ${m()}
185
185
 
186
186
  // \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
187
187
  // but the shard writer from \`createShardCtxDb\` always defines it — it
@@ -199,7 +199,7 @@ ${g()}
199
199
  protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
200
200
  this.ensureMigrated();
201
201
 
202
- ${g()}
202
+ ${m()}
203
203
 
204
204
  // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
205
205
  // but the shard writer from \`createShardCtxDb\` always defines it. The sort
@@ -220,18 +220,18 @@ ${g()}
220
220
  protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
221
221
  this.ensureMigrated();
222
222
 
223
- ${g()}
223
+ ${m()}
224
224
 
225
225
  await applyCdcChanges(writer, args.changes);
226
226
 
227
227
  return { applied: args.changes.length };
228
- }`,hr=({actionOnlyBuild:n,actionOnlyFields:e,agentsBuild:t,agentsContextField:a,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:f,everyContextField:v,facadeBlock:c,globalDatabaseLine:l,lazyFunctions:p=!1,notifyBuild:O,ormContextField:R,paymentsBuild:P,paymentsContextField:k,queuesBuild:N,queuesContextField:i,topicsBuild:b,topicsContextField:M,vectorsBuild:$,vectorsContextField:q,workflowsBuild:D,workflowsContextField:F})=>{const T=e.length>0,x=R===""?"{ db }":"{ db, orm: bindOrm(facade) }",u=R===""?"":`
229
- orm: databaseContext.orm,`,C=R===""?"":`
230
- orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,w=T?`
228
+ }`,mr=({actionOnlyBuild:n,actionOnlyFields:e,agentsBuild:t,agentsContextField:a,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:g,everyContextField:y,facadeBlock:c,globalDatabaseLine:f,lazyFunctions:l=!1,notifyBuild:I,ormContextField:v,paymentsBuild:P,paymentsContextField:N,queuesBuild:k,queuesContextField:M,topicsBuild:i,topicsContextField:b,vectorsBuild:$,vectorsContextField:q,workflowsBuild:F,workflowsContextField:A})=>{const D=e.length>0,U=v===""?"{ db }":"{ db, orm: bindOrm(facade) }",x=v===""?"":`
229
+ orm: databaseContext.orm,`,u=v===""?"":`
230
+ orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,T=D?`
231
231
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
232
232
  // and attached only for an \`action\` so query/mutation ctx never carry them.
233
233
  if (isAction) {
234
- ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(S=>` ctx.${S} = ${S};`).join(`
234
+ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(R=>` ctx.${R} = ${R};`).join(`
235
235
  `)}
236
236
  }
237
237
  `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark | undefined; functionPath?: string | undefined; headroom?: TransactionHeadroomTracker | undefined; identity?: SubscriptionIdentity | undefined; kind?: "query" | undefined; onRead?: ((table: string, idOrScan?: string) => void) | undefined; onReadRange?: ((range: KeyRange) => void) | undefined; scope?: QueryReadScope | undefined; trusted?: boolean | undefined } = {}): unknown {
@@ -261,7 +261,7 @@ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(S=>` ctx.${S} = ${S};`
261
261
  };
262
262
  })();
263
263
  const { identity, ip, userId } = caller;
264
- ${$}${f}${r}${D}${N}${b}${t}
264
+ ${$}${g}${r}${F}${k}${i}${t}
265
265
  // Which dispatch this ctx belongs to. Drives the two deferral facades
266
266
  // below and the \`ctx.run*\` caller guard; a ctx built for an
267
267
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -367,7 +367,7 @@ ${$}${f}${r}${D}${N}${b}${t}
367
367
  // so both write to the same trace.
368
368
  const span = this.makeDispatchSpan(traceAnchor, observability);
369
369
 
370
- ${l} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
370
+ ${f} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
371
371
  // adds aggregate counters (call count, total time, per-operation
372
372
  // breakdown) to the wide event rather than a span per call, so a
373
373
  // handler making hundreds of queries stays readable. See
@@ -376,7 +376,7 @@ ${l} // \`ctx.db\`, wrapped in automatic instrumentation: by default
376
376
  // mutation must rebuild its DB and table/ORM views with its own queue.
377
377
  const makeDatabaseContext = (scheduler: SchedulerLike) => {
378
378
  const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
379
- ${c} return ${x};
379
+ ${c} return ${U};
380
380
  };
381
381
  const databaseContext = makeDatabaseContext(scheduler);
382
382
  const db = databaseContext.db;
@@ -388,7 +388,7 @@ ${P}
388
388
  // writing mutation's trace from the shared per-request field.
389
389
  const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
390
390
  const metrics = this.makeMetrics(logFunctionPath, observability);
391
- ${O}
391
+ ${I}
392
392
  // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
393
393
  // captured ONCE so the whole handler body sees a single stable value.
394
394
  // A \`query\` handler is re-run by every live subscription that reads it,
@@ -439,21 +439,21 @@ ${O}
439
439
  // to the handler so code that signs its own URLs (a copy-in
440
440
  // \`createStorage\`) can fall back to it too. \`undefined\` for a
441
441
  // query and for a deferred dispatch, for the reasons given there.
442
- origin: requestOrigin,${u}
442
+ origin: requestOrigin,${x}
443
443
  scheduler,
444
444
  span,
445
445
  storage: contextStorage,
446
- trace,${q}${v}${k}${s}${F}${i}${M}${a}
446
+ trace,${q}${y}${N}${s}${A}${M}${b}${a}
447
447
  };
448
- ${T?` const isAction = contextKind === "action";
449
- `:""}${w}
450
- ${p?` const captureScope = (): (() => void) => {
448
+ ${D?` const isAction = contextKind === "action";
449
+ `:""}${T}
450
+ ${l?` const captureScope = (): (() => void) => {
451
451
  const requestScope = this.captureRequestScope();
452
452
  return () => this.restoreRequestScope(requestScope);
453
453
  };
454
454
 
455
455
  `:""} const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
456
- target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${p?", undefined, captureScope":""});
456
+ target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${l?", undefined, captureScope":""});
457
457
  // The composed mutation runs under the SAME wrapper the top-level RPC
458
458
  // uses, so "do the transactional work in a mutation and call it from the
459
459
  // action" — the recipe the docs give for atomicity — actually is atomic.
@@ -469,7 +469,7 @@ ${p?` const captureScope = (): (() => void) => {
469
469
 
470
470
  return Object.defineProperties({}, {
471
471
  ...Object.getOwnPropertyDescriptors(target),
472
- db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${C}
472
+ db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${u}
473
473
  scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
474
474
  storage: { configurable: true, enumerable: true, value: withDeferredDeletes(storage), writable: true },
475
475
  });
@@ -479,7 +479,7 @@ ${p?` const captureScope = (): (() => void) => {
479
479
  installRun(mutationCtx, kind);
480
480
  }
481
481
 
482
- return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${p?", captureScope":""});
482
+ return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${l?", captureScope":""});
483
483
  };
484
484
  // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
485
485
  // its OWN query context, built without the subscription's read-footprint
@@ -502,7 +502,7 @@ ${p?` const captureScope = (): (() => void) => {
502
502
  runOptions?.untracked === true
503
503
  ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope })
504
504
  : queryContext(),
505
- kind,${p?`
505
+ kind,${l?`
506
506
  undefined,
507
507
  captureScope,`:""}
508
508
  );
@@ -526,7 +526,7 @@ ${p?` const captureScope = (): (() => void) => {
526
526
 
527
527
  if (queryView === undefined) {
528
528
  const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
529
- ${e.map(S=>` delete descriptors.${S};
529
+ ${e.map(R=>` delete descriptors.${R};
530
530
  `).join("")} // Writable and configurable, like the plain fields they replace.
531
531
  const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
532
532
 
@@ -611,7 +611,7 @@ const dispatchRun = async (
611
611
  } finally {
612
612
  runDepth -= 1;
613
613
  }
614
- };`,pr=n=>n?ie.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
614
+ };`,gr=n=>n?ie.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
615
615
  captureScope?: () => () => void,`).replace(` try {
616
616
  // A mutation composed from an action`,` try {
617
617
  let loaded = getLoadedFunction(functionPath);
@@ -632,7 +632,7 @@ const dispatchRun = async (
632
632
 
633
633
  const loadedFunction = loaded;
634
634
 
635
- // A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ie,mr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
635
+ // A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ie,fr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
636
636
  __PREPARE_FUNCTION__ const registered = LUNORA_FUNCTIONS[functionPath];
637
637
 
638
638
  // Internal functions are reachable server-side only: via \`ctx.run*\`
@@ -816,7 +816,7 @@ __COMMITTED_CATCH__ } finally {
816
816
  // \`ctx.scheduler\` call that reached the buffer in the first place.
817
817
  protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
818
818
  return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
819
- }`,gr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
819
+ }`,br=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
820
820
  const registered = LUNORA_FUNCTIONS[functionPath];
821
821
 
822
822
  if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
@@ -857,7 +857,7 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
857
857
  // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
858
858
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
859
859
  };
860
- }`,fr=` } catch (error) {
860
+ }`,wr=` } catch (error) {
861
861
  // The write committed before this failed. Mark the error so the caller can tell
862
862
  // a durable write from a rollback: the rethrow still reaches the caller unchanged.
863
863
  if (typeof error === "object" && error !== null) {
@@ -865,7 +865,7 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
865
865
  }
866
866
 
867
867
  throw error;
868
- `,br=(n,e=!1)=>{const t=e?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
868
+ `,yr=(n,e=!1)=>{const t=e?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
869
869
 
870
870
  if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
871
871
  throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
@@ -882,7 +882,7 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
882
882
  }
883
883
  }
884
884
 
885
- `:"";return mr.replace("__COMMITTED_CATCH__",n?fr:"").replace("__PREPARE_FUNCTION__",`${t}${a}`)},wr=n=>{const e={};for(const t of n.tables){const a={};for(const[r,s]of Object.entries(t.shape)){const d=J(s);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(e[t.name]=a)}return e},yr=n=>{const e={};for(const t of n.tables){const a=[];for(const[r,s]of Object.entries(t.shape))J(s).kind==="storage"&&a.push(r);a.length>0&&(e[t.name]=a)}return e},vr=n=>{const e={};for(const t of n.tables){const a=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(e[t.name]=a)}return e},kr=n=>{const e=[];for(const t of n.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},Sr=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const e=[];for(const t of n.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const a=JSON.parse(t.literalValue);if(typeof a!="string")return;e.push(a)}catch{return}}return e},Rr=(n,e,t)=>{const a=J(e),r={name:n,optional:ar(e),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=t.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const s=Sr(a);return s!==void 0&&(r.enumValues=s),a.column?.notNull===!1&&(r.nullable=!0),r},xr=n=>{const e={};for(const t of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))a.push(Rr(s,d,r));e[t.name]=a}return e},Ar=({hasMutators:n,hasShapes:e,rlsData:t})=>{const a=e?`
885
+ `:"";return fr.replace("__COMMITTED_CATCH__",n?wr:"").replace("__PREPARE_FUNCTION__",`${t}${a}`)},vr=n=>{const e={};for(const t of n.tables){const a={};for(const[r,s]of Object.entries(t.shape)){const d=z(s);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(e[t.name]=a)}return e},kr=n=>{const e={};for(const t of n.tables){const a=[];for(const[r,s]of Object.entries(t.shape))z(s).kind==="storage"&&a.push(r);a.length>0&&(e[t.name]=a)}return e},Sr=n=>{const e={};for(const t of n.tables){const a=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(e[t.name]=a)}return e},Rr=n=>{const e=[];for(const t of n.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},xr=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const e=[];for(const t of n.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const a=JSON.parse(t.literalValue);if(typeof a!="string")return;e.push(a)}catch{return}}return e},Or=(n,e,t)=>{const a=z(e),r={name:n,optional:or(e),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=t.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const s=xr(a);return s!==void 0&&(r.enumValues=s),a.column?.notNull===!1&&(r.nullable=!0),r},Ar=n=>{const e={};for(const t of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))a.push(Or(s,d,r));e[t.name]=a}return e},Dr=({hasMutators:n,hasShapes:e,rlsData:t})=>{const a=e?`
886
886
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
887
887
  const shape = LUNORA_SHAPES[name];
888
888
 
@@ -945,14 +945,14 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
945
945
 
946
946
  return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
947
947
  }
948
- `:"",r=e?[...new Set(t.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,l)=>c.localeCompare(l)):[],s=r.length>0?`
948
+ `:"",r=e?[...new Set(t.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,f)=>c.localeCompare(f)):[],s=r.length>0?`
949
949
  /** Refuses to boot a shape that would replicate around the read policies its table is governed by (\`defineShape({ use })\` is how a shape opts in; \`use: []\` acknowledges an ungoverned one). */
950
950
  assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
951
951
  `:"";return{customMutatorOverride:n?`
952
952
  protected override isCustomMutator(functionPath: string): boolean {
953
953
  return LUNORA_MUTATOR_PATHS.has(functionPath);
954
954
  }
955
- `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},Or=(n,e)=>n?`
955
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},Tr=(n,e)=>n?`
956
956
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
957
957
  const env = this.env as Record<string, unknown>;
958
958
  // A shape read performs no writes, so the widened request only needs
@@ -1018,7 +1018,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
1018
1018
 
1019
1019
  return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
1020
1020
  }
1021
- `:"",Dr=n=>({externalSourceOverride:n?`
1021
+ `:"",Cr=n=>({externalSourceOverride:n?`
1022
1022
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1023
1023
  const env = (this.env ?? {}) as Record<string, unknown>;
1024
1024
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1171,8 +1171,8 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
1171
1171
  `:"",sourceClientCacheConst:n?`
1172
1172
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1173
1173
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1174
- `:""}),Tr=(n,e)=>{const t=e.length>0,r=n?I("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
1175
- `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",v=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(p=>JSON.stringify(p)).join(", ")}]`]:[]].join(", ")} }`,c=n?`
1174
+ `:""}),Er=(n,e)=>{const t=e.length>0,r=n?L("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
1175
+ `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",y=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(l=>JSON.stringify(l)).join(", ")}]`]:[]].join(", ")} }`,c=n?`
1176
1176
  const vectorSync = this.vectorSync(env);
1177
1177
  // Vectorize lives outside this shard's SQLite, so a query whose result
1178
1178
  // depends on a similarity search cannot be proven current on reconnect —
@@ -1189,7 +1189,7 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1189
1189
  }
1190
1190
 
1191
1191
  const lunora = createVectors({ indexes: config.vectors(env) });
1192
- ${s} const vectors = createContextVectors(lunora${v});
1192
+ ${s} const vectors = createContextVectors(lunora${y});
1193
1193
 
1194
1194
  return {
1195
1195
  backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
@@ -1215,14 +1215,14 @@ ${s} const vectors = createContextVectors(lunora${v});
1215
1215
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1216
1216
  });
1217
1217
  }
1218
- `:"",vectorsBuild:c,vectorsStub:r}},Br=({advisories:n=[],advisorProcedures:e=[],agents:t=[],capabilities:a=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:f=!1,hasNotify:v=!1,hasRooms:c=!1,lazyFunctions:l=!1,hasVectors:p=!0,liveStreams:O=!1,maskMetadata:R,mutators:P=[],queues:k=[],rlsMetadata:N,schema:i,schemaSnapshot:b,shapes:M=[],storageRules:$,studioFeatures:q,services:D=[],topics:F=[],useUmbrella:T=!1,workflows:x=[]})=>{const u=or(T),C=P.length>0,w=M.length>0,z=b===void 0?"":Mt(b),S=b===void 0?"":`
1218
+ `:"",vectorsBuild:c,vectorsStub:r}},Wr=({advisories:n=[],advisorProcedures:e=[],agents:t=[],capabilities:a=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:g=!1,hasNotify:y=!1,hasRooms:c=!1,hasSockets:f=!1,lazyFunctions:l=!1,hasVectors:I=!0,liveStreams:v=!1,maskMetadata:P,mutators:N=[],queues:k=[],rlsMetadata:M,schema:i,schemaSnapshot:b,shapes:$=[],storageRules:q,studioFeatures:F,services:A=[],topics:D=[],useUmbrella:U=!1,workflows:x=[]})=>{const u=dr(U),T=N.length>0,S=$.length>0,R=b===void 0?"":qt(b),de=b===void 0?"":`
1219
1219
  /** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
1220
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify($t(b))}, json: ${JSON.stringify(z)} };
1221
- `,de=b===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",y=Bt(a),E=jt(f,u.flags),U=Wt(d,f,u.flags),B=nr(v),j=Ht(s),{build:ce,contextField:le,importLines:ue,specs:he}=Vt(ir(k)),{build:pe,contextField:me,importLines:ge,specs:fe}=Kt(F,k),W=Gt(D,u.server),{build:be,contextField:we,importLines:ye,specs:ve}=Qt(r,i.jurisdiction),{build:ke,contextField:Se,importLines:Re,specs:xe}=Jt(x),{build:Ae,contextField:Oe,importLines:De,specs:Te}=zt(t),{build:Ce,configField:Ee,contextField:_e,imports:Le,stub:Ie}=Yt(a.has("payments")),Pe=n,{advisoryRules:Ne,advisoryRows:Me}=cr(Pe),$e=e,Y=N??{policies:[],roles:[]},qe=R??{columns:[]},Fe=$??{rules:[]},Ue=q??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Be,override:je}=Xt(x),{constant:We,override:He}=Zt(k),m=p&&i.vectorIndexes.length>0,H=new Set(i.tables.filter(o=>dr(o)).map(o=>o.name)),X=m&&i.vectorIndexes.some(o=>H.has(o.table)),A=i.tables.some(o=>o.shardMode==="global"),V=er(H),K=i.tables.some(o=>qt(o)),Z=i.tables.some(o=>Ft(o)),_=i.tables.some(o=>o.externalSource!==void 0),ee=i.tables.some(o=>o.memory===!0),G=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(Z&&K)throw new Nt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Q=i.tables.length>0,Ve=wr(i),Ke=vr(i),Ge=xr(i),Qe=yr(i),te=kr(i),re=tr(m,x.length>0,k.length>0,f,G);w&&re.push("WhereInput");const ne=rr(A),{customMutatorOverride:Je,shapeGuardImport:ze,shapeReadPolicyAssertion:Ye,shapeReadPolicyImport:Xe,shapeResolveOverride:Ze}=Ar({hasMutators:C,hasShapes:w,rlsData:Y}),L=[`import type { ${re.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, createStableIdFactory, ${G?"backfillSearchIndexes, ":""}${m?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ee?"clearMemoryTables, ":""}${ze}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${_?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${X?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ne.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,..._?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],w?`import { asBucketStorage, ${Xe}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];Q&&L.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),m&&L.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),L.push(...y.importLines,...E.importLines,...B.importLines,...j.importLines,...ye,...Re,...ue,...ge,...W.importLines,...De,...Le,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...l?["getLoadedFunction","loadFunction"]:[],...C?["LUNORA_MUTATOR_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...w?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const et=m?`
1222
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",tt=Z?`
1223
- d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",rt=K?`
1224
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",nt=_?`
1225
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",at="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",st="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",ot="ctx.storage: no storage configured. Pass `storage` to createShardDO().",it=A?I("globalDbStub: DatabaseWriterLike",at,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:dt,vectorsBuild:ct,vectorsStub:lt}=Tr(m,X?i.vectorIndexes.filter(o=>H.has(o.table)).map(o=>o.name):[]),ut=`{
1220
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Ft(b))}, json: ${JSON.stringify(R)} };
1221
+ `,ce=b===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",w=Wt(a),C=Ht(g,u.flags),B=Vt(d,g,u.flags),j=sr(y),W=Kt(s),{build:le,contextField:ue,importLines:he,specs:pe}=Gt(cr(k)),{build:me,contextField:ge,importLines:fe,specs:be}=Qt(D,k),H=Jt(A,u.server),{build:we,contextField:ye,importLines:ve,specs:ke}=zt(r,i.jurisdiction),{build:Se,contextField:Re,importLines:xe,specs:Oe}=Yt(x),{build:Ae,contextField:De,importLines:Te,specs:Ce}=Xt(t),{build:Ee,configField:_e,contextField:Le,imports:Ie,stub:Pe}=Zt(a.has("payments")),Ne=n,{advisoryRules:Me,advisoryRows:$e}=ur(Ne),qe=e,Y=M??{policies:[],roles:[]},Fe=P??{columns:[]},Ue=q??{rules:[]},Be=F??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:je,override:We}=er(x),{constant:He,override:Ve}=tr(k),p=I&&i.vectorIndexes.length>0,V=new Set(i.tables.filter(o=>lr(o)).map(o=>o.name)),X=p&&i.vectorIndexes.some(o=>V.has(o.table)),O=i.tables.some(o=>o.shardMode==="global"),K=rr(V),G=i.tables.some(o=>Ut(o)),Z=i.tables.some(o=>Bt(o)),E=i.tables.some(o=>o.externalSource!==void 0),ee=i.tables.some(o=>o.memory===!0),Q=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(Z&&G)throw new $t("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const J=i.tables.length>0,Ke=vr(i),Ge=Sr(i),Qe=Ar(i),Je=kr(i),te=Rr(i),re=nr(p,x.length>0,k.length>0,g,Q);S&&re.push("WhereInput");const ne=ar(O),{customMutatorOverride:ze,shapeGuardImport:Ye,shapeReadPolicyAssertion:Xe,shapeReadPolicyImport:Ze,shapeResolveOverride:et}=Dr({hasMutators:T,hasShapes:S,rlsData:Y}),_=[`import type { ${re.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, createStableIdFactory, ${Q?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ee?"clearMemoryTables, ":""}${Ye}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${E?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${X?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ne.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,...E?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],S?`import { asBucketStorage, ${Ze}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];J&&_.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),p&&_.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),_.push(...w.importLines,...C.importLines,...j.importLines,...W.importLines,...ve,...xe,...he,...fe,...H.importLines,...Te,...Ie,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...l?["getLoadedFunction","loadFunction"]:[],...T?["LUNORA_MUTATOR_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...f?["LUNORA_SOCKETS"]:[],...S?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const tt=p?`
1222
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",rt=Z?`
1223
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",nt=G?`
1224
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",at=E?`
1225
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",st="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",ot="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",it="ctx.storage: no storage configured. Pass `storage` to createShardDO().",dt=O?L("globalDbStub: DatabaseWriterLike",st,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:ct,vectorsBuild:lt,vectorsStub:ut}=Er(p,X?i.vectorIndexes.filter(o=>V.has(o.table)).map(o=>o.name):[]),ht=`{
1226
1226
  ...this.ctxDbTuning(),
1227
1227
  auth: { identity: identity ?? null, userId: userId ?? null },
1228
1228
  broadcast: (delta) => {
@@ -1262,7 +1262,7 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1262
1262
  // fallback rather than reporting into a no-op.
1263
1263
  ...(options.onReadRange !== undefined
1264
1264
  ? { onReadRange: options.onReadRange }
1265
- : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${m?`
1265
+ : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${p?`
1266
1266
  // Vectorize is outside this shard's SQLite and cannot roll back, so
1267
1267
  // the sync is held until the mutation's transaction has COMMITTED
1268
1268
  // (\`deferAfterCommit\`) instead of running inline. Inline, a write
@@ -1274,11 +1274,11 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1274
1274
  scheduler,
1275
1275
  schema: schema as unknown as SchemaLike,
1276
1276
  sql: this.sql as SqlExec,
1277
- storage,${A?`
1277
+ storage,${O?`
1278
1278
  globalDb,`:""}
1279
- }`,ht=m?`
1280
- vectors,`:"",pt=Q?`
1281
- orm: bindOrm(facade),`:"",ae=K?"config.hyperdriveGlobal":"config.d1",mt=A?` const bookmark = this.getInboundBookmark();
1279
+ }`,pt=p?`
1280
+ vectors,`:"",mt=J?`
1281
+ orm: bindOrm(facade),`:"",ae=G?"config.hyperdriveGlobal":"config.d1",gt=O?` const bookmark = this.getInboundBookmark();
1282
1282
  const globalRequest = {
1283
1283
  ...this.globalCdcOptions(config.cdc ?? false),
1284
1284
  ...(bookmark === undefined ? {} : { bookmark }),
@@ -1287,22 +1287,25 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1287
1287
  ...(userId === undefined ? {} : { userId }),
1288
1288
  };
1289
1289
  const globalDb: DatabaseWriterLike = ${ae}?.(env, globalRequest) ?? globalDbStub;
1290
- `:"",gt=Or(w&&A,ae),ft=c?` protected override roomHandlerPath(topic: string): string | undefined {
1290
+ `:"",ft=Tr(S&&O,ae),bt=c?` protected override roomHandlerPath(topic: string): string | undefined {
1291
1291
  // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1292
1292
  return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1293
1293
  }
1294
- `:"",{externalSourceOverride:bt,sourceBootstrap:wt,sourceClientCacheConst:yt}=Dr(_),vt=`
1294
+ `:"",wt=f?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1295
+ return LUNORA_SOCKETS[path];
1296
+ }
1297
+ `:"",{externalSourceOverride:yt,sourceBootstrap:vt,sourceClientCacheConst:kt}=Cr(E),St=`
1295
1298
  protected override async runShardInit(): Promise<void> {
1296
1299
  this.ensureMigrated();
1297
1300
  ${ee?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1298
1301
  `:""}
1299
1302
  await this.dispatchShardInit();
1300
1303
  }
1301
- `,kt=te.length>0?`
1304
+ `,Rt=te.length>0?`
1302
1305
  if (LUNORA_TTL_SWEEPS.length > 0) {
1303
1306
  void this.scheduleTtlSweep();
1304
1307
  }
1305
- `:"",St=`
1308
+ `:"",xt=`
1306
1309
  public constructor(state: ShardDOState, env: unknown) {
1307
1310
  super(state, env, {
1308
1311
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1319,7 +1322,7 @@ ${ee?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1319
1322
  // exists — a trigger that fails first still flushes and fuses.
1320
1323
  ...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
1321
1324
  });
1322
- ${wt}${kt} }
1325
+ ${vt}${Rt} }
1323
1326
 
1324
1327
  protected override isCacheableQuery(functionPath: string): boolean {
1325
1328
  // NOT \`kind === "query"\` alone. A cache hit answers without running
@@ -1358,25 +1361,25 @@ ${wt}${kt} }
1358
1361
 
1359
1362
  return loadFunction(functionPath).then(() => undefined);
1360
1363
  }
1361
- `:"",Rt=se===""?`
1364
+ `:"",Ot=se===""?`
1362
1365
 
1363
1366
  `:`${se}
1364
- `,xt=pr(l),At=l?` const preparation = this.prepareFunction(functionPath, "subscription");
1367
+ `,At=gr(l),Dt=l?` const preparation = this.prepareFunction(functionPath, "subscription");
1365
1368
  if (preparation !== undefined) await preparation;
1366
- `:"",Ot=gr.replace("__PREPARE_FUNCTION__",At),Dt=br(c,l),Tt=Q?`
1369
+ `:"",Tt=br.replace("__PREPARE_FUNCTION__",Dt),Ct=yr(c,l),Et=J?`
1367
1370
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1368
1371
  ${i.tables.map(o=>` facade[${JSON.stringify(o.name)}] = bindTableFacade(db, ${JSON.stringify(o.name)});`).join(`
1369
1372
  `)}
1370
- `:"",Ct=`${y.everyBuild}${E.build}${j.build}
1373
+ `:"",_t=`${w.everyBuild}${C.build}${W.build}
1371
1374
  const secrets = createSecrets(env);
1372
- `,Et=`${y.everyFields}${E.contextField}${B.contextField}${j.contextField}
1373
- secrets,`,_t=B.build,Lt=O?`
1375
+ `,Lt=`${w.everyFields}${C.contextField}${j.contextField}${W.contextField}
1376
+ secrets,`,It=j.build,Pt=v?`
1374
1377
  const live = {
1375
1378
  publish: async (topic: string, payload: unknown, publishOptions: { shardKey?: string; stream: string }): Promise<void> => {
1376
1379
  await this.publishLiveFromAction(topic, payload, publishOptions);
1377
1380
  },
1378
1381
  };
1379
- `:"",It=[...y.actionFields,...D.length>0?["services"]:[],...O?["live"]:[]],Pt=`${y.actionBuild}${W.build}${Lt}`;return`${sr}${L.join(`
1382
+ `:"",Nt=[...w.actionFields,...A.length>0?["services"]:[],...v?["live"]:[]],Mt=`${w.actionBuild}${H.build}${Pt}`;return`${ir}${_.join(`
1380
1383
  `)}
1381
1384
 
1382
1385
  type FunctionKind = "action" | "mutation" | "query";
@@ -1386,13 +1389,13 @@ interface FunctionReference {
1386
1389
  }
1387
1390
 
1388
1391
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1389
- const LUNORA_TABLE_REFS = ${h(Ve,"Record<string, Record<string, string>>")};
1392
+ const LUNORA_TABLE_REFS = ${h(Ke,"Record<string, Record<string, string>>")};
1390
1393
 
1391
1394
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1392
- const LUNORA_TABLE_INDEXES = ${h(Ke,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1395
+ const LUNORA_TABLE_INDEXES = ${h(Ge,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1393
1396
 
1394
1397
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1395
- const LUNORA_TABLE_COLUMNS = ${h(Ge,`Record<
1398
+ const LUNORA_TABLE_COLUMNS = ${h(Qe,`Record<
1396
1399
  string,
1397
1400
  Array<{
1398
1401
  bucket?: string;
@@ -1409,16 +1412,16 @@ const LUNORA_TABLE_COLUMNS = ${h(Ge,`Record<
1409
1412
  >`)};
1410
1413
 
1411
1414
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1412
- const LUNORA_STORAGE_COLUMNS = ${h(Qe,"Record<string, string[]>")};
1415
+ const LUNORA_STORAGE_COLUMNS = ${h(Je,"Record<string, string[]>")};
1413
1416
 
1414
1417
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1415
- const LUNORA_TTL_SWEEPS = ${Ut(te,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1418
+ const LUNORA_TTL_SWEEPS = ${jt(te,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1416
1419
 
1417
1420
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1418
- const LUNORA_ADVISORY_RULES = ${h(Ne,"Record<string, Partial<AdvisoryFinding>>")};
1421
+ const LUNORA_ADVISORY_RULES = ${h(Me,"Record<string, Partial<AdvisoryFinding>>")};
1419
1422
 
1420
1423
  /** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
1421
- const LUNORA_ADVISORY_ROWS = ${h(Me,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1424
+ const LUNORA_ADVISORY_ROWS = ${h($e,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1422
1425
 
1423
1426
  const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1424
1427
  let cached: AdvisoryFinding[] | undefined;
@@ -1426,20 +1429,20 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1426
1429
  })();
1427
1430
 
1428
1431
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1429
- const LUNORA_ADVISOR_PROCEDURES = ${h($e,"AdvisorProcedure[]")};
1432
+ const LUNORA_ADVISOR_PROCEDURES = ${h(qe,"AdvisorProcedure[]")};
1430
1433
 
1431
1434
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1432
1435
  const LUNORA_RLS_METADATA = ${h(Y,"RlsPoliciesResult")};
1433
- ${Ye}
1436
+ ${Xe}
1434
1437
  /** 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. */
1435
- const LUNORA_MASK_METADATA = ${h(qe,"MaskPoliciesResult")};
1438
+ const LUNORA_MASK_METADATA = ${h(Fe,"MaskPoliciesResult")};
1436
1439
 
1437
1440
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1438
- const LUNORA_STORAGE_RULES = ${h(Fe,"StorageRulesResult")};
1441
+ const LUNORA_STORAGE_RULES = ${h(Ue,"StorageRulesResult")};
1439
1442
 
1440
1443
  /** 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. */
1441
- const LUNORA_STUDIO_FEATURES = ${h(Ue,"StudioFeaturesResult")};
1442
- ${S}${V.constant}${U.constant}${Be}${We}${ve}${xe}${he}${fe}${W.specs}${Te}
1444
+ const LUNORA_STUDIO_FEATURES = ${h(Be,"StudioFeaturesResult")};
1445
+ ${de}${K.constant}${B.constant}${je}${He}${ke}${Oe}${pe}${be}${H.specs}${Ce}
1443
1446
  export interface ShardDOConfig {
1444
1447
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1445
1448
  cdc?: boolean;
@@ -1456,25 +1459,25 @@ export interface ShardDOConfig {
1456
1459
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1457
1460
  scheduler?: (env: Record<string, unknown>) => unknown;
1458
1461
  /** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
1459
- storage?: (env: Record<string, unknown>, origin?: string) => unknown;${et}${y.configFields}${E.configField}${Ee}${tt}${rt}${nt}${V.configField}
1462
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${tt}${w.configFields}${C.configField}${_e}${rt}${nt}${at}${K.configField}
1460
1463
  }
1461
- ${I("schedulerStub",st,["cancel","runAfter","runAt"])}${I("storageStub",ot,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${it}${yt}${lt}${y.stubs}${Ie}
1462
- ${xt}
1464
+ ${L("schedulerStub",ot,["cancel","runAfter","runAt"])}${L("storageStub",it,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${dt}${kt}${ut}${w.stubs}${Pe}
1465
+ ${At}
1463
1466
 
1464
1467
  /**
1465
1468
  * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1466
1469
  * from the worker entry so wrangler binds it by name.
1467
1470
  */
1468
1471
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1469
- class extends ShardDOBase {${St}
1470
- private migrated = false;${Rt}${Dt}
1472
+ class extends ShardDOBase {${xt}
1473
+ private migrated = false;${Ot}${Ct}
1471
1474
  ${ne.override}
1472
- ${Ot}
1473
- ${Je}${Ze}${gt}${bt}
1475
+ ${Tt}
1476
+ ${ze}${et}${ft}${yt}
1474
1477
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1475
1478
  return LUNORA_LIFECYCLE_HOOKS[event];
1476
1479
  }
1477
- ${ft}${V.override}${vt}
1480
+ ${bt}${wt}${K.override}${St}
1478
1481
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1479
1482
  // socket-terminated half of the same reactivity — and differs only in who
1480
1483
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1573,7 +1576,7 @@ ${l?` const requestScope = this.captureRequestScope();
1573
1576
  protected override studioFeatures(): StudioFeaturesResult {
1574
1577
  return LUNORA_STUDIO_FEATURES();
1575
1578
  }
1576
- ${U.evaluateOverride}${U.subscriptionOverride}${je}${He}
1579
+ ${B.evaluateOverride}${B.subscriptionOverride}${We}${Ve}
1577
1580
  protected override advisories(): AdvisoryFinding[] {
1578
1581
  return LUNORA_ADVISORIES();
1579
1582
  }
@@ -1582,17 +1585,17 @@ ${U.evaluateOverride}${U.subscriptionOverride}${je}${He}
1582
1585
  return LUNORA_ADVISOR_PROCEDURES();
1583
1586
  }
1584
1587
 
1585
- ${ur}
1588
+ ${pr}
1586
1589
 
1587
1590
  protected override ensureMigrated(): void {
1588
1591
  if (this.migrated) {
1589
1592
  return;
1590
1593
  }
1591
1594
 
1592
- runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${de} });
1595
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ce} });
1593
1596
  this.migrated = true;
1594
1597
  }
1595
- ${G?`
1598
+ ${Q?`
1596
1599
  protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1597
1600
  // Migrations create the fts5 companions; without them every backfill
1598
1601
  // statement would raise "no such table" on a shard that has never
@@ -1601,7 +1604,7 @@ ${G?`
1601
1604
 
1602
1605
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1603
1606
  }
1604
- `:""}${dt}
1605
- ${hr({lazyFunctions:l,actionOnlyFields:It,agentsBuild:Ae,agentsContextField:Oe,containersBuild:be,containersContextField:we,databaseOptions:ut,everyContextBuild:Ct,everyContextField:Et,facadeBlock:Tt,globalDatabaseLine:mt,notifyBuild:_t,ormContextField:pt,paymentsBuild:Ce,paymentsContextField:_e,queuesBuild:ce,queuesContextField:le,topicsBuild:pe,topicsContextField:me,vectorsBuild:ct,vectorsContextField:ht,workflowsBuild:ke,workflowsContextField:Se,actionOnlyBuild:Pt})}
1607
+ `:""}${ct}
1608
+ ${mr({lazyFunctions:l,actionOnlyFields:Nt,agentsBuild:Ae,agentsContextField:De,containersBuild:we,containersContextField:ye,databaseOptions:ht,everyContextBuild:_t,everyContextField:Lt,facadeBlock:Et,globalDatabaseLine:gt,notifyBuild:It,ormContextField:mt,paymentsBuild:Ee,paymentsContextField:Le,queuesBuild:le,queuesContextField:ue,topicsBuild:me,topicsContextField:ge,vectorsBuild:lt,vectorsContextField:pt,workflowsBuild:Se,workflowsContextField:Re,actionOnlyBuild:Mt})}
1606
1609
  };
1607
- `};export{yr as b,Br as e};
1610
+ `};export{kr as b,Wr as e};