@lunora/codegen 1.0.0-alpha.363 → 1.0.0-alpha.364

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 he}from"@lunora/errors";import{serializeSchemaSnapshot as Jt,hashSchemaSnapshot as Yt}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{isHyperdriveGlobalTable as zt,isD1GlobalTable as Xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Zt}from"./json-data-Chfs2Cz5.mjs";import{r as $,e as er,a as tr,b as rr,c as nr,d as ar,f as sr,g as or,h as ir,i as dr,j as cr,k as lr,l as ur,m as hr,n as pr,o as mr,p as fr,q as gr}from"./shard-runtime-DXlpfT3P.mjs";import{u as M,h as br,s as yr,a as wr,I as vr,c as kr,G as Sr,d as Rr}from"./shared-Br_OnErI.mjs";import{p as xr}from"./platform-8oj7iXQy.mjs";import{i as Ar}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,pe=["categories","description","facing","level","remediation","title"],Or=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(pe.filter(s=>s in o).map(s=>[s,o[s]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([s,i])=>!pe.includes(s)||JSON.stringify(i)!==JSON.stringify(n[s])))}),advisoryRules:t}},Dr=` /**
1
+ import{LunoraError as he}from"@lunora/errors";import{serializeSchemaSnapshot as Jt,hashSchemaSnapshot as zt}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{isHyperdriveGlobalTable as Yt,isD1GlobalTable as Xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Zt}from"./json-data-Chfs2Cz5.mjs";import{r as $,e as er,a as tr,b as rr,c as nr,d as ar,f as sr,g as or,h as ir,i as dr,j as cr,k as lr,l as ur,m as hr,n as pr,o as mr,p as fr,q as gr}from"./shard-runtime-DXlpfT3P.mjs";import{u as M,h as br,s as yr,a as wr,I as vr,c as kr,G as Sr,d as Rr}from"./shared-Br_OnErI.mjs";import{p as xr}from"./platform-8oj7iXQy.mjs";import{i as Ar}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,pe=["categories","description","facing","level","remediation","title"],Or=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(pe.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!pe.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Dr=` /**
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
@@ -234,7 +234,7 @@ ${y()}
234
234
  await applyCdcChanges(writer, args.changes);
235
235
 
236
236
  return { applied: args.changes.length };
237
- }`,_r=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,containersBuild:n,containersContextField:s,databaseOptions:i,everyContextBuild:l,everyContextField:u,facadeBlock:m,globalDatabaseLine:x,hasSensitiveArgs:S=!1,lazyFunctions:g=!1,notifyBuild:c,ormContextField:w,paymentsBuild:q,paymentsContextField:A,queuesBuild:F,queuesContextField:U,topicsBuild:R,topicsContextField:B,vectorsBuild:d,vectorsContextField:v,workflowsBuild:E,workflowsContextField:j})=>{const I=t.length>0,C=w===""?"{ db }":"{ db, orm: bindOrm(facade) }",W=w===""?"":`
237
+ }`,_r=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,containersBuild:n,containersContextField:a,databaseOptions:i,everyContextBuild:u,everyContextField:h,facadeBlock:m,globalDatabaseLine:x,hasSensitiveArgs:S=!1,lazyFunctions:g=!1,notifyBuild:c,ormContextField:w,paymentsBuild:q,paymentsContextField:A,queuesBuild:F,queuesContextField:U,topicsBuild:R,topicsContextField:B,vectorsBuild:d,vectorsContextField:v,workflowsBuild:E,workflowsContextField:j})=>{const I=t.length>0,C=w===""?"{ db }":"{ db, orm: bindOrm(facade) }",W=w===""?"":`
238
238
  orm: databaseContext.orm,`,K=w===""?"":`
239
239
  orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,O=I?`
240
240
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
@@ -270,7 +270,7 @@ ${r.replaceAll(/^(?=.)/gmu," ")}${t.map(f=>` ctx.${f} = ${f};`
270
270
  };
271
271
  })();
272
272
  const { identity, ip, userId } = caller;
273
- ${d}${l}${n}${E}${F}${R}${e}
273
+ ${d}${u}${n}${E}${F}${R}${e}
274
274
  // Which dispatch this ctx belongs to. Drives the two deferral facades
275
275
  // below and the \`ctx.run*\` caller guard; a ctx built for an
276
276
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -409,22 +409,14 @@ ${c}
409
409
  // advisor flags \`Date.now()\`. Actions may still use ambient \`Date.now()\`.
410
410
  const now = Date.now();
411
411
 
412
- // \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
413
- // mutation may be replayed, so a network call in either returns a different answer
414
- // on each run. Refused at runtime, not only linted: the advisor sees just the call
415
- // sites it can read, and a call inside a dependency is invisible to it.
416
- // Synchronous on purpose: an async refusal only rejects a promise the handler may
417
- // discard, and the handler would then return normally. A sync throw surfaces at the call.
418
- const refuseFetch = (): never => {
419
- throw new LunoraError("FORBIDDEN", "ctx.fetch is action-only: network I/O belongs in an action, not a query or mutation");
420
- };
421
-
422
412
  // A reactor run is driven by the writer's inline refresh, not replayed by the writer, so it must not
423
413
  // inherit the writer's key: every run would restart the same id and random sequence.
424
414
  const stableKey = options.replayKey !== false && options.identity === undefined && this.idempotencyNamespace() !== undefined ? this.getCurrentMutationId() : undefined;
425
- const stableScope = JSON.stringify([this.currentShardKey(), options.functionPath ?? "", this.idempotencyNamespace() ?? "", userId ?? ""]);
415
+ // Both factories ignore the scope without a replay key, and most dispatches have none.
416
+ const stableScope = stableKey === undefined ? "" : JSON.stringify([this.currentShardKey(), options.functionPath ?? "", this.idempotencyNamespace() ?? "", userId ?? ""]);
426
417
  // One sequence for every mutation this run composes: their ids share one counter (the copied \`newId\`), so their draws must too.
427
- const composedRandom = createStableRandomFactory(stableKey, stableScope);
418
+ // Created on the first composed mutation that gets a ctx of its own; most dispatches compose none.
419
+ let composedRandom: (() => number) | undefined;
428
420
 
429
421
  const ctx: Record<string, unknown> = {
430
422
  auth: {
@@ -470,7 +462,7 @@ ${c}
470
462
  scheduler,
471
463
  span,
472
464
  storage: contextStorage,
473
- trace,${v}${u}${A}${s}${j}${U}${B}${o}${S?`
465
+ trace,${v}${h}${A}${a}${j}${U}${B}${o}${S?`
474
466
  [Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
475
467
  };
476
468
  ${I?` const isAction = contextKind === "action";
@@ -500,6 +492,9 @@ ${g?` const captureScope = (): (() => void) => {
500
492
  : (() => {
501
493
  const mutationScheduler = withDeferredSchedules(schedulerBase, this.scheduleOutbox());
502
494
  const mutationDatabase = makeDatabaseContext(mutationScheduler);
495
+ // The composed mutation's ids come from the action's replay key and counter, so its draws do too; a
496
+ // fresh factory per call would repeat the same draws across sibling mutations.
497
+ const mutationRandom = (composedRandom ??= createStableRandomFactory(stableKey, stableScope));
503
498
 
504
499
  // Copied from an action's ctx, which carries the real \`fetch\`; a mutation
505
500
  // refuses network I/O wherever it runs, so its \`fetch\` is overridden here.
@@ -507,9 +502,7 @@ ${g?` const captureScope = (): (() => void) => {
507
502
  ...Object.getOwnPropertyDescriptors(target),
508
503
  db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${K}
509
504
  fetch: { configurable: true, enumerable: true, value: refuseFetch, writable: true },
510
- // The composed mutation's ids come from the action's replay key and counter, so its draws do too; a
511
- // fresh factory per call would repeat the same draws across sibling mutations.
512
- random: { configurable: true, enumerable: true, value: composedRandom, writable: true },
505
+ random: { configurable: true, enumerable: true, value: mutationRandom, writable: true },
513
506
  scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
514
507
  storage: { configurable: true, enumerable: true, value: withDeferredDeletes(storage), writable: true },
515
508
  });
@@ -949,7 +942,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
949
942
  }
950
943
  }
951
944
 
952
- `:"";return Ir.replace("__COMMITTED_CATCH__",r?Lr:"").replace("__PREPARE_FUNCTION__",`${e}${o}`)},Nr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,s]of Object.entries(e.shape)){const i=M(s);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},$r=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,s]of Object.entries(e.shape))M(s).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Mr=r=>{const t={};for(const e of r.tables){const o=[...e.indexes.map(n=>({fields:[...n.fields],name:n.name,type:"index",...n.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(n=>({fields:[n.field,...n.filterFields??[]],name:n.name,type:"search"})),...(e.geoIndexes??[]).map(n=>({fields:[n.field],name:n.name,type:"geo"})),...e.rankIndexes.map(n=>({fields:n.sortBy.map(s=>s.field),name:n.name,type:"rank"})),...e.vectorIndexes.map(n=>({fields:n.field===void 0?[]:[n.field],name:n.name,type:"vector"}))];o.length>0&&(t[e.name]=o)}return t},qr=r=>{const t=[];for(const e of r.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Fr=r=>{if(r.kind!=="union"||r.members===void 0||r.members.length===0)return;const t=[];for(const e of r.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const o=JSON.parse(e.literalValue);if(typeof o!="string")return;t.push(o)}catch{return}}return t},Ur=new Set(["bigint","boolean","date","number","timestamp"]),Br=r=>{const[t,e]=r.kind==="union"?r.members??[]:[];if(t===void 0||e===void 0||r.members?.length!==2)return;const o=s=>s.kind==="null"||s.kind==="literal"&&s.literalValue==="null",n=M(o(e)?t:e);return o(t)!==o(e)&&Ur.has(n.kind)?n:void 0},jr=(r,t,e)=>{const o=M(t),n=Br(o),s=n??o,i={name:r,optional:br(t),type:s.kind};if(s.kind==="id"&&s.tableName!==void 0){i.ref=s.tableName;const u=e.get(r);u!==void 0&&(i.onDelete=u)}s.kind==="storage"&&(i.isStorage=!0,s.bucket!==void 0&&(i.bucket=s.bucket));const l=Fr(s);return l!==void 0&&(i.enumValues=l),(s.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Wr=r=>{const t={};for(const e of r.tables){const o=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],n=new Map(e.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,i]of Object.entries(e.shape))o.push(jr(s,i,n));t[e.name]=o}return t},Kr=({hasMutators:r,hasSensitiveShapes:t,hasShapes:e,rlsData:o})=>{const n="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",s=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {
945
+ `:"";return Ir.replace("__COMMITTED_CATCH__",r?Lr:"").replace("__PREPARE_FUNCTION__",`${e}${o}`)},Nr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,a]of Object.entries(e.shape)){const i=M(a);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},$r=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,a]of Object.entries(e.shape))M(a).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Mr=r=>{const t={};for(const e of r.tables){const o=[...e.indexes.map(n=>({fields:[...n.fields],name:n.name,type:"index",...n.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(n=>({fields:[n.field,...n.filterFields??[]],name:n.name,type:"search"})),...(e.geoIndexes??[]).map(n=>({fields:[n.field],name:n.name,type:"geo"})),...e.rankIndexes.map(n=>({fields:n.sortBy.map(a=>a.field),name:n.name,type:"rank"})),...e.vectorIndexes.map(n=>({fields:n.field===void 0?[]:[n.field],name:n.name,type:"vector"}))];o.length>0&&(t[e.name]=o)}return t},qr=r=>{const t=[];for(const e of r.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Fr=r=>{if(r.kind!=="union"||r.members===void 0||r.members.length===0)return;const t=[];for(const e of r.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const o=JSON.parse(e.literalValue);if(typeof o!="string")return;t.push(o)}catch{return}}return t},Ur=new Set(["bigint","boolean","date","number","timestamp"]),Br=r=>{const[t,e]=r.kind==="union"?r.members??[]:[];if(t===void 0||e===void 0||r.members?.length!==2)return;const o=a=>a.kind==="null"||a.kind==="literal"&&a.literalValue==="null",n=M(o(e)?t:e);return o(t)!==o(e)&&Ur.has(n.kind)?n:void 0},jr=(r,t,e)=>{const o=M(t),n=Br(o),a=n??o,i={name:r,optional:br(t),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){i.ref=a.tableName;const h=e.get(r);h!==void 0&&(i.onDelete=h)}a.kind==="storage"&&(i.isStorage=!0,a.bucket!==void 0&&(i.bucket=a.bucket));const u=Fr(a);return u!==void 0&&(i.enumValues=u),(a.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Wr=r=>{const t={};for(const e of r.tables){const o=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],n=new Map(e.relations.flatMap(a=>a.kind==="one"?[[a.field,a.onDelete]]:[]));for(const[a,i]of Object.entries(e.shape))o.push(jr(a,i,n));t[e.name]=o}return t},Kr=({hasMutators:r,hasSensitiveShapes:t,hasShapes:e,rlsData:o})=>{const n="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",a=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {
953
946
  const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
954
947
 
955
948
  try {
@@ -961,8 +954,8 @@ __PREPARE_FUNCTION__ this.ensureServable();
961
954
  }
962
955
  }
963
956
 
964
- private resolveShapeWithScope(name: string, args: Record<string, unknown>, identity: SubscriptionIdentity | undefined, sensitive: SensitiveScope): ${n} {`:` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {`,l=e?`
965
- ${s}
957
+ private resolveShapeWithScope(name: string, args: Record<string, unknown>, identity: SubscriptionIdentity | undefined, sensitive: SensitiveScope): ${n} {`:` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {`,u=e?`
958
+ ${a}
966
959
  const shape = LUNORA_SHAPES[name];
967
960
 
968
961
  if (!shape) {
@@ -1024,14 +1017,14 @@ ${s}
1024
1017
 
1025
1018
  return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
1026
1019
  }
1027
- `:"",u=e?[...new Set(o.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],m=u.length>0?`
1020
+ `:"",h=e?[...new Set(o.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],m=h.length>0?`
1028
1021
  /** 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). */
1029
- assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(u)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
1022
+ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
1030
1023
  `:"";return{customMutatorOverride:r?`
1031
1024
  protected override isCustomMutator(functionPath: string): boolean {
1032
1025
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1033
1026
  }
1034
- `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:l}},Hr=(r,t)=>r?`
1027
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:u}},Hr=(r,t)=>r?`
1035
1028
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1036
1029
  const env = this.env as Record<string, unknown>;
1037
1030
  // A shape read performs no writes, so the widened request only needs
@@ -1250,8 +1243,8 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(u)}, (schema as
1250
1243
  `:"",sourceClientCacheConst:r?`
1251
1244
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1252
1245
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1253
- `:""}),Gr=(r,t)=>{const e=t.length>0,n=r?$("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=e?` const vectorShardKey = this.currentShardKey();
1254
- `:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",u=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,m=r?`
1246
+ `:""}),Gr=(r,t)=>{const e=t.length>0,n=r?$("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",a=e?` const vectorShardKey = this.currentShardKey();
1247
+ `:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",h=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,m=r?`
1255
1248
  const vectorSync = this.vectorSync(env);
1256
1249
  // Vectorize lives outside this shard's SQLite, so a query whose result
1257
1250
  // depends on a similarity search cannot be proven current on reconnect —
@@ -1268,7 +1261,7 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1268
1261
  }
1269
1262
 
1270
1263
  const lunora = createVectors({ indexes: config.vectors(env) });
1271
- ${s} const vectors = createContextVectors(lunora${u});
1264
+ ${a} const vectors = createContextVectors(lunora${h});
1272
1265
 
1273
1266
  return {
1274
1267
  backfill: createVectorBackfillSync({ ${i}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
@@ -1294,14 +1287,14 @@ ${s} const vectors = createContextVectors(lunora${u});
1294
1287
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1295
1288
  });
1296
1289
  }
1297
- `:"",vectorsBuild:m,vectorsStub:n}},cn=({advisories:r=[],advisorProcedures:t=[],agents:e=[],capabilities:o=new Set,containers:n=[],env:s,flagKeys:i=[],hasFlags:l=!1,hasNotify:u=!1,hasRooms:m=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:g=!1,lazyFunctions:c=!1,hasVectors:w=!0,liveStreamDeclarations:q=[],liveStreams:A=!1,maskMetadata:F,mutators:U=[],queues:R=[],rlsMetadata:B,schema:d,schemaSnapshot:v,shapes:E=[],storageRules:j,studioFeatures:I,services:C=[],topics:W=[],useUmbrella:K=!1,workflows:O=[]})=>{const h=Rr(K),H=U.length>0,f=E.length>0,D=E.some(a=>yr(a.args).length>0),V=S||D,fe=v===void 0?"":Jt(v),ge=v===void 0?"":`
1290
+ `:"",vectorsBuild:m,vectorsStub:n}},cn=({advisories:r=[],advisorProcedures:t=[],agents:e=[],capabilities:o=new Set,containers:n=[],env:a,flagKeys:i=[],hasFlags:u=!1,hasNotify:h=!1,hasRooms:m=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:g=!1,lazyFunctions:c=!1,hasVectors:w=!0,liveStreamDeclarations:q=[],liveStreams:A=!1,maskMetadata:F,mutators:U=[],queues:R=[],rlsMetadata:B,schema:d,schemaSnapshot:v,shapes:E=[],storageRules:j,studioFeatures:I,services:C=[],topics:W=[],useUmbrella:K=!1,workflows:O=[]})=>{const l=Rr(K),H=U.length>0,f=E.length>0,D=E.some(s=>yr(s.args).length>0),V=S||D,fe=v===void 0?"":Jt(v),ge=v===void 0?"":`
1298
1291
  /** 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. */
1299
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Yt(v))}, json: ${JSON.stringify(fe)} };
1300
- `,be=v===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=er(o),L=tr(l,h.flags),G=rr(i,l,h.flags),Q=gr(u),J=nr(s),{build:ye,contextField:we,importLines:ve,specs:ke}=ar(xr(R)),{build:Se,contextField:Re,importLines:xe,specs:Ae}=sr(W,R),Y=or(C,h.server),{build:Oe,contextField:De,importLines:Te,specs:_e}=ir(n,d.jurisdiction),{build:Ee,contextField:Ie,importLines:Ce,specs:Le}=dr(O),{build:Pe,contextField:Ne,importLines:$e,specs:Me}=cr(e,x&&e.length>0),{build:qe,configField:Fe,contextField:Ue,imports:Be,stub:je}=lr(o.has("payments")),We=r,{advisoryRules:Ke,advisoryRows:He}=Or(We),Ve=t,ne=B??{policies:[],roles:[]},Ge=F??{columns:[]},Qe=j??{rules:[]},Je=I??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ye,override:ze}=ur(O),{constant:Xe,override:Ze}=hr(R),b=w&&d.vectorIndexes.length>0,z=new Set(d.tables.filter(a=>Ar(a)).map(a=>a.name)),ae=b&&d.vectorIndexes.some(a=>z.has(a.table)),T=d.tables.some(a=>a.shardMode==="global"),X=pr(z),Z=d.tables.some(a=>zt(a)),se=d.tables.some(a=>Xt(a)),P=d.tables.some(a=>a.externalSource!==void 0),oe=d.tables.some(a=>a.memory===!0),ee=d.tables.some(a=>a.shardMode!=="global"&&a.searchIndexes.length>0);if(se&&Z)throw new he("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=d.tables.length>0,et=Nr(d),tt=Mr(d),rt=Wr(d),nt=$r(d),ie=qr(d),re=mr(b,O.length>0,R.length>0,l,ee);f&&re.push("WhereInput"),D&&re.push("SensitiveScope");const de=fr(T),{customMutatorOverride:at,shapeGuardImport:st,shapeReadPolicyAssertion:ot,shapeReadPolicyImport:it,shapeResolveOverride:dt}=Kr({hasMutators:H,hasSensitiveShapes:D,hasShapes:f,rlsData:ne}),_=A?q:[];for(const a of _)if(wr(a.exportName,"live stream export name"),!vr.test(a.filePath))throw new he("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(a.filePath)}`);const ct=c?[]:_.map(a=>`import { ${a.exportName} as liveStream_${a.exportName} } from "../${a.filePath}.js";`),lt=` protected override liveStreams() {
1301
- return { ${_.map(a=>`${kr(a.id)}: liveStream_${a.exportName}`).join(", ")} };
1292
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(zt(v))}, json: ${JSON.stringify(fe)} };
1293
+ `,be=v===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=er(o),L=tr(u,l.flags),G=rr(i,u,l.flags),Q=gr(h),J=nr(a),{build:ye,contextField:we,importLines:ve,specs:ke}=ar(xr(R)),{build:Se,contextField:Re,importLines:xe,specs:Ae}=sr(W,R),z=or(C,l.server),{build:Oe,contextField:De,importLines:Te,specs:_e}=ir(n,d.jurisdiction),{build:Ee,contextField:Ie,importLines:Ce,specs:Le}=dr(O),{build:Pe,contextField:Ne,importLines:$e,specs:Me}=cr(e,x&&e.length>0),{build:qe,configField:Fe,contextField:Ue,imports:Be,stub:je}=lr(o.has("payments")),We=r,{advisoryRules:Ke,advisoryRows:He}=Or(We),Ve=t,ne=B??{policies:[],roles:[]},Ge=F??{columns:[]},Qe=j??{rules:[]},Je=I??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:ze,override:Ye}=ur(O),{constant:Xe,override:Ze}=hr(R),b=w&&d.vectorIndexes.length>0,Y=new Set(d.tables.filter(s=>Ar(s)).map(s=>s.name)),ae=b&&d.vectorIndexes.some(s=>Y.has(s.table)),T=d.tables.some(s=>s.shardMode==="global"),X=pr(Y),Z=d.tables.some(s=>Yt(s)),se=d.tables.some(s=>Xt(s)),P=d.tables.some(s=>s.externalSource!==void 0),oe=d.tables.some(s=>s.memory===!0),ee=d.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&Z)throw new he("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=d.tables.length>0,et=Nr(d),tt=Mr(d),rt=Wr(d),nt=$r(d),ie=qr(d),re=mr(b,O.length>0,R.length>0,u,ee);f&&re.push("WhereInput"),D&&re.push("SensitiveScope");const de=fr(T),{customMutatorOverride:at,shapeGuardImport:st,shapeReadPolicyAssertion:ot,shapeReadPolicyImport:it,shapeResolveOverride:dt}=Kr({hasMutators:H,hasSensitiveShapes:D,hasShapes:f,rlsData:ne}),_=A?q:[];for(const s of _)if(wr(s.exportName,"live stream export name"),!vr.test(s.filePath))throw new he("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ct=c?[]:_.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),lt=` protected override liveStreams() {
1294
+ return { ${_.map(s=>`${kr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1302
1295
  }
1303
1296
  `,ut=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
1304
- ${_.map(a=>` [${JSON.stringify(a.id)}, () => import("../${a.filePath}.js").then((module) => module.${a.exportName})],`).join(`
1297
+ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1305
1298
  `)}
1306
1299
  ]);
1307
1300
 
@@ -1322,11 +1315,11 @@ ${_.map(a=>` [${JSON.stringify(a.id)}, () => import("../${a.filePath}
1322
1315
  protected override liveStreams() {
1323
1316
  return Object.fromEntries(this.loadedLiveStreams);
1324
1317
  }
1325
- `;let ce="";_.length>0&&(ce=c?ut:lt);const N=[`import type { ${re.join(", ")} } from "${h.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${ee?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${st}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${h.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${h.do}";`]:[],f?`import { asBucketStorage, ${it}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`];te&&N.push(`import { bindOrm, bindTableFacade } from "${h.server}";`),b&&N.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),N.push(...k.importLines,...L.importLines,...Q.importLines,...J.importLines,...Te,...Ce,...ve,...xe,...Y.importLines,...$e,...Be,...V?[`import { sensitiveArgumentNames } from "${h.values}";`]:[],"",'import schema from "../schema.js";',...ct,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...H?["LUNORA_MUTATOR_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...g?["LUNORA_SOCKETS"]:[],...f?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ht=b?`
1318
+ `;let ce="";_.length>0&&(ce=c?ut:lt);const N=[`import type { ${re.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${ee?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${st}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],f?`import { asBucketStorage, ${it}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];te&&N.push(`import type { FacadeEntry } from "${l.server}";`,`import { bindOrm, defineLazyFacade } from "${l.server}";`),b&&N.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),N.push(...k.importLines,...L.importLines,...Q.importLines,...J.importLines,...Te,...Ce,...ve,...xe,...z.importLines,...$e,...Be,...V?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ct,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...H?["LUNORA_MUTATOR_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...g?["LUNORA_SOCKETS"]:[],...f?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ht=b?`
1326
1319
  vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",pt=se?`
1327
1320
  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;`:"",mt=Z?`
1328
1321
  hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ft=P?`
1329
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",gt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",bt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",yt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",wt=T?$("globalDbStub: DatabaseWriterLike",gt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:vt,vectorsBuild:kt,vectorsStub:St}=Gr(b,ae?d.vectorIndexes.filter(a=>z.has(a.table)).map(a=>a.name):[]),Rt=`{
1322
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",gt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",bt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",yt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",wt=T?$("globalDbStub: DatabaseWriterLike",gt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:vt,vectorsBuild:kt,vectorsStub:St}=Gr(b,ae?d.vectorIndexes.filter(s=>Y.has(s.table)).map(s=>s.name):[]),Rt=`{
1330
1323
  ...this.ctxDbTuning(),
1331
1324
  auth: { identity: identity ?? null, userId: userId ?? null },
1332
1325
  broadcast: (delta) => {
@@ -1523,8 +1516,8 @@ ${It}${Pt} }
1523
1516
  `:"",qt=Er(c),Ft=c?` const preparation = this.prepareFunction(functionPath, "subscription");
1524
1517
  if (preparation !== undefined) await preparation;
1525
1518
  `:"",Ut=Cr.replace("__PREPARE_FUNCTION__",Ft),Bt=Pr(m,c),jt=te?`
1526
- const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1527
- ${d.tables.map(a=>` facade[${JSON.stringify(a.name)}] = bindTableFacade(db, ${JSON.stringify(a.name)});`).join(`
1519
+ const facade = db as unknown as Record<string, FacadeEntry>;
1520
+ ${d.tables.map(s=>` defineLazyFacade(db, ${JSON.stringify(s.name)});`).join(`
1528
1521
  `)}
1529
1522
  `:"",Wt=`${k.everyBuild}${L.build}${J.build}
1530
1523
  const secrets = createSecrets(env);
@@ -1535,7 +1528,7 @@ ${d.tables.map(a=>` facade[${JSON.stringify(a.name)}] = bindTableFaca
1535
1528
  await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
1536
1529
  },
1537
1530
  };
1538
- `:"",Gt=[...k.actionFields,...C.length>0?["services"]:[],...A?["live"]:[]],Qt=`${k.actionBuild}${Y.build}${Vt}`;return`${Sr}${N.join(`
1531
+ `:"",Gt=[...k.actionFields,...C.length>0?["services"]:[],...A?["live"]:[]],Qt=`${k.actionBuild}${z.build}${Vt}`;return`${Sr}${N.join(`
1539
1532
  `)}
1540
1533
 
1541
1534
  type FunctionKind = "action" | "mutation" | "query";
@@ -1601,7 +1594,7 @@ const LUNORA_STUDIO_FEATURES = ${p(Je,"StudioFeaturesResult")};
1601
1594
 
1602
1595
  /** How long a shard with a UNIQUE index blocked by duplicate rows serves the cached diagnostic before re-attempting the build. */
1603
1596
  const BLOCKED_MIGRATION_RETRY_MS = 5000;
1604
- ${ge}${X.constant}${G.constant}${Ye}${Xe}${_e}${Le}${ke}${Ae}${Y.specs}${Me}
1597
+ ${ge}${X.constant}${G.constant}${ze}${Xe}${_e}${Le}${ke}${Ae}${z.specs}${Me}
1605
1598
  export interface ShardDOConfig {
1606
1599
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1607
1600
  cdc?: boolean;
@@ -1621,6 +1614,17 @@ export interface ShardDOConfig {
1621
1614
  storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ht}${k.configFields}${L.configField}${Fe}${pt}${mt}${ft}${X.configField}
1622
1615
  }
1623
1616
  ${$("schedulerStub",bt,["cancel","runAfter","runAt"])}${$("storageStub",yt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${wt}${Ct}${St}${k.stubs}${je}
1617
+ // \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
1618
+ // mutation may be replayed, so a network call in either returns a different answer
1619
+ // on each run. Refused at runtime, not only linted: the advisor sees just the call
1620
+ // sites it can read, and a call inside a dependency is invisible to it.
1621
+ // Synchronous on purpose: an async refusal only rejects a promise the handler may
1622
+ // discard, and the handler would then return normally. A sync throw surfaces at the call.
1623
+ // Module scope: it captures nothing, so one instance serves every dispatch.
1624
+ const refuseFetch = (): never => {
1625
+ throw new LunoraError("FORBIDDEN", "ctx.fetch is action-only: network I/O belongs in an action, not a query or mutation");
1626
+ };
1627
+
1624
1628
  ${qt}
1625
1629
 
1626
1630
  /**
@@ -1737,7 +1741,7 @@ ${c?` const requestScope = this.captureRequestScope();
1737
1741
  protected override studioFeatures(): StudioFeaturesResult {
1738
1742
  return LUNORA_STUDIO_FEATURES();
1739
1743
  }
1740
- ${G.evaluateOverride}${G.subscriptionOverride}${ze}${Ze}
1744
+ ${G.evaluateOverride}${G.subscriptionOverride}${Ye}${Ze}
1741
1745
  protected override advisories(): AdvisoryFinding[] {
1742
1746
  return LUNORA_ADVISORIES();
1743
1747
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.363",
3
+ "version": "1.0.0-alpha.364",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,8 +50,8 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/advisor": "1.0.0-alpha.262",
54
- "@lunora/agent": "1.0.0-alpha.253",
53
+ "@lunora/advisor": "1.0.0-alpha.263",
54
+ "@lunora/agent": "1.0.0-alpha.254",
55
55
  "@lunora/container": "1.0.0-alpha.94",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
57
  "@lunora/platform": "1.0.0-alpha.75",