@lunora/codegen 1.0.0-alpha.334 → 1.0.0-alpha.336

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 (86) hide show
  1. package/dist/index.d.mts +20 -1
  2. package/dist/index.d.ts +20 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-8zoeGNsB.mjs → AGENTS_FILENAME-isdHqPIt.mjs} +1 -1
  5. package/dist/packem_shared/CONTAINERS_FILENAME-mK4cZpcz.mjs +1 -0
  6. package/dist/packem_shared/{DEFAULT_TARGET-CDksdcYc.mjs → DEFAULT_TARGET-3OLdJhTj.mjs} +1 -1
  7. package/dist/packem_shared/{FLAGS_FILENAME-Cwq0B2Nl.mjs → FLAGS_FILENAME-BQk3SX8D.mjs} +1 -1
  8. package/dist/packem_shared/GENERATED_HEADER-BXK9A_wP.mjs +1 -0
  9. package/dist/packem_shared/LUNORA_ERROR_CODES-CIAJQeKB.mjs +1 -0
  10. package/dist/packem_shared/{MUTATORS_FILENAME-DZFH7a9G.mjs → MUTATORS_FILENAME-Cy9h3EVW.mjs} +1 -1
  11. package/dist/packem_shared/{NOTIFY_FILENAME-DZIt-rb0.mjs → NOTIFY_FILENAME-9to_l_Kh.mjs} +1 -1
  12. package/dist/packem_shared/{OPENRPC_VERSION-CeEGdAZ9.mjs → OPENRPC_VERSION-l4HD4osw.mjs} +1 -1
  13. package/dist/packem_shared/{QUEUES_FILENAME-EvfCmmv6.mjs → QUEUES_FILENAME-Civ-7SiI.mjs} +1 -1
  14. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DcWyFDv9.mjs +31 -0
  15. package/dist/packem_shared/{SHAPES_FILENAME-Ciu5tx7B.mjs → SHAPES_FILENAME-DVJbfDZ8.mjs} +1 -1
  16. package/dist/packem_shared/{WORKFLOWS_FILENAME-C5tz9gMh.mjs → WORKFLOWS_FILENAME-kXq07aGl.mjs} +1 -1
  17. package/dist/packem_shared/{attribution-RI-H1KPm.mjs → attribution-CG8-kUcl.mjs} +1 -1
  18. package/dist/packem_shared/{buildOpenApiDocument-BBao-3vL.mjs → buildOpenApiDocument-DWdj2jvW.mjs} +1 -1
  19. package/dist/packem_shared/capabilitiesUsedBy-C-7D7vlH.mjs +1 -0
  20. package/dist/packem_shared/chain-74gjwZMP.mjs +1 -0
  21. package/dist/packem_shared/{classify-procedure-call-C5JY2w5V.mjs → classify-procedure-call-BkaeM9Ej.mjs} +1 -1
  22. package/dist/packem_shared/{context-property-calls-M6Oo1xQT.mjs → context-property-calls-dFjpeIlP.mjs} +1 -1
  23. package/dist/packem_shared/{context-root-DQd48e1F.mjs → context-root-CNR6TAsP.mjs} +1 -1
  24. package/dist/packem_shared/{createCodegenProject-C-fKC9h4.mjs → createCodegenProject-R4so-yTU.mjs} +1 -1
  25. package/dist/packem_shared/{database-calls-BNoSJRFy.mjs → database-calls-UPlhi3Ks.mjs} +1 -1
  26. package/dist/packem_shared/discoverAuthApiCalls-CScPrUD-.mjs +1 -0
  27. package/dist/packem_shared/discoverCrons-B1_NUt19.mjs +1 -0
  28. package/dist/packem_shared/{discoverFunctions-CJu5EH_G.mjs → discoverFunctions-DkPOc8b9.mjs} +1 -1
  29. package/dist/packem_shared/{discoverHttpRoutes-MrMxIY66.mjs → discoverHttpRoutes-DCDgDIYv.mjs} +1 -1
  30. package/dist/packem_shared/discoverHyperdriveCalls-CL-d0IVo.mjs +1 -0
  31. package/dist/packem_shared/{discoverInserts-Boh6WAYw.mjs → discoverInserts-BcoTjXqI.mjs} +1 -1
  32. package/dist/packem_shared/discoverMaskProcedures-Bw-BOIbA.mjs +1 -0
  33. package/dist/packem_shared/{discoverMigrations-BMdGxHeq.mjs → discoverMigrations-BWxx8Wv9.mjs} +1 -1
  34. package/dist/packem_shared/{discoverNondeterministicCalls-c9xenrIN.mjs → discoverNondeterministicCalls-3INW8oqs.mjs} +1 -1
  35. package/dist/packem_shared/{discoverQueries-o_00HnBB.mjs → discoverQueries-CxQRVuIV.mjs} +1 -1
  36. package/dist/packem_shared/discoverR2sqlCalls-B4oeTYEM.mjs +1 -0
  37. package/dist/packem_shared/{discoverRlsMetadata-C7J8dgVz.mjs → discoverRlsMetadata-D0B4nCmG.mjs} +1 -1
  38. package/dist/packem_shared/{discoverRlsProcedures-Di3VEk-D.mjs → discoverRlsProcedures-Cl6UKT7L.mjs} +1 -1
  39. package/dist/packem_shared/{discoverSandboxUsage-CrhZZJZS.mjs → discoverSandboxUsage--Z1vx7GM.mjs} +1 -1
  40. package/dist/packem_shared/discoverSchema-Cwt-DQgh.mjs +1 -0
  41. package/dist/packem_shared/{discoverStorageRulesMetadata-BFCmbsIN.mjs → discoverStorageRulesMetadata-CitX6ziW.mjs} +1 -1
  42. package/dist/packem_shared/{emitAgents-CR2_X_ov.mjs → emitAgents-C9JRmvrC.mjs} +1 -1
  43. package/dist/packem_shared/{emitApi-CDgIPAG2.mjs → emitApi-c14__tie.mjs} +24 -24
  44. package/dist/packem_shared/{emitApp-DuJW6LKD.mjs → emitApp-BL16wvE9.mjs} +1 -1
  45. package/dist/packem_shared/{emitCrons-BQW2lviZ.mjs → emitCrons-lc-hnJYn.mjs} +1 -1
  46. package/dist/packem_shared/{emitDataModel-BskFt9Wv.mjs → emitDataModel-CuFqq97x.mjs} +1 -1
  47. package/dist/packem_shared/{emitDrizzleSchema-DitcRZ1a.mjs → emitDrizzleSchema-bct1OuH5.mjs} +1 -1
  48. package/dist/packem_shared/{emitFunctions-Cd0Tuw73.mjs → emitFunctions-CkBPtGDF.mjs} +71 -65
  49. package/dist/packem_shared/{emitServer-D1vA5_X1.mjs → emitServer-CGUhLmlG.mjs} +1 -1
  50. package/dist/packem_shared/{emitShard-DtfjUgjj.mjs → emitShard-FJhdFx9H.mjs} +1 -1
  51. package/dist/packem_shared/{exported-procedure-chains-Bol_VtzO.mjs → exported-procedure-chains-D1WlRfqJ.mjs} +1 -1
  52. package/dist/packem_shared/{fingerprintSchemaSources-BdFj8vPc.mjs → fingerprintSchemaSources-BKXkgkj4.mjs} +1 -1
  53. package/dist/packem_shared/{handler-reference-8w_VU4XY.mjs → handler-reference-CClSR4bi.mjs} +1 -1
  54. package/dist/packem_shared/index-CN8FVvr-.mjs +1 -0
  55. package/dist/packem_shared/{isTestPath-Cdv_LoVU.mjs → isTestPath-C3QumE88.mjs} +1 -1
  56. package/dist/packem_shared/loadProjectConfig-B7RmxIeD.mjs +1 -0
  57. package/dist/packem_shared/{modules-DDIIcM7P.mjs → modules-l-Db0C4S.mjs} +1 -1
  58. package/dist/packem_shared/parse-validator-iVTounLK.mjs +1 -0
  59. package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
  60. package/dist/packem_shared/{qualifiers-DEdXn5wP.mjs → qualifiers-Bl5fSmav.mjs} +1 -1
  61. package/dist/packem_shared/readServiceBindings-BA49C6aN.mjs +1 -0
  62. package/dist/packem_shared/{server-DAvi_bv_.mjs → server-B6VhYK7m.mjs} +1 -1
  63. package/dist/packem_shared/{shard-CsfiXxV0.mjs → shard-B6afe1Uh.mjs} +170 -122
  64. package/dist/packem_shared/{shard-runtime-BpoCV-aM.mjs → shard-runtime-BW1kffN4.mjs} +9 -7
  65. package/dist/packem_shared/shared-8vTRkL2-.mjs +13 -0
  66. package/dist/packem_shared/{unwrap-handler-return-Bfz7lH0C.mjs → unwrap-handler-return-CGdJGvGh.mjs} +1 -1
  67. package/dist/sdk/index.mjs +15 -15
  68. package/package.json +9 -9
  69. package/dist/packem_shared/CONTAINERS_FILENAME-QiNt84QA.mjs +0 -1
  70. package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +0 -1
  71. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +0 -1
  72. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-V7LYutDl.mjs +0 -31
  73. package/dist/packem_shared/capabilitiesUsedBy-BC7ldWJI.mjs +0 -1
  74. package/dist/packem_shared/chain-C9qZxjM_.mjs +0 -1
  75. package/dist/packem_shared/discoverAuthApiCalls-GPzUN_-_.mjs +0 -1
  76. package/dist/packem_shared/discoverCrons-C1fKEf4g.mjs +0 -1
  77. package/dist/packem_shared/discoverHyperdriveCalls-VVJGsgxj.mjs +0 -1
  78. package/dist/packem_shared/discoverMaskProcedures-D3Tu8Q8Y.mjs +0 -1
  79. package/dist/packem_shared/discoverR2sqlCalls-D_H1v-UD.mjs +0 -1
  80. package/dist/packem_shared/discoverSchema-Bdmw34_P.mjs +0 -1
  81. package/dist/packem_shared/index-BMMBKqsT.mjs +0 -1
  82. package/dist/packem_shared/loadProjectConfig-B0uxUGF-.mjs +0 -1
  83. package/dist/packem_shared/parse-validator-BqDQLzDZ.mjs +0 -1
  84. package/dist/packem_shared/project-config-file-CBY6llht.mjs +0 -1
  85. package/dist/packem_shared/readServiceBindings-4xlUucKw.mjs +0 -1
  86. package/dist/packem_shared/shared-DnCokNcE.mjs +0 -13
@@ -1,4 +1,4 @@
1
- import{LunoraError as de}from"@lunora/errors";import{serializeSchemaSnapshot as Ht,hashSchemaSnapshot as Vt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Kt,isD1GlobalTable as Gt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Qt}from"./json-data-Chfs2Cz5.mjs";import{r as E,e as Jt,a as zt,b as Yt,c as Xt,d as Zt,f as er,g as tr,h as rr,i as nr,j as ar,k as sr,l as or,m as ir,n as dr,o as cr,p as lr,q as ur}from"./shard-runtime-BpoCV-aM.mjs";import{u as Y,i as hr,a as pr,I as mr,c as gr,G as fr,d as br}from"./shared-DnCokNcE.mjs";import{p as wr}from"./platform-8oj7iXQy.mjs";import{i as yr}from"./schema-BgM8A3XV.mjs";const h=(n,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${e}); })()`,ce=["categories","description","facing","level","remediation","title"],vr=n=>{const e={};return{advisoryRows:n.map(a=>{let r=e[a.name];return r||(r=Object.fromEntries(ce.filter(o=>o in a).map(o=>[o,a[o]])),e[a.name]=r),Object.fromEntries(Object.entries(a).filter(([o,d])=>!ce.includes(o)||JSON.stringify(d)!==JSON.stringify(r[o])))}),advisoryRules:e}},kr=` /**
1
+ import{LunoraError as he}from"@lunora/errors";import{serializeSchemaSnapshot as Jt,hashSchemaSnapshot as zt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.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 gr,q as fr}from"./shard-runtime-BW1kffN4.mjs";import{u as re,h as br,s as wr,a as yr,I as vr,c as kr,G as Sr,d as Rr}from"./shared-8vTRkL2-.mjs";import{p as xr}from"./platform-8oj7iXQy.mjs";import{i as Ar}from"./schema-BgM8A3XV.mjs";const u=(n,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${t}); })()`,pe=["categories","description","facing","level","remediation","title"],Or=n=>{const t={};return{advisoryRows:n.map(a=>{let r=t[a.name];return r||(r=Object.fromEntries(pe.filter(o=>o in a).map(o=>[o,a[o]])),t[a.name]=r),Object.fromEntries(Object.entries(a).filter(([o,d])=>!pe.includes(o)||JSON.stringify(d)!==JSON.stringify(r[o])))}),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
@@ -30,7 +30,7 @@ import{LunoraError as de}from"@lunora/errors";import{serializeSchemaSnapshot as
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,g=(n="")=>` const writer = this.adminWriter(${n});`,Sr=`${kr}
33
+ }`,w=(n="")=>` const writer = this.adminWriter(${n});`,Tr=`${Dr}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -47,7 +47,7 @@ import{LunoraError as de}from"@lunora/errors";import{serializeSchemaSnapshot as
47
47
  throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
48
48
  }
49
49
 
50
- ${g()}
50
+ ${w()}
51
51
 
52
52
  return runDataMigration({
53
53
  ...(args.batchSize === undefined ? {} : { batchSize: args.batchSize }),
@@ -80,7 +80,7 @@ ${g()}
80
80
 
81
81
  this.ensureMigrated();
82
82
 
83
- ${g("headroom ?? this.transactionHeadroom()")}
83
+ ${w("headroom ?? this.transactionHeadroom()")}
84
84
 
85
85
  if (args.op === "insert") {
86
86
  const id = await writer.insert(args.table, args.doc ?? {});
@@ -135,7 +135,7 @@ ${g("headroom ?? this.transactionHeadroom()")}
135
135
  protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
136
136
  this.ensureMigrated();
137
137
 
138
- ${g()}
138
+ ${w()}
139
139
 
140
140
  const rows: ExportRow[] = [];
141
141
 
@@ -152,7 +152,7 @@ ${g()}
152
152
  protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
153
153
  this.ensureMigrated();
154
154
 
155
- ${g()}
155
+ ${w()}
156
156
 
157
157
  // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
158
158
  // database's \`_id\`s carry across verbatim and every foreign key
@@ -163,7 +163,7 @@ ${g()}
163
163
  protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
164
164
  this.ensureMigrated();
165
165
 
166
- ${g()}
166
+ ${w()}
167
167
 
168
168
  // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
169
169
  // but the shard writer from \`createShardCtxDb\` always defines it.
@@ -181,7 +181,7 @@ ${g()}
181
181
  protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
182
182
  this.ensureMigrated();
183
183
 
184
- ${g()}
184
+ ${w()}
185
185
 
186
186
  // \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
187
187
  // but the shard writer from \`createShardCtxDb\` always defines it — it
@@ -199,7 +199,7 @@ ${g()}
199
199
  protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
200
200
  this.ensureMigrated();
201
201
 
202
- ${g()}
202
+ ${w()}
203
203
 
204
204
  // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
205
205
  // but the shard writer from \`createShardCtxDb\` always defines it. The sort
@@ -220,21 +220,21 @@ ${g()}
220
220
  protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
221
221
  this.ensureMigrated();
222
222
 
223
- ${g()}
223
+ ${w()}
224
224
 
225
225
  await applyCdcChanges(writer, args.changes);
226
226
 
227
227
  return { applied: args.changes.length };
228
- }`,Rr=({actionOnlyBuild:n,actionOnlyFields:e,agentsBuild:t,agentsContextField:a,containersBuild:r,containersContextField:o,databaseOptions:d,everyContextBuild:f,everyContextField:v,facadeBlock:l,globalDatabaseLine:b,lazyFunctions:c=!1,notifyBuild:L,ormContextField:S,paymentsBuild:R,paymentsContextField:I,queuesBuild:P,queuesContextField:k,topicsBuild:N,topicsContextField:i,vectorsBuild:w,vectorsContextField:M,workflowsBuild:$,workflowsContextField:q})=>{const x=e.length>0,F=S===""?"{ db }":"{ db, orm: bindOrm(facade) }",U=S===""?"":`
229
- orm: databaseContext.orm,`,O=S===""?"":`
230
- orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,u=x?`
228
+ }`,_r=({actionOnlyBuild:n,actionOnlyFields:t,agentsBuild:e,agentsContextField:a,containersBuild:r,containersContextField:o,databaseOptions:d,everyContextBuild:m,everyContextField:g,facadeBlock:h,globalDatabaseLine:x,hasSensitiveArgs:S=!1,lazyFunctions:f=!1,notifyBuild:c,ormContextField:y,paymentsBuild:M,paymentsContextField:A,queuesBuild:q,queuesContextField:F,topicsBuild:R,topicsContextField:U,vectorsBuild:i,vectorsContextField:v,workflowsBuild:C,workflowsContextField:B})=>{const E=t.length>0,L=y===""?"{ db }":"{ db, orm: bindOrm(facade) }",j=y===""?"":`
229
+ orm: databaseContext.orm,`,W=y===""?"":`
230
+ orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,O=E?`
231
231
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
232
232
  // and attached only for an \`action\` so query/mutation ctx never carry them.
233
233
  if (isAction) {
234
- ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(p=>` ctx.${p} = ${p};`).join(`
234
+ ${n.replaceAll(/^(?=.)/gmu," ")}${t.map(p=>` ctx.${p} = ${p};`).join(`
235
235
  `)}
236
236
  }
237
- `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark | undefined; functionPath?: string | undefined; headroom?: TransactionHeadroomTracker | undefined; identity?: SubscriptionIdentity | undefined; kind?: "query" | undefined; onRead?: ((table: string, idOrScan?: string) => void) | undefined; onReadRange?: ((range: KeyRange) => void) | undefined; scope?: QueryReadScope | undefined; trusted?: boolean | undefined } = {}): unknown {
237
+ `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark | undefined; functionPath?: string | undefined; headroom?: TransactionHeadroomTracker | undefined; identity?: SubscriptionIdentity | undefined; kind?: "query" | undefined; onRead?: ((table: string, idOrScan?: string) => void) | undefined; onReadRange?: ((range: KeyRange) => void) | undefined; scope?: QueryReadScope | undefined; sensitive?: SensitiveScope | undefined; trusted?: boolean | undefined } = {}): unknown {
238
238
  const env = (this.env ?? {}) as Record<string, unknown>;
239
239
  // The caller context this ctx runs under, resolved ONCE on one
240
240
  // discriminant. When the caller threads an explicit identity
@@ -261,7 +261,7 @@ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(p=>` ctx.${p} = ${p};`
261
261
  };
262
262
  })();
263
263
  const { identity, ip, userId } = caller;
264
- ${w}${f}${r}${$}${P}${N}${t}
264
+ ${i}${m}${r}${C}${q}${R}${e}
265
265
  // Which dispatch this ctx belongs to. Drives the two deferral facades
266
266
  // below and the \`ctx.run*\` caller guard; a ctx built for an
267
267
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -357,7 +357,7 @@ ${w}${f}${r}${$}${P}${N}${t}
357
357
  // dispatch's wide-event handle.
358
358
  const observability = config.observability?.(env);
359
359
  const logFunctionPath = options.functionPath ?? "";
360
- const log = this.makeLogger(logFunctionPath, observability);
360
+ const log = this.makeLogger(logFunctionPath, observability, undefined, options.sensitive);
361
361
  const traceAnchor = this.resolveDispatchAnchor(Boolean(options.identity));
362
362
 
363
363
  // \`ctx.span\`: the handle onto the DISPATCH's own span — the wide-event
@@ -365,9 +365,9 @@ ${w}${f}${r}${$}${P}${N}${t}
365
365
  // and are folded into the one span it already emits, instead of
366
366
  // becoming N separate log lines. Shares \`traceAnchor\` with \`ctx.trace\`
367
367
  // so both write to the same trace.
368
- const span = this.makeDispatchSpan(traceAnchor, observability);
368
+ const span = this.makeDispatchSpan(traceAnchor, observability, options.sensitive);
369
369
 
370
- ${b} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
370
+ ${x} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
371
371
  // adds aggregate counters (call count, total time, per-operation
372
372
  // breakdown) to the wide event rather than a span per call, so a
373
373
  // handler making hundreds of queries stays readable. See
@@ -375,20 +375,20 @@ ${b} // \`ctx.db\`, wrapped in automatic instrumentation: by default
375
375
  // Schema triggers close over this DB's scheduler, so a composed
376
376
  // mutation must rebuild its DB and table/ORM views with its own queue.
377
377
  const makeDatabaseContext = (scheduler: SchedulerLike) => {
378
- const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
379
- ${l} return ${F};
378
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability, options.sensitive);
379
+ ${h} return ${L};
380
380
  };
381
381
  const databaseContext = makeDatabaseContext(scheduler);
382
382
  const db = databaseContext.db;
383
- ${R}
383
+ ${M}
384
384
 
385
385
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
386
386
  // The trace anchor is threaded explicitly for the same reason \`identity\`
387
387
  // is — a deferred caller (a subscription re-run) must not inherit the
388
388
  // writing mutation's trace from the shared per-request field.
389
- const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
390
- const metrics = this.makeMetrics(logFunctionPath, observability);
391
- ${L}
389
+ const trace = this.makeTracer(logFunctionPath, observability, traceAnchor, options.sensitive);
390
+ const metrics = this.makeMetrics(logFunctionPath, observability, options.sensitive);
391
+ ${c}
392
392
  // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
393
393
  // captured ONCE so the whole handler body sees a single stable value.
394
394
  // A \`query\` handler is re-run by every live subscription that reads it,
@@ -418,7 +418,7 @@ ${L}
418
418
  // \`traceparent\` propagation, so time spent in a downstream service
419
419
  // is visible and its spans join this trace. Degrades to the bare
420
420
  // global when no sink is configured.
421
- fetch: this.makeFetch(logFunctionPath, traceAnchor, observability),
421
+ fetch: this.makeFetch(logFunctionPath, traceAnchor, observability, options.sensitive),
422
422
  // A GETTER, not a plain field, so the reactive cache can tell a
423
423
  // handler that reads the caller's address from the majority that
424
424
  // never do. \`ctx.ip\` is per-request state the memo must be keyed
@@ -439,25 +439,32 @@ ${L}
439
439
  // to the handler so code that signs its own URLs (a copy-in
440
440
  // \`createStorage\`) can fall back to it too. \`undefined\` for a
441
441
  // query and for a deferred dispatch, for the reasons given there.
442
- origin: requestOrigin,${U}
442
+ origin: requestOrigin,${j}
443
443
  scheduler,
444
444
  span,
445
445
  storage: contextStorage,
446
- trace,${M}${v}${I}${o}${q}${k}${i}${a}
446
+ trace,${v}${g}${A}${o}${B}${F}${U}${a}${S?`
447
+ [Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
447
448
  };
448
- ${x?` const isAction = contextKind === "action";
449
- `:""}${u}
450
- ${c?` const captureScope = (): (() => void) => {
449
+ ${E?` const isAction = contextKind === "action";
450
+ `:""}${O}
451
+ ${f?` const captureScope = (): (() => void) => {
451
452
  const requestScope = this.captureRequestScope();
452
453
  return () => this.restoreRequestScope(requestScope);
453
454
  };
454
455
 
455
456
  `:""} const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
456
- target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${c?", undefined, captureScope":""});
457
+ target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => {
458
+ // The callee runs inside this invocation, so its marked arguments are scrubbed here too.
459
+ this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
460
+
461
+ return dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${f?", undefined, captureScope":""});
462
+ };
457
463
  // The composed mutation runs under the SAME wrapper the top-level RPC
458
464
  // uses, so "do the transactional work in a mutation and call it from the
459
465
  // action" — the recipe the docs give for atomicity — actually is atomic.
460
466
  target.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => {
467
+ this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
461
468
  // An action can start sibling mutations concurrently. Each owns its
462
469
  // context and deferral queues; only calls from an admitted mutation
463
470
  // inherit that mutation's transaction.
@@ -469,7 +476,7 @@ ${c?` const captureScope = (): (() => void) => {
469
476
 
470
477
  return Object.defineProperties({}, {
471
478
  ...Object.getOwnPropertyDescriptors(target),
472
- db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${O}
479
+ db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${W}
473
480
  scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
474
481
  storage: { configurable: true, enumerable: true, value: withDeferredDeletes(storage), writable: true },
475
482
  });
@@ -479,7 +486,7 @@ ${c?` const captureScope = (): (() => void) => {
479
486
  installRun(mutationCtx, kind);
480
487
  }
481
488
 
482
- return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${c?", captureScope":""});
489
+ return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${f?", captureScope":""});
483
490
  };
484
491
  // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
485
492
  // its OWN query context, built without the subscription's read-footprint
@@ -494,18 +501,21 @@ ${c?` const captureScope = (): (() => void) => {
494
501
  // to the shared per-request fields, which a concurrent RPC may have
495
502
  // re-set, and an RLS-scoped sub-query would then read as the wrong user
496
503
  // from the wrong address. A tracked call runs on \`queryContext()\` below.
497
- target.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>, runOptions?: { untracked?: boolean }) =>
498
- dispatchRun(
504
+ target.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>, runOptions?: { untracked?: boolean }) => {
505
+ this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
506
+
507
+ return dispatchRun(
499
508
  "query",
500
509
  reference.__lunoraRef,
501
510
  fnArgs,
502
511
  runOptions?.untracked === true
503
- ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope })
512
+ ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope, sensitive: options.sensitive })
504
513
  : queryContext(),
505
- kind,${c?`
514
+ kind,${f?`
506
515
  undefined,
507
516
  captureScope,`:""}
508
517
  );
518
+ };
509
519
  };
510
520
 
511
521
  // A query composed from a mutation or action runs on a QUERY view of
@@ -526,7 +536,7 @@ ${c?` const captureScope = (): (() => void) => {
526
536
 
527
537
  if (queryView === undefined) {
528
538
  const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
529
- ${e.map(p=>` delete descriptors.${p};
539
+ ${t.map(p=>` delete descriptors.${p};
530
540
  `).join("")} // Writable and configurable, like the plain fields they replace.
531
541
  const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
532
542
 
@@ -545,7 +555,7 @@ ${e.map(p=>` delete descriptors.${p};
545
555
  installRun(ctx, contextKind);
546
556
 
547
557
  return ctx;
548
- }`},le=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
558
+ }`},me=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
549
559
  // referencing call fails loudly with a clear error instead of overflowing the
550
560
  // stack. Tracked across the awaited handler chain (one DO invocation is
551
561
  // single-threaded), so the counter reflects true nesting depth.
@@ -611,7 +621,7 @@ const dispatchRun = async (
611
621
  } finally {
612
622
  runDepth -= 1;
613
623
  }
614
- };`,xr=n=>n?le.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
624
+ };`,Cr=n=>n?me.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
615
625
  captureScope?: () => () => void,`).replace(` try {
616
626
  // A mutation composed from an action`,` try {
617
627
  let loaded = getLoadedFunction(functionPath);
@@ -632,7 +642,20 @@ const dispatchRun = async (
632
642
 
633
643
  const loadedFunction = loaded;
634
644
 
635
- // A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):le,Or=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
645
+ // A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):me,Er=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark, sensitive?: SensitiveScope): Promise<unknown> {
646
+ // A dispatch that did not come through the shard's \`/rpc\` (a scheduled call,
647
+ // a lifecycle hook, an admin run) has no scope of its own, so it opens one here
648
+ // and releases it when the handler settles.
649
+ if (sensitive === undefined) {
650
+ const own = this.openSensitiveScope(functionPath, args);
651
+
652
+ try {
653
+ return await this.handleRpc(functionPath, args, headroom, scope, bookmarks, own);
654
+ } finally {
655
+ own.clear();
656
+ }
657
+ }
658
+
636
659
  __PREPARE_FUNCTION__ const registered = LUNORA_FUNCTIONS[functionPath];
637
660
 
638
661
  // Internal functions are reachable server-side only: via \`ctx.run*\`
@@ -659,7 +682,7 @@ __PREPARE_FUNCTION__ const registered = LUNORA_FUNCTIONS[functionPath
659
682
  // our dep set — and ours out of theirs. A dispatch with no scope (a
660
683
  // mutation, an action, a cache-less shard) builds unbound hooks that
661
684
  // stamp no deps.
662
- const ctx = this.buildCtx({ bookmarks, functionPath, headroom, scope, trusted: registered.lifecycle === "init" });
685
+ const ctx = this.buildCtx({ bookmarks, functionPath, headroom, scope, sensitive, trusted: registered.lifecycle === "init" });
663
686
 
664
687
  // A mutation's writes must commit all-or-nothing, so its dispatch runs
665
688
  // under \`runMutationTransaction\` — the ONE place that opens the span,
@@ -816,7 +839,7 @@ __COMMITTED_CATCH__ } finally {
816
839
  // \`ctx.scheduler\` call that reached the buffer in the first place.
817
840
  protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
818
841
  return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
819
- }`,Ar=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
842
+ }`,Lr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
820
843
  const registered = LUNORA_FUNCTIONS[functionPath];
821
844
 
822
845
  if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
@@ -857,7 +880,7 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
857
880
  // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
858
881
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
859
882
  };
860
- }`,Dr=` } catch (error) {
883
+ }`,Ir=` } catch (error) {
861
884
  // The write committed before this failed. Mark the error so the caller can tell
862
885
  // a durable write from a rollback: the rethrow still reaches the caller unchanged.
863
886
  if (typeof error === "object" && error !== null) {
@@ -865,13 +888,13 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
865
888
  }
866
889
 
867
890
  throw error;
868
- `,Tr=(n,e=!1)=>{const t=e?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
891
+ `,Pr=(n,t=!1)=>{const e=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
869
892
 
870
893
  if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
871
894
  throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
872
895
  }
873
896
 
874
- `:"",a=e?` const requestScope = this.captureRequestScope();
897
+ `:"",a=t?` const requestScope = this.captureRequestScope();
875
898
  const preparation = this.prepareFunction(functionPath, "rpc");
876
899
 
877
900
  if (preparation !== undefined) {
@@ -882,8 +905,20 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
882
905
  }
883
906
  }
884
907
 
885
- `:"";return Or.replace("__COMMITTED_CATCH__",n?Dr:"").replace("__PREPARE_FUNCTION__",`${t}${a}`)},Cr=n=>{const e={};for(const t of n.tables){const a={};for(const[r,o]of Object.entries(t.shape)){const d=Y(o);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(e[t.name]=a)}return e},_r=n=>{const e={};for(const t of n.tables){const a=[];for(const[r,o]of Object.entries(t.shape))Y(o).kind==="storage"&&a.push(r);a.length>0&&(e[t.name]=a)}return e},Er=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(o=>o.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},Lr=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},Ir=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},Pr=(n,e,t)=>{const a=Y(e),r={name:n,optional:hr(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 o=Ir(a);return o!==void 0&&(r.enumValues=o),a.column?.notNull===!1&&(r.nullable=!0),r},Nr=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(o=>o.kind==="one"?[[o.field,o.onDelete]]:[]));for(const[o,d]of Object.entries(t.shape))a.push(Pr(o,d,r));e[t.name]=a}return e},Mr=({hasMutators:n,hasShapes:e,rlsData:t})=>{const a=e?`
886
- protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
908
+ `:"";return Er.replace("__COMMITTED_CATCH__",n?Ir:"").replace("__PREPARE_FUNCTION__",`${e}${a}`)},Nr=n=>{const t={};for(const e of n.tables){const a={};for(const[r,o]of Object.entries(e.shape)){const d=re(o);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(t[e.name]=a)}return t},$r=n=>{const t={};for(const e of n.tables){const a=[];for(const[r,o]of Object.entries(e.shape))re(o).kind==="storage"&&a.push(r);a.length>0&&(t[e.name]=a)}return t},Mr=n=>{const t={};for(const e of n.tables){const a=[...e.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(e.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...e.rankIndexes.map(r=>({fields:r.sortBy.map(o=>o.field),name:r.name,type:"rank"})),...e.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(t[e.name]=a)}return t},qr=n=>{const t=[];for(const e of n.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=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const t=[];for(const e of n.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const a=JSON.parse(e.literalValue);if(typeof a!="string")return;t.push(a)}catch{return}}return t},Ur=(n,t,e)=>{const a=re(t),r={name:n,optional:br(t),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=e.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const o=Fr(a);return o!==void 0&&(r.enumValues=o),a.column?.notNull===!1&&(r.nullable=!0),r},Br=n=>{const t={};for(const e of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(e.relations.flatMap(o=>o.kind==="one"?[[o.field,o.onDelete]]:[]));for(const[o,d]of Object.entries(e.shape))a.push(Ur(o,d,r));t[e.name]=a}return t},jr=({hasMutators:n,hasSensitiveShapes:t,hasShapes:e,rlsData:a})=>{const r="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",o=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${r} {
909
+ const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
910
+
911
+ try {
912
+ return this.resolveShapeWithScope(name, args, identity, sensitive);
913
+ } catch (error) {
914
+ throw this.maskSensitiveError(error, sensitive);
915
+ } finally {
916
+ sensitive.clear();
917
+ }
918
+ }
919
+
920
+ private resolveShapeWithScope(name: string, args: Record<string, unknown>, identity: SubscriptionIdentity | undefined, sensitive: SensitiveScope): ${r} {`:` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${r} {`,m=e?`
921
+ ${o}
887
922
  const shape = LUNORA_SHAPES[name];
888
923
 
889
924
  if (!shape) {
@@ -896,7 +931,7 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
896
931
  // supplies only the shape name + args; \`compileWhere\` validates the
897
932
  // args then runs the shape's \`where(ctx, args)\` under that identity,
898
933
  // so which rows replicate is a server decision (reads-as-permissions).
899
- const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity });
934
+ const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity${t?", sensitive":""} });
900
935
  // \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
901
936
  // \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
902
937
  // rather than every shape restating the ownership check in its \`where\`.
@@ -945,14 +980,14 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
945
980
 
946
981
  return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
947
982
  }
948
- `:"",r=e?[...new Set(t.policies.filter(l=>l.on==="read"&&l.table!=="").map(l=>l.table))].toSorted((l,b)=>l.localeCompare(b)):[],o=r.length>0?`
983
+ `:"",g=e?[...new Set(a.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,y)=>c.localeCompare(y)):[],h=g.length>0?`
949
984
  /** 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). */
950
- assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
985
+ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(g)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
951
986
  `:"";return{customMutatorOverride:n?`
952
987
  protected override isCustomMutator(functionPath: string): boolean {
953
988
  return LUNORA_MUTATOR_PATHS.has(functionPath);
954
989
  }
955
- `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},$r=(n,e)=>n?`
990
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:h,shapeReadPolicyImport:h===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:m}},Wr=(n,t)=>n?`
956
991
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
957
992
  const env = this.env as Record<string, unknown>;
958
993
  // A shape read performs no writes, so the widened request only needs
@@ -972,7 +1007,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
972
1007
  ...(identity?.identity === undefined ? {} : { identity: identity.identity }),
973
1008
  ...(identity?.userId === undefined ? {} : { userId: identity.userId }),
974
1009
  };
975
- const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
1010
+ const globalDb: DatabaseWriterLike = ${t}?.(env, globalRequest) ?? globalDbStub;
976
1011
  const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
977
1012
 
978
1013
  let cursor: null | string = null;
@@ -1014,11 +1049,11 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
1014
1049
  // a \`defineShape\`. The Hyperdrive factory simply never reads it.
1015
1050
  const bookmark = this.getInboundBookmark();
1016
1051
  const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), ...(bookmark === undefined ? {} : { bookmark }) };
1017
- const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
1052
+ const globalDb: DatabaseWriterLike = ${t}?.(env, globalRequest) ?? globalDbStub;
1018
1053
 
1019
1054
  return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
1020
1055
  }
1021
- `:"",qr=n=>({externalSourceOverride:n?`
1056
+ `:"",Hr=n=>({externalSourceOverride:n?`
1022
1057
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1023
1058
  const env = (this.env ?? {}) as Record<string, unknown>;
1024
1059
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1171,8 +1206,8 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
1171
1206
  `:"",sourceClientCacheConst:n?`
1172
1207
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1173
1208
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1174
- `:""}),Fr=(n,e)=>{const t=e.length>0,r=n?E("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",o=t?` const vectorShardKey = this.currentShardKey();
1175
- `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",v=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(c=>JSON.stringify(c)).join(", ")}]`]:[]].join(", ")} }`,l=n?`
1209
+ `:""}),Vr=(n,t)=>{const e=t.length>0,r=n?$("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
1210
+ `:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",g=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,h=n?`
1176
1211
  const vectorSync = this.vectorSync(env);
1177
1212
  // Vectorize lives outside this shard's SQLite, so a query whose result
1178
1213
  // depends on a similarity search cannot be proven current on reconnect —
@@ -1189,7 +1224,7 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1189
1224
  }
1190
1225
 
1191
1226
  const lunora = createVectors({ indexes: config.vectors(env) });
1192
- ${o} const vectors = createContextVectors(lunora${v});
1227
+ ${o} const vectors = createContextVectors(lunora${g});
1193
1228
 
1194
1229
  return {
1195
1230
  backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
@@ -1215,14 +1250,14 @@ ${o} const vectors = createContextVectors(lunora${v});
1215
1250
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1216
1251
  });
1217
1252
  }
1218
- `:"",vectorsBuild:l,vectorsStub:r}},Xr=({advisories:n=[],advisorProcedures:e=[],agents:t=[],capabilities:a=new Set,containers:r=[],env:o,flagKeys:d=[],hasFlags:f=!1,hasNotify:v=!1,hasRooms:l=!1,hasSockets:b=!1,lazyFunctions:c=!1,hasVectors:L=!0,liveStreamDeclarations:S=[],liveStreams:R=!1,maskMetadata:I,mutators:P=[],queues:k=[],rlsMetadata:N,schema:i,schemaSnapshot:w,shapes:M=[],storageRules:$,studioFeatures:q,services:x=[],topics:F=[],useUmbrella:U=!1,workflows:O=[]})=>{const u=br(U),B=P.length>0,p=M.length>0,ue=w===void 0?"":Ht(w),he=w===void 0?"":`
1253
+ `:"",vectorsBuild:h,vectorsStub:r}},on=({advisories:n=[],advisorProcedures:t=[],agents:e=[],capabilities:a=new Set,containers:r=[],env:o,flagKeys:d=[],hasFlags:m=!1,hasNotify:g=!1,hasRooms:h=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:f=!1,lazyFunctions:c=!1,hasVectors:y=!0,liveStreamDeclarations:M=[],liveStreams:A=!1,maskMetadata:q,mutators:F=[],queues:R=[],rlsMetadata:U,schema:i,schemaSnapshot:v,shapes:C=[],storageRules:B,studioFeatures:E,services:L=[],topics:j=[],useUmbrella:W=!1,workflows:O=[]})=>{const l=Rr(W),H=F.length>0,p=C.length>0,D=C.some(s=>wr(s.args).length>0),V=S||D,ge=v===void 0?"":Jt(v),fe=v===void 0?"":`
1219
1254
  /** 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. */
1220
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Vt(w))}, json: ${JSON.stringify(ue)} };
1221
- `,pe=w===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",y=Jt(a),T=zt(f,u.flags),j=Yt(d,f,u.flags),W=ur(v),H=Xt(o),{build:me,contextField:ge,importLines:fe,specs:be}=Zt(wr(k)),{build:we,contextField:ye,importLines:ve,specs:ke}=er(F,k),V=tr(x,u.server),{build:Se,contextField:Re,importLines:xe,specs:Oe}=rr(r,i.jurisdiction),{build:Ae,contextField:De,importLines:Te,specs:Ce}=nr(O),{build:_e,contextField:Ee,importLines:Le,specs:Ie}=ar(t),{build:Pe,configField:Ne,contextField:Me,imports:$e,stub:qe}=sr(a.has("payments")),Fe=n,{advisoryRules:Ue,advisoryRows:Be}=vr(Fe),je=e,X=N??{policies:[],roles:[]},We=I??{columns:[]},He=$??{rules:[]},Ve=q??{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:Ke,override:Ge}=or(O),{constant:Qe,override:Je}=ir(k),m=L&&i.vectorIndexes.length>0,K=new Set(i.tables.filter(s=>yr(s)).map(s=>s.name)),Z=m&&i.vectorIndexes.some(s=>K.has(s.table)),A=i.tables.some(s=>s.shardMode==="global"),G=dr(K),Q=i.tables.some(s=>Kt(s)),ee=i.tables.some(s=>Gt(s)),C=i.tables.some(s=>s.externalSource!==void 0),te=i.tables.some(s=>s.memory===!0),J=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(ee&&Q)throw new de("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const z=i.tables.length>0,ze=Cr(i),Ye=Er(i),Xe=Nr(i),Ze=_r(i),re=Lr(i),ne=cr(m,O.length>0,k.length>0,f,J);p&&ne.push("WhereInput");const ae=lr(A),{customMutatorOverride:et,shapeGuardImport:tt,shapeReadPolicyAssertion:rt,shapeReadPolicyImport:nt,shapeResolveOverride:at}=Mr({hasMutators:B,hasShapes:p,rlsData:X}),D=R?S:[];for(const s of D)if(pr(s.exportName,"live stream export name"),!mr.test(s.filePath))throw new de("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const st=c?[]:D.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),ot=` protected override liveStreams() {
1222
- return { ${D.map(s=>`${gr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1255
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(zt(v))}, json: ${JSON.stringify(ge)} };
1256
+ `,be=v===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=er(a),I=tr(m,l.flags),K=rr(d,m,l.flags),G=fr(g),Q=nr(o),{build:we,contextField:ye,importLines:ve,specs:ke}=ar(xr(R)),{build:Se,contextField:Re,importLines:xe,specs:Ae}=sr(j,R),J=or(L,l.server),{build:Oe,contextField:De,importLines:Te,specs:_e}=ir(r,i.jurisdiction),{build:Ce,contextField:Ee,importLines:Le,specs:Ie}=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(a.has("payments")),We=n,{advisoryRules:He,advisoryRows:Ve}=Or(We),Ke=t,ne=U??{policies:[],roles:[]},Ge=q??{columns:[]},Qe=B??{rules:[]},Je=E??{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=y&&i.vectorIndexes.length>0,z=new Set(i.tables.filter(s=>Ar(s)).map(s=>s.name)),ae=b&&i.vectorIndexes.some(s=>z.has(s.table)),T=i.tables.some(s=>s.shardMode==="global"),Y=pr(z),X=i.tables.some(s=>Yt(s)),se=i.tables.some(s=>Xt(s)),P=i.tables.some(s=>s.externalSource!==void 0),oe=i.tables.some(s=>s.memory===!0),Z=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&X)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 ee=i.tables.length>0,et=Nr(i),tt=Mr(i),rt=Br(i),nt=$r(i),ie=qr(i),te=mr(b,O.length>0,R.length>0,m,Z);p&&te.push("WhereInput"),D&&te.push("SensitiveScope");const de=gr(T),{customMutatorOverride:at,shapeGuardImport:st,shapeReadPolicyAssertion:ot,shapeReadPolicyImport:it,shapeResolveOverride:dt}=jr({hasMutators:H,hasSensitiveShapes:D,hasShapes:p,rlsData:ne}),_=A?M:[];for(const s of _)if(yr(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() {
1257
+ return { ${_.map(s=>`${kr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1223
1258
  }
1224
- `,it=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
1225
- ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1259
+ `,ut=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
1260
+ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1226
1261
  `)}
1227
1262
  ]);
1228
1263
 
@@ -1243,11 +1278,11 @@ ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1243
1278
  protected override liveStreams() {
1244
1279
  return Object.fromEntries(this.loadedLiveStreams);
1245
1280
  }
1246
- `;let se="";D.length>0&&(se=c?it:ot);const _=[`import type { ${ne.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, createStableIdFactory, ${J?"backfillSearchIndexes, ":""}${m?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${te?"clearMemoryTables, ":""}${tt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${C?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Z?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ae.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,...C?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],p?`import { asBucketStorage, ${nt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];z&&_.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),m&&_.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),_.push(...y.importLines,...T.importLines,...W.importLines,...H.importLines,...xe,...Te,...fe,...ve,...V.importLines,...Le,...$e,"",'import schema from "../schema.js";',...st,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...B?["LUNORA_MUTATOR_PATHS"]:[],...l?["LUNORA_ROOMS"]:[],...b?["LUNORA_SOCKETS"]:[],...p?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const dt=m?`
1247
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",ct=ee?`
1248
- d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",lt=Q?`
1249
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ut=C?`
1250
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",ht="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",pt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",mt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",gt=A?E("globalDbStub: DatabaseWriterLike",ht,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:ft,vectorsBuild:bt,vectorsStub:wt}=Fr(m,Z?i.vectorIndexes.filter(s=>K.has(s.table)).map(s=>s.name):[]),yt=`{
1281
+ `;let ce="";_.length>0&&(ce=c?ut:lt);const N=[`import type { ${te.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, ${Z?"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}";`]:[],p?`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}";`];ee&&N.push(`import { bindOrm, bindTableFacade } 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,...I.importLines,...G.importLines,...Q.importLines,...Te,...Le,...ve,...xe,...J.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"]:[],...h?["LUNORA_ROOMS"]:[],...f?["LUNORA_SOCKETS"]:[],...p?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ht=b?`
1282
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",pt=se?`
1283
+ 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=X?`
1284
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",gt=P?`
1285
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",ft="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",bt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",wt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",yt=T?$("globalDbStub: DatabaseWriterLike",ft,["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}=Vr(b,ae?i.vectorIndexes.filter(s=>z.has(s.table)).map(s=>s.name):[]),Rt=`{
1251
1286
  ...this.ctxDbTuning(),
1252
1287
  auth: { identity: identity ?? null, userId: userId ?? null },
1253
1288
  broadcast: (delta) => {
@@ -1287,7 +1322,7 @@ ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1287
1322
  // fallback rather than reporting into a no-op.
1288
1323
  ...(options.onReadRange !== undefined
1289
1324
  ? { onReadRange: options.onReadRange }
1290
- : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${m?`
1325
+ : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${b?`
1291
1326
  // Vectorize is outside this shard's SQLite and cannot roll back, so
1292
1327
  // the sync is held until the mutation's transaction has COMMITTED
1293
1328
  // (\`deferAfterCommit\`) instead of running inline. Inline, a write
@@ -1299,11 +1334,11 @@ ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1299
1334
  scheduler,
1300
1335
  schema: schema as unknown as SchemaLike,
1301
1336
  sql: this.sql as SqlExec,
1302
- storage,${A?`
1337
+ storage,${T?`
1303
1338
  globalDb,`:""}
1304
- }`,vt=m?`
1305
- vectors,`:"",kt=z?`
1306
- orm: bindOrm(facade),`:"",oe=Q?"config.hyperdriveGlobal":"config.d1",St=A?` const bookmark = this.getInboundBookmark();
1339
+ }`,xt=b?`
1340
+ vectors,`:"",At=ee?`
1341
+ orm: bindOrm(facade),`:"",le=X?"config.hyperdriveGlobal":"config.d1",Ot=T?` const bookmark = this.getInboundBookmark();
1307
1342
  const globalRequest = {
1308
1343
  ...this.globalCdcOptions(config.cdc ?? false),
1309
1344
  ...(bookmark === undefined ? {} : { bookmark }),
@@ -1311,26 +1346,26 @@ ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1311
1346
  onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
1312
1347
  ...(userId === undefined ? {} : { userId }),
1313
1348
  };
1314
- const globalDb: DatabaseWriterLike = ${oe}?.(env, globalRequest) ?? globalDbStub;
1315
- `:"",Rt=$r(p&&A,oe),xt=l?` protected override roomHandlerPath(topic: string): string | undefined {
1349
+ const globalDb: DatabaseWriterLike = ${le}?.(env, globalRequest) ?? globalDbStub;
1350
+ `:"",Dt=Wr(p&&T,le),Tt=h?` protected override roomHandlerPath(topic: string): string | undefined {
1316
1351
  // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1317
1352
  return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1318
1353
  }
1319
- `:"",Ot=b?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1354
+ `:"",_t=f?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1320
1355
  return LUNORA_SOCKETS[path];
1321
1356
  }
1322
- `:"",{externalSourceOverride:At,sourceBootstrap:Dt,sourceClientCacheConst:Tt}=qr(C),Ct=`
1357
+ `:"",{externalSourceOverride:Ct,sourceBootstrap:Et,sourceClientCacheConst:Lt}=Hr(P),It=`
1323
1358
  protected override async runShardInit(): Promise<void> {
1324
1359
  this.ensureMigrated();
1325
- ${te?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1360
+ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1326
1361
  `:""}
1327
1362
  await this.dispatchShardInit();
1328
1363
  }
1329
- `,_t=re.length>0?`
1364
+ `,Pt=ie.length>0?`
1330
1365
  if (LUNORA_TTL_SWEEPS.length > 0) {
1331
1366
  void this.scheduleTtlSweep();
1332
1367
  }
1333
- `:"",Et=`
1368
+ `:"",Nt=`
1334
1369
  public constructor(state: ShardDOState, env: unknown) {
1335
1370
  super(state, env, {
1336
1371
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1347,7 +1382,7 @@ ${te?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1347
1382
  // exists — a trigger that fails first still flushes and fuses.
1348
1383
  ...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
1349
1384
  });
1350
- ${Dt}${_t} }
1385
+ ${Et}${Pt} }
1351
1386
 
1352
1387
  protected override isCacheableQuery(functionPath: string): boolean {
1353
1388
  // NOT \`kind === "query"\` alone. A cache hit answers without running
@@ -1371,7 +1406,7 @@ ${Dt}${_t} }
1371
1406
  protected override isPaidFunction(functionPath: string): boolean {
1372
1407
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1373
1408
  }
1374
- `,ie=c?`
1409
+ `,ue=c?`
1375
1410
  protected override prepareFunction(functionPath: string, reason: "rpc" | "subscription" | "stream" | "reactor"): Promise<void> | undefined {
1376
1411
  const registered = LUNORA_FUNCTIONS[functionPath];
1377
1412
  const allowsInternal = reason === "reactor" || (reason === "rpc" && this.isSystemDispatch());
@@ -1386,25 +1421,38 @@ ${Dt}${_t} }
1386
1421
 
1387
1422
  return loadFunction(functionPath).then(() => undefined);
1388
1423
  }
1389
- `:"",Lt=ie===""?`
1424
+ `:"",$t=ue===""?`
1425
+
1426
+ `:`${ue}
1427
+ `,Mt=V?`
1428
+ protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
1429
+ const registered = LUNORA_FUNCTIONS[functionPath];${D?`
1430
+ const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
1431
+ const fromValidators = sensitiveArgumentNames(registered?.args ?? ${D?"shape?.args ?? ":""}{});
1432
+
1433
+ if (registered?.sensitiveArgs === undefined) {
1434
+ return fromValidators;
1435
+ }
1436
+
1437
+ return new Set([...registered.sensitiveArgs, ...fromValidators]);
1438
+ }
1390
1439
 
1391
- `:`${ie}
1392
- `,It=xr(c),Pt=c?` const preparation = this.prepareFunction(functionPath, "subscription");
1440
+ `:"",qt=Cr(c),Ft=c?` const preparation = this.prepareFunction(functionPath, "subscription");
1393
1441
  if (preparation !== undefined) await preparation;
1394
- `:"",Nt=Ar.replace("__PREPARE_FUNCTION__",Pt),Mt=Tr(l,c),$t=z?`
1442
+ `:"",Ut=Lr.replace("__PREPARE_FUNCTION__",Ft),Bt=Pr(h,c),jt=ee?`
1395
1443
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1396
1444
  ${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFacade(db, ${JSON.stringify(s.name)});`).join(`
1397
1445
  `)}
1398
- `:"",qt=`${y.everyBuild}${T.build}${H.build}
1446
+ `:"",Wt=`${k.everyBuild}${I.build}${Q.build}
1399
1447
  const secrets = createSecrets(env);
1400
- `,Ft=`${y.everyFields}${T.contextField}${W.contextField}${H.contextField}
1401
- secrets,`,Ut=W.build,Bt=R?`
1448
+ `,Ht=`${k.everyFields}${I.contextField}${G.contextField}${Q.contextField}
1449
+ secrets,`,Vt=G.build,Kt=A?`
1402
1450
  const live = {
1403
1451
  publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
1404
1452
  await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
1405
1453
  },
1406
1454
  };
1407
- `:"",jt=[...y.actionFields,...x.length>0?["services"]:[],...R?["live"]:[]],Wt=`${y.actionBuild}${V.build}${Bt}`;return`${fr}${_.join(`
1455
+ `:"",Gt=[...k.actionFields,...L.length>0?["services"]:[],...A?["live"]:[]],Qt=`${k.actionBuild}${J.build}${Kt}`;return`${Sr}${N.join(`
1408
1456
  `)}
1409
1457
 
1410
1458
  type FunctionKind = "action" | "mutation" | "query";
@@ -1414,13 +1462,13 @@ interface FunctionReference {
1414
1462
  }
1415
1463
 
1416
1464
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1417
- const LUNORA_TABLE_REFS = ${h(ze,"Record<string, Record<string, string>>")};
1465
+ const LUNORA_TABLE_REFS = ${u(et,"Record<string, Record<string, string>>")};
1418
1466
 
1419
1467
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1420
- const LUNORA_TABLE_INDEXES = ${h(Ye,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1468
+ const LUNORA_TABLE_INDEXES = ${u(tt,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1421
1469
 
1422
1470
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1423
- const LUNORA_TABLE_COLUMNS = ${h(Xe,`Record<
1471
+ const LUNORA_TABLE_COLUMNS = ${u(rt,`Record<
1424
1472
  string,
1425
1473
  Array<{
1426
1474
  bucket?: string;
@@ -1437,16 +1485,16 @@ const LUNORA_TABLE_COLUMNS = ${h(Xe,`Record<
1437
1485
  >`)};
1438
1486
 
1439
1487
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1440
- const LUNORA_STORAGE_COLUMNS = ${h(Ze,"Record<string, string[]>")};
1488
+ const LUNORA_STORAGE_COLUMNS = ${u(nt,"Record<string, string[]>")};
1441
1489
 
1442
1490
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1443
- const LUNORA_TTL_SWEEPS = ${Qt(re,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1491
+ const LUNORA_TTL_SWEEPS = ${Zt(ie,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1444
1492
 
1445
1493
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1446
- const LUNORA_ADVISORY_RULES = ${h(Ue,"Record<string, Partial<AdvisoryFinding>>")};
1494
+ const LUNORA_ADVISORY_RULES = ${u(He,"Record<string, Partial<AdvisoryFinding>>")};
1447
1495
 
1448
1496
  /** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
1449
- const LUNORA_ADVISORY_ROWS = ${h(Be,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1497
+ const LUNORA_ADVISORY_ROWS = ${u(Ve,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1450
1498
 
1451
1499
  const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1452
1500
  let cached: AdvisoryFinding[] | undefined;
@@ -1454,20 +1502,20 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1454
1502
  })();
1455
1503
 
1456
1504
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1457
- const LUNORA_ADVISOR_PROCEDURES = ${h(je,"AdvisorProcedure[]")};
1505
+ const LUNORA_ADVISOR_PROCEDURES = ${u(Ke,"AdvisorProcedure[]")};
1458
1506
 
1459
1507
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1460
- const LUNORA_RLS_METADATA = ${h(X,"RlsPoliciesResult")};
1461
- ${rt}
1508
+ const LUNORA_RLS_METADATA = ${u(ne,"RlsPoliciesResult")};
1509
+ ${ot}
1462
1510
  /** 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. */
1463
- const LUNORA_MASK_METADATA = ${h(We,"MaskPoliciesResult")};
1511
+ const LUNORA_MASK_METADATA = ${u(Ge,"MaskPoliciesResult")};
1464
1512
 
1465
1513
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1466
- const LUNORA_STORAGE_RULES = ${h(He,"StorageRulesResult")};
1514
+ const LUNORA_STORAGE_RULES = ${u(Qe,"StorageRulesResult")};
1467
1515
 
1468
1516
  /** 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. */
1469
- const LUNORA_STUDIO_FEATURES = ${h(Ve,"StudioFeaturesResult")};
1470
- ${he}${G.constant}${j.constant}${Ke}${Qe}${Oe}${Ce}${be}${ke}${V.specs}${Ie}
1517
+ const LUNORA_STUDIO_FEATURES = ${u(Je,"StudioFeaturesResult")};
1518
+ ${fe}${Y.constant}${K.constant}${ze}${Xe}${_e}${Ie}${ke}${Ae}${J.specs}${Me}
1471
1519
  export interface ShardDOConfig {
1472
1520
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1473
1521
  cdc?: boolean;
@@ -1484,25 +1532,25 @@ export interface ShardDOConfig {
1484
1532
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1485
1533
  scheduler?: (env: Record<string, unknown>) => unknown;
1486
1534
  /** \`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. */
1487
- storage?: (env: Record<string, unknown>, origin?: string) => unknown;${dt}${y.configFields}${T.configField}${Ne}${ct}${lt}${ut}${G.configField}
1535
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ht}${k.configFields}${I.configField}${Fe}${pt}${mt}${gt}${Y.configField}
1488
1536
  }
1489
- ${E("schedulerStub",pt,["cancel","runAfter","runAt"])}${E("storageStub",mt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${gt}${Tt}${wt}${y.stubs}${qe}
1490
- ${It}
1537
+ ${$("schedulerStub",bt,["cancel","runAfter","runAt"])}${$("storageStub",wt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${yt}${Lt}${St}${k.stubs}${je}
1538
+ ${qt}
1491
1539
 
1492
1540
  /**
1493
1541
  * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1494
1542
  * from the worker entry so wrangler binds it by name.
1495
1543
  */
1496
1544
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1497
- class extends ShardDOBase {${Et}
1498
- private migrated = false;${Lt}${Mt}
1499
- ${ae.override}
1500
- ${Nt}
1501
- ${et}${at}${Rt}${At}
1545
+ class extends ShardDOBase {${Nt}
1546
+ private migrated = false;${$t}${Mt}${Bt}
1547
+ ${de.override}
1548
+ ${Ut}
1549
+ ${at}${dt}${Dt}${Ct}
1502
1550
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1503
1551
  return LUNORA_LIFECYCLE_HOOKS[event];
1504
1552
  }
1505
- ${xt}${Ot}${se}${G.override}${Ct}
1553
+ ${Tt}${_t}${ce}${Y.override}${It}
1506
1554
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1507
1555
  // socket-terminated half of the same reactivity — and differs only in who
1508
1556
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1601,7 +1649,7 @@ ${c?` const requestScope = this.captureRequestScope();
1601
1649
  protected override studioFeatures(): StudioFeaturesResult {
1602
1650
  return LUNORA_STUDIO_FEATURES();
1603
1651
  }
1604
- ${j.evaluateOverride}${j.subscriptionOverride}${Ge}${Je}
1652
+ ${K.evaluateOverride}${K.subscriptionOverride}${Ye}${Ze}
1605
1653
  protected override advisories(): AdvisoryFinding[] {
1606
1654
  return LUNORA_ADVISORIES();
1607
1655
  }
@@ -1610,17 +1658,17 @@ ${j.evaluateOverride}${j.subscriptionOverride}${Ge}${Je}
1610
1658
  return LUNORA_ADVISOR_PROCEDURES();
1611
1659
  }
1612
1660
 
1613
- ${Sr}
1661
+ ${Tr}
1614
1662
 
1615
1663
  protected override ensureMigrated(): void {
1616
1664
  if (this.migrated) {
1617
1665
  return;
1618
1666
  }
1619
1667
 
1620
- runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${pe} });
1668
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${be} });
1621
1669
  this.migrated = true;
1622
1670
  }
1623
- ${J?`
1671
+ ${Z?`
1624
1672
  protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1625
1673
  // Migrations create the fts5 companions; without them every backfill
1626
1674
  // statement would raise "no such table" on a shard that has never
@@ -1629,7 +1677,7 @@ ${J?`
1629
1677
 
1630
1678
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1631
1679
  }
1632
- `:""}${ft}
1633
- ${Rr({lazyFunctions:c,actionOnlyFields:jt,agentsBuild:_e,agentsContextField:Ee,containersBuild:Se,containersContextField:Re,databaseOptions:yt,everyContextBuild:qt,everyContextField:Ft,facadeBlock:$t,globalDatabaseLine:St,notifyBuild:Ut,ormContextField:kt,paymentsBuild:Pe,paymentsContextField:Me,queuesBuild:me,queuesContextField:ge,topicsBuild:we,topicsContextField:ye,vectorsBuild:bt,vectorsContextField:vt,workflowsBuild:Ae,workflowsContextField:De,actionOnlyBuild:Wt})}
1680
+ `:""}${vt}
1681
+ ${_r({hasSensitiveArgs:V,lazyFunctions:c,actionOnlyFields:Gt,agentsBuild:Pe,agentsContextField:Ne,containersBuild:Oe,containersContextField:De,databaseOptions:Rt,everyContextBuild:Wt,everyContextField:Ht,facadeBlock:jt,globalDatabaseLine:Ot,notifyBuild:Vt,ormContextField:At,paymentsBuild:qe,paymentsContextField:Ue,queuesBuild:we,queuesContextField:ye,topicsBuild:Se,topicsContextField:Re,vectorsBuild:kt,vectorsContextField:xt,workflowsBuild:Ce,workflowsContextField:Ee,actionOnlyBuild:Qt})}
1634
1682
  };
1635
- `};export{_r as b,Xr as e};
1683
+ `};export{$r as b,on as e};