@lunora/codegen 1.0.0-alpha.244 → 1.0.0-alpha.245

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 Ut}from"@lunora/errors";import{serializeSchemaSnapshot as Wt,hashSchemaSnapshot as jt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Ht,isD1GlobalTable as Vt}from"./isD1GlobalTable-udvHAAzD.mjs";import{p as Kt,i as Gt}from"./ir-DBSvhNa-.mjs";import{r as l}from"./json-data-Chfs2Cz5.mjs";import{r as F,e as Qt,a as zt,b as Xt,c as Jt,d as Yt,f as Zt,g as er,h as tr,i as rr,j as ar,k as nr,l as sr,m as or,n as ir,o as dr,p as cr,q as lr,s as hr,t as ur,u as pr,v as mr,w as gr,x as br,y as fr,z as wr}from"./shard-runtime-oIXHEMU7.mjs";import{u as te,i as yr,G as vr,d as kr}from"./shared-DjUziztz.mjs";const Sr=` /**
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-D9GRosnD.mjs";import{u as re,i as Sr,G as Rr,d as xr}from"./shared-DjUziztz.mjs";const Ar=` /**
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 Ut}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});`,Rr=`${Sr}
33
+ }`,m=(a="")=>` const writer = this.adminWriter(${a});`,Dr=`${Ar}
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
- }`,xr=({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: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
+ }`,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?`
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) {
@@ -362,7 +362,7 @@ ${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
- ${h} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
365
+ ${u} // \`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
@@ -496,7 +496,7 @@ ${r.map(v=>` delete descriptors.${v};
496
496
  installRun(ctx, contextKind);
497
497
 
498
498
  return ctx;
499
- }`},Ar=`// 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
- };`,Dr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
565
+ };`,Er=` 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
- }`,Or=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
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> {
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
- }`,Tr=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=te(o);d.kind==="id"&&d.tableName!==void 0&&(n[t]=d.tableName)}Object.keys(n).length>0&&(r[e.name]=n)}return r},Er=a=>{const r={};for(const e of a.tables){const n=[];for(const[t,o]of Object.entries(e.shape))te(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},Lr=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},Cr=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},Ir=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},_r=(a,r,e)=>{const n=te(r),t={name:a,optional:yr(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=Ir(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},$r=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(_r(o,d,t));r[e.name]=n}return r},Mr=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=r?`
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?`
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,h)=>c.localeCompare(h)):[],o=t.length>0?`
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?`
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
848
  `:"";return{customMutatorOverride:a?`
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}},Pr=(a,r)=>a?`
852
+ `:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},Nr=(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
- `:"",qr=a=>({externalSourceOverride:a?`
911
+ `:"",Br=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
- `:""}),Fr=(a,r)=>{const e=r.length>0,t=a?F("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
+ `:""}),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
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}},Xr=({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: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:he,studioFeatures:ue,topics:pe=[],useUmbrella:me=!1,workflows:V=[]})=>{const u=kr(me),re=H.length>0,k=v.length>0,ge=y===void 0?"":Wt(y),be=y===void 0?"":`
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?"":`
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(jt(y))}, json: ${JSON.stringify(ge)} };
1111
- `,fe=y===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:we,configField:ye}=Qt(g),K=fr(d),S=zt(N),R=Xt(h,u.flags),G=Jt(o,h,u.flags),Q=wr(B),z=Yt(t),x=Zt(b),I=er(O),_=tr(f),$=rr(c),M=ar(E),P=nr(T),{build:ve,contextField:ke,importLines:Se,specs:Re}=sr(Kt(w)),{build:xe,contextField:Ae,importLines:De,specs:Oe}=or(pe,w),{build:Te,contextField:Ee,importLines:Le,specs:Ce}=ir(n,i.jurisdiction),{build:Ie,contextField:_e,importLines:$e,specs:Me}=dr(V),{build:Pe,contextField:qe,importLines:Fe,specs:Ne}=cr(e),{build:Be,configField:Ue,contextField:We,imports:je,stub:He}=lr(U),{build:Ve,configField:Ke,imports:Ge,stub:Qe}=hr(L),ze=a,Xe=r,ae=C??{policies:[],roles:[]},Je=j??{columns:[]},Ye=he??{rules:[]},Ze=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:et,override:tt}=ur(V),{constant:rt,override:at}=pr(w),p=W&&i.vectorIndexes.length>0,X=new Set(i.tables.filter(s=>Gt(s)).map(s=>s.name)),ne=p&&i.vectorIndexes.some(s=>X.has(s.table)),A=i.tables.some(s=>s.shardMode==="global"),J=mr(X),Y=i.tables.some(s=>Ht(s)),se=i.tables.some(s=>Vt(s)),q=i.tables.some(s=>s.externalSource!==void 0),oe=i.tables.some(s=>s.memory===!0),Z=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&Y)throw new Ut("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const ee=i.tables.length>0,nt=Tr(i),st=Lr(i),ot=$r(i),it=Er(i),ie=Cr(i),de=gr(p,V.length>0,w.length>0,h,Z);k&&de.push("WhereInput");const ce=br(A),{customMutatorOverride:dt,shapeGuardImport:ct,shapeReadPolicyAssertion:lt,shapeReadPolicyImport:ht,shapeResolveOverride:ut}=Mr({hasMutators:re,hasShapes:k,rlsData:ae}),D=[`import type { ${de.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, ${Z?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${ct}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${q?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ne?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ce.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,...q?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],k?`import { asBucketStorage, ${ht}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];ee&&D.push(`import { bindOrm, bindTableFacade } from "${u.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,...Le,...$e,...Se,...De,...Fe,...je,...Ge,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...re?["LUNORA_MUTATOR_PATHS"]:[],...k?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const pt=p?`
1112
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",mt=se?`
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;`:"",gt=Y?`
1114
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",bt=q?`
1115
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",ft='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',wt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',yt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',vt=A?F("globalDbStub: DatabaseWriterLike",ft,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:kt,vectorsBuild:St,vectorsStub:Rt}=Fr(p,ne?i.vectorIndexes.filter(s=>X.has(s.table)).map(s=>s.name):[]),xt=`{
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=`{
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,${A?`
1166
1166
  globalDb,`:""}
1167
- }`,At=p?`
1168
- vectors,`:"",Dt=ee?`
1169
- orm: bindOrm(facade),`:"",le=Y?"config.hyperdriveGlobal":"config.d1",Ot=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 = ${le}?.(env, globalRequest) ?? globalDbStub;
1171
- `:"",Tt=Pr(k&&A,le),{externalSourceOverride:Et,sourceBootstrap:Lt,sourceClientCacheConst:Ct}=qr(q),It=`
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=`
1172
1172
  protected override async runShardInit(): Promise<void> {
1173
1173
  this.ensureMigrated();
1174
- ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1174
+ ${de?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1175
1175
  `:""}
1176
1176
  await this.dispatchShardInit();
1177
1177
  }
1178
- `,_t=ie.length>0?`
1178
+ `,Mt=ce.length>0?`
1179
1179
  if (LUNORA_TTL_SWEEPS.length > 0) {
1180
1180
  void this.scheduleTtlSweep();
1181
1181
  }
1182
- `:"",$t=`
1182
+ `:"",Pt=`
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 @@ ${oe?` 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
- ${Lt}${_t} }
1195
+ ${It}${Mt} }
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 @@ ${Lt}${_t} }
1216
1216
  protected override isPaidFunction(functionPath: string): boolean {
1217
1217
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1218
1218
  }
1219
- `,Mt=ee?`
1219
+ `,Ft=te?`
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
- `:"",Pt=`${K.build}${S.build}${R.build}${x.build}${z.build}
1223
+ `:"",qt=`${K.build}${S.build}${R.build}${x.build}${z.build}
1224
1224
  const secrets = createSecrets(env);
1225
- `,qt=`${K.contextField}${S.contextField}${R.contextField}${Q.contextField}${x.contextField}${z.contextField}
1226
- secrets,`,Ft=Q.build,Nt=[...g?["ai"]:[],...O?["images"]:[],...f?["sql"]:[],...c?["browser"]:[],...E?["r2sql"]:[],...T?["pipelines"]:[],...L?["x402"]:[]],Bt=`${we}${I.build}${_.build}${$.build}${M.build}${P.build}${Ve}`;return`${vr}${D.join(`
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(`
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(nt,"Record<string, Record<string, string>>")};
1236
+ const LUNORA_TABLE_REFS = ${l(ot,"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(st,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1239
+ const LUNORA_TABLE_INDEXES = ${l(it,'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(ot,`Record<
1242
+ const LUNORA_TABLE_COLUMNS = ${l(dt,`Record<
1243
1243
  string,
1244
1244
  Array<{
1245
1245
  bucket?: string;
@@ -1256,29 +1256,29 @@ const LUNORA_TABLE_COLUMNS = ${l(ot,`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(it,"Record<string, string[]>")};
1259
+ const LUNORA_STORAGE_COLUMNS = ${l(ct,"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(ie,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1262
+ const LUNORA_TTL_SWEEPS = ${l(ce,"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(ze,"AdvisoryFinding[]")};
1265
+ const LUNORA_ADVISORIES = ${l(Je,"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(Xe,"AdvisorProcedure[]")};
1268
+ const LUNORA_ADVISOR_PROCEDURES = ${l(Ye,"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(ae,"RlsPoliciesResult")};
1272
- ${lt}
1271
+ const LUNORA_RLS_METADATA = ${l(se,"RlsPoliciesResult")};
1272
+ ${ut}
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(Je,"MaskPoliciesResult")};
1274
+ const LUNORA_MASK_METADATA = ${l(Ze,"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(Ye,"StorageRulesResult")};
1277
+ const LUNORA_STORAGE_RULES = ${l(et,"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(Ze,"StudioFeaturesResult")};
1281
- ${be}${J.constant}${G.constant}${et}${rt}${Ce}${Me}${Re}${Oe}${Ne}
1280
+ const LUNORA_STUDIO_FEATURES = ${l(tt,"StudioFeaturesResult")};
1281
+ ${we}${Y.constant}${G.constant}${rt}${nt}${_e}${Fe}${Ae}${Ee}${X.specs}${Ue}
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;${pt}${ye}${S.configField}${R.configField}${x.configField}${I.configField}${_.configField}${$.configField}${M.configField}${P.configField}${Ue}${Ke}${mt}${gt}${bt}${J.configField}
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}
1297
1297
  }
1298
- ${F("schedulerStub",wt,["cancel","runAfter","runAt"])}${F("storageStub",yt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${vt}${Ct}${Rt}${S.stub}${R.stub}${x.stub}${I.stub}${_.stub}${$.stub}${M.stub}${P.stub}${He}${Qe}
1299
- ${Ar}
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}
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 {${$t}
1306
+ class extends ShardDOBase {${Pt}
1307
1307
  private migrated = false;
1308
1308
 
1309
- ${Dr}
1310
- ${ce.override}
1311
- ${Or}
1312
- ${dt}${ut}${Tt}${Et}
1309
+ ${Er}
1310
+ ${he.override}
1311
+ ${Lr}
1312
+ ${lt}${mt}${Lt}${Ct}
1313
1313
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1314
1314
  return LUNORA_LIFECYCLE_HOOKS[event];
1315
1315
  }
1316
- ${J.override}${It}
1316
+ ${Y.override}${$t}
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 @@ ${J.override}${It}
1401
1401
  protected override studioFeatures(): StudioFeaturesResult {
1402
1402
  return LUNORA_STUDIO_FEATURES;
1403
1403
  }
1404
- ${G.evaluateOverride}${G.subscriptionOverride}${tt}${at}
1404
+ ${G.evaluateOverride}${G.subscriptionOverride}${at}${st}
1405
1405
  protected override advisories(): AdvisoryFinding[] {
1406
1406
  return LUNORA_ADVISORIES;
1407
1407
  }
@@ -1410,17 +1410,17 @@ ${G.evaluateOverride}${G.subscriptionOverride}${tt}${at}
1410
1410
  return LUNORA_ADVISOR_PROCEDURES;
1411
1411
  }
1412
1412
 
1413
- ${Rr}
1413
+ ${Dr}
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${fe} });
1420
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ye} });
1421
1421
  this.migrated = true;
1422
1422
  }
1423
- ${Z?`
1423
+ ${ee?`
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
- `:""}${kt}
1433
- ${xr({actionOnlyFields:Nt,agentsBuild:Pe,agentsContextField:qe,containersBuild:Te,containersContextField:Ee,databaseOptions:xt,everyContextBuild:Pt,everyContextField:qt,facadeBlock:Mt,globalDatabaseLine:Ot,notifyBuild:Ft,ormContextField:Dt,paymentsBuild:Be,paymentsContextField:We,queuesBuild:ve,queuesContextField:ke,topicsBuild:xe,topicsContextField:Ae,vectorsBuild:St,vectorsContextField:At,workflowsBuild:Ie,workflowsContextField:_e,actionOnlyBuild:Bt})}
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})}
1434
1434
  };
1435
- `};export{Er as b,Xr as e};
1435
+ `};export{Ir as b,Zr as e};
@@ -30,7 +30,7 @@ import{s as h}from"./ir-DBSvhNa-.mjs";import{r as g}from"./json-data-Chfs2Cz5.mj
30
30
  const ${e} = {
31
31
  ${i}
32
32
  }${r};
33
- `},c={build:"",configField:"",contextField:"",importLines:[],stub:""},N=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:`
33
+ `},c={build:"",configField:"",contextField:"",importLines:[],stub:""},S=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
34
  /** The \`.shardBy()\` tables this shard registers with the shard registry when it writes them. */
35
35
  const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(t=>JSON.stringify(t)).join(", ")}]);
36
36
  `,override:`
@@ -39,7 +39,7 @@ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(t=>JSON.string
39
39
 
40
40
  return namespace === undefined ? undefined : { namespace, shardedTables: SHARDED_TABLES };
41
41
  }
42
- `},S=e=>e?{build:`
42
+ `},N=e=>e?{build:`
43
43
  const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
44
44
  // KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
45
45
  // when a value changes — a subscription that read one can never be proven
@@ -297,7 +297,15 @@ ${t}
297
297
  const LUNORA_TOPICS: ReadonlyArray<TopicBindingSpec> = [
298
298
  ${n}
299
299
  ];
300
- `}},K=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`agent export "${n.exportName}"`),a(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
300
+ `}},K=(e,t)=>{if(e.length===0)return{build:"",importLines:[],specs:""};const n=e.map(r=>(a(r.name,`service "${r.name}"`),a(r.binding,`service binding "${r.binding}"`),` { binding: "${r.binding}", name: "${r.name}"${r.entrypoint===void 0?"":", rpc: true"} },`)).join(`
301
+ `);return{build:`
302
+ const services = createServices(env, LUNORA_SERVICES);
303
+ `,importLines:[`import type { ServiceBindingSpec } from "${t}";`,`import { createServices } from "${t}";`],specs:`
304
+ /** Wiring specs for \`ctx.services\` (codegen-derived from \`lunora.config\` \`services\`). */
305
+ const LUNORA_SERVICES: ReadonlyArray<ServiceBindingSpec> = [
306
+ ${n}
307
+ ];
308
+ `}},V=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`agent export "${n.exportName}"`),a(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
301
309
  `);return{build:`
302
310
  const agents = createAgentContext(env, LUNORA_AGENTS, { exports: this.state.exports });
303
311
  `,contextField:`
@@ -313,15 +321,15 @@ const ${e} = ${g(r,t)};
313
321
  protected override ${n}(): ${t} {
314
322
  return ${e};
315
323
  }
316
- `}),V=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({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. */")},H=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,...n.topic===void 0?{}:{topic:n.topic}}))};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. */")},G=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
324
+ `}),H=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({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. */")},G=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,...n.topic===void 0?{}:{topic:n.topic}}))};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. */")},Y=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
317
325
  const payments: LunoraPayment = config.payment
318
326
  ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
319
327
  : paymentStub;
320
328
  `,configField:`
321
329
  payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
322
- 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:""},Y=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
330
+ 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:""},J=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
323
331
  const x402: X402Pay = config.x402
324
332
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
325
333
  : x402Stub;
326
334
  `,configField:`
327
- 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:""},J=(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{T as A,B,D as C,j as D,S as a,L as b,C as c,A as d,R as e,_ as f,E as g,O as h,P as i,q as j,I as k,M as l,Q as m,W as n,U as o,K as p,G as q,l as r,Y as s,V as t,H as u,N as v,J as w,w as x,F as y,$ as z};
335
+ 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:""},X=(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{$ as A,T as B,B as C,D,j as E,N as a,L as b,C as c,A as d,R as e,_ as f,E as g,O as h,P as i,q as j,I as k,M as l,Q as m,K as n,W as o,U as p,V as q,l as r,Y as s,J as t,H as u,G as v,S as w,X as x,w as y,F as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.244",
3
+ "version": "1.0.0-alpha.245",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.176",
50
- "@lunora/agent": "1.0.0-alpha.158",
49
+ "@lunora/advisor": "1.0.0-alpha.177",
50
+ "@lunora/agent": "1.0.0-alpha.159",
51
51
  "@lunora/container": "1.0.0-alpha.64",
52
52
  "@lunora/errors": "1.0.0-alpha.48",
53
- "@lunora/platform": "1.0.0-alpha.47",
54
- "@lunora/queue": "1.0.0-alpha.83",
55
- "@lunora/scheduler": "1.0.0-alpha.101",
53
+ "@lunora/platform": "1.0.0-alpha.48",
54
+ "@lunora/queue": "1.0.0-alpha.84",
55
+ "@lunora/scheduler": "1.0.0-alpha.102",
56
56
  "@lunora/values": "1.0.0-alpha.58",
57
57
  "@lunora/workflow": "1.0.0-alpha.69",
58
58
  "jiti": "^2.7.0",
@@ -1 +0,0 @@
1
- import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h,CELLD_CAPABILITIES as v}from"@lunora/platform";import{readProjectConfigLiterals as m}from"./loadProjectConfig-CktK_il-.mjs";const c="cloudflare",b=t=>{const{target:e}=m(t);return e!==void 0&&e.length>0?e:void 0},L=(t,e)=>e??b(t)??c,x=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=m(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${c}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${c}" }\`), or pass \`--target\`.`,target:c}]},u={celld:v,cloudflare:h,node:f},C=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),w={access:null,ai:"ai",analytics:"analytics",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:null},S=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","cronTriggers","crossShardFanout","durableStreams","globalTables","queues","relationGraph","secrets","topics","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],g={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},y=(t,e,a)=>({level:"error",message:`${e.name} does not support ${g[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:a}),T=(t,e,a)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${g[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:a}),k=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:n,signals:d,target:i}=t;for(const s of S){if(d[s]!==!0)continue;const o=r.features[s]?.level;o!=="unsupported"&&o!==void 0||(a[s]=!1,!n.has(s)&&e.push(o==="unsupported"?y(s,r,i):T(s,r,i)))}},_=(t,e,a,r={})=>{const n={...t},d={...r},i=[],s=new Set;for(const[o,l]of Object.entries(w)){if(l===null||!t[o])continue;const p=e.features[l]?.level;p==="unsupported"?(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name} does not support "${o}" (ctx.${o}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${o} usage, or deploy to a target whose capability matrix marks "${l}" as native or emulated.`,target:a})):p===void 0&&(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${o}" (ctx.${o}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${l}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return k({diagnostics:i,gatedSignals:d,matrix:e,reported:s,signals:r,target:a}),{diagnostics:i,signals:d,usage:n}},E=(t,e,a={})=>{const r=u[e];return r===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],signals:{...a},usage:{...t}}:_(t,r,e,a)},I=t=>{const e=u[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,n)=>r.localeCompare(n));return{id:e.id,name:e.name,unsupported:a}};export{w as CAPABILITY_TO_FEATURE,c as DEFAULT_TARGET,_ as gateAgainstMatrix,E as gatePlatformFeatures,C as platformMatrixIds,b as readProjectTarget,x as readTargetDiagnostics,L as resolveCodegenTarget,I as studioPlatformFor};