@lunora/codegen 1.0.0-alpha.300 → 1.0.0-alpha.302

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/index.mjs +1 -1
  2. package/dist/packem_shared/{MUTATORS_FILENAME-Bw0YtaO8.mjs → MUTATORS_FILENAME-qVDmv8st.mjs} +1 -1
  3. package/dist/packem_shared/{NOTIFY_FILENAME-CPjbiHQl.mjs → NOTIFY_FILENAME-CLoeWMb5.mjs} +1 -1
  4. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-BfK-dKlK.mjs → SCHEMA_SNAPSHOT_FILENAME-Reo6uCpZ.mjs} +1 -1
  5. package/dist/packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs +1 -0
  6. package/dist/packem_shared/{context-property-calls-DJ_A1R5i.mjs → context-property-calls-CQWCNUVH.mjs} +1 -1
  7. package/dist/packem_shared/{context-root-wBahDTzk.mjs → context-root-LyOsqj_o.mjs} +1 -1
  8. package/dist/packem_shared/{database-calls-CHZbBUCZ.mjs → database-calls-BPpefKqO.mjs} +1 -1
  9. package/dist/packem_shared/discoverCrons-DBnCama4.mjs +1 -0
  10. package/dist/packem_shared/{discoverFunctions-DaEZl3uE.mjs → discoverFunctions-CbxZGGj0.mjs} +1 -1
  11. package/dist/packem_shared/{discoverHttpRoutes-C_u9YiFb.mjs → discoverHttpRoutes-DgfoyNcf.mjs} +1 -1
  12. package/dist/packem_shared/discoverHyperdriveCalls-CwnXgjFJ.mjs +1 -0
  13. package/dist/packem_shared/{discoverInserts-OT_fiEGq.mjs → discoverInserts-mHOX_dJR.mjs} +1 -1
  14. package/dist/packem_shared/discoverMaskProcedures-BTePIpmk.mjs +1 -0
  15. package/dist/packem_shared/{discoverQueries-C8V4cMIP.mjs → discoverQueries-CfxkjP5X.mjs} +1 -1
  16. package/dist/packem_shared/discoverR2sqlCalls-XBhs4XRZ.mjs +1 -0
  17. package/dist/packem_shared/{discoverRlsProcedures-BlUd32bU.mjs → discoverRlsProcedures-TskedRMh.mjs} +1 -1
  18. package/dist/packem_shared/{emitApp-DAZCUDbr.mjs → emitApp-CJe2L06A.mjs} +10 -7
  19. package/dist/packem_shared/{emitShard-C8I2zw1K.mjs → emitShard-zun44Krh.mjs} +1 -1
  20. package/dist/packem_shared/{index-DZZpHXMv.mjs → index-CkS96b8a.mjs} +1 -1
  21. package/dist/packem_shared/{shard-BTj5Z44S.mjs → shard-QKj9rp3r.mjs} +92 -84
  22. package/dist/packem_shared/{unwrap-handler-return-B-jQde6M.mjs → unwrap-handler-return-CJrkfrSH.mjs} +1 -1
  23. package/package.json +8 -8
  24. package/dist/packem_shared/WORKFLOWS_FILENAME-CQR8fE9B.mjs +0 -1
  25. package/dist/packem_shared/discoverCrons-DF7dOP9x.mjs +0 -1
  26. package/dist/packem_shared/discoverHyperdriveCalls-BUrA_96X.mjs +0 -1
  27. package/dist/packem_shared/discoverMaskProcedures-CcB18tzB.mjs +0 -1
  28. package/dist/packem_shared/discoverR2sqlCalls-COKmDnih.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{LunoraError as vt}from"@lunora/errors";import{serializeSchemaSnapshot as kt,hashSchemaSnapshot as St}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Rt,isD1GlobalTable as xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as h}from"./json-data-Chfs2Cz5.mjs";import{r as C,e as At,a as Dt,b as Ot,c as Tt,d as Et,f as Ct,g as Lt,h as It,i as _t,j as Mt,k as Pt,l as Nt,m as qt,n as $t,o as Ft,p as Ut,q as Bt}from"./shard-runtime-BX0xmo0P.mjs";import{u as K,i as Wt,G as jt,d as Ht}from"./shared-DnCokNcE.mjs";import{p as Vt}from"./platform-8oj7iXQy.mjs";import{i as Kt}from"./schema-BgM8A3XV.mjs";const Gt=` /**
1
+ import{LunoraError as Rt}from"@lunora/errors";import{serializeSchemaSnapshot as xt,hashSchemaSnapshot as At}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Ot,isD1GlobalTable as Dt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Tt}from"./json-data-Chfs2Cz5.mjs";import{r as L,e as Et,a as Lt,b as Ct,c as It,d as _t,f as Mt,g as Pt,h as Nt,i as $t,j as qt,k as Ft,l as Ut,m as Bt,n as Wt,o as jt,p as Ht,q as Vt}from"./shard-runtime-BX0xmo0P.mjs";import{u as K,i as Kt,G as Gt,d as Qt}from"./shared-DnCokNcE.mjs";import{p as zt}from"./platform-8oj7iXQy.mjs";import{i as Jt}from"./schema-BgM8A3XV.mjs";const h=(n,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${e}); })()`,te=["categories","description","facing","level","remediation","title"],Yt=n=>{const e={};return{advisoryRows:n.map(a=>{let r=e[a.name];return r||(r=Object.fromEntries(te.filter(s=>s in a).map(s=>[s,a[s]])),e[a.name]=r),Object.fromEntries(Object.entries(a).filter(([s,d])=>!te.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},Xt=` /**
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 vt}from"@lunora/errors";import{serializeSchemaSnapshot as
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,p=(a="")=>` const writer = this.adminWriter(${a});`,Qt=`${Gt}
33
+ }`,p=(n="")=>` const writer = this.adminWriter(${n});`,Zt=`${Xt}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -225,11 +225,11 @@ ${p()}
225
225
  await applyCdcChanges(writer, args.changes);
226
226
 
227
227
  return { applied: args.changes.length };
228
- }`,zt=({actionOnlyBuild:a,actionOnlyFields:r,agentsBuild:e,agentsContextField:n,containersBuild:t,containersContextField:o,databaseOptions:d,everyContextBuild:m,everyContextField:f,facadeBlock:c,globalDatabaseLine:w,notifyBuild:S,ormContextField:y,paymentsBuild:L,paymentsContextField:i,queuesBuild:g,queuesContextField:I,topicsBuild:_,topicsContextField:M,vectorsBuild:A,vectorsContextField:P,workflowsBuild:N,workflowsContextField:R})=>{const l=r.length>0,D=l?`
228
+ }`,er=({actionOnlyBuild:n,actionOnlyFields:e,agentsBuild:t,agentsContextField:a,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:m,everyContextField:f,facadeBlock:c,globalDatabaseLine:y,notifyBuild:S,ormContextField:w,paymentsBuild:C,paymentsContextField:i,queuesBuild:g,queuesContextField:I,topicsBuild:_,topicsContextField:M,vectorsBuild:A,vectorsContextField:P,workflowsBuild:N,workflowsContextField:R})=>{const l=e.length>0,O=l?`
229
229
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
230
230
  // and attached only for an \`action\` so query/mutation ctx never carry them.
231
231
  if (isAction) {
232
- ${a.replaceAll(/^(?=.)/gmu," ")}${r.map(k=>` ctx.${k} = ${k};`).join(`
232
+ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(k=>` ctx.${k} = ${k};`).join(`
233
233
  `)}
234
234
  }
235
235
  `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; kind?: "query"; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
@@ -253,7 +253,7 @@ ${a.replaceAll(/^(?=.)/gmu," ")}${r.map(k=>` ctx.${k} = ${k};`
253
253
  userId: this.getCurrentUserId(),
254
254
  };
255
255
  const { identity, ip, userId } = caller;
256
- ${A}${m}${t}${N}${g}${_}${e}
256
+ ${A}${m}${r}${N}${g}${_}${t}
257
257
  // Which dispatch this ctx belongs to. Drives the two deferral facades
258
258
  // below and the \`ctx.run*\` caller guard; a ctx built for an
259
259
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -362,13 +362,13 @@ ${A}${m}${t}${N}${g}${_}${e}
362
362
  // so both write to the same trace.
363
363
  const span = this.makeDispatchSpan(traceAnchor, observability);
364
364
 
365
- ${w} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
365
+ ${y} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
366
366
  // adds aggregate counters (call count, total time, per-operation
367
367
  // breakdown) to the wide event rather than a span per call, so a
368
368
  // handler making hundreds of queries stays readable. See
369
369
  // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
370
370
  const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
371
- ${c}${L}
371
+ ${c}${C}
372
372
 
373
373
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
374
374
  // The trace anchor is threaded explicitly for the same reason \`identity\`
@@ -427,14 +427,14 @@ ${S}
427
427
  // to the handler so code that signs its own URLs (a copy-in
428
428
  // \`createStorage\`) can fall back to it too. \`undefined\` for a
429
429
  // query and for a deferred dispatch, for the reasons given there.
430
- origin: requestOrigin,${y}
430
+ origin: requestOrigin,${w}
431
431
  scheduler,
432
432
  span,
433
433
  storage: contextStorage,
434
- trace,${P}${f}${i}${o}${R}${I}${M}${n}
434
+ trace,${P}${f}${i}${s}${R}${I}${M}${a}
435
435
  };
436
436
  ${l?` const isAction = contextKind === "action";
437
- `:""}${D}
437
+ `:""}${O}
438
438
  const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
439
439
  target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind);
440
440
  // The composed mutation runs under the SAME wrapper the top-level RPC
@@ -485,7 +485,7 @@ ${l?` const isAction = contextKind === "action";
485
485
 
486
486
  if (queryView === undefined) {
487
487
  const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
488
- ${r.map(k=>` delete descriptors.${k};
488
+ ${e.map(k=>` delete descriptors.${k};
489
489
  `).join("")} // Writable and configurable, like the plain fields they replace.
490
490
  const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
491
491
 
@@ -504,7 +504,7 @@ ${r.map(k=>` delete descriptors.${k};
504
504
  installRun(ctx, contextKind);
505
505
 
506
506
  return ctx;
507
- }`},Xt=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
507
+ }`},tr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
508
508
  // referencing call fails loudly with a clear error instead of overflowing the
509
509
  // stack. Tracked across the awaited handler chain (one DO invocation is
510
510
  // single-threaded), so the counter reflects true nesting depth.
@@ -570,7 +570,7 @@ const dispatchRun = async (
570
570
  } finally {
571
571
  runDepth -= 1;
572
572
  }
573
- };`,Jt=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
573
+ };`,rr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
574
574
  const registered = LUNORA_FUNCTIONS[functionPath];
575
575
 
576
576
  // Internal functions are reachable server-side only: via \`ctx.run*\`
@@ -747,7 +747,7 @@ const dispatchRun = async (
747
747
  // \`ctx.scheduler\` call that reached the buffer in the first place.
748
748
  protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
749
749
  return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
750
- }`,Yt=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
750
+ }`,ar=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
751
751
  const registered = LUNORA_FUNCTIONS[functionPath];
752
752
 
753
753
  if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
@@ -786,7 +786,7 @@ const dispatchRun = async (
786
786
  // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
787
787
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
788
788
  };
789
- }`,Zt=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=K(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))K(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},tr=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},rr=a=>{const r=[];for(const e of a.tables)!e.ttl||e.shardMode==="global"||r.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return r},ar=a=>{if(a.kind!=="union"||a.members===void 0||a.members.length===0)return;const r=[];for(const e of a.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const n=JSON.parse(e.literalValue);if(typeof n!="string")return;r.push(n)}catch{return}}return r},nr=(a,r,e)=>{const n=K(r),t={name:a,optional:Wt(r),type:n.kind};if(n.kind==="id"&&n.tableName!==void 0){t.ref=n.tableName;const d=e.get(a);d!==void 0&&(t.onDelete=d)}n.kind==="storage"&&(t.isStorage=!0,n.bucket!==void 0&&(t.bucket=n.bucket));const o=ar(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},sr=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.flatMap(o=>o.kind==="one"?[[o.field,o.onDelete]]:[]));for(const[o,d]of Object.entries(e.shape))n.push(nr(o,d,t));r[e.name]=n}return r},or=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=r?`
789
+ }`,nr=n=>{const e={};for(const t of n.tables){const a={};for(const[r,s]of Object.entries(t.shape)){const d=K(s);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(e[t.name]=a)}return e},sr=n=>{const e={};for(const t of n.tables){const a=[];for(const[r,s]of Object.entries(t.shape))K(s).kind==="storage"&&a.push(r);a.length>0&&(e[t.name]=a)}return e},or=n=>{const e={};for(const t of n.tables){const a=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(e[t.name]=a)}return e},ir=n=>{const e=[];for(const t of n.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},dr=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const e=[];for(const t of n.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const a=JSON.parse(t.literalValue);if(typeof a!="string")return;e.push(a)}catch{return}}return e},cr=(n,e,t)=>{const a=K(e),r={name:n,optional:Kt(e),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=t.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const s=dr(a);return s!==void 0&&(r.enumValues=s),a.column?.notNull===!1&&(r.nullable=!0),r},lr=n=>{const e={};for(const t of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))a.push(cr(s,d,r));e[t.name]=a}return e},hr=({hasMutators:n,hasShapes:e,rlsData:t})=>{const a=e?`
790
790
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
791
791
  const shape = LUNORA_SHAPES[name];
792
792
 
@@ -850,14 +850,14 @@ const dispatchRun = async (
850
850
 
851
851
  return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
852
852
  }
853
- `:"",t=r?[...new Set(e.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],o=t.length>0?`
853
+ `:"",r=e?[...new Set(t.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,y)=>c.localeCompare(y)):[],s=r.length>0?`
854
854
  /** 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). */
855
- assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
856
- `:"";return{customMutatorOverride:a?`
855
+ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
856
+ `:"";return{customMutatorOverride:n?`
857
857
  protected override isCustomMutator(functionPath: string): boolean {
858
858
  return LUNORA_MUTATOR_PATHS.has(functionPath);
859
859
  }
860
- `:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},ir=(a,r)=>a?`
860
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},ur=(n,e)=>n?`
861
861
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
862
862
  const env = this.env as Record<string, unknown>;
863
863
  // A shape read performs no writes, so the widened request only needs
@@ -871,7 +871,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
871
871
  // keys must mean equal rows, so a field the writer can scope by has to
872
872
  // be either in the key or out of the request; it is out.
873
873
  const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity: identity?.identity, userId: identity?.userId };
874
- const globalDb: DatabaseWriterLike = ${r}?.(env, globalRequest) ?? globalDbStub;
874
+ const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
875
875
  const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
876
876
 
877
877
  let cursor: null | string = null;
@@ -912,11 +912,11 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
912
912
  // emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
913
913
  // a \`defineShape\`. The Hyperdrive factory simply never reads it.
914
914
  const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
915
- const globalDb: DatabaseWriterLike = ${r}?.(env, globalRequest) ?? globalDbStub;
915
+ const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
916
916
 
917
917
  return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
918
918
  }
919
- `:"",dr=a=>({externalSourceOverride:a?`
919
+ `:"",pr=n=>({externalSourceOverride:n?`
920
920
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
921
921
  const env = (this.env ?? {}) as Record<string, unknown>;
922
922
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1056,7 +1056,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
1056
1056
 
1057
1057
  return nextDueAt;
1058
1058
  }
1059
- `:"",sourceBootstrap:a?`
1059
+ `:"",sourceBootstrap:n?`
1060
1060
  const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1061
1061
  const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1062
1062
 
@@ -1066,11 +1066,11 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
1066
1066
  if (autoSourced) {
1067
1067
  void this.scheduleSourcePoll();
1068
1068
  }
1069
- `:"",sourceClientCacheConst:a?`
1069
+ `:"",sourceClientCacheConst:n?`
1070
1070
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1071
1071
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1072
- `:""}),cr=(a,r)=>{const e=r.length>0,t=a?C("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
1073
- `:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",f=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${r.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=a?`
1072
+ `:""}),mr=(n,e)=>{const t=e.length>0,r=n?L("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
1073
+ `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",f=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=n?`
1074
1074
  const vectorSync = this.vectorSync(env);
1075
1075
  // Vectorize lives outside this shard's SQLite, so a query whose result
1076
1076
  // depends on a similarity search cannot be proven current on reconnect —
@@ -1080,14 +1080,14 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1080
1080
  const bareVectors = vectorSync?.vectors ?? vectorsStub;
1081
1081
  const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
1082
1082
  const onWrite = vectorSync?.onWrite;
1083
- `:"";return{vectorSyncMethod:a?`
1083
+ `:"";return{vectorSyncMethod:n?`
1084
1084
  private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
1085
1085
  if (!config.vectors) {
1086
1086
  return undefined;
1087
1087
  }
1088
1088
 
1089
1089
  const lunora = createVectors({ indexes: config.vectors(env) });
1090
- ${o} const vectors = createContextVectors(lunora${f});
1090
+ ${s} const vectors = createContextVectors(lunora${f});
1091
1091
 
1092
1092
  return {
1093
1093
  backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
@@ -1113,14 +1113,14 @@ ${o} const vectors = createContextVectors(lunora${f});
1113
1113
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1114
1114
  });
1115
1115
  }
1116
- `:"",vectorsBuild:c,vectorsStub:t}},Sr=({advisories:a=[],advisorProcedures:r=[],agents:e=[],capabilities:n=new Set,containers:t=[],env:o,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasVectors:c=!0,maskMetadata:w,mutators:S=[],queues:y=[],rlsMetadata:L,schema:i,schemaSnapshot:g,shapes:I=[],storageRules:_,studioFeatures:M,services:A=[],topics:P=[],useUmbrella:N=!1,workflows:R=[]})=>{const l=Ht(N),D=S.length>0,v=I.length>0,k=g===void 0?"":kt(g),te=g===void 0?"":`
1116
+ `:"",vectorsBuild:c,vectorsStub:r}},Dr=({advisories:n=[],advisorProcedures:e=[],agents:t=[],capabilities:a=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasVectors:c=!0,maskMetadata:y,mutators:S=[],queues:w=[],rlsMetadata:C,schema:i,schemaSnapshot:g,shapes:I=[],storageRules:_,studioFeatures:M,services:A=[],topics:P=[],useUmbrella:N=!1,workflows:R=[]})=>{const l=Qt(N),O=S.length>0,v=I.length>0,k=g===void 0?"":xt(g),re=g===void 0?"":`
1117
1117
  /** 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. */
1118
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(St(g))}, json: ${JSON.stringify(k)} };
1119
- `,re=g===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=At(n),O=Dt(m,l.flags),q=Ot(d,m,l.flags),$=Bt(f),F=Tt(o),{build:ae,contextField:ne,importLines:se,specs:oe}=Et(Vt(y)),{build:ie,contextField:de,importLines:ce,specs:le}=Ct(P,y),U=Lt(A,l.server),{build:he,contextField:ue,importLines:pe,specs:me}=It(t,i.jurisdiction),{build:ge,contextField:be,importLines:fe,specs:we}=_t(R),{build:ye,contextField:ve,importLines:ke,specs:Se}=Mt(e),{build:Re,configField:xe,contextField:Ae,imports:De,stub:Oe}=Pt(n.has("payments")),Te=a,Ee=r,G=L??{policies:[],roles:[]},Ce=w??{columns:[]},Le=_??{rules:[]},Ie=M??{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:_e,override:Me}=Nt(R),{constant:Pe,override:Ne}=qt(y),u=c&&i.vectorIndexes.length>0,B=new Set(i.tables.filter(s=>Kt(s)).map(s=>s.name)),Q=u&&i.vectorIndexes.some(s=>B.has(s.table)),x=i.tables.some(s=>s.shardMode==="global"),W=$t(B),j=i.tables.some(s=>Rt(s)),z=i.tables.some(s=>xt(s)),T=i.tables.some(s=>s.externalSource!==void 0),X=i.tables.some(s=>s.memory===!0),H=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(z&&j)throw new vt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,qe=Zt(i),$e=tr(i),Fe=sr(i),Ue=er(i),J=rr(i),Y=Ft(u,R.length>0,y.length>0,m,H);v&&Y.push("WhereInput");const Z=Ut(x),{customMutatorOverride:Be,shapeGuardImport:We,shapeReadPolicyAssertion:je,shapeReadPolicyImport:He,shapeResolveOverride:Ve}=or({hasMutators:D,hasShapes:v,rlsData:G}),E=[`import type { ${Y.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, ${H?"backfillSearchIndexes, ":""}${u?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${X?"clearMemoryTables, ":""}${We}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${T?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Q?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...T?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],v?`import { asBucketStorage, ${He}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&E.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),u&&E.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),E.push(...b.importLines,...O.importLines,...$.importLines,...F.importLines,...pe,...fe,...se,...ce,...U.importLines,...ke,...De,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...D?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ke=u?`
1120
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Ge=z?`
1121
- 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;`:"",Qe=j?`
1122
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ze=T?`
1123
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Xe="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",Je="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",Ye="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Ze=x?C("globalDbStub: DatabaseWriterLike",Xe,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:et,vectorsBuild:tt,vectorsStub:rt}=cr(u,Q?i.vectorIndexes.filter(s=>B.has(s.table)).map(s=>s.name):[]),at=`{
1118
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(At(g))}, json: ${JSON.stringify(k)} };
1119
+ `,ae=g===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=Et(a),D=Lt(m,l.flags),$=Ct(d,m,l.flags),q=Vt(f),F=It(s),{build:ne,contextField:se,importLines:oe,specs:ie}=_t(zt(w)),{build:de,contextField:ce,importLines:le,specs:he}=Mt(P,w),U=Pt(A,l.server),{build:ue,contextField:pe,importLines:me,specs:ge}=Nt(r,i.jurisdiction),{build:be,contextField:fe,importLines:ye,specs:we}=$t(R),{build:ve,contextField:ke,importLines:Se,specs:Re}=qt(t),{build:xe,configField:Ae,contextField:Oe,imports:De,stub:Te}=Ft(a.has("payments")),Ee=n,{advisoryRules:Le,advisoryRows:Ce}=Yt(Ee),Ie=e,G=C??{policies:[],roles:[]},_e=y??{columns:[]},Me=_??{rules:[]},Pe=M??{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:Ne,override:$e}=Ut(R),{constant:qe,override:Fe}=Bt(w),u=c&&i.vectorIndexes.length>0,B=new Set(i.tables.filter(o=>Jt(o)).map(o=>o.name)),Q=u&&i.vectorIndexes.some(o=>B.has(o.table)),x=i.tables.some(o=>o.shardMode==="global"),W=Wt(B),j=i.tables.some(o=>Ot(o)),z=i.tables.some(o=>Dt(o)),T=i.tables.some(o=>o.externalSource!==void 0),J=i.tables.some(o=>o.memory===!0),H=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(z&&j)throw new Rt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,Ue=nr(i),Be=or(i),We=lr(i),je=sr(i),Y=ir(i),X=jt(u,R.length>0,w.length>0,m,H);v&&X.push("WhereInput");const Z=Ht(x),{customMutatorOverride:He,shapeGuardImport:Ve,shapeReadPolicyAssertion:Ke,shapeReadPolicyImport:Ge,shapeResolveOverride:Qe}=hr({hasMutators:O,hasShapes:v,rlsData:G}),E=[`import type { ${X.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, ${H?"backfillSearchIndexes, ":""}${u?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${J?"clearMemoryTables, ":""}${Ve}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${T?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Q?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...T?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],v?`import { asBucketStorage, ${Ge}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&E.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),u&&E.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),E.push(...b.importLines,...D.importLines,...q.importLines,...F.importLines,...me,...ye,...oe,...le,...U.importLines,...Se,...De,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...O?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ze=u?`
1120
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Je=z?`
1121
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ye=j?`
1122
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Xe=T?`
1123
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Ze="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",et="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",tt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",rt=x?L("globalDbStub: DatabaseWriterLike",Ze,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:at,vectorsBuild:nt,vectorsStub:st}=mr(u,Q?i.vectorIndexes.filter(o=>B.has(o.table)).map(o=>o.name):[]),ot=`{
1124
1124
  ...this.ctxDbTuning(),
1125
1125
  auth: { identity: identity ?? null, userId: userId ?? null },
1126
1126
  broadcast: (delta) => {
@@ -1172,22 +1172,22 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1172
1172
  sql: this.sql as SqlExec,
1173
1173
  storage,${x?`
1174
1174
  globalDb,`:""}
1175
- }`,nt=u?`
1176
- vectors,`:"",st=V?`
1177
- orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",ot=x?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1175
+ }`,it=u?`
1176
+ vectors,`:"",dt=V?`
1177
+ orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",ct=x?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1178
1178
  const globalDb: DatabaseWriterLike = ${ee}?.(env, globalRequest) ?? globalDbStub;
1179
- `:"",it=ir(v&&x,ee),{externalSourceOverride:dt,sourceBootstrap:ct,sourceClientCacheConst:lt}=dr(T),ht=`
1179
+ `:"",lt=ur(v&&x,ee),{externalSourceOverride:ht,sourceBootstrap:ut,sourceClientCacheConst:pt}=pr(T),mt=`
1180
1180
  protected override async runShardInit(): Promise<void> {
1181
1181
  this.ensureMigrated();
1182
- ${X?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1182
+ ${J?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1183
1183
  `:""}
1184
1184
  await this.dispatchShardInit();
1185
1185
  }
1186
- `,ut=J.length>0?`
1186
+ `,gt=Y.length>0?`
1187
1187
  if (LUNORA_TTL_SWEEPS.length > 0) {
1188
1188
  void this.scheduleTtlSweep();
1189
1189
  }
1190
- `:"",pt=`
1190
+ `:"",bt=`
1191
1191
  public constructor(state: ShardDOState, env: unknown) {
1192
1192
  super(state, env, {
1193
1193
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1203,7 +1203,7 @@ ${X?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sch
1203
1203
  // exists — a trigger that fails first still flushes and fuses.
1204
1204
  ...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
1205
1205
  });
1206
- ${ct}${ut} }
1206
+ ${ut}${gt} }
1207
1207
 
1208
1208
  protected override isCacheableQuery(functionPath: string): boolean {
1209
1209
  // NOT \`kind === "query"\` alone. A cache hit answers without running
@@ -1227,14 +1227,14 @@ ${ct}${ut} }
1227
1227
  protected override isPaidFunction(functionPath: string): boolean {
1228
1228
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1229
1229
  }
1230
- `,mt=V?`
1230
+ `,ft=V?`
1231
1231
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1232
- ${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFacade(db, ${JSON.stringify(s.name)});`).join(`
1232
+ ${i.tables.map(o=>` facade[${JSON.stringify(o.name)}] = bindTableFacade(db, ${JSON.stringify(o.name)});`).join(`
1233
1233
  `)}
1234
- `:"",gt=`${b.everyBuild}${O.build}${F.build}
1234
+ `:"",yt=`${b.everyBuild}${D.build}${F.build}
1235
1235
  const secrets = createSecrets(env);
1236
- `,bt=`${b.everyFields}${O.contextField}${$.contextField}${F.contextField}
1237
- secrets,`,ft=$.build,wt=[...b.actionFields,...A.length>0?["services"]:[]],yt=`${b.actionBuild}${U.build}`;return`${jt}${E.join(`
1236
+ `,wt=`${b.everyFields}${D.contextField}${q.contextField}${F.contextField}
1237
+ secrets,`,vt=q.build,kt=[...b.actionFields,...A.length>0?["services"]:[]],St=`${b.actionBuild}${U.build}`;return`${Gt}${E.join(`
1238
1238
  `)}
1239
1239
 
1240
1240
  type FunctionKind = "action" | "mutation" | "query";
@@ -1244,13 +1244,13 @@ interface FunctionReference {
1244
1244
  }
1245
1245
 
1246
1246
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1247
- const LUNORA_TABLE_REFS = ${h(qe,"Record<string, Record<string, string>>")};
1247
+ const LUNORA_TABLE_REFS = ${h(Ue,"Record<string, Record<string, string>>")};
1248
1248
 
1249
1249
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1250
- const LUNORA_TABLE_INDEXES = ${h($e,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1250
+ const LUNORA_TABLE_INDEXES = ${h(Be,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1251
1251
 
1252
1252
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1253
- const LUNORA_TABLE_COLUMNS = ${h(Fe,`Record<
1253
+ const LUNORA_TABLE_COLUMNS = ${h(We,`Record<
1254
1254
  string,
1255
1255
  Array<{
1256
1256
  bucket?: string;
@@ -1267,29 +1267,37 @@ const LUNORA_TABLE_COLUMNS = ${h(Fe,`Record<
1267
1267
  >`)};
1268
1268
 
1269
1269
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1270
- const LUNORA_STORAGE_COLUMNS = ${h(Ue,"Record<string, string[]>")};
1270
+ const LUNORA_STORAGE_COLUMNS = ${h(je,"Record<string, string[]>")};
1271
1271
 
1272
1272
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1273
- const LUNORA_TTL_SWEEPS = ${h(J,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1273
+ const LUNORA_TTL_SWEEPS = ${Tt(Y,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1274
1274
 
1275
1275
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1276
- const LUNORA_ADVISORIES = ${h(Te,"AdvisoryFinding[]")};
1276
+ const LUNORA_ADVISORY_RULES = ${h(Le,"Record<string, Partial<AdvisoryFinding>>")};
1277
+
1278
+ /** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
1279
+ const LUNORA_ADVISORY_ROWS = ${h(Ce,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1280
+
1281
+ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1282
+ let cached: AdvisoryFinding[] | undefined;
1283
+ return () => (cached ??= LUNORA_ADVISORY_ROWS().map((row) => ({ ...LUNORA_ADVISORY_RULES()[row.name], ...row }) as AdvisoryFinding));
1284
+ })();
1277
1285
 
1278
1286
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1279
- const LUNORA_ADVISOR_PROCEDURES = ${h(Ee,"AdvisorProcedure[]")};
1287
+ const LUNORA_ADVISOR_PROCEDURES = ${h(Ie,"AdvisorProcedure[]")};
1280
1288
 
1281
1289
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1282
1290
  const LUNORA_RLS_METADATA = ${h(G,"RlsPoliciesResult")};
1283
- ${je}
1291
+ ${Ke}
1284
1292
  /** 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. */
1285
- const LUNORA_MASK_METADATA = ${h(Ce,"MaskPoliciesResult")};
1293
+ const LUNORA_MASK_METADATA = ${h(_e,"MaskPoliciesResult")};
1286
1294
 
1287
1295
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1288
- const LUNORA_STORAGE_RULES = ${h(Le,"StorageRulesResult")};
1296
+ const LUNORA_STORAGE_RULES = ${h(Me,"StorageRulesResult")};
1289
1297
 
1290
1298
  /** 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. */
1291
- const LUNORA_STUDIO_FEATURES = ${h(Ie,"StudioFeaturesResult")};
1292
- ${te}${W.constant}${q.constant}${_e}${Pe}${me}${we}${oe}${le}${U.specs}${Se}
1299
+ const LUNORA_STUDIO_FEATURES = ${h(Pe,"StudioFeaturesResult")};
1300
+ ${re}${W.constant}${$.constant}${Ne}${qe}${ge}${we}${ie}${he}${U.specs}${Re}
1293
1301
  export interface ShardDOConfig {
1294
1302
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1295
1303
  cdc?: boolean;
@@ -1304,27 +1312,27 @@ export interface ShardDOConfig {
1304
1312
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1305
1313
  scheduler?: (env: Record<string, unknown>) => unknown;
1306
1314
  /** \`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. */
1307
- storage?: (env: Record<string, unknown>, origin?: string) => unknown;${Ke}${b.configFields}${O.configField}${xe}${Ge}${Qe}${ze}${W.configField}
1315
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ze}${b.configFields}${D.configField}${Ae}${Je}${Ye}${Xe}${W.configField}
1308
1316
  }
1309
- ${C("schedulerStub",Je,["cancel","runAfter","runAt"])}${C("storageStub",Ye,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${Ze}${lt}${rt}${b.stubs}${Oe}
1310
- ${Xt}
1317
+ ${L("schedulerStub",et,["cancel","runAfter","runAt"])}${L("storageStub",tt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${rt}${pt}${st}${b.stubs}${Te}
1318
+ ${tr}
1311
1319
 
1312
1320
  /**
1313
1321
  * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1314
1322
  * from the worker entry so wrangler binds it by name.
1315
1323
  */
1316
1324
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1317
- class extends ShardDOBase {${pt}
1325
+ class extends ShardDOBase {${bt}
1318
1326
  private migrated = false;
1319
1327
 
1320
- ${Jt}
1328
+ ${rr}
1321
1329
  ${Z.override}
1322
- ${Yt}
1323
- ${Be}${Ve}${it}${dt}
1330
+ ${ar}
1331
+ ${He}${Qe}${lt}${ht}
1324
1332
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1325
1333
  return LUNORA_LIFECYCLE_HOOKS[event];
1326
1334
  }
1327
- ${W.override}${ht}
1335
+ ${W.override}${mt}
1328
1336
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1329
1337
  // socket-terminated half of the same reactivity — and differs only in who
1330
1338
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1367,11 +1375,11 @@ ${W.override}${ht}
1367
1375
 
1368
1376
 
1369
1377
  protected override tableRefs(table: string): Record<string, string> | undefined {
1370
- return LUNORA_TABLE_REFS[table];
1378
+ return LUNORA_TABLE_REFS()[table];
1371
1379
  }
1372
1380
 
1373
1381
  protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> {
1374
- return LUNORA_TABLE_INDEXES[table] ?? [];
1382
+ return LUNORA_TABLE_INDEXES()[table] ?? [];
1375
1383
  }
1376
1384
 
1377
1385
  protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> {
@@ -1390,45 +1398,45 @@ ${W.override}${ht}
1390
1398
  ref?: string;
1391
1399
  type: string;
1392
1400
  }> {
1393
- return LUNORA_TABLE_COLUMNS[table] ?? [];
1401
+ return LUNORA_TABLE_COLUMNS()[table] ?? [];
1394
1402
  }
1395
1403
 
1396
1404
  protected override storageColumns(): Record<string, string[]> {
1397
- return LUNORA_STORAGE_COLUMNS;
1405
+ return LUNORA_STORAGE_COLUMNS();
1398
1406
  }
1399
1407
 
1400
1408
  protected override rlsMetadata(): RlsPoliciesResult {
1401
- return LUNORA_RLS_METADATA;
1409
+ return LUNORA_RLS_METADATA();
1402
1410
  }
1403
1411
 
1404
1412
  protected override maskMetadata(): MaskPoliciesResult {
1405
- return LUNORA_MASK_METADATA;
1413
+ return LUNORA_MASK_METADATA();
1406
1414
  }
1407
1415
 
1408
1416
  protected override storageRulesMetadata(): StorageRulesResult {
1409
- return LUNORA_STORAGE_RULES;
1417
+ return LUNORA_STORAGE_RULES();
1410
1418
  }
1411
1419
 
1412
1420
  protected override studioFeatures(): StudioFeaturesResult {
1413
- return LUNORA_STUDIO_FEATURES;
1421
+ return LUNORA_STUDIO_FEATURES();
1414
1422
  }
1415
- ${q.evaluateOverride}${q.subscriptionOverride}${Me}${Ne}
1423
+ ${$.evaluateOverride}${$.subscriptionOverride}${$e}${Fe}
1416
1424
  protected override advisories(): AdvisoryFinding[] {
1417
- return LUNORA_ADVISORIES;
1425
+ return LUNORA_ADVISORIES();
1418
1426
  }
1419
1427
 
1420
1428
  protected override advisorProcedures(): AdvisorProcedure[] {
1421
- return LUNORA_ADVISOR_PROCEDURES;
1429
+ return LUNORA_ADVISOR_PROCEDURES();
1422
1430
  }
1423
1431
 
1424
- ${Qt}
1432
+ ${Zt}
1425
1433
 
1426
1434
  protected override ensureMigrated(): void {
1427
1435
  if (this.migrated) {
1428
1436
  return;
1429
1437
  }
1430
1438
 
1431
- runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${re} });
1439
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ae} });
1432
1440
  this.migrated = true;
1433
1441
  }
1434
1442
  ${H?`
@@ -1440,7 +1448,7 @@ ${H?`
1440
1448
 
1441
1449
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1442
1450
  }
1443
- `:""}${et}
1444
- ${zt({actionOnlyFields:wt,agentsBuild:ye,agentsContextField:ve,containersBuild:he,containersContextField:ue,databaseOptions:at,everyContextBuild:gt,everyContextField:bt,facadeBlock:mt,globalDatabaseLine:ot,notifyBuild:ft,ormContextField:st,paymentsBuild:Re,paymentsContextField:Ae,queuesBuild:ae,queuesContextField:ne,topicsBuild:ie,topicsContextField:de,vectorsBuild:tt,vectorsContextField:nt,workflowsBuild:ge,workflowsContextField:be,actionOnlyBuild:yt})}
1451
+ `:""}${at}
1452
+ ${er({actionOnlyFields:kt,agentsBuild:ve,agentsContextField:ke,containersBuild:ue,containersContextField:pe,databaseOptions:ot,everyContextBuild:yt,everyContextField:wt,facadeBlock:ft,globalDatabaseLine:ct,notifyBuild:vt,ormContextField:dt,paymentsBuild:xe,paymentsContextField:Oe,queuesBuild:ne,queuesContextField:se,topicsBuild:de,topicsContextField:ce,vectorsBuild:nt,vectorsContextField:it,workflowsBuild:be,workflowsContextField:fe,actionOnlyBuild:St})}
1445
1453
  };
1446
- `};export{er as b,Sr as e};
1454
+ `};export{sr as b,Dr as e};
@@ -1 +1 @@
1
- import{Node as l,SyntaxKind as g,DiagnosticCategory as j}from"ts-morph";import{lunoraRelativePath as P}from"./isTestPath-B81lOULB.mjs";import{posix as h}from"node:path";let S,v;const _e=e=>{const t=S,r=[];S=r;try{return{erased:r,value:e()}}finally{S=t}},Re=e=>{S?.push(...e)},U=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},E=(e,t)=>{S?.push({exportName:U(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},$e=e=>{v!==void 0&&E(v,e)},Ce=(e,t)=>{const r=v;v=e;try{return t()}finally{v=r}},K=(e,t)=>{const r=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${r}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${r}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},ke=(e,t)=>{const r=new Map;for(const n of e){const s=K(n,P(t,n.filePath));r.set(s.cacheKey,s)}return[...r.values()].toSorted((n,s)=>n.cacheKey.localeCompare(s.cacheKey))},F=/\bany\b(?!\s*(?:\?\s*)?:)/u,B=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,V=e=>F.test(e.replaceAll(B,"")),W="/_generated/",q=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(r=>r?.getDeclarations()??[]);return t.length>0&&t.every(r=>r.getSourceFile().getSymbol()===void 0)},G=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,N=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const r=G.exec(t.getName());if(r?.groups?.specifier!==void 0)return r.groups.specifier}},w=new WeakMap,X=(e,t)=>{const r=e.getSymbol();if(r===void 0)return;let n=w.get(r.compilerSymbol);return n===void 0&&(n=new Map,w.set(r.compilerSymbol,n)),n.has(t)||n.set(t,r.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),n.get(t)},$=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(r=>r.getName()===t),H=(e,t,r)=>e.getModuleSpecifierValue()===t&&$(e,r)?r:void 0,Y=(e,t)=>{const r=e.getDefaultImport();if(r===void 0)return;const n=r.getSymbol();return(n?.getAliasedSymbol()??n)?.getDeclarations().includes(t)===!0?"default":void 0},J=(e,t,r)=>{if(!$(e,r))return;const n=e.getModuleSpecifierSourceFile(),s=n===void 0?void 0:X(n,r);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?r:void 0},z=/^\.\.?(?:$|\/)/u,Q=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),Z=(e,t)=>{const r=t.getModuleSpecifierValue();if(!z.test(r))return;const n=t.getModuleSpecifierSourceFile(),s=n===void 0?void 0:Q.get(n.getExtension());if(n===void 0||s===void 0)return;const o=`${h.join(n.getDirectoryPath(),n.getBaseNameWithoutExtension())}${s}`,i=h.relative(e.getDirectoryPath(),o);return i.startsWith(".")?i:`./${i}`},ee=(e,t,r)=>{const n=N(t);for(const s of e.getImportDeclarations()){const o=n===void 0?Y(s,t)??J(s,t,r):H(s,n,r);if(o!==void 0)return{exportName:o,specifier:Z(e,s)??s.getModuleSpecifierValue()}}},te=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(r=>{const n=r.indexOf("*");return n===-1?e===r:e.startsWith(r.slice(0,n))&&e.endsWith(r.slice(n+1))}),f={kind:"verbatim"},p={kind:"expand"},re=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ne=e=>N(e)!==void 0||l.isExportable(e)&&e.isExported(),se=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),C=(e,t,r,n)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&N(e)===void 0||!re.has(e.getKind()))return f;const o=s.getFilePath();if(o.includes(W))return f;if(o===r)return p;const i=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(i))return p;const a=ee(t.getSourceFile(),i,i.getName());return a===void 0?ne(i)||!se(n(),i.getName())?f:p:te(a.specifier,t)?p:{kind:"qualify",qualified:a}},oe=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),M=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(r=>r.getSourceFile().getSymbol()===void 0)},ie=e=>{for(const t of e.getDeclarations()){const r=t.getFirstChildByKind(g.ComputedPropertyName);if(r!==void 0){let n=r.getExpression();for(;l.isPropertyAccessExpression(n);)n=n.getExpression();return n}}},ae=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const o=ie(s);return o===void 0||!M(o.getSymbol())}))return!0;const n=e.getSymbol();return n!==void 0&&n.getDeclarations().some(s=>oe.has(s.getKind()))&&!M(n)&&t().startsWith("typeof ")},k=(e,t,r)=>{const n=e.getAliasSymbol(),s=e.getSymbol(),o=new Set((n??s)?.getDeclarations());let i=!1,a;const c=()=>(a??=e.getText(t),a);for(const u of[s,n].flatMap(d=>d?.getDeclarations()??[])){const d=C(u,t,r,c);if(d.kind==="qualify"&&o.has(u))return d;i||=d.kind!=="verbatim"}return i||ae(e,c)?p:f},ce=(e,t,r)=>{const n=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(n===void 0)return f;let s=!1;for(const o of[n,...n.getDescendantsOfKind(g.TypeReference)].filter(i=>l.isTypeReference(i))){const i=o.getTypeName().getSymbol();for(const a of(i?.getAliasedSymbol()??i)?.getDeclarations()??[]){const c=C(a,t,r,()=>o.getText());if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?p:f},ue=/^[A-Za-z_$][\w$]*$/u,le=e=>ue.test(e)?e:JSON.stringify(e),O=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,r,n=new Set)=>n.has(e)?!1:(n.add(e),k(e,t,r).kind!=="verbatim"||O(e).some(s=>T(s,t,r,n))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(o=>ce(o,t,r).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,r,n)):!1),ge=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(l.isPropertySignature(r)||l.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(n=>n.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,de=32,fe=8,me=(e,t,r,n,s,o)=>{const i=e.getArrayElementType(),a=i?o(i,t,r,n,s):void 0;if(a!==void 0)return`${L(i,a)}[]`},pe=(e,t,r,n,s,o)=>{const i=[];for(const a of e.getUnionTypes()){const c=o(a,t,r,n,s);if(c===void 0)return;i.push(c)}return i.join(" | ")},Se=(e,t,r,n,s,o)=>{const i=[];for(const a of e.getIntersectionTypes()){const c=o(a,t,r,n,s);if(c===void 0)return;i.push(L(a,c))}return i.join(" & ")},ve=(e,t,r,n,s,o)=>{if(!A(e))return;const i=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=ge(a,c),d=u&&c.isUnion()?c.getUnionTypes().filter(x=>!x.isUndefined()):[c],D=[];for(const x of d){const I=o(x,t,r,n+1,s);if(I===void 0)return;D.push(I)}i.push(`${le(a.getName())}${u?"?":""}: ${D.join(" | ")}`)}return i.length>0?`{ ${i.join("; ")} }`:"{}"},Ee=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},be=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),b=(e,t,r,n,s=new Set)=>{if(n.has(e)||s.has(e))return!1;if(r>de)return!0;const o=new Set(n).add(e);if(O(e).some(u=>b(u,t,r+1,o,s)))return!0;const i=e.getArrayElementType();if(i!==void 0)return b(i,t,r+1,o,s);if(q(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const c=A(e)&&e.getProperties().some(u=>b(u.getTypeAtLocation(t),t,r+1,o,s));return c||s.add(e),c},ye=(e,t,r,n,s,o,i)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=i(c,r,n,s+1,o);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},Te=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,r,n,s)=>{if(n>fe||s.has(e))return;const o=k(e,t,r);if(o.kind==="verbatim"&&!T(e,t,r))return e.getText(t);const i=new Set(s).add(e);if(!be(e)){if(e.isEnumLiteral())return Ee(e);if(o.kind==="qualify"&&!Te(e)){const a=ye(o.qualified,e,t,r,n,i,m);if(a!==void 0)return a}return e.isArray()?me(e,t,r,n,i,m):e.isUnion()?pe(e,t,r,n,i,m):e.isIntersection()?Se(e,t,r,n,i,m):ve(e,t,r,n,i,m)}},_=new WeakMap,Ae=e=>{const t=_.get(e);if(t)return t;const r=e.getPreEmitDiagnostics().filter(n=>n.getCategory()===j.Error);return _.set(e,r),r},y=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},xe=/is of type 'unknown'|on type '\{\}'/,Ne=e=>xe.test(e),De=/has no exported member '([^']+)'/,Ie=(e,t,r,n)=>{const s=e.getSourceFile();for(const o of e.getDescendantsOfKind(g.Identifier))for(const i of o.getSymbol()?.getDeclarations()??[]){const a=i.getStart();if(i.getSourceFile()!==s||a>=r&&a<=n)continue;const c=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=i.getStart()&&d<=i.getEnd()});if(c!==void 0)return y(c)}},R=e=>{const t=e.getStart(),r=e.getEnd(),n=Ae(e.getSourceFile()),s=n.find(c=>{const u=c.getStart();return u!==void 0&&u>=t&&u<=r});if(s===void 0){const c=Ie(e,n,t,r);return c===void 0?void 0:{derivative:!0,message:c}}const o=y(s);if(!Ne(o))return{derivative:!1,message:o};const i=new Set(e.getDescendantsOfKind(g.Identifier).map(c=>c.getText())),a=n.find(c=>{const u=De.exec(y(c))?.[1];return u!==void 0&&i.has(u)});return{derivative:!0,message:a?`${o}; caused by: ${y(a)}`:o}},Oe=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const s=(r.getSymbol()??r.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=r.getText(e);if(!o||o==="any"||o==="never"||o==="unknown"){const a=R(e);return a!==void 0&&(o!=="unknown"||a.derivative)&&E(e,`${o||"any"} (${a.message})`),"unknown"}if(V(o)){const a=R(e);return a!==void 0&&E(e,`${o} (${a.message})`),"unknown"}if(b(r,e,0,new Set))return"unknown";const i=e.getSourceFile().getFilePath();if(T(r,e,i)){const a=m(r,e,i,0,new Set);return a===void 0&&E(e,o),a??"unknown"}return o};export{T as a,$e as b,_e as c,ke as d,m as e,V as i,Ce as p,Re as r,Oe as u};
1
+ import{Node as l,SyntaxKind as g,DiagnosticCategory as j}from"ts-morph";import{lunoraRelativePath as P}from"./isTestPath-B81lOULB.mjs";import{posix as h}from"node:path";let S,v;const _e=e=>{const t=S,r=[];S=r;try{return{erased:r,value:e()}}finally{S=t}},Re=e=>{S?.push(...e)},U=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},E=(e,t)=>{S?.push({exportName:U(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},$e=e=>{v!==void 0&&E(v,e)},Ce=(e,t)=>{const r=v;v=e;try{return t()}finally{v=r}},K=(e,t)=>{const r=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${r}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${r}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},ke=(e,t)=>{const r=new Map;for(const n of e){const s=K(n,P(t,n.filePath));r.set(s.cacheKey,s)}return[...r.values()].toSorted((n,s)=>n.cacheKey.localeCompare(s.cacheKey))},F=/\bany\b(?!\s*(?:\?\s*)?:)/u,B=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,V=e=>F.test(e.replaceAll(B,"")),W="/_generated/",q=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(r=>r?.getDeclarations()??[]);return t.length>0&&t.every(r=>r.getSourceFile().getSymbol()===void 0)},G=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,N=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const r=G.exec(t.getName());if(r?.groups?.specifier!==void 0)return r.groups.specifier}},w=new WeakMap,X=(e,t)=>{const r=e.getSymbol();if(r===void 0)return;let n=w.get(r.compilerSymbol);return n===void 0&&(n=new Map,w.set(r.compilerSymbol,n)),n.has(t)||n.set(t,r.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),n.get(t)},$=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(r=>r.getName()===t),H=(e,t,r)=>e.getModuleSpecifierValue()===t&&$(e,r)?r:void 0,Y=(e,t)=>{const r=e.getDefaultImport();if(r===void 0)return;const n=r.getSymbol();return(n?.getAliasedSymbol()??n)?.getDeclarations().includes(t)===!0?"default":void 0},J=(e,t,r)=>{if(!$(e,r))return;const n=e.getModuleSpecifierSourceFile(),s=n===void 0?void 0:X(n,r);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?r:void 0},z=/^\.\.?(?:$|\/)/u,Q=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),Z=(e,t)=>{const r=t.getModuleSpecifierValue();if(!z.test(r))return;const n=t.getModuleSpecifierSourceFile(),s=n===void 0?void 0:Q.get(n.getExtension());if(n===void 0||s===void 0)return;const o=`${h.join(n.getDirectoryPath(),n.getBaseNameWithoutExtension())}${s}`,i=h.relative(e.getDirectoryPath(),o);return i.startsWith(".")?i:`./${i}`},ee=(e,t,r)=>{const n=N(t);for(const s of e.getImportDeclarations()){const o=n===void 0?Y(s,t)??J(s,t,r):H(s,n,r);if(o!==void 0)return{exportName:o,specifier:Z(e,s)??s.getModuleSpecifierValue()}}},te=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(r=>{const n=r.indexOf("*");return n===-1?e===r:e.startsWith(r.slice(0,n))&&e.endsWith(r.slice(n+1))}),f={kind:"verbatim"},p={kind:"expand"},re=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ne=e=>N(e)!==void 0||l.isExportable(e)&&e.isExported(),se=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),C=(e,t,r,n)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&N(e)===void 0||!re.has(e.getKind()))return f;const o=s.getFilePath();if(o.includes(W))return f;if(o===r)return p;const i=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(i))return p;const a=ee(t.getSourceFile(),i,i.getName());return a===void 0?ne(i)||!se(n(),i.getName())?f:p:te(a.specifier,t)?p:{kind:"qualify",qualified:a}},oe=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),M=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(r=>r.getSourceFile().getSymbol()===void 0)},ie=e=>{for(const t of e.getDeclarations()){const r=t.getFirstChildByKind(g.ComputedPropertyName);if(r!==void 0){let n=r.getExpression();for(;l.isPropertyAccessExpression(n);)n=n.getExpression();return n}}},ae=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const o=ie(s);return o===void 0||!M(o.getSymbol())}))return!0;const n=e.getSymbol();return n!==void 0&&n.getDeclarations().some(s=>oe.has(s.getKind()))&&!M(n)&&t().startsWith("typeof ")},k=(e,t,r)=>{const n=e.getAliasSymbol(),s=e.getSymbol(),o=new Set((n??s)?.getDeclarations());let i=!1,a;const c=()=>(a??=e.getText(t),a);for(const u of[s,n].flatMap(d=>d?.getDeclarations()??[])){const d=C(u,t,r,c);if(d.kind==="qualify"&&o.has(u))return d;i||=d.kind!=="verbatim"}return i||ae(e,c)?p:f},ce=(e,t,r)=>{const n=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(n===void 0)return f;let s=!1;for(const o of[n,...n.getDescendantsOfKind(g.TypeReference)].filter(i=>l.isTypeReference(i))){const i=o.getTypeName().getSymbol();for(const a of(i?.getAliasedSymbol()??i)?.getDeclarations()??[]){const c=C(a,t,r,()=>o.getText());if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?p:f},ue=/^[A-Za-z_$][\w$]*$/u,le=e=>ue.test(e)?e:JSON.stringify(e),O=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,r,n=new Set)=>n.has(e)?!1:(n.add(e),k(e,t,r).kind!=="verbatim"||O(e).some(s=>T(s,t,r,n))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(o=>ce(o,t,r).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,r,n)):!1),ge=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(l.isPropertySignature(r)||l.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(n=>n.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,de=32,fe=8,me=(e,t,r,n,s,o)=>{const i=e.getArrayElementType(),a=i?o(i,t,r,n,s):void 0;if(a!==void 0)return`${L(i,a)}[]`},pe=(e,t,r,n,s,o)=>{const i=[];for(const a of e.getUnionTypes()){const c=o(a,t,r,n,s);if(c===void 0)return;i.push(c)}return i.join(" | ")},Se=(e,t,r,n,s,o)=>{const i=[];for(const a of e.getIntersectionTypes()){const c=o(a,t,r,n,s);if(c===void 0)return;i.push(L(a,c))}return i.join(" & ")},ve=(e,t,r,n,s,o)=>{if(!A(e))return;const i=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=ge(a,c),d=u&&c.isUnion()?c.getUnionTypes().filter(x=>!x.isUndefined()):[c],D=[];for(const x of d){const I=o(x,t,r,n+1,s);if(I===void 0)return;D.push(I)}i.push(`${le(a.getName())}${u?"?":""}: ${D.join(" | ")}`)}return i.length>0?`{ ${i.join("; ")} }`:"{}"},Ee=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},be=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),b=(e,t,r,n,s=new Set)=>{if(n.has(e)||s.has(e))return!1;if(r>de)return!0;const o=new Set(n).add(e);if(O(e).some(u=>b(u,t,r+1,o,s)))return!0;const i=e.getArrayElementType();if(i!==void 0)return b(i,t,r+1,o,s);if(q(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const c=A(e)&&e.getProperties().some(u=>b(u.getTypeAtLocation(t),t,r+1,o,s));return c||s.add(e),c},ye=(e,t,r,n,s,o,i)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=i(c,r,n,s+1,o);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},Te=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,r,n,s)=>{if(n>fe||s.has(e))return;const o=k(e,t,r);if(o.kind==="verbatim"&&!T(e,t,r))return e.getText(t);const i=new Set(s).add(e);if(!be(e)){if(e.isEnumLiteral())return Ee(e);if(o.kind==="qualify"&&!Te(e)){const a=ye(o.qualified,e,t,r,n,i,m);if(a!==void 0)return a}return e.isArray()?me(e,t,r,n,i,m):e.isUnion()?pe(e,t,r,n,i,m):e.isIntersection()?Se(e,t,r,n,i,m):ve(e,t,r,n,i,m)}},_=new WeakMap,Ae=e=>{const t=_.get(e.compilerNode);if(t)return t;const r=e.getPreEmitDiagnostics().filter(n=>n.getCategory()===j.Error);return _.set(e.compilerNode,r),r},y=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},xe=/is of type 'unknown'|on type '\{\}'/,Ne=e=>xe.test(e),De=/has no exported member '([^']+)'/,Ie=(e,t,r,n)=>{const s=e.getSourceFile();for(const o of e.getDescendantsOfKind(g.Identifier))for(const i of o.getSymbol()?.getDeclarations()??[]){const a=i.getStart();if(i.getSourceFile()!==s||a>=r&&a<=n)continue;const c=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=i.getStart()&&d<=i.getEnd()});if(c!==void 0)return y(c)}},R=e=>{const t=e.getStart(),r=e.getEnd(),n=Ae(e.getSourceFile()),s=n.find(c=>{const u=c.getStart();return u!==void 0&&u>=t&&u<=r});if(s===void 0){const c=Ie(e,n,t,r);return c===void 0?void 0:{derivative:!0,message:c}}const o=y(s);if(!Ne(o))return{derivative:!1,message:o};const i=new Set(e.getDescendantsOfKind(g.Identifier).map(c=>c.getText())),a=n.find(c=>{const u=De.exec(y(c))?.[1];return u!==void 0&&i.has(u)});return{derivative:!0,message:a?`${o}; caused by: ${y(a)}`:o}},Oe=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const s=(r.getSymbol()??r.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=r.getText(e);if(!o||o==="any"||o==="never"||o==="unknown"){const a=R(e);return a!==void 0&&(o!=="unknown"||a.derivative)&&E(e,`${o||"any"} (${a.message})`),"unknown"}if(V(o)){const a=R(e);return a!==void 0&&E(e,`${o} (${a.message})`),"unknown"}if(b(r,e,0,new Set))return"unknown";const i=e.getSourceFile().getFilePath();if(T(r,e,i)){const a=m(r,e,i,0,new Set);return a===void 0&&E(e,o),a??"unknown"}return o};export{T as a,$e as b,_e as c,ke as d,m as e,V as i,Ce as p,Re as r,Oe as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.300",
3
+ "version": "1.0.0-alpha.302",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,15 +46,15 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.214",
50
- "@lunora/agent": "1.0.0-alpha.203",
51
- "@lunora/container": "1.0.0-alpha.74",
49
+ "@lunora/advisor": "1.0.0-alpha.216",
50
+ "@lunora/agent": "1.0.0-alpha.205",
51
+ "@lunora/container": "1.0.0-alpha.75",
52
52
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
53
53
  "@lunora/platform": "1.0.0-alpha.64",
54
- "@lunora/queue": "1.0.0-alpha.105",
55
- "@lunora/scheduler": "1.0.0-alpha.124",
56
- "@lunora/values": "1.0.0-alpha.64",
57
- "@lunora/workflow": "1.0.0-alpha.76",
54
+ "@lunora/queue": "1.0.0-alpha.106",
55
+ "@lunora/scheduler": "1.0.0-alpha.126",
56
+ "@lunora/values": "1.0.0-alpha.65",
57
+ "@lunora/workflow": "1.0.0-alpha.77",
58
58
  "@visulima/fs": "6.0.29",
59
59
  "jiti": "^2.7.0",
60
60
  "quicktype-core": "^26.0.0",