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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{LunoraError as Mt}from"@lunora/errors";import{serializeSchemaSnapshot as Pt,hashSchemaSnapshot as qt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Nt,isD1GlobalTable as Ft}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as l}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as Ut,a as Bt,b as Wt,c as jt,d as Ht,f as Vt,g as Kt,h as Gt,i as Qt,j as zt,k as Xt,l as Jt,m as Yt,n as Zt,o as er,p as tr,q as rr,s as ar,t as nr,u as sr,v as or,w as ir,x as dr}from"./shard-runtime-CM5qthZc.mjs";import{u as J,i as cr,G as lr,d as hr}from"./shared-DjUziztz.mjs";const ur=` /**
1
+ import{LunoraError as Pt}from"@lunora/errors";import{serializeSchemaSnapshot as qt,hashSchemaSnapshot as Ft}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Nt,isD1GlobalTable as Ut}from"./isD1GlobalTable-udvHAAzD.mjs";import{i as Bt}from"./ir-BgM8A3XV.mjs";import{r as l}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as Wt,a as jt,b as Ht,c as Vt,d as Kt,f as Gt,g as Qt,h as zt,i as Xt,j as Jt,k as Yt,l as Zt,m as er,n as tr,o as rr,p as ar,q as nr,s as sr,t as or,u as ir,v as dr,w as cr,x as lr,y as hr}from"./shard-runtime-B5SUfdZB.mjs";import{u as Z,i as ur,G as pr,d as mr}from"./shared-DjUziztz.mjs";const gr=` /**
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 Mt}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});`,pr=`${ur}
33
+ }`,m=(a="")=>` const writer = this.adminWriter(${a});`,br=`${gr}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -225,7 +225,7 @@ ${m()}
225
225
  await applyCdcChanges(writer, args.changes);
226
226
 
227
227
  return { applied: args.changes.length };
228
- }`,mr=({actionOnlyBuild:a,actionOnlyFields:r,agentsBuild:e,agentsContextField:n,containersBuild:t,containersContextField:o,databaseOptions:d,everyContextBuild:g,everyContextField:b,facadeBlock:c,globalDatabaseLine:h,notifyBuild:f,ormContextField:D,paymentsBuild:N,paymentsContextField:F,queuesBuild:U,queuesContextField:O,vectorsBuild:T,vectorsContextField:B,workflowsBuild:E,workflowsContextField:W})=>{const C=r.length>0,w=C?`
228
+ }`,fr=({actionOnlyBuild:a,actionOnlyFields:r,agentsBuild:e,agentsContextField:n,containersBuild:t,containersContextField:o,databaseOptions:d,everyContextBuild:g,everyContextField:b,facadeBlock:c,globalDatabaseLine:h,notifyBuild:f,ormContextField:D,paymentsBuild:F,paymentsContextField:N,queuesBuild:U,queuesContextField:O,vectorsBuild:T,vectorsContextField:B,workflowsBuild:E,workflowsContextField:W})=>{const C=r.length>0,w=C?`
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) {
@@ -368,7 +368,7 @@ ${h} // \`ctx.db\`, wrapped in automatic instrumentation: by default
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}${F}
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\`
@@ -423,7 +423,7 @@ ${f}
423
423
  scheduler,
424
424
  span,
425
425
  storage: contextStorage,
426
- trace,${B}${b}${F}${o}${W}${O}${n}
426
+ trace,${B}${b}${N}${o}${W}${O}${n}
427
427
  };
428
428
  ${C?` const isAction = contextKind === "action";
429
429
  `:""}${w}
@@ -496,7 +496,7 @@ ${r.map(i=>` delete descriptors.${i};
496
496
  installRun(ctx, contextKind);
497
497
 
498
498
  return ctx;
499
- }`},gr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
499
+ }`},wr=`// 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
- };`,br=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
565
+ };`,yr=` 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
- }`,fr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
742
+ }`,vr=` 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
- }`,wr=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=J(o);d.kind==="id"&&d.tableName!==void 0&&(n[t]=d.tableName)}Object.keys(n).length>0&&(r[e.name]=n)}return r},yr=a=>{const r={};for(const e of a.tables){const n=[];for(const[t,o]of Object.entries(e.shape))J(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},vr=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},kr=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},Sr=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},Rr=(a,r,e)=>{const n=J(r),t={name:a,optional:cr(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=Sr(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},xr=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(Rr(o,d,t));r[e.name]=n}return r},Ar=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=r?`
781
+ }`,kr=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=Z(o);d.kind==="id"&&d.tableName!==void 0&&(n[t]=d.tableName)}Object.keys(n).length>0&&(r[e.name]=n)}return r},Sr=a=>{const r={};for(const e of a.tables){const n=[];for(const[t,o]of Object.entries(e.shape))Z(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},Rr=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},xr=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},Ar=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},Dr=(a,r,e)=>{const n=Z(r),t={name:a,optional:ur(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=Ar(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},Or=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(Dr(o,d,t));r[e.name]=n}return r},Tr=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=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
 
@@ -849,7 +849,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
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}},Dr=(a,r)=>a?`
852
+ `:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},Er=(a,r)=>a?`
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
- `:"",Or=a=>({externalSourceOverride:a?`
911
+ `:"",Cr=a=>({externalSourceOverride:a?`
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)
@@ -1061,7 +1061,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
1061
1061
  `:"",sourceClientCacheConst:a?`
1062
1062
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1063
1063
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1064
- `:""}),Tr=(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();
1064
+ `:""}),Lr=(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
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?`
1066
1066
  const vectorSync = this.vectorSync(env);
1067
1067
  // Vectorize lives outside this shard's SQLite, so a query whose result
@@ -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}},Fr=({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:h=!1,hasHyperdrive:f=!1,hasImages:D=!1,hasKv:N=!1,hasNotify:F=!1,hasPayments:U=!1,hasPipelines:O=!1,hasR2sql:T=!1,hasVectors:B=!0,hasX402:E=!1,maskMetadata:W,mutators:C=[],queues:w=[],rlsMetadata:Y,schema:i,schemaSnapshot:y,shapes:ce=[],storageRules:le,studioFeatures:he,useUmbrella:ue=!1,workflows:j=[]})=>{const u=hr(ue),Z=C.length>0,v=ce.length>0,pe=y===void 0?"":Pt(y),me=y===void 0?"":`
1108
+ `:"",vectorsBuild:c,vectorsStub:t}},jr=({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:h=!1,hasHyperdrive:f=!1,hasImages:D=!1,hasKv:F=!1,hasNotify:N=!1,hasPayments:U=!1,hasPipelines:O=!1,hasR2sql:T=!1,hasVectors:B=!0,hasX402:E=!1,maskMetadata:W,mutators:C=[],queues:w=[],rlsMetadata:ee,schema:i,schemaSnapshot:y,shapes:le=[],storageRules:he,studioFeatures:ue,useUmbrella:pe=!1,workflows:j=[]})=>{const u=mr(pe),te=C.length>0,v=le.length>0,me=y===void 0?"":qt(y),ge=y===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(qt(y))}, json: ${JSON.stringify(pe)} };
1111
- `,ge=y===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:be,configField:fe}=Ut(g),H=ir(d),k=Bt(N),S=Wt(h,u.flags),V=jt(o,h,u.flags),K=dr(F),G=Ht(t),R=Vt(b),L=Kt(D),I=Gt(f),_=Qt(c),$=zt(T),M=Xt(O),{build:we,contextField:ye,importLines:ve,specs:ke}=Jt(w),{build:Se,contextField:Re,importLines:xe,specs:Ae}=Yt(n,i.jurisdiction),{build:De,contextField:Oe,importLines:Te,specs:Ee}=Zt(j),{build:Ce,contextField:Le,importLines:Ie,specs:_e}=er(e),{build:$e,configField:Me,contextField:Pe,imports:qe,stub:Ne}=tr(U),{build:Fe,configField:Ue,imports:Be,stub:We}=rr(E),je=a,He=r,ee=Y??{policies:[],roles:[]},Ve=W??{columns:[]},Ke=le??{rules:[]},Ge=he??{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:ze}=ar(j),{constant:Xe,override:Je}=nr(w),p=B&&i.vectorIndexes.length>0,te=new Set(i.tables.filter(s=>typeof s.shardMode=="object"&&s.shardMode.kind==="shardBy").map(s=>s.name)),re=p&&i.vectorIndexes.some(s=>te.has(s.table)),x=i.tables.some(s=>s.shardMode==="global"),Q=i.tables.some(s=>Nt(s)),ae=i.tables.some(s=>Ft(s)),P=i.tables.some(s=>s.externalSource!==void 0),ne=i.tables.some(s=>s.memory===!0),z=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(ae&&Q)throw new Mt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const X=i.tables.length>0,Ye=wr(i),Ze=vr(i),et=xr(i),tt=yr(i),se=kr(i),oe=sr(p,j.length>0,w.length>0,h,z);v&&oe.push("WhereInput");const ie=or(x),{customMutatorOverride:rt,shapeGuardImport:at,shapeReadPolicyAssertion:nt,shapeReadPolicyImport:st,shapeResolveOverride:ot}=Ar({hasMutators:Z,hasShapes:v,rlsData:ee}),A=[`import type { ${oe.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, ${z?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ne?"clearMemoryTables, ":""}${at}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${re?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ie.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],v?`import { asBucketStorage, ${st}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];X&&A.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),p&&A.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),g&&A.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),A.push(...H.importLines,...k.importLines,...S.importLines,...K.importLines,...G.importLines,...R.importLines,...L.importLines,...I.importLines,..._.importLines,...$.importLines,...M.importLines,...xe,...Te,...ve,...Ie,...qe,...Be,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...Z?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const it=p?`
1112
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",dt=ae?`
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;`:"",ct=Q?`
1114
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",lt=P?`
1115
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",ht='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',ut='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',pt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',mt=x?q("globalDbStub: DatabaseWriterLike",ht,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:gt,vectorsBuild:bt,vectorsStub:ft}=Tr(p,re?i.vectorIndexes.filter(s=>te.has(s.table)).map(s=>s.name):[]),wt=`{
1110
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Ft(y))}, json: ${JSON.stringify(me)} };
1111
+ `,be=y===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:fe,configField:we}=Wt(g),H=lr(d),k=jt(F),S=Ht(h,u.flags),V=Vt(o,h,u.flags),K=hr(N),G=Kt(t),R=Gt(b),L=Qt(D),I=zt(f),_=Xt(c),$=Jt(T),M=Yt(O),{build:ye,contextField:ve,importLines:ke,specs:Se}=Zt(w),{build:Re,contextField:xe,importLines:Ae,specs:De}=er(n,i.jurisdiction),{build:Oe,contextField:Te,importLines:Ee,specs:Ce}=tr(j),{build:Le,contextField:Ie,importLines:_e,specs:$e}=rr(e),{build:Me,configField:Pe,contextField:qe,imports:Fe,stub:Ne}=ar(U),{build:Ue,configField:Be,imports:We,stub:je}=nr(E),He=a,Ve=r,re=ee??{policies:[],roles:[]},Ke=W??{columns:[]},Ge=he??{rules:[]},Qe=ue??{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:ze,override:Xe}=sr(j),{constant:Je,override:Ye}=or(w),p=B&&i.vectorIndexes.length>0,Q=new Set(i.tables.filter(s=>Bt(s)).map(s=>s.name)),ae=p&&i.vectorIndexes.some(s=>Q.has(s.table)),x=i.tables.some(s=>s.shardMode==="global"),z=ir(Q),X=i.tables.some(s=>Nt(s)),ne=i.tables.some(s=>Ut(s)),P=i.tables.some(s=>s.externalSource!==void 0),se=i.tables.some(s=>s.memory===!0),J=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(ne&&X)throw new Pt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Y=i.tables.length>0,Ze=kr(i),et=Rr(i),tt=Or(i),rt=Sr(i),oe=xr(i),ie=dr(p,j.length>0,w.length>0,h,J);v&&ie.push("WhereInput");const de=cr(x),{customMutatorOverride:at,shapeGuardImport:nt,shapeReadPolicyAssertion:st,shapeReadPolicyImport:ot,shapeResolveOverride:it}=Tr({hasMutators:te,hasShapes:v,rlsData:re}),A=[`import type { ${ie.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, ${J?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${se?"clearMemoryTables, ":""}${nt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],v?`import { asBucketStorage, ${ot}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];Y&&A.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),p&&A.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),g&&A.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),A.push(...H.importLines,...k.importLines,...S.importLines,...K.importLines,...G.importLines,...R.importLines,...L.importLines,...I.importLines,..._.importLines,...$.importLines,...M.importLines,...Ae,...Ee,...ke,..._e,...Fe,...We,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...te?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const dt=p?`
1112
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",ct=ne?`
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;`:"",lt=X?`
1114
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ht=P?`
1115
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",ut='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',pt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',mt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',gt=x?q("globalDbStub: DatabaseWriterLike",ut,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:bt,vectorsBuild:ft,vectorsStub:wt}=Lr(p,ae?i.vectorIndexes.filter(s=>Q.has(s.table)).map(s=>s.name):[]),yt=`{
1116
1116
  ...this.ctxDbTuning(),
1117
1117
  auth: { identity: identity ?? null, userId: userId ?? null },
1118
1118
  broadcast: (delta) => {
@@ -1164,22 +1164,22 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1164
1164
  sql: this.sql as SqlExec,
1165
1165
  storage,${x?`
1166
1166
  globalDb,`:""}
1167
- }`,yt=p?`
1168
- vectors,`:"",vt=X?`
1169
- orm: bindOrm(facade),`:"",de=Q?"config.hyperdriveGlobal":"config.d1",kt=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 = ${de}?.(env, globalRequest) ?? globalDbStub;
1171
- `:"",St=Dr(v&&x,de),{externalSourceOverride:Rt,sourceBootstrap:xt,sourceClientCacheConst:At}=Or(P),Dt=`
1167
+ }`,vt=p?`
1168
+ vectors,`:"",kt=Y?`
1169
+ orm: bindOrm(facade),`:"",ce=X?"config.hyperdriveGlobal":"config.d1",St=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 = ${ce}?.(env, globalRequest) ?? globalDbStub;
1171
+ `:"",Rt=Er(v&&x,ce),{externalSourceOverride:xt,sourceBootstrap:At,sourceClientCacheConst:Dt}=Cr(P),Ot=`
1172
1172
  protected override async runShardInit(): Promise<void> {
1173
1173
  this.ensureMigrated();
1174
- ${ne?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1174
+ ${se?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1175
1175
  `:""}
1176
1176
  await this.dispatchShardInit();
1177
1177
  }
1178
- `,Ot=se.length>0?`
1178
+ `,Tt=oe.length>0?`
1179
1179
  if (LUNORA_TTL_SWEEPS.length > 0) {
1180
1180
  void this.scheduleTtlSweep();
1181
1181
  }
1182
- `:"",Tt=`
1182
+ `:"",Et=`
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 @@ ${ne?` 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
- ${xt}${Ot} }
1195
+ ${At}${Tt} }
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 @@ ${xt}${Ot} }
1216
1216
  protected override isPaidFunction(functionPath: string): boolean {
1217
1217
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1218
1218
  }
1219
- `,Et=X?`
1219
+ `,Ct=Y?`
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
- `:"",Ct=`${H.build}${k.build}${S.build}${R.build}${G.build}
1223
+ `:"",Lt=`${H.build}${k.build}${S.build}${R.build}${G.build}
1224
1224
  const secrets = createSecrets(env);
1225
- `,Lt=`${H.contextField}${k.contextField}${S.contextField}${K.contextField}${R.contextField}${G.contextField}
1226
- secrets,`,It=K.build,_t=[...g?["ai"]:[],...D?["images"]:[],...f?["sql"]:[],...c?["browser"]:[],...T?["r2sql"]:[],...O?["pipelines"]:[],...E?["x402"]:[]],$t=`${be}${L.build}${I.build}${_.build}${$.build}${M.build}${Fe}`;return`${lr}${A.join(`
1225
+ `,It=`${H.contextField}${k.contextField}${S.contextField}${K.contextField}${R.contextField}${G.contextField}
1226
+ secrets,`,_t=K.build,$t=[...g?["ai"]:[],...D?["images"]:[],...f?["sql"]:[],...c?["browser"]:[],...T?["r2sql"]:[],...O?["pipelines"]:[],...E?["x402"]:[]],Mt=`${fe}${L.build}${I.build}${_.build}${$.build}${M.build}${Ue}`;return`${pr}${A.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(Ye,"Record<string, Record<string, string>>")};
1236
+ const LUNORA_TABLE_REFS = ${l(Ze,"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(Ze,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1239
+ const LUNORA_TABLE_INDEXES = ${l(et,'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(et,`Record<
1242
+ const LUNORA_TABLE_COLUMNS = ${l(tt,`Record<
1243
1243
  string,
1244
1244
  Array<{
1245
1245
  bucket?: string;
@@ -1256,29 +1256,29 @@ const LUNORA_TABLE_COLUMNS = ${l(et,`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(tt,"Record<string, string[]>")};
1259
+ const LUNORA_STORAGE_COLUMNS = ${l(rt,"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(se,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1262
+ const LUNORA_TTL_SWEEPS = ${l(oe,"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 = ${l(He,"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(He,"AdvisorProcedure[]")};
1268
+ const LUNORA_ADVISOR_PROCEDURES = ${l(Ve,"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(ee,"RlsPoliciesResult")};
1272
- ${nt}
1271
+ const LUNORA_RLS_METADATA = ${l(re,"RlsPoliciesResult")};
1272
+ ${st}
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(Ve,"MaskPoliciesResult")};
1274
+ const LUNORA_MASK_METADATA = ${l(Ke,"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(Ke,"StorageRulesResult")};
1277
+ const LUNORA_STORAGE_RULES = ${l(Ge,"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(Ge,"StudioFeaturesResult")};
1281
- ${me}${V.constant}${Qe}${Xe}${Ae}${Ee}${ke}${_e}
1280
+ const LUNORA_STUDIO_FEATURES = ${l(Qe,"StudioFeaturesResult")};
1281
+ ${ge}${z.constant}${V.constant}${ze}${Je}${De}${Ce}${Se}${$e}
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;${it}${fe}${k.configField}${S.configField}${R.configField}${L.configField}${I.configField}${_.configField}${$.configField}${M.configField}${Me}${Ue}${dt}${ct}${lt}
1296
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${dt}${we}${k.configField}${S.configField}${R.configField}${L.configField}${I.configField}${_.configField}${$.configField}${M.configField}${Pe}${Be}${ct}${lt}${ht}${z.configField}
1297
1297
  }
1298
- ${q("schedulerStub",ut,["cancel","runAfter","runAt"])}${q("storageStub",pt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${mt}${At}${ft}${k.stub}${S.stub}${R.stub}${L.stub}${I.stub}${_.stub}${$.stub}${M.stub}${Ne}${We}
1299
- ${gr}
1298
+ ${q("schedulerStub",pt,["cancel","runAfter","runAt"])}${q("storageStub",mt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${gt}${Dt}${wt}${k.stub}${S.stub}${R.stub}${L.stub}${I.stub}${_.stub}${$.stub}${M.stub}${Ne}${je}
1299
+ ${wr}
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 {${Tt}
1306
+ class extends ShardDOBase {${Et}
1307
1307
  private migrated = false;
1308
1308
 
1309
- ${br}
1310
- ${ie.override}
1311
- ${fr}
1312
- ${rt}${ot}${St}${Rt}
1309
+ ${yr}
1310
+ ${de.override}
1311
+ ${vr}
1312
+ ${at}${it}${Rt}${xt}
1313
1313
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1314
1314
  return LUNORA_LIFECYCLE_HOOKS[event];
1315
1315
  }
1316
- ${Dt}
1316
+ ${z.override}${Ot}
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 @@ ${Dt}
1401
1401
  protected override studioFeatures(): StudioFeaturesResult {
1402
1402
  return LUNORA_STUDIO_FEATURES;
1403
1403
  }
1404
- ${V.evaluateOverride}${V.subscriptionOverride}${ze}${Je}
1404
+ ${V.evaluateOverride}${V.subscriptionOverride}${Xe}${Ye}
1405
1405
  protected override advisories(): AdvisoryFinding[] {
1406
1406
  return LUNORA_ADVISORIES;
1407
1407
  }
@@ -1410,17 +1410,17 @@ ${V.evaluateOverride}${V.subscriptionOverride}${ze}${Je}
1410
1410
  return LUNORA_ADVISOR_PROCEDURES;
1411
1411
  }
1412
1412
 
1413
- ${pr}
1413
+ ${br}
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${ge} });
1420
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${be} });
1421
1421
  this.migrated = true;
1422
1422
  }
1423
- ${z?`
1423
+ ${J?`
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 @@ ${z?`
1429
1429
 
1430
1430
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1431
1431
  }
1432
- `:""}${gt}
1433
- ${mr({actionOnlyFields:_t,agentsBuild:Ce,agentsContextField:Le,containersBuild:Se,containersContextField:Re,databaseOptions:wt,everyContextBuild:Ct,everyContextField:Lt,facadeBlock:Et,globalDatabaseLine:kt,notifyBuild:It,ormContextField:vt,paymentsBuild:$e,paymentsContextField:Pe,queuesBuild:we,queuesContextField:ye,vectorsBuild:bt,vectorsContextField:yt,workflowsBuild:De,workflowsContextField:Oe,actionOnlyBuild:$t})}
1432
+ `:""}${bt}
1433
+ ${fr({actionOnlyFields:$t,agentsBuild:Le,agentsContextField:Ie,containersBuild:Re,containersContextField:xe,databaseOptions:yt,everyContextBuild:Lt,everyContextField:It,facadeBlock:Ct,globalDatabaseLine:St,notifyBuild:_t,ormContextField:kt,paymentsBuild:Me,paymentsContextField:qe,queuesBuild:ye,queuesContextField:ve,vectorsBuild:ft,vectorsContextField:vt,workflowsBuild:Oe,workflowsContextField:Te,actionOnlyBuild:Mt})}
1434
1434
  };
1435
- `};export{yr as b,Fr as e};
1435
+ `};export{Sr as b,jr as e};
@@ -1,4 +1,4 @@
1
- import{r as p}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUziztz.mjs";const x=e=>e?{importFragment:"serveRelationFanout, ",override:`
1
+ import{r as p}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUziztz.mjs";const k=e=>e?{importFragment:"serveRelationFanout, ",override:`
2
2
  protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
3
3
  this.ensureMigrated();
4
4
 
@@ -6,7 +6,7 @@ import{r as p}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUzi
6
6
 
7
7
  return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
8
8
  }
9
- `}:{importFragment:"",override:""},k=e=>e?{build:`
9
+ `}:{importFragment:"",override:""},x=e=>e?{build:`
10
10
  const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
11
11
  // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
12
12
  // function path + trace id into createAi, which folds them into the
@@ -30,7 +30,16 @@ import{r as p}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUzi
30
30
  const ${e} = {
31
31
  ${s}
32
32
  }${r};
33
- `},c={build:"",configField:"",contextField:"",importLines:[],stub:""},w=e=>e?{build:`
33
+ `},c={build:"",configField:"",contextField:"",importLines:[],stub:""},w=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
34
+ /** The \`.shardBy()\` tables this shard registers with the shard registry when it writes them. */
35
+ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(t=>JSON.stringify(t)).join(", ")}]);
36
+ `,override:`
37
+ protected override shardRegistry(): undefined | { namespace: unknown; shardedTables: ReadonlySet<string> } {
38
+ const namespace = config.shardRegistry?.((this.env ?? {}) as Record<string, unknown>);
39
+
40
+ return namespace === undefined ? undefined : { namespace, shardedTables: SHARDED_TABLES };
41
+ }
42
+ `},R=e=>e?{build:`
34
43
  const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
35
44
  // KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
36
45
  // when a value changes — a subscription that read one can never be proven
@@ -44,24 +53,24 @@ ${s}
44
53
  ]);
45
54
  `,configField:`
46
55
  kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
47
- kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:l("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:c,R=(e,t)=>e?{build:`
56
+ kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:l("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:c,N=(e,t)=>e?{build:`
48
57
  const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
49
58
  provider: () => config.flags?.(env),
50
59
  targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
51
60
  });
52
61
  `,configField:`
53
62
  flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
54
- flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:c,N=e=>e?{build:`
63
+ flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:c,S=e=>e?{build:`
55
64
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
56
65
  `,configField:"",contextField:`
57
66
  notify,
58
- push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:c,S=e=>e?{build:`
67
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:c,L=e=>e?{build:`
59
68
  const envConfig = lunoraEnvContract.${e.exportName}(env);
60
69
  `,configField:"",contextField:`
61
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:c,L=e=>e?{build:`
70
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:c,A=e=>e?{build:`
62
71
  const access = accessFacade(identity, userId);
63
72
  `,configField:"",contextField:`
64
- access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:c,$=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=i=>`
73
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:c,F=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=i=>`
65
74
  const env = (this.env ?? {}) as Record<string, unknown>;
66
75
  const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
67
76
  provider: () => config.flags?.(env),
@@ -123,25 +132,25 @@ const LUNORA_FLAG_KEYS = ${p(e,'ReadonlyArray<{ key: string; type: "boolean" | "
123
132
 
124
133
  return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
125
134
  }
126
- `;return{constant:o,evaluateOverride:s,subscriptionOverride:u}},F=e=>e?{build:`
135
+ `;return{constant:o,evaluateOverride:s,subscriptionOverride:u}},$=e=>e?{build:`
127
136
  const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
128
137
  const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
129
138
  `,configField:`
130
139
  analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
131
- analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:l("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:c,A=e=>e?{build:`
140
+ analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:l("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:c,C=e=>e?{build:`
132
141
  const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
133
142
  const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
134
143
  `,configField:`
135
144
  images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
136
- images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:l("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:c,C=e=>e?{build:`
145
+ images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:l("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:c,_=e=>e?{build:`
137
146
  const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
138
147
  `,configField:`
139
148
  sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
140
- sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:l("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:c,_=e=>e?{build:`
149
+ sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:l("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:c,E=e=>e?{build:`
141
150
  const browser: Browser = config.browser ? config.browser(env) : browserStub;
142
151
  `,configField:`
143
152
  browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
144
- browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:l("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:c,E=e=>e?{build:`
153
+ browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:l("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:c,O=e=>e?{build:`
145
154
  const r2sqlEnv = env as Record<string, unknown>;
146
155
  const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
147
156
  const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
@@ -152,11 +161,11 @@ const LUNORA_FLAG_KEYS = ${p(e,'ReadonlyArray<{ key: string; type: "boolean" | "
152
161
  ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
153
162
  : r2sqlStub;
154
163
  `,configField:`
155
- r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:l("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:c,O=e=>e?{build:`
164
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:l("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:c,P=e=>e?{build:`
156
165
  const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
157
166
  const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
158
167
  `,configField:`
159
- pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:l("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:c,P=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(a(s.exportName,`container export "${s.exportName}"`),a(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
168
+ pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:l("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:c,q=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(a(s.exportName,`container export "${s.exportName}"`),a(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
160
169
  export class ${s.className} extends LunoraContainer {
161
170
  public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
162
171
  super(ctx, env, ${s.exportName}, "${s.exportName}"${n});
@@ -181,7 +190,7 @@ import { ${o} } from "../containers.js";
181
190
 
182
191
  export { ContainerProxy } from "@lunora/container/do";
183
192
 
184
- ${r}`},q=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)a(r.exportName,`container export "${r.exportName}"`),a(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
193
+ ${r}`},I=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)a(r.exportName,`container export "${r.exportName}"`),a(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
185
194
  `);return{build:`
186
195
  const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
187
196
  `,contextField:`
@@ -190,7 +199,7 @@ ${r}`},q=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],
190
199
  const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
191
200
  ${n}
192
201
  ];
193
- `}},I=e=>{if(e.length===0)return"";const t=e.map(r=>(a(r.exportName,`workflow export "${r.exportName}"`),a(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
202
+ `}},B=e=>{if(e.length===0)return"";const t=e.map(r=>(a(r.exportName,`workflow export "${r.exportName}"`),a(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
194
203
  export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
195
204
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
196
205
  super(ctx, env, ${r.exportName}, "${r.exportName}");
@@ -246,7 +255,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
246
255
 
247
256
  import { ${o} } from "../agents.js";
248
257
 
249
- ${r}`},B=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)a(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { binding: ${JSON.stringify(o.bindingName)}, definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
258
+ ${r}`},D=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)a(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { binding: ${JSON.stringify(o.bindingName)}, definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
250
259
  `);return`${d}/**
251
260
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
252
261
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
@@ -261,7 +270,7 @@ import { ${n} } from "../queues.js";
261
270
  export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
262
271
  ${r}
263
272
  };
264
- `},D=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`workflow export "${n.exportName}"`),a(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
273
+ `},T=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`workflow export "${n.exportName}"`),a(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
265
274
  `);return{build:`
266
275
  const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
267
276
  `,contextField:`
@@ -270,7 +279,7 @@ ${r}
270
279
  const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
271
280
  ${t}
272
281
  ];
273
- `}},T=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`queue export "${n.exportName}"`),a(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
282
+ `}},j=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`queue export "${n.exportName}"`),a(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
274
283
  `);return{build:`
275
284
  const queues = createQueueContext(env, LUNORA_QUEUES);
276
285
  `,contextField:`
@@ -279,7 +288,7 @@ ${t}
279
288
  const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
280
289
  ${t}
281
290
  ];
282
- `}},j=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`agent export "${n.exportName}"`),a(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
291
+ `}},U=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`agent export "${n.exportName}"`),a(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
283
292
  `);return{build:`
284
293
  const agents = createAgentContext(env, LUNORA_AGENTS);
285
294
  `,contextField:`
@@ -295,15 +304,15 @@ const ${e} = ${p(r,t)};
295
304
  protected override ${n}(): ${t} {
296
305
  return ${e};
297
306
  }
298
- `}),U=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return f("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},M=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return f("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Q=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
307
+ `}),M=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return f("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Q=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return f("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},K=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
299
308
  const payments: LunoraPayment = config.payment
300
309
  ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
301
310
  : paymentStub;
302
311
  `,configField:`
303
312
  payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
304
- payments,`,stub:l("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},K=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
313
+ payments,`,stub:l("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},V=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
305
314
  const x402: X402Pay = config.x402
306
315
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
307
316
  : x402Stub;
308
317
  `,configField:`
309
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:l("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},V=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{I as A,B,w as a,R as b,$ as c,S as d,k as e,F as f,A as g,C as h,_ as i,E as j,O as k,T as l,q as m,D as n,j as o,Q as p,K as q,l as r,U as s,M as t,V as u,x as v,L as w,N as x,W as y,P as z};
318
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:l("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},H=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{q as A,B,D as C,R as a,N as b,F as c,L as d,x as e,$ as f,C as g,_ as h,E as i,O as j,P as k,j as l,I as m,T as n,U as o,K as p,V as q,l as r,M as s,Q as t,w as u,H as v,k as w,A as x,S as y,W as z};