@lunora/codegen 1.0.0-alpha.249 → 1.0.0-alpha.250

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.
@@ -1,4 +1,4 @@
1
- import{LunoraError as jt}from"@lunora/errors";import{serializeSchemaSnapshot as Ht,hashSchemaSnapshot as Vt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Kt,isD1GlobalTable as Gt}from"./isD1GlobalTable-udvHAAzD.mjs";import{p as Qt,i as zt}from"./ir-DBSvhNa-.mjs";import{r as l}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as Xt,a as Jt,b as Yt,c as Zt,d as er,f as tr,g as rr,h as ar,i as nr,j as sr,k as or,l as ir,m as dr,n as cr,o as lr,p as hr,q as ur,s as pr,t as mr,u as gr,v as br,w as fr,x as wr,y as yr,z as vr,A as kr}from"./shard-runtime-DvqfDuYO.mjs";import{u as re,i as Sr,G as Rr,d as xr}from"./shared-DjUziztz.mjs";const Ar=` /**
1
+ import{LunoraError as xt}from"@lunora/errors";import{serializeSchemaSnapshot as At,hashSchemaSnapshot as Dt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Ot,isD1GlobalTable as Tt}from"./isD1GlobalTable-udvHAAzD.mjs";import{p as Et,i as Ct}from"./ir-DBSvhNa-.mjs";import{r as h}from"./json-data-Chfs2Cz5.mjs";import{r as C,e as Lt,a as It,b as _t,c as Mt,d as Pt,f as $t,g as qt,h as Nt,i as Ft,j as Bt,k as Ut,l as Wt,m as jt,n as Ht,o as Vt,p as Kt,q as Gt,s as Qt}from"./shard-runtime-CyEbIjPA.mjs";import{u as K,i as zt,G as Xt,d as Jt}from"./shared-DjUziztz.mjs";const Yt=` /**
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 jt}from"@lunora/errors";import{serializeSchemaSnapshot as
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,m=(a="")=>` const writer = this.adminWriter(${a});`,Dr=`${Ar}
33
+ }`,p=(n="")=>` const writer = this.adminWriter(${n});`,Zt=`${Yt}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -47,7 +47,7 @@ import{LunoraError as jt}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
- ${m()}
50
+ ${p()}
51
51
 
52
52
  return runDataMigration({
53
53
  batchSize: args.batchSize,
@@ -80,7 +80,7 @@ ${m()}
80
80
 
81
81
  this.ensureMigrated();
82
82
 
83
- ${m("headroom ?? this.transactionHeadroom()")}
83
+ ${p("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 @@ ${m("headroom ?? this.transactionHeadroom()")}
135
135
  protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
136
136
  this.ensureMigrated();
137
137
 
138
- ${m()}
138
+ ${p()}
139
139
 
140
140
  const rows: ExportRow[] = [];
141
141
 
@@ -152,7 +152,7 @@ ${m()}
152
152
  protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
153
153
  this.ensureMigrated();
154
154
 
155
- ${m()}
155
+ ${p()}
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 @@ ${m()}
163
163
  protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
164
164
  this.ensureMigrated();
165
165
 
166
- ${m()}
166
+ ${p()}
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 @@ ${m()}
181
181
  protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
182
182
  this.ensureMigrated();
183
183
 
184
- ${m()}
184
+ ${p()}
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 @@ ${m()}
199
199
  protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
200
200
  this.ensureMigrated();
201
201
 
202
- ${m()}
202
+ ${p()}
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,16 +220,16 @@ ${m()}
220
220
  protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
221
221
  this.ensureMigrated();
222
222
 
223
- ${m()}
223
+ ${p()}
224
224
 
225
225
  await applyCdcChanges(writer, args.changes);
226
226
 
227
227
  return { applied: args.changes.length };
228
- }`,Or=({actionOnlyBuild:a,actionOnlyFields:r,agentsBuild:e,agentsContextField:n,containersBuild:t,containersContextField:o,databaseOptions:d,everyContextBuild:g,everyContextField:b,facadeBlock:c,globalDatabaseLine:u,notifyBuild:f,ormContextField:O,paymentsBuild:N,paymentsContextField:B,queuesBuild:U,queuesContextField:T,topicsBuild:E,topicsContextField:W,vectorsBuild:L,vectorsContextField:j,workflowsBuild:H,workflowsContextField:w})=>{const C=r.length>0,i=C?`
228
+ }`,er=({actionOnlyBuild:n,actionOnlyFields:r,agentsBuild:e,agentsContextField:a,containersBuild:t,containersContextField:o,databaseOptions:d,everyContextBuild:m,everyContextField:f,facadeBlock:c,globalDatabaseLine:w,notifyBuild:S,ormContextField:y,paymentsBuild:L,paymentsContextField:i,queuesBuild:g,queuesContextField:I,topicsBuild:_,topicsContextField:M,vectorsBuild:A,vectorsContextField:P,workflowsBuild:$,workflowsContextField:R})=>{const l=r.length>0,D=l?`
229
229
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
230
230
  // and attached only for an \`action\` so query/mutation ctx never carry them.
231
231
  if (isAction) {
232
- ${a.replaceAll(/^(?=.)/gmu," ")}${r.map(v=>` ctx.${v} = ${v};`).join(`
232
+ ${n.replaceAll(/^(?=.)/gmu," ")}${r.map(k=>` ctx.${k} = ${k};`).join(`
233
233
  `)}
234
234
  }
235
235
  `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; kind?: "query"; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
@@ -253,7 +253,7 @@ ${a.replaceAll(/^(?=.)/gmu," ")}${r.map(v=>` ctx.${v} = ${v};`
253
253
  userId: this.getCurrentUserId(),
254
254
  };
255
255
  const { identity, ip, userId } = caller;
256
- ${L}${g}${t}${H}${U}${E}${e}
256
+ ${A}${m}${t}${$}${g}${_}${e}
257
257
  // Which dispatch this ctx belongs to. Drives the two deferral facades
258
258
  // below and the \`ctx.run*\` caller guard; a ctx built for an
259
259
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -362,13 +362,13 @@ ${L}${g}${t}${H}${U}${E}${e}
362
362
  // so both write to the same trace.
363
363
  const span = this.makeDispatchSpan(traceAnchor, observability);
364
364
 
365
- ${u} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
365
+ ${w} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
366
366
  // adds aggregate counters (call count, total time, per-operation
367
367
  // breakdown) to the wide event rather than a span per call, so a
368
368
  // handler making hundreds of queries stays readable. See
369
369
  // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
370
370
  const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
371
- ${c}${N}
371
+ ${c}${L}
372
372
 
373
373
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
374
374
  // The trace anchor is threaded explicitly for the same reason \`identity\`
@@ -376,7 +376,7 @@ ${c}${N}
376
376
  // writing mutation's trace from the shared per-request field.
377
377
  const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
378
378
  const metrics = this.makeMetrics(logFunctionPath, observability);
379
- ${f}
379
+ ${S}
380
380
  // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
381
381
  // captured ONCE so the whole handler body sees a single stable value.
382
382
  // A \`query\` handler is re-run by every live subscription that reads it,
@@ -419,14 +419,14 @@ ${f}
419
419
  // to the handler so code that signs its own URLs (a copy-in
420
420
  // \`createStorage\`) can fall back to it too. \`undefined\` for a
421
421
  // query and for a deferred dispatch, for the reasons given there.
422
- origin: requestOrigin,${O}
422
+ origin: requestOrigin,${y}
423
423
  scheduler,
424
424
  span,
425
425
  storage: contextStorage,
426
- trace,${j}${b}${B}${o}${w}${T}${W}${n}
426
+ trace,${P}${f}${i}${o}${R}${I}${M}${a}
427
427
  };
428
- ${C?` const isAction = contextKind === "action";
429
- `:""}${i}
428
+ ${l?` const isAction = contextKind === "action";
429
+ `:""}${D}
430
430
  const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
431
431
  target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind);
432
432
  // The composed mutation runs under the SAME wrapper the top-level RPC
@@ -477,7 +477,7 @@ ${C?` const isAction = contextKind === "action";
477
477
 
478
478
  if (queryView === undefined) {
479
479
  const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
480
- ${r.map(v=>` delete descriptors.${v};
480
+ ${r.map(k=>` delete descriptors.${k};
481
481
  `).join("")} // Writable and configurable, like the plain fields they replace.
482
482
  const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
483
483
 
@@ -496,7 +496,7 @@ ${r.map(v=>` delete descriptors.${v};
496
496
  installRun(ctx, contextKind);
497
497
 
498
498
  return ctx;
499
- }`},Tr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
499
+ }`},tr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
500
500
  // referencing call fails loudly with a clear error instead of overflowing the
501
501
  // stack. Tracked across the awaited handler chain (one DO invocation is
502
502
  // single-threaded), so the counter reflects true nesting depth.
@@ -562,7 +562,7 @@ const dispatchRun = async (
562
562
  } finally {
563
563
  runDepth -= 1;
564
564
  }
565
- };`,Er=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
565
+ };`,rr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
566
566
  const registered = LUNORA_FUNCTIONS[functionPath];
567
567
 
568
568
  // Internal functions are reachable server-side only: via \`ctx.run*\`
@@ -739,7 +739,7 @@ const dispatchRun = async (
739
739
  // \`ctx.scheduler\` call that reached the buffer in the first place.
740
740
  protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
741
741
  return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
742
- }`,Lr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
742
+ }`,ar=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
743
743
  const registered = LUNORA_FUNCTIONS[functionPath];
744
744
 
745
745
  if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
@@ -778,7 +778,7 @@ const dispatchRun = async (
778
778
  // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
779
779
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
780
780
  };
781
- }`,Cr=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=re(o);d.kind==="id"&&d.tableName!==void 0&&(n[t]=d.tableName)}Object.keys(n).length>0&&(r[e.name]=n)}return r},Ir=a=>{const r={};for(const e of a.tables){const n=[];for(const[t,o]of Object.entries(e.shape))re(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},_r=a=>{const r={};for(const e of a.tables){const n=[...e.indexes.map(t=>({fields:[...t.fields],name:t.name,type:"index",...t.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(t=>({fields:[t.field,...t.filterFields??[]],name:t.name,type:"search"})),...(e.geoIndexes??[]).map(t=>({fields:[t.field],name:t.name,type:"geo"})),...e.rankIndexes.map(t=>({fields:t.sortBy.map(o=>o.field),name:t.name,type:"rank"})),...e.vectorIndexes.map(t=>({fields:t.field===void 0?[]:[t.field],name:t.name,type:"vector"}))];n.length>0&&(r[e.name]=n)}return r},$r=a=>{const r=[];for(const e of a.tables)!e.ttl||e.shardMode==="global"||r.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return r},Mr=a=>{if(a.kind!=="union"||a.members===void 0||a.members.length===0)return;const r=[];for(const e of a.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const n=JSON.parse(e.literalValue);if(typeof n!="string")return;r.push(n)}catch{return}}return r},Pr=(a,r,e)=>{const n=re(r),t={name:a,optional:Sr(r),type:n.kind};if(n.kind==="id"&&n.tableName!==void 0){t.ref=n.tableName;const d=e.get(a);d!==void 0&&(t.onDelete=d)}n.kind==="storage"&&(t.isStorage=!0,n.bucket!==void 0&&(t.bucket=n.bucket));const o=Mr(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},Fr=a=>{const r={};for(const e of a.tables){const n=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],t=new Map(e.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,d]of Object.entries(e.shape))n.push(Pr(o,d,t));r[e.name]=n}return r},qr=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=r?`
781
+ }`,nr=n=>{const r={};for(const e of n.tables){const a={};for(const[t,o]of Object.entries(e.shape)){const d=K(o);d.kind==="id"&&d.tableName!==void 0&&(a[t]=d.tableName)}Object.keys(a).length>0&&(r[e.name]=a)}return r},sr=n=>{const r={};for(const e of n.tables){const a=[];for(const[t,o]of Object.entries(e.shape))K(o).kind==="storage"&&a.push(t);a.length>0&&(r[e.name]=a)}return r},or=n=>{const r={};for(const e of n.tables){const a=[...e.indexes.map(t=>({fields:[...t.fields],name:t.name,type:"index",...t.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(t=>({fields:[t.field,...t.filterFields??[]],name:t.name,type:"search"})),...(e.geoIndexes??[]).map(t=>({fields:[t.field],name:t.name,type:"geo"})),...e.rankIndexes.map(t=>({fields:t.sortBy.map(o=>o.field),name:t.name,type:"rank"})),...e.vectorIndexes.map(t=>({fields:t.field===void 0?[]:[t.field],name:t.name,type:"vector"}))];a.length>0&&(r[e.name]=a)}return r},ir=n=>{const r=[];for(const e of n.tables)!e.ttl||e.shardMode==="global"||r.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return r},dr=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const r=[];for(const e of n.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const a=JSON.parse(e.literalValue);if(typeof a!="string")return;r.push(a)}catch{return}}return r},cr=(n,r,e)=>{const a=K(r),t={name:n,optional:zt(r),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){t.ref=a.tableName;const d=e.get(n);d!==void 0&&(t.onDelete=d)}a.kind==="storage"&&(t.isStorage=!0,a.bucket!==void 0&&(t.bucket=a.bucket));const o=dr(a);return o!==void 0&&(t.enumValues=o),a.column?.notNull===!1&&(t.nullable=!0),t},lr=n=>{const r={};for(const e of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],t=new Map(e.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,d]of Object.entries(e.shape))a.push(cr(o,d,t));r[e.name]=a}return r},hr=({hasMutators:n,hasShapes:r,rlsData:e})=>{const a=r?`
782
782
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
783
783
  const shape = LUNORA_SHAPES[name];
784
784
 
@@ -842,14 +842,14 @@ const dispatchRun = async (
842
842
 
843
843
  return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
844
844
  }
845
- `:"",t=r?[...new Set(e.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,u)=>c.localeCompare(u)):[],o=t.length>0?`
845
+ `:"",t=r?[...new Set(e.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],o=t.length>0?`
846
846
  /** 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). */
847
847
  assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
848
- `:"";return{customMutatorOverride:a?`
848
+ `:"";return{customMutatorOverride:n?`
849
849
  protected override isCustomMutator(functionPath: string): boolean {
850
850
  return LUNORA_MUTATOR_PATHS.has(functionPath);
851
851
  }
852
- `:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},Nr=(a,r)=>a?`
852
+ `:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},ur=(n,r)=>n?`
853
853
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
854
854
  const env = this.env as Record<string, unknown>;
855
855
  // A shape read performs no writes, so the widened request only needs
@@ -908,7 +908,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
908
908
 
909
909
  return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
910
910
  }
911
- `:"",Br=a=>({externalSourceOverride:a?`
911
+ `:"",pr=n=>({externalSourceOverride:n?`
912
912
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
913
913
  const env = (this.env ?? {}) as Record<string, unknown>;
914
914
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1048,7 +1048,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
1048
1048
 
1049
1049
  return nextDueAt;
1050
1050
  }
1051
- `:"",sourceBootstrap:a?`
1051
+ `:"",sourceBootstrap:n?`
1052
1052
  const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1053
1053
  const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1054
1054
 
@@ -1058,11 +1058,11 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
1058
1058
  if (autoSourced) {
1059
1059
  void this.scheduleSourcePoll();
1060
1060
  }
1061
- `:"",sourceClientCacheConst:a?`
1061
+ `:"",sourceClientCacheConst:n?`
1062
1062
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1063
1063
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1064
- `:""}),Ur=(a,r)=>{const e=r.length>0,t=a?q("vectorsStub: VectorSearchLike",'throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',["deleteByIds","getByIds","query","upsert","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
1065
- `:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",b=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${r.map(f=>JSON.stringify(f)).join(", ")}]`]:[]].join(", ")} }`,c=a?`
1064
+ `:""}),mr=(n,r)=>{const e=r.length>0,t=n?C("vectorsStub: VectorSearchLike",'throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',["deleteByIds","getByIds","query","upsert","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
1065
+ `:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",f=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${r.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=n?`
1066
1066
  const vectorSync = this.vectorSync(env);
1067
1067
  // Vectorize lives outside this shard's SQLite, so a query whose result
1068
1068
  // depends on a similarity search cannot be proven current on reconnect —
@@ -1072,14 +1072,14 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1072
1072
  const bareVectors = vectorSync?.vectors ?? vectorsStub;
1073
1073
  const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
1074
1074
  const onWrite = vectorSync?.onWrite;
1075
- `:"";return{vectorSyncMethod:a?`
1075
+ `:"";return{vectorSyncMethod:n?`
1076
1076
  private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
1077
1077
  if (!config.vectors) {
1078
1078
  return undefined;
1079
1079
  }
1080
1080
 
1081
1081
  const lunora = createVectors({ indexes: config.vectors(env) });
1082
- ${o} const vectors = createContextVectors(lunora${b});
1082
+ ${o} const vectors = createContextVectors(lunora${f});
1083
1083
 
1084
1084
  return {
1085
1085
  backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
@@ -1105,14 +1105,14 @@ ${o} const vectors = createContextVectors(lunora${b});
1105
1105
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1106
1106
  });
1107
1107
  }
1108
- `:"",vectorsBuild:c,vectorsStub:t}},Zr=({advisories:a=[],advisorProcedures:r=[],agents:e=[],containers:n=[],env:t,flagKeys:o=[],hasAccessFacade:d=!1,hasAi:g=!1,hasAnalytics:b=!1,hasBrowser:c=!1,hasFlags:u=!1,hasHyperdrive:f=!1,hasImages:O=!1,hasKv:N=!1,hasNotify:B=!1,hasPayments:U=!1,hasPipelines:T=!1,hasR2sql:E=!1,hasVectors:W=!0,hasX402:L=!1,maskMetadata:j,mutators:H=[],queues:w=[],rlsMetadata:C,schema:i,schemaSnapshot:y,shapes:v=[],storageRules:pe,studioFeatures:me,services:ae=[],topics:ge=[],useUmbrella:be=!1,workflows:V=[]})=>{const h=xr(be),ne=H.length>0,k=v.length>0,fe=y===void 0?"":Ht(y),we=y===void 0?"":`
1108
+ `:"",vectorsBuild:c,vectorsStub:t}},Dr=({advisories:n=[],advisorProcedures:r=[],agents:e=[],capabilities:a=new Set,containers:t=[],env:o,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasVectors:c=!0,maskMetadata:w,mutators:S=[],queues:y=[],rlsMetadata:L,schema:i,schemaSnapshot:g,shapes:I=[],storageRules:_,studioFeatures:M,services:A=[],topics:P=[],useUmbrella:$=!1,workflows:R=[]})=>{const l=Jt($),D=S.length>0,v=I.length>0,k=g===void 0?"":At(g),te=g===void 0?"":`
1109
1109
  /** 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. */
1110
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Vt(y))}, json: ${JSON.stringify(fe)} };
1111
- `,ye=y===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:ve,configField:ke}=Xt(g),K=vr(d),S=Jt(N),R=Yt(u,h.flags),G=Zt(o,u,h.flags),Q=kr(B),z=er(t),x=tr(b),I=rr(O),_=ar(f),$=nr(c),M=sr(E),P=or(T),{build:Se,contextField:Re,importLines:xe,specs:Ae}=ir(Qt(w)),{build:De,contextField:Oe,importLines:Te,specs:Ee}=dr(ge,w),X=cr(ae,h.server),{build:Le,contextField:Ce,importLines:Ie,specs:_e}=lr(n,i.jurisdiction),{build:$e,contextField:Me,importLines:Pe,specs:Fe}=hr(V),{build:qe,contextField:Ne,importLines:Be,specs:Ue}=ur(e),{build:We,configField:je,contextField:He,imports:Ve,stub:Ke}=pr(U),{build:Ge,configField:Qe,imports:ze,stub:Xe}=mr(L),Je=a,Ye=r,se=C??{policies:[],roles:[]},Ze=j??{columns:[]},et=pe??{rules:[]},tt=me??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:rt,override:at}=gr(V),{constant:nt,override:st}=br(w),p=W&&i.vectorIndexes.length>0,J=new Set(i.tables.filter(s=>zt(s)).map(s=>s.name)),oe=p&&i.vectorIndexes.some(s=>J.has(s.table)),A=i.tables.some(s=>s.shardMode==="global"),Y=fr(J),Z=i.tables.some(s=>Kt(s)),ie=i.tables.some(s=>Gt(s)),F=i.tables.some(s=>s.externalSource!==void 0),de=i.tables.some(s=>s.memory===!0),ee=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(ie&&Z)throw new jt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const te=i.tables.length>0,ot=Cr(i),it=_r(i),dt=Fr(i),ct=Ir(i),ce=$r(i),le=wr(p,V.length>0,w.length>0,u,ee);k&&le.push("WhereInput");const he=yr(A),{customMutatorOverride:lt,shapeGuardImport:ht,shapeReadPolicyAssertion:ut,shapeReadPolicyImport:pt,shapeResolveOverride:mt}=qr({hasMutators:ne,hasShapes:k,rlsData:se}),D=[`import type { ${le.join(", ")} } from "${h.do}";`,`import { applyCdcChanges, ${ee?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${de?"clearMemoryTables, ":""}${ht}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${F?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${oe?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${he.importFragment}ShardDO as ShardDOBase } from "${h.do}";`,...F?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${h.do}";`]:[],k?`import { asBucketStorage, ${pt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`];te&&D.push(`import { bindOrm, bindTableFacade } from "${h.server}";`),p&&D.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),g&&D.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),D.push(...K.importLines,...S.importLines,...R.importLines,...Q.importLines,...z.importLines,...x.importLines,...I.importLines,..._.importLines,...$.importLines,...M.importLines,...P.importLines,...Ie,...Pe,...xe,...Te,...X.importLines,...Be,...Ve,...ze,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ne?["LUNORA_MUTATOR_PATHS"]:[],...k?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const gt=p?`
1112
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",bt=ie?`
1113
- 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;`:"",ft=Z?`
1114
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",wt=F?`
1115
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",yt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',vt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',kt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',St=A?q("globalDbStub: DatabaseWriterLike",yt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:Rt,vectorsBuild:xt,vectorsStub:At}=Ur(p,oe?i.vectorIndexes.filter(s=>J.has(s.table)).map(s=>s.name):[]),Dt=`{
1110
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Dt(g))}, json: ${JSON.stringify(k)} };
1111
+ `,re=g===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=Lt(a),O=It(m,l.flags),q=_t(d,m,l.flags),N=Qt(f),F=Mt(o),{build:ae,contextField:ne,importLines:se,specs:oe}=Pt(Et(y)),{build:ie,contextField:de,importLines:ce,specs:le}=$t(P,y),B=qt(A,l.server),{build:he,contextField:ue,importLines:pe,specs:me}=Nt(t,i.jurisdiction),{build:ge,contextField:be,importLines:fe,specs:we}=Ft(R),{build:ye,contextField:ve,importLines:ke,specs:Se}=Bt(e),{build:Re,configField:xe,contextField:Ae,imports:De,stub:Oe}=Ut(a.has("payments")),{build:Te,configField:Ee,imports:Ce,stub:Le}=Wt(a.has("x402")),Ie=n,_e=r,G=L??{policies:[],roles:[]},Me=w??{columns:[]},Pe=_??{rules:[]},$e=M??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:qe,override:Ne}=jt(R),{constant:Fe,override:Be}=Ht(y),u=c&&i.vectorIndexes.length>0,U=new Set(i.tables.filter(s=>Ct(s)).map(s=>s.name)),Q=u&&i.vectorIndexes.some(s=>U.has(s.table)),x=i.tables.some(s=>s.shardMode==="global"),W=Vt(U),j=i.tables.some(s=>Ot(s)),z=i.tables.some(s=>Tt(s)),T=i.tables.some(s=>s.externalSource!==void 0),X=i.tables.some(s=>s.memory===!0),H=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(z&&j)throw new xt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,Ue=nr(i),We=or(i),je=lr(i),He=sr(i),J=ir(i),Y=Kt(u,R.length>0,y.length>0,m,H);v&&Y.push("WhereInput");const Z=Gt(x),{customMutatorOverride:Ve,shapeGuardImport:Ke,shapeReadPolicyAssertion:Ge,shapeReadPolicyImport:Qe,shapeResolveOverride:ze}=hr({hasMutators:D,hasShapes:v,rlsData:G}),E=[`import type { ${Y.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, ${H?"backfillSearchIndexes, ":""}${u?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${X?"clearMemoryTables, ":""}${Ke}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${T?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Q?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...T?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],v?`import { asBucketStorage, ${Qe}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&E.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),u&&E.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),E.push(...b.importLines,...O.importLines,...N.importLines,...F.importLines,...pe,...fe,...se,...ce,...B.importLines,...ke,...De,...Ce,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...D?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Xe=u?`
1112
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Je=z?`
1113
+ 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;`:"",Ye=j?`
1114
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ze=T?`
1115
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",et='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',tt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',rt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',at=x?C("globalDbStub: DatabaseWriterLike",et,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:nt,vectorsBuild:st,vectorsStub:ot}=mr(u,Q?i.vectorIndexes.filter(s=>U.has(s.table)).map(s=>s.name):[]),it=`{
1116
1116
  ...this.ctxDbTuning(),
1117
1117
  auth: { identity: identity ?? null, userId: userId ?? null },
1118
1118
  broadcast: (delta) => {
@@ -1150,7 +1150,7 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1150
1150
  // Left \`undefined\` when there is no scope so \`createShardCtxDb\`
1151
1151
  // keeps its own "degrade a provable slice to a whole-table dep"
1152
1152
  // fallback rather than reporting into a no-op.
1153
- onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${p?`
1153
+ onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${u?`
1154
1154
  // Vectorize is outside this shard's SQLite and cannot roll back, so
1155
1155
  // the sync is held until the mutation's transaction has COMMITTED
1156
1156
  // (\`deferAfterCommit\`) instead of running inline. Inline, a write
@@ -1162,24 +1162,24 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1162
1162
  scheduler,
1163
1163
  schema: schema as unknown as SchemaLike,
1164
1164
  sql: this.sql as SqlExec,
1165
- storage,${A?`
1165
+ storage,${x?`
1166
1166
  globalDb,`:""}
1167
- }`,Ot=p?`
1168
- vectors,`:"",Tt=te?`
1169
- orm: bindOrm(facade),`:"",ue=Z?"config.hyperdriveGlobal":"config.d1",Et=A?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1170
- const globalDb: DatabaseWriterLike = ${ue}?.(env, globalRequest) ?? globalDbStub;
1171
- `:"",Lt=Nr(k&&A,ue),{externalSourceOverride:Ct,sourceBootstrap:It,sourceClientCacheConst:_t}=Br(F),$t=`
1167
+ }`,dt=u?`
1168
+ vectors,`:"",ct=V?`
1169
+ orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",lt=x?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1170
+ const globalDb: DatabaseWriterLike = ${ee}?.(env, globalRequest) ?? globalDbStub;
1171
+ `:"",ht=ur(v&&x,ee),{externalSourceOverride:ut,sourceBootstrap:pt,sourceClientCacheConst:mt}=pr(T),gt=`
1172
1172
  protected override async runShardInit(): Promise<void> {
1173
1173
  this.ensureMigrated();
1174
- ${de?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1174
+ ${X?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1175
1175
  `:""}
1176
1176
  await this.dispatchShardInit();
1177
1177
  }
1178
- `,Mt=ce.length>0?`
1178
+ `,bt=J.length>0?`
1179
1179
  if (LUNORA_TTL_SWEEPS.length > 0) {
1180
1180
  void this.scheduleTtlSweep();
1181
1181
  }
1182
- `:"",Pt=`
1182
+ `:"",ft=`
1183
1183
  public constructor(state: ShardDOState, env: unknown) {
1184
1184
  super(state, env, {
1185
1185
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1192,7 +1192,7 @@ ${de?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1192
1192
  ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1193
1193
  ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1194
1194
  });
1195
- ${It}${Mt} }
1195
+ ${pt}${bt} }
1196
1196
 
1197
1197
  protected override isCacheableQuery(functionPath: string): boolean {
1198
1198
  // NOT \`kind === "query"\` alone. A cache hit answers without running
@@ -1216,14 +1216,14 @@ ${It}${Mt} }
1216
1216
  protected override isPaidFunction(functionPath: string): boolean {
1217
1217
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1218
1218
  }
1219
- `,Ft=te?`
1219
+ `,wt=V?`
1220
1220
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1221
1221
  ${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFacade(db, ${JSON.stringify(s.name)});`).join(`
1222
1222
  `)}
1223
- `:"",qt=`${K.build}${S.build}${R.build}${x.build}${z.build}
1223
+ `:"",yt=`${b.everyBuild}${O.build}${F.build}
1224
1224
  const secrets = createSecrets(env);
1225
- `,Nt=`${K.contextField}${S.contextField}${R.contextField}${Q.contextField}${x.contextField}${z.contextField}
1226
- secrets,`,Bt=Q.build,Ut=[...g?["ai"]:[],...O?["images"]:[],...f?["sql"]:[],...c?["browser"]:[],...E?["r2sql"]:[],...T?["pipelines"]:[],...L?["x402"]:[],...ae.length>0?["services"]:[]],Wt=`${ve}${I.build}${_.build}${$.build}${M.build}${P.build}${Ge}${X.build}`;return`${Rr}${D.join(`
1225
+ `,vt=`${b.everyFields}${O.contextField}${N.contextField}${F.contextField}
1226
+ secrets,`,kt=N.build,St=[...b.actionFields,...a.has("x402")?["x402"]:[],...A.length>0?["services"]:[]],Rt=`${b.actionBuild}${Te}${B.build}`;return`${Xt}${E.join(`
1227
1227
  `)}
1228
1228
 
1229
1229
  type FunctionKind = "action" | "mutation" | "query";
@@ -1233,13 +1233,13 @@ interface FunctionReference {
1233
1233
  }
1234
1234
 
1235
1235
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1236
- const LUNORA_TABLE_REFS = ${l(ot,"Record<string, Record<string, string>>")};
1236
+ const LUNORA_TABLE_REFS = ${h(Ue,"Record<string, Record<string, string>>")};
1237
1237
 
1238
1238
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1239
- const LUNORA_TABLE_INDEXES = ${l(it,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1239
+ const LUNORA_TABLE_INDEXES = ${h(We,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1240
1240
 
1241
1241
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1242
- const LUNORA_TABLE_COLUMNS = ${l(dt,`Record<
1242
+ const LUNORA_TABLE_COLUMNS = ${h(je,`Record<
1243
1243
  string,
1244
1244
  Array<{
1245
1245
  bucket?: string;
@@ -1256,29 +1256,29 @@ const LUNORA_TABLE_COLUMNS = ${l(dt,`Record<
1256
1256
  >`)};
1257
1257
 
1258
1258
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1259
- const LUNORA_STORAGE_COLUMNS = ${l(ct,"Record<string, string[]>")};
1259
+ const LUNORA_STORAGE_COLUMNS = ${h(He,"Record<string, string[]>")};
1260
1260
 
1261
1261
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1262
- const LUNORA_TTL_SWEEPS = ${l(ce,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1262
+ const LUNORA_TTL_SWEEPS = ${h(J,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1263
1263
 
1264
1264
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1265
- const LUNORA_ADVISORIES = ${l(Je,"AdvisoryFinding[]")};
1265
+ const LUNORA_ADVISORIES = ${h(Ie,"AdvisoryFinding[]")};
1266
1266
 
1267
1267
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1268
- const LUNORA_ADVISOR_PROCEDURES = ${l(Ye,"AdvisorProcedure[]")};
1268
+ const LUNORA_ADVISOR_PROCEDURES = ${h(_e,"AdvisorProcedure[]")};
1269
1269
 
1270
1270
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1271
- const LUNORA_RLS_METADATA = ${l(se,"RlsPoliciesResult")};
1272
- ${ut}
1271
+ const LUNORA_RLS_METADATA = ${h(G,"RlsPoliciesResult")};
1272
+ ${Ge}
1273
1273
  /** 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. */
1274
- const LUNORA_MASK_METADATA = ${l(Ze,"MaskPoliciesResult")};
1274
+ const LUNORA_MASK_METADATA = ${h(Me,"MaskPoliciesResult")};
1275
1275
 
1276
1276
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1277
- const LUNORA_STORAGE_RULES = ${l(et,"StorageRulesResult")};
1277
+ const LUNORA_STORAGE_RULES = ${h(Pe,"StorageRulesResult")};
1278
1278
 
1279
1279
  /** 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. */
1280
- const LUNORA_STUDIO_FEATURES = ${l(tt,"StudioFeaturesResult")};
1281
- ${we}${Y.constant}${G.constant}${rt}${nt}${_e}${Fe}${Ae}${Ee}${X.specs}${Ue}
1280
+ const LUNORA_STUDIO_FEATURES = ${h($e,"StudioFeaturesResult")};
1281
+ ${te}${W.constant}${q.constant}${qe}${Fe}${me}${we}${oe}${le}${B.specs}${Se}
1282
1282
  export interface ShardDOConfig {
1283
1283
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1284
1284
  cdc?: boolean;
@@ -1293,27 +1293,27 @@ export interface ShardDOConfig {
1293
1293
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1294
1294
  scheduler?: (env: Record<string, unknown>) => unknown;
1295
1295
  /** \`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. */
1296
- storage?: (env: Record<string, unknown>, origin?: string) => unknown;${gt}${ke}${S.configField}${R.configField}${x.configField}${I.configField}${_.configField}${$.configField}${M.configField}${P.configField}${je}${Qe}${bt}${ft}${wt}${Y.configField}
1296
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${Xe}${b.configFields}${O.configField}${xe}${Ee}${Je}${Ye}${Ze}${W.configField}
1297
1297
  }
1298
- ${q("schedulerStub",vt,["cancel","runAfter","runAt"])}${q("storageStub",kt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${St}${_t}${At}${S.stub}${R.stub}${x.stub}${I.stub}${_.stub}${$.stub}${M.stub}${P.stub}${Ke}${Xe}
1299
- ${Tr}
1298
+ ${C("schedulerStub",tt,["cancel","runAfter","runAt"])}${C("storageStub",rt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${at}${mt}${ot}${b.stubs}${Oe}${Le}
1299
+ ${tr}
1300
1300
 
1301
1301
  /**
1302
1302
  * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1303
1303
  * from the worker entry so wrangler binds it by name.
1304
1304
  */
1305
1305
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1306
- class extends ShardDOBase {${Pt}
1306
+ class extends ShardDOBase {${ft}
1307
1307
  private migrated = false;
1308
1308
 
1309
- ${Er}
1310
- ${he.override}
1311
- ${Lr}
1312
- ${lt}${mt}${Lt}${Ct}
1309
+ ${rr}
1310
+ ${Z.override}
1311
+ ${ar}
1312
+ ${Ve}${ze}${ht}${ut}
1313
1313
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1314
1314
  return LUNORA_LIFECYCLE_HOOKS[event];
1315
1315
  }
1316
- ${Y.override}${$t}
1316
+ ${W.override}${gt}
1317
1317
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1318
1318
  // socket-terminated half of the same reactivity — and differs only in who
1319
1319
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1401,7 +1401,7 @@ ${Y.override}${$t}
1401
1401
  protected override studioFeatures(): StudioFeaturesResult {
1402
1402
  return LUNORA_STUDIO_FEATURES;
1403
1403
  }
1404
- ${G.evaluateOverride}${G.subscriptionOverride}${at}${st}
1404
+ ${q.evaluateOverride}${q.subscriptionOverride}${Ne}${Be}
1405
1405
  protected override advisories(): AdvisoryFinding[] {
1406
1406
  return LUNORA_ADVISORIES;
1407
1407
  }
@@ -1410,17 +1410,17 @@ ${G.evaluateOverride}${G.subscriptionOverride}${at}${st}
1410
1410
  return LUNORA_ADVISOR_PROCEDURES;
1411
1411
  }
1412
1412
 
1413
- ${Dr}
1413
+ ${Zt}
1414
1414
 
1415
1415
  protected override ensureMigrated(): void {
1416
1416
  if (this.migrated) {
1417
1417
  return;
1418
1418
  }
1419
1419
 
1420
- runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ye} });
1420
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${re} });
1421
1421
  this.migrated = true;
1422
1422
  }
1423
- ${ee?`
1423
+ ${H?`
1424
1424
  protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1425
1425
  // Migrations create the fts5 companions; without them every backfill
1426
1426
  // statement would raise "no such table" on a shard that has never
@@ -1429,7 +1429,7 @@ ${ee?`
1429
1429
 
1430
1430
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1431
1431
  }
1432
- `:""}${Rt}
1433
- ${Or({actionOnlyFields:Ut,agentsBuild:qe,agentsContextField:Ne,containersBuild:Le,containersContextField:Ce,databaseOptions:Dt,everyContextBuild:qt,everyContextField:Nt,facadeBlock:Ft,globalDatabaseLine:Et,notifyBuild:Bt,ormContextField:Tt,paymentsBuild:We,paymentsContextField:He,queuesBuild:Se,queuesContextField:Re,topicsBuild:De,topicsContextField:Oe,vectorsBuild:xt,vectorsContextField:Ot,workflowsBuild:$e,workflowsContextField:Me,actionOnlyBuild:Wt})}
1432
+ `:""}${nt}
1433
+ ${er({actionOnlyFields:St,agentsBuild:ye,agentsContextField:ve,containersBuild:he,containersContextField:ue,databaseOptions:it,everyContextBuild:yt,everyContextField:vt,facadeBlock:wt,globalDatabaseLine:lt,notifyBuild:kt,ormContextField:ct,paymentsBuild:Re,paymentsContextField:Ae,queuesBuild:ae,queuesContextField:ne,topicsBuild:ie,topicsContextField:de,vectorsBuild:st,vectorsContextField:dt,workflowsBuild:ge,workflowsContextField:be,actionOnlyBuild:Rt})}
1434
1434
  };
1435
- `};export{Ir as b,Zr as e};
1435
+ `};export{sr as b,Dr as e};