@lunora/codegen 1.0.0-alpha.33 → 1.0.0-alpha.330

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 (124) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.mts +4298 -2183
  3. package/dist/index.d.ts +4298 -2183
  4. package/dist/index.mjs +1 -35
  5. package/dist/packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs +1 -0
  6. package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs +1 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_TARGET-BbWiB-rs.mjs +1 -0
  10. package/dist/packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-B_I0kkvJ.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-DOIxn0Qb.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs +3 -0
  16. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  17. package/dist/packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs +1 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DdPW4JCi.mjs +31 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  20. package/dist/packem_shared/SHAPES_FILENAME-D7Ifi5Ce.mjs +1 -0
  21. package/dist/packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs +18 -0
  22. package/dist/packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs +1 -0
  23. package/dist/packem_shared/attribution-hVBriwzy.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-DFv-RYZU.mjs +3 -0
  25. package/dist/packem_shared/capabilitiesUsedBy-CF7sUwa8.mjs +1 -0
  26. package/dist/packem_shared/chain-ZlTHdRo2.mjs +1 -0
  27. package/dist/packem_shared/classify-procedure-call-Bw5sia-K.mjs +1 -0
  28. package/dist/packem_shared/context-property-calls-Co_G3ENU.mjs +1 -0
  29. package/dist/packem_shared/context-root-BTW5XwVq.mjs +1 -0
  30. package/dist/packem_shared/createCodegenProject-V51_yBw3.mjs +1 -0
  31. package/dist/packem_shared/database-calls-D-GwIhWO.mjs +1 -0
  32. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  33. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  34. package/dist/packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs +1 -0
  35. package/dist/packem_shared/discoverCrons-B2SdRjRO.mjs +1 -0
  36. package/dist/packem_shared/discoverFunctions-C9Ra5XXH.mjs +1 -0
  37. package/dist/packem_shared/discoverHttpRoutes-WBAqBcfK.mjs +1 -0
  38. package/dist/packem_shared/discoverHyperdriveCalls-DfCAjBgd.mjs +1 -0
  39. package/dist/packem_shared/discoverInserts-T5ojinqL.mjs +1 -0
  40. package/dist/packem_shared/discoverMaskProcedures-DKd9fVDa.mjs +1 -0
  41. package/dist/packem_shared/discoverMigrations-ClgjUkaG.mjs +1 -0
  42. package/dist/packem_shared/discoverNondeterministicCalls-UCUCyCox.mjs +1 -0
  43. package/dist/packem_shared/discoverQueries-u2XNpxsn.mjs +1 -0
  44. package/dist/packem_shared/discoverR2sqlCalls-jz5KouxF.mjs +1 -0
  45. package/dist/packem_shared/discoverRlsMetadata-D2G3YAoe.mjs +1 -0
  46. package/dist/packem_shared/discoverRlsProcedures-BD8aG1BU.mjs +1 -0
  47. package/dist/packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs +1 -0
  48. package/dist/packem_shared/discoverSchema-BtsX-CN9.mjs +1 -0
  49. package/dist/packem_shared/discoverStorageRulesMetadata-C2ceH0ZO.mjs +1 -0
  50. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  51. package/dist/packem_shared/emitAgents-CR2_X_ov.mjs +1 -0
  52. package/dist/packem_shared/emitApi-CDgIPAG2.mjs +147 -0
  53. package/dist/packem_shared/emitApp-DuJW6LKD.mjs +986 -0
  54. package/dist/packem_shared/emitCrons-BQW2lviZ.mjs +96 -0
  55. package/dist/packem_shared/emitDataModel-BskFt9Wv.mjs +114 -0
  56. package/dist/packem_shared/emitDrizzleSchema-DitcRZ1a.mjs +15 -0
  57. package/dist/packem_shared/emitFunctions-Cd0Tuw73.mjs +500 -0
  58. package/dist/packem_shared/emitServer-D1vA5_X1.mjs +1 -0
  59. package/dist/packem_shared/emitShard-DtfjUgjj.mjs +1 -0
  60. package/dist/packem_shared/exported-procedure-chains-CVzkVdq4.mjs +1 -0
  61. package/dist/packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs +1 -0
  62. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
  63. package/dist/packem_shared/handler-reference-vIeqkhV_.mjs +1 -0
  64. package/dist/packem_shared/index-BPUxZYM5.mjs +1 -0
  65. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  66. package/dist/packem_shared/isTestPath-B81lOULB.mjs +1 -0
  67. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  68. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  69. package/dist/packem_shared/loadProjectConfig-NO0dVJSl.mjs +1 -0
  70. package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
  71. package/dist/packem_shared/modules-CjOcuQnK.mjs +1 -0
  72. package/dist/packem_shared/parse-validator-IDBKIT7M.mjs +1 -0
  73. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  74. package/dist/packem_shared/project-config-file-BV7RR-l6.mjs +1 -0
  75. package/dist/packem_shared/qualifiers-DEdXn5wP.mjs +1 -0
  76. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  77. package/dist/packem_shared/readServiceBindings-DvqIThzd.mjs +1 -0
  78. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  79. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  80. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  81. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  82. package/dist/packem_shared/server-DAvi_bv_.mjs +368 -0
  83. package/dist/packem_shared/shard-CsfiXxV0.mjs +1635 -0
  84. package/dist/packem_shared/shard-runtime-BpoCV-aM.mjs +331 -0
  85. package/dist/packem_shared/shared-DnCokNcE.mjs +13 -0
  86. package/dist/packem_shared/unwrap-handler-return-CeaOifqX.mjs +1 -0
  87. package/dist/sdk/index.d.mts +288 -0
  88. package/dist/sdk/index.d.ts +288 -0
  89. package/dist/sdk/index.mjs +372 -0
  90. package/package.json +21 -8
  91. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  92. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  93. package/dist/packem_shared/FLAGS_FILENAME-BjpS5w08.mjs +0 -139
  94. package/dist/packem_shared/GENERATED_HEADER-CLwPlCQe.mjs +0 -3
  95. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  96. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  97. package/dist/packem_shared/OPENRPC_VERSION-4YIeMkOI.mjs +0 -60
  98. package/dist/packem_shared/QUEUES_FILENAME-BF0iUmx7.mjs +0 -119
  99. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-C9FkE1cW.mjs +0 -3521
  100. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  101. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  102. package/dist/packem_shared/WORKFLOWS_FILENAME-CCC_42o3.mjs +0 -124
  103. package/dist/packem_shared/buildOpenApiDocument-bp1pYSV6.mjs +0 -183
  104. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  105. package/dist/packem_shared/discoverAuthApiCalls-URDoTADN.mjs +0 -62
  106. package/dist/packem_shared/discoverCrons-DdZOeroL.mjs +0 -257
  107. package/dist/packem_shared/discoverFunctions-BJdF7lRs.mjs +0 -514
  108. package/dist/packem_shared/discoverHttpRoutes-CcwP-Rkr.mjs +0 -131
  109. package/dist/packem_shared/discoverInserts-BpFhM32L.mjs +0 -61
  110. package/dist/packem_shared/discoverMaskProcedures-DT-v8wvj.mjs +0 -273
  111. package/dist/packem_shared/discoverMigrations-cG1idBVM.mjs +0 -97
  112. package/dist/packem_shared/discoverNondeterministicCalls-CEOjmfk4.mjs +0 -122
  113. package/dist/packem_shared/discoverQueries-DeVBQVAG.mjs +0 -62
  114. package/dist/packem_shared/discoverR2sqlCalls-CWCAU-xJ.mjs +0 -80
  115. package/dist/packem_shared/discoverRlsMetadata-BL0oukaK.mjs +0 -280
  116. package/dist/packem_shared/discoverSchema-CeXJWVKV.mjs +0 -874
  117. package/dist/packem_shared/discoverStorageRulesMetadata-CFHByjIl.mjs +0 -97
  118. package/dist/packem_shared/emit-CBwEvCXQ.mjs +0 -3451
  119. package/dist/packem_shared/emitApp-nQ2oC-8G.mjs +0 -668
  120. package/dist/packem_shared/formatAdvisories-DLIqHq5l.mjs +0 -114
  121. package/dist/packem_shared/parse-validator-D6zI2i85.mjs +0 -134
  122. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  123. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  124. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,1635 @@
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=` /**
2
+ * The bare writer every admin/maintenance entry point writes through.
3
+ *
4
+ * Admin and maintenance writes go through the SAME reactive-cache hooks as a
5
+ * user mutation. Without this, a studio row edit, a TTL sweep, an admin
6
+ * import, a CDC apply or a data-migration backfill writes without
7
+ * invalidating, and the next query answers from the pre-write snapshot.
8
+ *
9
+ * \`headroom\` meters the transaction. An admin \`/rpc\` caller passes nothing
10
+ * and falls back to \`this.transactionHeadroom()\`, which for an admin RPC is
11
+ * \`undefined\` — \`handleAdminRpc\` answers before \`beginDispatch\`, so no
12
+ * per-dispatch meter is in flight and a bulk loop is bounded by its per-call
13
+ * row cap alone. The TTL sweep (an alarm work item, no dispatch) passes its
14
+ * own by-value tracker explicitly instead.
15
+ */
16
+ private adminWriter(headroom?: TransactionHeadroomTracker): DatabaseWriterLike {
17
+ const env = (this.env ?? {}) as Record<string, unknown>;
18
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
19
+
20
+ return createShardCtxDb({
21
+ ...this.ctxDbTuning(),
22
+ broadcast: (delta) => {
23
+ this.recordChangedTable(delta.table, delta.indexKeys);
24
+ },
25
+ cdc: config.cdc ?? false,
26
+ ...(headroom === undefined ? {} : { headroom }),
27
+ // Live predicate, same as the user-facing ctx — see \`databaseOptions\`.
28
+ inTransaction: () => this.isInTransaction(),
29
+ scheduler,
30
+ schema: schema as unknown as SchemaLike,
31
+ sql: this.sql as SqlExec,
32
+ });
33
+ }`,g=(n="")=>` const writer = this.adminWriter(${n});`,Sr=`${kr}
34
+
35
+ protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
+ this.ensureMigrated();
37
+
38
+ // Falls back to the framework's reserved re-projection backfill
39
+ // (\`__lunora_reproject__<table>\`), which rewrites rows whose
40
+ // v.bigint()/v.bytes() columns are still stored in the pre-projection
41
+ // tagged form. Built here rather than at module scope because it
42
+ // needs this shard's \`sql\` handle to tell a legacy row from a
43
+ // current one.
44
+ const migration = LUNORA_MIGRATIONS[args.id] ?? buildReprojectionMigration(args.id, schema as unknown as SchemaLike, this.sql as SqlExec);
45
+
46
+ if (!migration) {
47
+ throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
48
+ }
49
+
50
+ ${g()}
51
+
52
+ return runDataMigration({
53
+ ...(args.batchSize === undefined ? {} : { batchSize: args.batchSize }),
54
+ ...(args.direction === undefined ? {} : { direction: args.direction }),
55
+ ...(args.dryRun === undefined ? {} : { dryRun: args.dryRun }),
56
+ ...(args.maxBatches === undefined ? {} : { maxBatches: args.maxBatches }),
57
+ migration: migration as unknown as DataMigrationLike,
58
+ // Flush after each batch so live migrationStatus subscribers see
59
+ // progress mid-run (the base method records the reserved state
60
+ // table the raw-SQL progress write is invisible to the tracker).
61
+ onBatch: () => this.flushMigrationProgress(),
62
+ sql: this.sql as SqlExec,
63
+ writer,
64
+ });
65
+ }
66
+
67
+ protected override async runShardWrite(args: RunShardWriteArgs, headroom?: TransactionHeadroomTracker): Promise<RunShardWriteResult> {
68
+ const definition = (schema as unknown as SchemaLike).tables[args.table];
69
+
70
+ if (!definition) {
71
+ throw new LunoraError("UNKNOWN_TABLE", \`unknown table: \${args.table}\`, { status: 404 });
72
+ }
73
+
74
+ // \`.global()\` tables live in D1, not this DO's SQLite — editing them
75
+ // here would corrupt nothing but would fail confusingly, so reject up
76
+ // front with a clear code the studio can surface.
77
+ if (definition.shardMode?.kind === "global") {
78
+ throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", \`table "\${args.table}" is global; edit it through D1, not the shard\`, { status: 400 });
79
+ }
80
+
81
+ this.ensureMigrated();
82
+
83
+ ${g("headroom ?? this.transactionHeadroom()")}
84
+
85
+ if (args.op === "insert") {
86
+ const id = await writer.insert(args.table, args.doc ?? {});
87
+
88
+ return { id, op: "insert" };
89
+ }
90
+
91
+ // Every by-id op PINS \`args.table\`. Unpinned, \`locateRowById\` probes
92
+ // every non-global table for the id, so a request naming table A with an
93
+ // id belonging to table B locates and mutates B's row — the by-id IDOR
94
+ // the per-table \`ctx.db.<table>\` facade pins against. Pinning also stops
95
+ // an absent row falling through to the \`.global()\` D1 twin, though that
96
+ // branch is already unreachable here: \`adminWriter\` is built without a
97
+ // \`globalDb\`, so a miss throws \`NOT_FOUND\` either way.
98
+ // \`hard\` is set only by the BULK delete arm, which needs the row gone
99
+ // from the physical table for its next batch's scan to make progress.
100
+ // A single-row \`writeRow\` delete never carries it, so it keeps the
101
+ // table's declared \`.softDelete()\` behaviour.
102
+ if (args.op === "delete") {
103
+ await writer.delete(args.id ?? "", args.table, { hard: args.hard === true });
104
+
105
+ return { id: args.id ?? null, op: "delete" };
106
+ }
107
+
108
+ if (args.op === "replace") {
109
+ await writer.replace(args.id ?? "", args.doc ?? {}, args.table);
110
+
111
+ return { id: args.id ?? null, op: "replace" };
112
+ }
113
+
114
+ await writer.patch(args.id ?? "", args.doc ?? {}, args.table);
115
+
116
+ return { id: args.id ?? null, op: "patch" };
117
+ }
118
+
119
+ // The base \`ShardDO\` cannot build a schema-aware writer, so its
120
+ // \`runShardExport\`/\`runShardImport\` return \`[]\` and \`{inserted:{}}\`.
121
+ // Those are success-shaped: an empty export is what a correct export of
122
+ // an empty shard looks like, so a backup of a populated sharded schema
123
+ // reported success and wrote nothing, and an import reported success and
124
+ // dropped every row. Overriding both here is what makes the two admin
125
+ // RPCs real for a \`.shardBy()\` table.
126
+ //
127
+ // NOTE: the admin export RPC is not paginated — \`parseExportShardArgs\`
128
+ // takes \`tables\`/\`batchSize\` but no cursor, and the coordinator issues
129
+ // one call per shard — so the rows are collected into a single response.
130
+ // \`batchSize\` bounds the SQLite scan page, not the reply. A shard holding
131
+ // more rows than fit in the DO's memory budget will therefore fail the
132
+ // export rather than stream it. That is a loud failure where the bug this
133
+ // replaces was a silent empty one, but a cursor on the RPC is what makes
134
+ // this a complete backup path for large shards.
135
+ protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
136
+ this.ensureMigrated();
137
+
138
+ ${g()}
139
+
140
+ const rows: ExportRow[] = [];
141
+
142
+ // \`exportShardRows\` walks in keyset batches so a large table does not
143
+ // materialize at once inside the generator; the admin RPC's response
144
+ // is a single array, so it is collected here rather than streamed.
145
+ for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, args)) {
146
+ rows.push(row);
147
+ }
148
+
149
+ return rows;
150
+ }
151
+
152
+ protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
153
+ this.ensureMigrated();
154
+
155
+ ${g()}
156
+
157
+ // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
158
+ // database's \`_id\`s carry across verbatim and every foreign key
159
+ // referencing them stays valid without a second remapping pass.
160
+ return importShardRows(writer, schema as unknown as SchemaLike, args);
161
+ }
162
+
163
+ protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
164
+ this.ensureMigrated();
165
+
166
+ ${g()}
167
+
168
+ // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
169
+ // but the shard writer from \`createShardCtxDb\` always defines it.
170
+ if (!writer.rankBefore) {
171
+ throw new LunoraError("NOT_IMPLEMENTED", "rankBefore is unavailable on the shard writer", { status: 500 });
172
+ }
173
+
174
+ return writer.rankBefore(args.table, args.index, {
175
+ partitionKey: args.partitionKey,
176
+ rowId: args.rowId,
177
+ sortValues: args.sortValues,
178
+ });
179
+ }
180
+
181
+ protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
182
+ this.ensureMigrated();
183
+
184
+ ${g()}
185
+
186
+ // \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
187
+ // but the shard writer from \`createShardCtxDb\` always defines it — it
188
+ // derives the edge set from this app's schema.
189
+ if (!writer.related) {
190
+ throw new LunoraError("NOT_IMPLEMENTED", "findRelated is unavailable on the shard writer", { status: 500 });
191
+ }
192
+
193
+ return writer.related(
194
+ { id: args.id, table: args.table },
195
+ args,
196
+ );
197
+ }
198
+
199
+ protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
200
+ this.ensureMigrated();
201
+
202
+ ${g()}
203
+
204
+ // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
205
+ // but the shard writer from \`createShardCtxDb\` always defines it. The sort
206
+ // directions live in the schema's rankIndex, so the shard reads them itself;
207
+ // \`args.directions\` is only the coordinator's comparator hint and isn't forwarded.
208
+ if (!writer.rankPageRows) {
209
+ throw new LunoraError("NOT_IMPLEMENTED", "rankPage is unavailable on the shard writer", { status: 500 });
210
+ }
211
+
212
+ return writer.rankPageRows(args.table, args.index, {
213
+ ...(args.after === undefined ? {} : { after: args.after }),
214
+ ...(args.cursor === undefined ? {} : { cursor: args.cursor }),
215
+ ...(args.partitionKey === undefined ? {} : { partitionKey: args.partitionKey }),
216
+ ...(args.take === undefined ? {} : { take: args.take }),
217
+ });
218
+ }
219
+
220
+ protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
221
+ this.ensureMigrated();
222
+
223
+ ${g()}
224
+
225
+ await applyCdcChanges(writer, args.changes);
226
+
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?`
231
+ // ActionCtx-only helpers (external, non-deterministic I/O): constructed
232
+ // and attached only for an \`action\` so query/mutation ctx never carry them.
233
+ if (isAction) {
234
+ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(p=>` ctx.${p} = ${p};`).join(`
235
+ `)}
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 {
238
+ const env = (this.env ?? {}) as Record<string, unknown>;
239
+ // The caller context this ctx runs under, resolved ONCE on one
240
+ // discriminant. When the caller threads an explicit identity
241
+ // (subscription seed / refresh / stream pull / shape resolve — all
242
+ // deferred or interleaved), it is used by value and the shared
243
+ // per-request fields are never read, because a concurrent RPC owns
244
+ // them: a refresh in particular runs inside the writing dispatch's
245
+ // \`flushChangedTables\`, BEFORE its \`endDispatch\`, so \`getCurrentIp()\`
246
+ // there is the MUTATING caller's address. Otherwise (the synchronous
247
+ // RPC dispatch path) it falls back to those fields as before.
248
+ //
249
+ // One expression, not one per field: three parallel ternaries on the
250
+ // same discriminant is how \`ip\` came to be the only one still reading
251
+ // the shared field.
252
+ const caller: SubscriptionIdentity = options.identity ?? (() => {
253
+ const identity = this.getCurrentIdentity();
254
+ const ip = this.getCurrentIp();
255
+ const userId = this.getCurrentUserId();
256
+
257
+ return {
258
+ ...(identity === undefined ? {} : { identity }),
259
+ ...(ip === undefined ? {} : { ip }),
260
+ ...(userId === undefined ? {} : { userId }),
261
+ };
262
+ })();
263
+ const { identity, ip, userId } = caller;
264
+ ${w}${f}${r}${$}${P}${N}${t}
265
+ // Which dispatch this ctx belongs to. Drives the two deferral facades
266
+ // below and the \`ctx.run*\` caller guard; a ctx built for an
267
+ // admin/lifecycle path has no registered function, and so no kind. An
268
+ // untracked \`ctx.runQuery\` overrides it with \`"query"\`: the sub-query
269
+ // keeps the caller's \`functionPath\` for attribution but runs as a query.
270
+ const contextKind = options.kind ?? LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind;
271
+ // \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
272
+ // reaches through, and pending jobs live in the SchedulerDO — nothing the
273
+ // CDC changelog records — so reading them must forfeit a delta resume.
274
+ // The scheduler's own \`runAfter\`/\`runAt\`/\`cancel\` are writes and stay unstamped.
275
+ const schedulerBase = markUnvouchableReads((config.scheduler?.(env) ?? schedulerStub) as SchedulerLike, options.onRead, ["get", "list"]);
276
+ // \`ctx.scheduler.runAfter(0, ...)\` is documented as the deterministic
277
+ // equivalent of an \`afterCommit\` hook, and the SchedulerDO persists the
278
+ // job the moment it is called — so inside a mutation the call is BUFFERED
279
+ // and replayed after the transaction commits (a rollback drops it).
280
+ // Composed mutations get their own facade when the caller is outside
281
+ // a transaction. True nested calls share the enclosing facade and open
282
+ // a nested window. The action's own schedules stay immediate.
283
+ //
284
+ // Every kind but \`query\` is wrapped, because \`runMutationTransaction\`
285
+ // is installed on \`ctx.runMutation\` for every kind but \`query\`: a
286
+ // STREAM ctx, and an admin/lifecycle ctx with no registered kind at all,
287
+ // both get the BEGIN/COMMIT span for a mutation they compose, and used
288
+ // to get it with the deferral missing — so that mutation's job reached
289
+ // the SchedulerDO while its transaction was still open, and survived the
290
+ // rollback. A query cannot host a mutation handler (\`dispatchRun\`
291
+ // refuses it) and its ctx is built on the hot subscription path, so it
292
+ // stays unwrapped.
293
+ //
294
+ // Wrapped OUTSIDE the read-stamping facade so \`get\`/\`list\` stay stamped.
295
+ //
296
+ // \`this.scheduleOutbox()\` is what keeps the buffer honest. Everything
297
+ // between the COMMIT and the scheduler's acknowledgement is outside the
298
+ // transaction, so a failure there leaves writes that are durable and a
299
+ // job that exists nowhere — and the mutation's replay-dedup row committed
300
+ // inside the span, so the client's retry is answered from cache and told
301
+ // it succeeded. The outbox takes custody of each buffered call inside the
302
+ // transaction and releases it once the scheduler has the job; what
303
+ // survives is retried by \`pollScheduleOutbox\` on the shared poll alarm.
304
+ const scheduler = contextKind === "query" ? schedulerBase : withDeferredSchedules(schedulerBase, this.scheduleOutbox());
305
+ // Build the storage adapter once and share it between \`ctx.storage\`
306
+ // and \`ctx.db.system._storage\` so both read the same R2 binding. The
307
+ // \`storageStub\` fallback satisfies SystemReaderStorageLike structurally
308
+ // (its \`list\`/\`getMetadata\` throw the "no storage configured" error).
309
+ //
310
+ // Wrapped BEFORE the split so both consumers share one stamping facade.
311
+ // Only the methods that actually reach R2 are stamped: \`getUrl\` and
312
+ // \`getSignedUrl\` build a URL from the configured base (and an HMAC) and
313
+ // read nothing, and they are what handlers overwhelmingly call — stamping
314
+ // them would forfeit resumes for a dependency that cannot move the result.
315
+ // \`bucket\` IS stamped: it hands back a sub-facade this wrapper does not
316
+ // reach, so the selection is the last point at which the read can be seen.
317
+ //
318
+ // The request origin is the storage base fallback for mutations and
319
+ // actions on the synchronous dispatch only. A deferred caller
320
+ // (\`options.identity\` set) runs outside the dispatch that owns the
321
+ // field, the same hazard \`getCurrentIp\` has. A query never gets it: a
322
+ // live query re-runs with no request behind it, and the reactive
323
+ // cache does not key on the host, so a query that signs URLs needs a
324
+ // declared \`publicBaseUrl\` either way.
325
+ const requestOrigin = contextKind !== "query" && options.identity === undefined ? this.getCurrentOrigin() : undefined;
326
+ const makeStorage = (origin?: string): SystemReaderStorageLike =>
327
+ markUnvouchableReads(asBucketStorage(config.storage?.(env, origin) ?? storageStub) as SystemReaderStorageLike, options.onRead, [
328
+ "bucket",
329
+ "download",
330
+ "getMetadata",
331
+ "list",
332
+ ]);
333
+ const storage = makeStorage(requestOrigin);
334
+ // \`ctx.storage.deleteAfterCommit(key)\`, on every dispatch that can host
335
+ // a MUTATION handler — which is not only a mutation dispatch. An
336
+ // action's composed mutation gets a child ctx with its own deferred
337
+ // delete queue, while mutations reuse the admitted ctx. Queries stay
338
+ // unwrapped: they cannot host one, and their ctx is built on the hot
339
+ // subscription path.
340
+ //
341
+ // Every dispatch wrapped here also flushes (see \`handleRpc\` and
342
+ // \`runReactor\`) — a queue nothing drains leaks silently, which is worse
343
+ // than not having the method at all.
344
+ //
345
+ // Wrapped OUTSIDE the read-stamping facade so \`bucket(name)\` still
346
+ // resolves through it and stays stamped, and applied only to
347
+ // \`ctx.storage\` so \`ctx.db.system._storage\` (which shares the adapter
348
+ // above) is untouched.
349
+ const contextStorage = contextKind === "mutation" || contextKind === "action" ? withDeferredDeletes(storage) : storage;
350
+ // \`ctx.log\`: the DO base builds the attributed logger (structured
351
+ // fields + \`.with(...)\` child + trace correlation) and routes each call
352
+ // to the optional \`observability\` sink. It also buffers the line (studio
353
+ // Logs panel) and emits a structured console event the dev-server formats.
354
+ //
355
+ // Resolved BEFORE \`ctx.db\` below, because the database is wrapped in
356
+ // auto-instrumentation that needs the sink, the trace anchor, and the
357
+ // dispatch's wide-event handle.
358
+ const observability = config.observability?.(env);
359
+ const logFunctionPath = options.functionPath ?? "";
360
+ const log = this.makeLogger(logFunctionPath, observability);
361
+ const traceAnchor = this.resolveDispatchAnchor(Boolean(options.identity));
362
+
363
+ // \`ctx.span\`: the handle onto the DISPATCH's own span — the wide-event
364
+ // surface. Attributes attached here accumulate for the whole request
365
+ // and are folded into the one span it already emits, instead of
366
+ // becoming N separate log lines. Shares \`traceAnchor\` with \`ctx.trace\`
367
+ // so both write to the same trace.
368
+ const span = this.makeDispatchSpan(traceAnchor, observability);
369
+
370
+ ${b} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
371
+ // adds aggregate counters (call count, total time, per-operation
372
+ // breakdown) to the wide event rather than a span per call, so a
373
+ // handler making hundreds of queries stays readable. See
374
+ // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
375
+ // Schema triggers close over this DB's scheduler, so a composed
376
+ // mutation must rebuild its DB and table/ORM views with its own queue.
377
+ const makeDatabaseContext = (scheduler: SchedulerLike) => {
378
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
379
+ ${l} return ${F};
380
+ };
381
+ const databaseContext = makeDatabaseContext(scheduler);
382
+ const db = databaseContext.db;
383
+ ${R}
384
+
385
+ // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
386
+ // The trace anchor is threaded explicitly for the same reason \`identity\`
387
+ // is — a deferred caller (a subscription re-run) must not inherit the
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}
392
+ // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
393
+ // captured ONCE so the whole handler body sees a single stable value.
394
+ // A \`query\` handler is re-run by every live subscription that reads it,
395
+ // so \`Date.now()\` there flickers between re-evaluations. A \`mutation\`
396
+ // handler does not replay under ordinary dispatch (an OCC conflict throws
397
+ // to the caller rather than retrying internally), but one called from a
398
+ // workflow step or queue consumer runs again when that step replays. Both
399
+ // read time through \`ctx.now\` — the \`nondeterministic_query_mutation\`
400
+ // advisor flags \`Date.now()\`. Actions may still use ambient \`Date.now()\`.
401
+ const now = Date.now();
402
+
403
+ const ctx: Record<string, unknown> = {
404
+ auth: {
405
+ getIdentity: async () => identity ?? null,
406
+ userId: userId ?? null,
407
+ },
408
+ db,
409
+ // \`ctx.newId()\`: a replay of the same top-level mutation gets the same ids. A nested or
410
+ // subscription-driven build (\`options.identity\`) is not a replay.
411
+ // A replay key only means something inside the caller's dedup namespace; without one the call is not
412
+ // deduplicated, so its ids stay random.
413
+ newId: createStableIdFactory(
414
+ options.identity === undefined && this.idempotencyNamespace() !== undefined ? this.getCurrentMutationId() : undefined,
415
+ JSON.stringify([this.currentShardKey(), options.functionPath ?? "", this.idempotencyNamespace() ?? "", userId ?? ""]),
416
+ ),
417
+ // Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
418
+ // \`traceparent\` propagation, so time spent in a downstream service
419
+ // is visible and its spans join this trace. Degrades to the bare
420
+ // global when no sink is configured.
421
+ fetch: this.makeFetch(logFunctionPath, traceAnchor, observability),
422
+ // A GETTER, not a plain field, so the reactive cache can tell a
423
+ // handler that reads the caller's address from the majority that
424
+ // never do. \`ctx.ip\` is per-request state the memo must be keyed
425
+ // by — otherwise two anonymous callers share one entry and the
426
+ // second is served the first's address — but keying every entry
427
+ // by address would shard the cache per client for every query.
428
+ // Reading it here marks the dispatch's scope; \`runCachedQuery\`
429
+ // folds the address into the key for this function from then on.
430
+ get ip() {
431
+ options.scope?.markIpRead();
432
+
433
+ return ip;
434
+ },
435
+ log,
436
+ metrics,
437
+ now,
438
+ // The same request origin the storage fallback above uses, handed
439
+ // to the handler so code that signs its own URLs (a copy-in
440
+ // \`createStorage\`) can fall back to it too. \`undefined\` for a
441
+ // query and for a deferred dispatch, for the reasons given there.
442
+ origin: requestOrigin,${U}
443
+ scheduler,
444
+ span,
445
+ storage: contextStorage,
446
+ trace,${M}${v}${I}${o}${q}${k}${i}${a}
447
+ };
448
+ ${x?` const isAction = contextKind === "action";
449
+ `:""}${u}
450
+ ${c?` const captureScope = (): (() => void) => {
451
+ const requestScope = this.captureRequestScope();
452
+ return () => this.restoreRequestScope(requestScope);
453
+ };
454
+
455
+ `:""} 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
+ // The composed mutation runs under the SAME wrapper the top-level RPC
458
+ // uses, so "do the transactional work in a mutation and call it from the
459
+ // action" — the recipe the docs give for atomicity — actually is atomic.
460
+ target.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => {
461
+ // An action can start sibling mutations concurrently. Each owns its
462
+ // context and deferral queues; only calls from an admitted mutation
463
+ // inherit that mutation's transaction.
464
+ const mutationCtx: Record<string, unknown> = this.mutationContexts.has(target)
465
+ ? target
466
+ : (() => {
467
+ const mutationScheduler = withDeferredSchedules(schedulerBase, this.scheduleOutbox());
468
+ const mutationDatabase = makeDatabaseContext(mutationScheduler);
469
+
470
+ return Object.defineProperties({}, {
471
+ ...Object.getOwnPropertyDescriptors(target),
472
+ db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${O}
473
+ scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
474
+ storage: { configurable: true, enumerable: true, value: withDeferredDeletes(storage), writable: true },
475
+ });
476
+ })();
477
+
478
+ if (mutationCtx !== target) {
479
+ installRun(mutationCtx, kind);
480
+ }
481
+
482
+ return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${c?", captureScope":""});
483
+ };
484
+ // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
485
+ // its OWN query context, built without the subscription's read-footprint
486
+ // hooks — so its reads never enter this subscription's footprint and a
487
+ // write to the tables it touched does not re-run us. Everything else is
488
+ // inherited: \`functionPath\` (log/metric attribution), \`headroom\` (the
489
+ // sub-query must not escape this dispatch's resource ceiling),
490
+ // \`scope\` (the reactive-cache capture — an untracked sub-query's reads
491
+ // must still be deps of the entry the OUTER query is memoized as, or
492
+ // the memo goes stale), and — load-bearing — the resolved \`caller\` BY VALUE
493
+ // (identity, userId AND ip). Omitting it would let \`buildCtx\` fall back
494
+ // to the shared per-request fields, which a concurrent RPC may have
495
+ // re-set, and an RLS-scoped sub-query would then read as the wrong user
496
+ // 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(
499
+ "query",
500
+ reference.__lunoraRef,
501
+ fnArgs,
502
+ runOptions?.untracked === true
503
+ ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope })
504
+ : queryContext(),
505
+ kind,${c?`
506
+ undefined,
507
+ captureScope,`:""}
508
+ );
509
+ };
510
+
511
+ // A query composed from a mutation or action runs on a QUERY view of
512
+ // this ctx, so it behaves exactly as it does when called directly or
513
+ // live: same \`db\`, read hooks, trace and \`now\`, but every field that
514
+ // depends on the dispatch kind or the request origin is re-derived for a
515
+ // query — no \`ctx.origin\`, storage with no origin fallback (and no
516
+ // \`deleteAfterCommit\`), the unwrapped scheduler, no ActionCtx-only
517
+ // helpers, and a \`run*\` guard that refuses a mutation or action. A new
518
+ // kind- or origin-dependent ctx field must be overridden here too.
519
+ // Copied by descriptor so the \`ip\` getter is carried over, not read.
520
+ // Built on the first composed call only; a query ctx is its own view.
521
+ let queryView: Record<string, unknown> | undefined;
522
+ const queryContext = (): Record<string, unknown> => {
523
+ if (contextKind === "query") {
524
+ return ctx;
525
+ }
526
+
527
+ if (queryView === undefined) {
528
+ const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
529
+ ${e.map(p=>` delete descriptors.${p};
530
+ `).join("")} // Writable and configurable, like the plain fields they replace.
531
+ const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
532
+
533
+ queryView = Object.defineProperties({}, {
534
+ ...descriptors,
535
+ origin: field(undefined),
536
+ scheduler: field(schedulerBase),
537
+ storage: field(makeStorage()),
538
+ }) as Record<string, unknown>;
539
+ installRun(queryView, "query");
540
+ }
541
+
542
+ return queryView;
543
+ };
544
+
545
+ installRun(ctx, contextKind);
546
+
547
+ return ctx;
548
+ }`},le=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
549
+ // referencing call fails loudly with a clear error instead of overflowing the
550
+ // stack. Tracked across the awaited handler chain (one DO invocation is
551
+ // single-threaded), so the counter reflects true nesting depth.
552
+ const MAX_RUN_DEPTH = 32;
553
+ let runDepth = 0;
554
+
555
+ const dispatchRun = async (
556
+ expected: FunctionKind,
557
+ functionPath: string,
558
+ args: Record<string, unknown>,
559
+ ctx: unknown,
560
+ // The kind of the context making the call, and — for a mutation target — the
561
+ // transaction wrapper to run it under. Both are supplied by \`buildCtx\`, which
562
+ // is the only place that knows which dispatch this \`ctx\` belongs to. Widened
563
+ // past \`FunctionKind\` because the registry also carries \`"stream"\`, and
564
+ // \`undefined\` for a ctx built outside a registered function (admin, migration).
565
+ callerKind?: "stream" | FunctionKind,
566
+ runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
567
+ ): Promise<unknown> => {
568
+ // A query is read-only. The ctx object installs \`run*\` on every kind (one
569
+ // shape, built once), so the TYPE is all that stops a query from writing —
570
+ // and a cast walks straight past it, inside a subscription re-run that can
571
+ // execute many times per write. Checked on the CALLER, before the registry
572
+ // lookup, so \`ctx.runMutation\` from a query fails identically whatever it
573
+ // aimed at.
574
+ if (callerKind === "query" && expected !== "query") {
575
+ throw new LunoraError(
576
+ "RUN_KIND_FORBIDDEN",
577
+ \`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: a query may only compose other queries (tried to run "\${functionPath}")\`,
578
+ );
579
+ }
580
+
581
+ const registered = LUNORA_FUNCTIONS[functionPath];
582
+
583
+ if (!registered) {
584
+ throw new Error(\`unknown function: \${functionPath}\`);
585
+ }
586
+
587
+ if (registered.kind !== expected) {
588
+ throw new Error(\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: "\${functionPath}" is registered as a \${registered.kind}, not a \${expected}\`);
589
+ }
590
+
591
+ if (runDepth >= MAX_RUN_DEPTH) {
592
+ throw new LunoraError("RUN_DEPTH_EXCEEDED", \`ctx.run*: composition depth limit (\${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation\`);
593
+ }
594
+
595
+ runDepth += 1;
596
+
597
+ try {
598
+ // A mutation composed from an action (or an http action) is the shape the
599
+ // docs prescribe for atomicity — "do the transactional reads and writes in
600
+ // a mutation and call it from the action". It only holds if the composed
601
+ // dispatch gets the same BEGIN/COMMIT span and single-writer gate the
602
+ // top-level mutation path gets; without it every write autocommits and a
603
+ // mid-handler throw leaves the earlier ones durable. A \`runMutation\` from
604
+ // inside a mutation rides the enclosing span instead of opening a second
605
+ // one (see \`runMutationTransaction\`).
606
+ if (runTransactional) {
607
+ return await runTransactional(async () => registered.handler(ctx, args));
608
+ }
609
+
610
+ return await registered.handler(ctx, args);
611
+ } finally {
612
+ runDepth -= 1;
613
+ }
614
+ };`,xr=n=>n?le.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
615
+ captureScope?: () => () => void,`).replace(` try {
616
+ // A mutation composed from an action`,` try {
617
+ let loaded = getLoadedFunction(functionPath);
618
+
619
+ if (loaded === undefined) {
620
+ const restoreScope = captureScope?.();
621
+
622
+ try {
623
+ loaded = await loadFunction(functionPath);
624
+ } finally {
625
+ restoreScope?.();
626
+ }
627
+ }
628
+
629
+ if (!loaded) {
630
+ throw new Error(\`unknown function: \${functionPath}\`);
631
+ }
632
+
633
+ const loadedFunction = loaded;
634
+
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> {
636
+ __PREPARE_FUNCTION__ const registered = LUNORA_FUNCTIONS[functionPath];
637
+
638
+ // Internal functions are reachable server-side only: via \`ctx.run*\`
639
+ // composition, or a trusted system dispatch (scheduler/cron, marked by
640
+ // \`isSystemDispatch()\`). A client RPC never carries that flag, so its
641
+ // internals stay not-found and never leak across the external boundary.
642
+ if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) {
643
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
644
+ }
645
+
646
+ this.ensureMigrated();
647
+
648
+ // \`headroom\`, when the caller supplied one, is threaded straight
649
+ // through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
650
+ // fallback (the racy shared-field read) entirely for THIS dispatch.
651
+ // The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
652
+ // \`handleRunAs\` don't mint their own and omit it, so they keep the
653
+ // prior fallback behavior unchanged.
654
+ //
655
+ // \`scope\` is the reactive cache's per-dispatch read capture, threaded
656
+ // the same way and for the same reason: the ctx-db read hooks resolve
657
+ // their tracker at READ time, so binding them to the scope THIS
658
+ // dispatch was handed is what keeps a concurrent query's reads out of
659
+ // our dep set — and ours out of theirs. A dispatch with no scope (a
660
+ // mutation, an action, a cache-less shard) builds unbound hooks that
661
+ // stamp no deps.
662
+ const ctx = this.buildCtx({ bookmarks, functionPath, headroom, scope, trusted: registered.lifecycle === "init" });
663
+
664
+ // A mutation's writes must commit all-or-nothing, so its dispatch runs
665
+ // under \`runMutationTransaction\` — the ONE place that opens the span,
666
+ // settles the deferred schedules and flushes the deferred deletes. The
667
+ // same helper backs \`ctx.runMutation\` and \`runReactor\`, because a
668
+ // mutation reached by composition is promised exactly these guarantees
669
+ // and used to get none of them.
670
+ //
671
+ // The replay bookkeeping (idempotency dedup row + custom-mutator
672
+ // watermark advance) commits INSIDE the span via
673
+ // \`commitMutationBookkeeping\`, so the writes, the dedup row, and the
674
+ // watermark are atomic — a crash can't leave the writes durable without
675
+ // the replay guard. It is deliberately NOT in the shared helper: it is
676
+ // per-REQUEST bookkeeping, and a composed sub-mutation has no request of
677
+ // its own to record.
678
+ if (registered.kind === "mutation") {
679
+ return await this.runMutationTransaction(ctx, async () => {
680
+ const value = await registered.handler(ctx, args);
681
+
682
+ this.commitMutationBookkeeping(value);
683
+
684
+ return value;
685
+ });
686
+ }
687
+
688
+ const result = await registered.handler(ctx, args);
689
+
690
+ // Composed mutations settle their own delete queues. An action can
691
+ // also queue deletes outside those mutations; drain its own queue here.
692
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
693
+
694
+ return result;
695
+ }
696
+
697
+ private readonly mutationContexts = new WeakSet<object>();
698
+
699
+ /**
700
+ * Run one mutation handler with the atomicity every caller of a mutation is
701
+ * promised: a BEGIN/COMMIT span (with the single-writer gate
702
+ * \`ShardRunner.runInTransaction\` composes in front of it), scheduled jobs
703
+ * held until that span commits, and the deferred object deletes flushed
704
+ * only once it has.
705
+ *
706
+ * Shared by the three entry points that dispatch a mutation handler — the
707
+ * top-level RPC, \`ctx.runMutation\` from an action or http action, and a
708
+ * reactor — because the guarantee is a property of the mutation, not of how
709
+ * it was reached. The docs tell users to put the transactional part in a
710
+ * mutation and call it from the action precisely so that composition is
711
+ * atomic.
712
+ *
713
+ * A \`ctx.runMutation\` issued from inside a mutation is NESTED: SQLite-in-DO
714
+ * has no savepoints and \`runInTransaction\` rejects a second open, so it
715
+ * rides the enclosing span, which also owns its commit and therefore its
716
+ * scheduler flush.
717
+ *
718
+ * Both deferral windows are opened here and settled against the SAME
719
+ * outcome. True nested calls share their caller's context, so each window
720
+ * must discard its own failed delete and schedule intents even when the
721
+ * outer handler catches the error and commits.
722
+ */
723
+ private async runMutationTransaction<T>(ctx: unknown, work: () => Promise<T>): Promise<T> {
724
+ const settleSchedules = beginDeferredSchedules(ctx as { scheduler?: unknown });
725
+ // Synchronous and non-throwing (it only moves queue entries), so it can
726
+ // settle first on every path and cannot mask the outcome.
727
+ const settleDeletes = beginDeferredDeletes(ctx);
728
+
729
+ if (this.mutationContexts.has(ctx as object)) {
730
+ try {
731
+ const nested = await work();
732
+
733
+ settleDeletes(true);
734
+ await settleSchedules(true);
735
+
736
+ return nested;
737
+ } catch (error) {
738
+ settleDeletes(false);
739
+ await settleSchedules(false);
740
+
741
+ throw error;
742
+ }
743
+ }
744
+
745
+ let result: T;
746
+
747
+ try {
748
+ result = await this.runInTransaction(async () => {
749
+ this.mutationContexts.add(ctx as object);
750
+
751
+ try {
752
+ return await work();
753
+ } finally {
754
+ this.mutationContexts.delete(ctx as object);
755
+ }
756
+ }, { independent: true });
757
+ } catch (error) {
758
+ // The span rolled back, so the rows are gone and the jobs that were
759
+ // to run "after I commit" must go with them. Dropping them is the
760
+ // whole point of buffering: a persisted job for a write that never
761
+ // landed fires against state that does not exist.
762
+ //
763
+ // The queued object deletes go the same way, and for a sharper
764
+ // reason: the rows they were to clean up after are still there, and
765
+ // an R2 delete cannot be undone.
766
+ settleDeletes(false);
767
+ await settleSchedules(false);
768
+
769
+ throw error;
770
+ }
771
+
772
+ // Committed, so this span's queued keys join whatever the flush below
773
+ // (or an enclosing span's) will drain.
774
+ settleDeletes(true);
775
+
776
+ // Committed. Schedules first and AWAITED: \`runAfter(0, ...)\` is
777
+ // documented as the deterministic equivalent of an \`afterCommit\` hook,
778
+ // so the job must be enqueued after the commit, and a failure to enqueue
779
+ // it must be visible rather than swallowed.
780
+ //
781
+ // In a \`finally\`, because both halves of this are post-commit cleanup
782
+ // and neither is allowed to cancel the other. \`settleSchedules\` drains
783
+ // its whole queue and then rethrows what failed, so a SchedulerDO that
784
+ // refused one job used to take the object cleanup down with it — the
785
+ // rows were durably gone and their objects leaked with nothing logged.
786
+ try {
787
+ await settleSchedules(true);
788
+ __COMMITTED_CATCH__ } finally {
789
+ // Then the objects whose rows are now durably gone. Deliberately AFTER
790
+ // the span, never inside it: an R2 delete cannot roll back, so a delete
791
+ // issued from within a transaction that later aborts destroys data the
792
+ // surviving row still points at.
793
+ //
794
+ // \`flushDeferredDeletes\` never rejects — the mutation has already
795
+ // succeeded, so a failed cleanup must not turn into a failed response.
796
+ // A leaked object is reported through \`ctx.log\` instead, with its key.
797
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
798
+ }
799
+
800
+ return result;
801
+ }
802
+
803
+ // Only a \`mutation\` may enter the base class's single-writer gate for
804
+ // mutation-replay dedup — it is \`blockConcurrencyWhile\`, so gating an
805
+ // action would stall every other dispatch on the shard for the length of
806
+ // its outbound I/O, on nothing but a caller-supplied header. Unregistered
807
+ // paths answer \`false\`; \`handleRpc\` above rejects them anyway.
808
+ protected override isMutationFunction(functionPath: string): boolean {
809
+ return LUNORA_FUNCTIONS[functionPath]?.kind === "mutation";
810
+ }
811
+
812
+ // The scheduler the deferred-schedule outbox retries through. Only the
813
+ // CONFIGURED one: falling back to \`schedulerStub\` would have an app with no
814
+ // scheduler retry every entry against a thrower until the attempt ceiling
815
+ // parked it, and there is nothing to park — an app with no scheduler has no
816
+ // \`ctx.scheduler\` call that reached the buffer in the first place.
817
+ protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
818
+ 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> {
820
+ const registered = LUNORA_FUNCTIONS[functionPath];
821
+
822
+ if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
823
+ return null;
824
+ }
825
+
826
+ __PREPARE_FUNCTION__ this.ensureMigrated();
827
+
828
+ const footprint = createReadFootprint();
829
+ // Identity is threaded EXPLICITLY from the (deferred/interleaved)
830
+ // subscription caller — never read from the shared per-request field
831
+ // here — so a concurrent RPC can't leak its identity into this re-run.
832
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange });
833
+ const result = await registered.handler(ctx, args);
834
+
835
+ // Ranges come from THIS run's reads, never a shared field on the DO:
836
+ // a deferred re-run interleaves with unrelated dispatches.
837
+ const ranges = footprint.ranges();
838
+
839
+ return { ...(ranges === undefined ? {} : { ranges }), result, tables: footprint.tables };
840
+ }
841
+
842
+ protected override executeStream(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
843
+ const registered = LUNORA_FUNCTIONS[functionPath];
844
+
845
+ if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
846
+ return null;
847
+ }
848
+
849
+ this.ensureMigrated();
850
+
851
+ return {
852
+ ...(registered.durable ? { durable: registered.durable as { ttlMs?: number } } : {}),
853
+ // Identity threaded EXPLICITLY from the socket, exactly as
854
+ // \`executeSubscription\` above: the iterator is pulled after this
855
+ // frame returned, interleaved with unrelated dispatches, so
856
+ // \`buildCtx\`'s per-request fallback would run an \`rls()\` /
857
+ // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
858
+ iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
859
+ };
860
+ }`,Dr=` } catch (error) {
861
+ // The write committed before this failed. Mark the error so the caller can tell
862
+ // a durable write from a rollback: the rethrow still reaches the caller unchanged.
863
+ if (typeof error === "object" && error !== null) {
864
+ Object.assign(error, { committed: true });
865
+ }
866
+
867
+ throw error;
868
+ `,Tr=(n,e=!1)=>{const t=e?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
869
+
870
+ if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
871
+ throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
872
+ }
873
+
874
+ `:"",a=e?` const requestScope = this.captureRequestScope();
875
+ const preparation = this.prepareFunction(functionPath, "rpc");
876
+
877
+ if (preparation !== undefined) {
878
+ try {
879
+ await preparation;
880
+ } finally {
881
+ this.restoreRequestScope(requestScope);
882
+ }
883
+ }
884
+
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 {
887
+ const shape = LUNORA_SHAPES[name];
888
+
889
+ if (!shape) {
890
+ return undefined;
891
+ }
892
+
893
+ this.ensureMigrated();
894
+
895
+ // Trusted ctx from the socket's OWN verified identity — the client
896
+ // supplies only the shape name + args; \`compileWhere\` validates the
897
+ // args then runs the shape's \`where(ctx, args)\` under that identity,
898
+ // so which rows replicate is a server decision (reads-as-permissions).
899
+ const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity });
900
+ // \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
901
+ // \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
902
+ // rather than every shape restating the ownership check in its \`where\`.
903
+ const ownerField = (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField;
904
+ const shapeWhere = shape.compileWhere(ctx, args, ownerField === undefined ? {} : { ownerField }) as unknown as WhereInput;
905
+
906
+ // AND-compose with the read policies this SHAPE declares
907
+ // (\`defineShape({ use: [guard] })\`, pre-indexed into
908
+ // \`shape.rlsRegistry\`). A shape runs no procedure, so the
909
+ // \`.use(rls(...))\` middleware never fires; without this merge its
910
+ // reads would bypass the read policies it opted into.
911
+ // \`composeShapeReadWhere\` evaluates them under this same trusted ctx
912
+ // and fails closed under a \`.rls("required")\` schema for a
913
+ // non-\`.public()\` table the shape declared no read policy for.
914
+ //
915
+ // The registry is the shape's OWN — never one folded from every
916
+ // registered function. A project-wide union let one admin-only
917
+ // procedure's allow-all read policy unrestrict every shape on the
918
+ // table; see the SCOPE note in \`shape-read-base.ts\`.
919
+ //
920
+ // It is NOT identical to the request-time path, and must not be
921
+ // described as such: roles come from the identity's \`roles\` claim
922
+ // only, because no middleware runs here to contribute
923
+ // \`ctx.auth.roles\`. Derive roles at the identity if a policy gates
924
+ // on them — see \`shape-read-base.ts\`.
925
+ const effectiveWhere = composeShapeReadWhere(shape.rlsRegistry, {
926
+ ctx,
927
+ identity: identity?.identity ?? null,
928
+ rlsRequired: (schema as unknown as { rlsMode?: string }).rlsMode === "required",
929
+ shapeWhere,
930
+ table: shape.table,
931
+ tablePublic: (schema as unknown as { tables: Record<string, { isPublic?: boolean }> }).tables[shape.table]?.isPublic === true,
932
+ userId: identity?.userId ?? null,
933
+ });
934
+
935
+ // A live shape pokes only from its OWN shard's op-log, so a \`where()\`
936
+ // that joins to a \`.shardBy()\` table (rows in another DO) is rejected
937
+ // here — the first point the compiled predicate + shard modes are both
938
+ // known. Remedy: denormalize, or move the joined table to \`.global()\`.
939
+ assertShapeShardable(effectiveWhere, schema as unknown as SchemaLike, shape.table);
940
+
941
+ // A \`.global()\` table lives in D1 (no per-DO op-log): flag it so the
942
+ // base serves it through the latency-tiered poll path (\`readGlobalShapeRows\`)
943
+ // instead of the CDC poke path.
944
+ const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global";
945
+
946
+ return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
947
+ }
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?`
949
+ /** 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");
951
+ `:"";return{customMutatorOverride:n?`
952
+ protected override isCustomMutator(functionPath: string): boolean {
953
+ return LUNORA_MUTATOR_PATHS.has(functionPath);
954
+ }
955
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},$r=(n,e)=>n?`
956
+ 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
+ const env = this.env as Record<string, unknown>;
958
+ // A shape read performs no writes, so the widened request only needs
959
+ // the inbound bookmark (pin the membership drain to the caller's own
960
+ // prior writes) — no \`onBookmark\` here.
961
+ //
962
+ // The two identity members are named rather than spread, matching the
963
+ // dispatch-path request built in \`buildCtx\`. A spread would also hand
964
+ // the global writer \`ip\`, and \`globalShapeReadKey\` — the per-flush
965
+ // cache in front of this read — keys on identity + userId only. Equal
966
+ // keys must mean equal rows, so a field the writer can scope by has to
967
+ // be either in the key or out of the request; it is out.
968
+ const bookmark = this.getInboundBookmark();
969
+ const globalRequest = {
970
+ ...this.globalCdcOptions(config.cdc ?? false),
971
+ ...(bookmark === undefined ? {} : { bookmark }),
972
+ ...(identity?.identity === undefined ? {} : { identity: identity.identity }),
973
+ ...(identity?.userId === undefined ? {} : { userId: identity.userId }),
974
+ };
975
+ const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
976
+ const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
977
+
978
+ let cursor: null | string = null;
979
+
980
+ // Drain every page of the global membership so the seed/diff sees the
981
+ // full rowset (D1 \`findMany\` is paginated). Stop one row past the cap:
982
+ // a broad \`.global()\` shape would otherwise materialize an unbounded
983
+ // array before the caller's \`withinGlobalShapeBound\` check rejects it,
984
+ // so bail early and let the caller fail it closed.
985
+ do {
986
+ // eslint-disable-next-line no-await-in-loop -- sequential page drain to assemble the full membership
987
+ const page = await globalDb.findMany(resolved.table, { cursor, ...(resolved.effectiveWhere === undefined ? {} : { where: resolved.effectiveWhere }) });
988
+
989
+ for (const doc of page.page) {
990
+ rows.push({ doc, id: String((doc as { _id?: unknown })._id) });
991
+
992
+ if (rows.length > ShardDOBase.GLOBAL_SHAPE_MAX_ROWS) {
993
+ return rows;
994
+ }
995
+ }
996
+
997
+ cursor = page.isDone ? null : page.continueCursor;
998
+ } while (cursor !== null);
999
+
1000
+ return rows;
1001
+ }
1002
+
1003
+ protected override async readGlobalChangedTables(sinceSeq: number, cursorOnly?: boolean): Promise<{ cursor: number; floor?: number; tables: string[] } | undefined> {
1004
+ const env = this.env as Record<string, unknown>;
1005
+ // Metadata-only: this asks the global changelog which TABLES moved,
1006
+ // never what changed in them, so it costs one small read per poll tick
1007
+ // for the whole shard — and a tick whose answer omits a shape's table
1008
+ // skips that shape's membership drain entirely.
1009
+ // Named local, not an inline object literal — same reason as the
1010
+ // dispatch path and \`readGlobalShapeRows\`: \`bookmark\` is not declared
1011
+ // on the narrower Hyperdrive thunk's \`request\` type, and an inline
1012
+ // literal trips an excess-property error (TS2353) that makes the
1013
+ // emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
1014
+ // a \`defineShape\`. The Hyperdrive factory simply never reads it.
1015
+ const bookmark = this.getInboundBookmark();
1016
+ const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), ...(bookmark === undefined ? {} : { bookmark }) };
1017
+ const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
1018
+
1019
+ return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
1020
+ }
1021
+ `:"",qr=n=>({externalSourceOverride:n?`
1022
+ protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1023
+ const env = (this.env ?? {}) as Record<string, unknown>;
1024
+ const sourced = Object.entries((schema as unknown as SchemaLike).tables)
1025
+ .map(([table, definition]) => [table, (definition as { externalSource?: ExternalSourceLike }).externalSource] as const)
1026
+ .filter((entry): entry is [string, ExternalSourceLike] => entry[1] !== undefined);
1027
+
1028
+ if (sourced.length === 0) {
1029
+ return undefined;
1030
+ }
1031
+
1032
+ const shardKey = this.currentShardKey();
1033
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1034
+
1035
+ let clients = sourceClientCache.get(this);
1036
+
1037
+ if (clients === undefined) {
1038
+ clients = new Map();
1039
+ sourceClientCache.set(this, clients);
1040
+ }
1041
+
1042
+ let polledAt = sourcePollAtCache.get(this);
1043
+
1044
+ if (polledAt === undefined) {
1045
+ polledAt = new Map();
1046
+ sourcePollAtCache.set(this, polledAt);
1047
+ }
1048
+
1049
+ const now = Date.now();
1050
+ // \`nextDueAt\` tracks the EARLIEST next-due timestamp across every
1051
+ // non-manual source; the shared alarm re-arms there instead of the
1052
+ // fixed 2 s global-shape floor, so a large \`refresh.everyMs\` actually
1053
+ // sleeps until it's due. Stays \`undefined\` when every source is
1054
+ // \`refresh: "manual"\`, so the shared alarm goes idle for this tier.
1055
+ let nextDueAt: number | undefined;
1056
+
1057
+ for (const [table, source] of sourced) {
1058
+ if (source.refresh === "manual") {
1059
+ continue;
1060
+ }
1061
+
1062
+ if (isSourceDue(source.refresh, polledAt.get(table), now)) {
1063
+ try {
1064
+ let client = clients.get(source.binding);
1065
+
1066
+ if (client === undefined) {
1067
+ client = config.sourceClient?.(env, source.binding);
1068
+
1069
+ if (client !== undefined) {
1070
+ clients.set(source.binding, client);
1071
+ }
1072
+ }
1073
+
1074
+ if (client === undefined) {
1075
+ // No SqlClient resolved for this binding (host never wired
1076
+ // \`config.sourceClient\`, or wired it wrong). Surface it in the
1077
+ // Logs panel and stamp \`polledAt\` so a persistent misconfig backs
1078
+ // off to \`refresh.everyMs\` instead of retrying every alarm tick.
1079
+ this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`), trace);
1080
+ } else {
1081
+ // A FRESH tracker per TABLE, not one shared across the whole
1082
+ // loop: one table's runaway pull must not spend a budget a
1083
+ // sibling table needs, and a limit hit here must not block
1084
+ // that sibling from getting its own full budget this tick.
1085
+ const writer = createShardCtxDb({
1086
+ // Admin and maintenance writes go through the SAME reactive-cache hooks as
1087
+ // a user mutation. Without this, a studio row edit, a TTL sweep, an admin
1088
+ // import, a CDC apply or a data-migration backfill writes without
1089
+ // invalidating, and the next query answers from the pre-write snapshot.
1090
+ ...this.ctxDbTuning(),
1091
+ broadcast: (delta) => {
1092
+ this.recordChangedTable(delta.table, delta.indexKeys);
1093
+ },
1094
+ cdc: config.cdc ?? false,
1095
+ headroom: this.alarmHeadroom(),
1096
+ scheduler,
1097
+ schema: schema as unknown as SchemaLike,
1098
+ sql: this.sql as SqlExec,
1099
+ });
1100
+
1101
+ if (source.mode === "incremental") {
1102
+ // Incremental (plan 136): pull only rows past the durable
1103
+ // watermark (or a full-pull seed/reconcile), upsert-only.
1104
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
1105
+ await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
1106
+ } else {
1107
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; slices are independent but small and sequential keeps the writer transaction simple
1108
+ await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
1109
+ }
1110
+ }
1111
+
1112
+ // Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
1113
+ // poll that outruns \`everyMs\` must not make \`nextDueAt\` (below)
1114
+ // stale-immediate and re-arm the alarm in a hammering loop.
1115
+ polledAt.set(table, Date.now());
1116
+ } catch (error) {
1117
+ if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
1118
+ // Batch full, not a genuine failure. Incremental mode only
1119
+ // persists its watermark AFTER a full apply (see
1120
+ // \`pullExternalSourceIncrementalTick\`), so this throw left it
1121
+ // untouched — the next tick safely re-pulls/re-applies the
1122
+ // SAME slice (idempotent upsert). Full-pull mode (and an
1123
+ // incremental source's own occasional full-pull/reconcile
1124
+ // sweep) has no resumable cursor at all — deliberately not
1125
+ // inventing one here; a retry just redoes the whole pull,
1126
+ // safe if wasteful. Either way: warn instead of
1127
+ // \`recordExternalSourceError\`, and leave \`polledAt\`
1128
+ // UNCHANGED (skip the stamp below via \`continue\`) so this
1129
+ // table stays "due" and \`nextPollAlarmTarget\`'s existing
1130
+ // due-now floor re-arms the shared alarm promptly — not a
1131
+ // fresh \`setAlarm(now)\`.
1132
+ this.recordExternalSourceWarning(
1133
+ table,
1134
+ \`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
1135
+ trace,
1136
+ );
1137
+
1138
+ nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
1139
+
1140
+ continue;
1141
+ }
1142
+
1143
+ this.recordExternalSourceError(table, error, trace);
1144
+ // Stamp on failure too, so a persistently failing source throttles
1145
+ // to \`refresh.everyMs\` rather than being hammered every tick.
1146
+ polledAt.set(table, Date.now());
1147
+ }
1148
+ }
1149
+
1150
+ // This source's own next-due time, read AFTER the poll-or-skip above
1151
+ // so a just-polled source reports \`now + everyMs\` (its FRESH due
1152
+ // time), not the stale pre-poll one. An omitted \`refresh\` (poll
1153
+ // every tick) is due again immediately.
1154
+ const sourceNextDueAt = source.refresh === undefined ? now : (polledAt.get(table) ?? now) + source.refresh.everyMs;
1155
+
1156
+ nextDueAt = nextDueAt === undefined ? sourceNextDueAt : Math.min(nextDueAt, sourceNextDueAt);
1157
+ }
1158
+
1159
+ return nextDueAt;
1160
+ }
1161
+ `:"",sourceBootstrap:n?`
1162
+ const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1163
+ const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1164
+
1165
+ return source !== undefined && source.refresh !== "manual";
1166
+ });
1167
+
1168
+ if (autoSourced) {
1169
+ void this.scheduleSourcePoll();
1170
+ }
1171
+ `:"",sourceClientCacheConst:n?`
1172
+ const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1173
+ 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?`
1176
+ const vectorSync = this.vectorSync(env);
1177
+ // Vectorize lives outside this shard's SQLite, so a query whose result
1178
+ // depends on a similarity search cannot be proven current on reconnect —
1179
+ // an unrelated upsert (or a re-index) moves the matches without touching
1180
+ // \`__cdc_log\`. Only \`ctx.vectors\` is wrapped: the write-through
1181
+ // vector-sync hook keeps calling the bare facade.
1182
+ const bareVectors = vectorSync?.vectors ?? vectorsStub;
1183
+ const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
1184
+ const onWrite = vectorSync?.onWrite;
1185
+ `:"";return{vectorSyncMethod:n?`
1186
+ private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
1187
+ if (!config.vectors) {
1188
+ return undefined;
1189
+ }
1190
+
1191
+ const lunora = createVectors({ indexes: config.vectors(env) });
1192
+ ${o} const vectors = createContextVectors(lunora${v});
1193
+
1194
+ return {
1195
+ backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
1196
+ onWrite: createVectorSyncHook({ ${d}schema: schema as unknown as VectorSchemaLike, vectors }),
1197
+ vectors,
1198
+ };
1199
+ }
1200
+
1201
+ // \`__lunora_admin__:backfillVectors\`: the rows that predate a vector index,
1202
+ // a page at a time, each page ordered on the after-commit chain so it
1203
+ // never lands over a newer write's vector.
1204
+ protected override async runShardVectorBackfill(options: { maxPages?: number; restart?: boolean }): Promise<VectorBackfillProgress> {
1205
+ this.ensureMigrated();
1206
+
1207
+ const vectorSync = this.vectorSync((this.env ?? {}) as Record<string, unknown>);
1208
+
1209
+ if (!vectorSync) {
1210
+ throw new LunoraError("NOT_IMPLEMENTED", "vector backfill is unavailable: no vectors configured. Pass \`vectors\` to createShardDO().");
1211
+ }
1212
+
1213
+ return backfillVectorIndexes(this.sql as SqlExec, vectorBackfillTargets(schema as unknown as VectorSchemaLike), vectorSync.backfill, {
1214
+ ...options,
1215
+ ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1216
+ });
1217
+ }
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?"":`
1219
+ /** 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(", ")} };
1223
+ }
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(`
1226
+ `)}
1227
+ ]);
1228
+
1229
+ private readonly loadedLiveStreams = new Map<string, { validatePublish: (topic: string, payload: unknown) => unknown }>();
1230
+
1231
+ protected override loadLiveStream(stream: string): Promise<void> | undefined {
1232
+ const load = this.loadedLiveStreams.has(stream) ? undefined : this.liveStreamLoaders.get(stream);
1233
+
1234
+ return load === undefined
1235
+ ? undefined
1236
+ : load().then((declaration) => {
1237
+ this.loadedLiveStreams.set(stream, declaration);
1238
+ });
1239
+ }
1240
+
1241
+ // Only the streams a publish has already loaded: a stream not yet loaded was either never published to or is
1242
+ // unknown, and either way \`declaredLivePayload\` refuses what this does not hold.
1243
+ protected override liveStreams() {
1244
+ return Object.fromEntries(this.loadedLiveStreams);
1245
+ }
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=`{
1251
+ ...this.ctxDbTuning(),
1252
+ auth: { identity: identity ?? null, userId: userId ?? null },
1253
+ broadcast: (delta) => {
1254
+ this.recordChangedTable(delta.table, delta.indexKeys);
1255
+ },
1256
+ // Read at call time, not captured: the baseline belongs to the
1257
+ // dispatch in flight, and a queued mutation admitted after a
1258
+ // sibling's prologue must be judged against ITS caller's cursor.
1259
+ baselineSeq: () => this.getCurrentBaselineSeq(),
1260
+ cdc: config.cdc ?? false,
1261
+ // A dispatch with NO caller identity runs system-trusted: RLS scopes
1262
+ // rows to a user, and these have no user to scope to. This is the tier
1263
+ // migrations, imports and the external-source poll loop already run in
1264
+ // (see \`adminWriterPrelude\`). Only \`onShardInit\` and \`onQueryChange\`
1265
+ // reach it; \`onConnect\`/\`onDisconnect\` carry a verified identity and
1266
+ // stay guarded like any request.
1267
+ enforceRls: options.trusted !== true,
1268
+ headroom: options.headroom ?? this.transactionHeadroom(),
1269
+ // A live predicate, not a flag: the transaction opens AFTER this ctx
1270
+ // is built (a mutation dispatch wraps the handler), so only a call-time
1271
+ // read reports the truth. \`_commitSeq\` reuses one sequence across
1272
+ // writes only while they commit together — an action is not wrapped, so
1273
+ // each of its writes allocates its own.
1274
+ inTransaction: () => this.isInTransaction(),
1275
+ onIndexUse: this.getCtxDbIndexUseHook(),
1276
+ onStalePatchDropped: (event) => {
1277
+ this.recordStalePatchDropped(event);
1278
+ },
1279
+ // Bound to THIS dispatch's reactive-cache read scope (\`handleRpc\`
1280
+ // threads it in), so two concurrent queries never stamp each
1281
+ // other's dep sets. \`executeSubscription\` overrides both with its
1282
+ // own \`ReadFootprint\` pair instead, and a dispatch with neither
1283
+ // gets an unbound hook that stamps no deps.
1284
+ onRead: options.onRead ?? this.getCtxDbReadHook(options.scope),
1285
+ // Omitted when there is no scope so \`createShardCtxDb\`
1286
+ // keeps its own "degrade a provable slice to a whole-table dep"
1287
+ // fallback rather than reporting into a no-op.
1288
+ ...(options.onReadRange !== undefined
1289
+ ? { onReadRange: options.onReadRange }
1290
+ : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${m?`
1291
+ // Vectorize is outside this shard's SQLite and cannot roll back, so
1292
+ // the sync is held until the mutation's transaction has COMMITTED
1293
+ // (\`deferAfterCommit\`) instead of running inline. Inline, a write
1294
+ // that later aborted left a vector pointing at a row that does not
1295
+ // exist — which a search then surfaces — and a rolled-back delete
1296
+ // left the row with its vector already purged. Outside a
1297
+ // transaction (an action) nothing is open and it runs at once.
1298
+ ...(onWrite === undefined ? {} : { onWrite: (event) => this.deferAfterCommit(() => onWrite(event)) }),`:""}
1299
+ scheduler,
1300
+ schema: schema as unknown as SchemaLike,
1301
+ sql: this.sql as SqlExec,
1302
+ storage,${A?`
1303
+ globalDb,`:""}
1304
+ }`,vt=m?`
1305
+ vectors,`:"",kt=z?`
1306
+ orm: bindOrm(facade),`:"",oe=Q?"config.hyperdriveGlobal":"config.d1",St=A?` const bookmark = this.getInboundBookmark();
1307
+ const globalRequest = {
1308
+ ...this.globalCdcOptions(config.cdc ?? false),
1309
+ ...(bookmark === undefined ? {} : { bookmark }),
1310
+ ...(identity === undefined ? {} : { identity }),
1311
+ onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
1312
+ ...(userId === undefined ? {} : { userId }),
1313
+ };
1314
+ const globalDb: DatabaseWriterLike = ${oe}?.(env, globalRequest) ?? globalDbStub;
1315
+ `:"",Rt=$r(p&&A,oe),xt=l?` protected override roomHandlerPath(topic: string): string | undefined {
1316
+ // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1317
+ return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1318
+ }
1319
+ `:"",Ot=b?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1320
+ return LUNORA_SOCKETS[path];
1321
+ }
1322
+ `:"",{externalSourceOverride:At,sourceBootstrap:Dt,sourceClientCacheConst:Tt}=qr(C),Ct=`
1323
+ protected override async runShardInit(): Promise<void> {
1324
+ this.ensureMigrated();
1325
+ ${te?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1326
+ `:""}
1327
+ await this.dispatchShardInit();
1328
+ }
1329
+ `,_t=re.length>0?`
1330
+ if (LUNORA_TTL_SWEEPS.length > 0) {
1331
+ void this.scheduleTtlSweep();
1332
+ }
1333
+ `:"",Et=`
1334
+ public constructor(state: ShardDOState, env: unknown) {
1335
+ super(state, env, {
1336
+ // Every writer this file builds spreads the ctxDbTuning() slice —
1337
+ // the user-facing ctx and all three admin/maintenance writers — so
1338
+ // the base class can drop its coarse invalidation backstop. Only the
1339
+ // emitter can know that; a hand-written subclass leaves this unset
1340
+ // and keeps the backstop.
1341
+ ctxDbCacheWired: true,
1342
+ ...(config.deliveryAuthorization === undefined ? {} : { deliveryAuthorization: config.deliveryAuthorization((env ?? {}) as Record<string, unknown>) }),
1343
+ ...(config.maxRelationKeys === undefined ? {} : { maxRelationKeys: config.maxRelationKeys }),
1344
+ ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1345
+ ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1346
+ // The same sink \`buildCtx\` resolves, made reachable before any ctx
1347
+ // exists — a trigger that fails first still flushes and fuses.
1348
+ ...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
1349
+ });
1350
+ ${Dt}${_t} }
1351
+
1352
+ protected override isCacheableQuery(functionPath: string): boolean {
1353
+ // NOT \`kind === "query"\` alone. A cache hit answers without running
1354
+ // \`handleRpc\`, so the \`internal\` refusal at the top of it is skipped —
1355
+ // and an \`internalQuery\` primed by a trusted system dispatch was then
1356
+ // served to an anonymous client that the refusal would have 404'd.
1357
+ //
1358
+ // \`perDispatch\` is the same argument one layer out: the procedure's
1359
+ // own \`.use()\` chain runs INSIDE \`handleRpc\`, so a hit skips it too.
1360
+ // A \`.use(rateLimit(...))\` query was therefore charged once and then
1361
+ // served from the memo to every later request — each of which still
1362
+ // reached this Durable Object and still cost it a dispatch, so only
1363
+ // the accounting was skipped. Metering and memoizing are mutually
1364
+ // exclusive; the author asking for the first is choosing against the
1365
+ // second.
1366
+ const registered = LUNORA_FUNCTIONS[functionPath];
1367
+
1368
+ return registered?.kind === "query" && registered.visibility !== "internal" && registered.perDispatch !== true;
1369
+ }
1370
+
1371
+ protected override isPaidFunction(functionPath: string): boolean {
1372
+ return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1373
+ }
1374
+ `,ie=c?`
1375
+ protected override prepareFunction(functionPath: string, reason: "rpc" | "subscription" | "stream" | "reactor"): Promise<void> | undefined {
1376
+ const registered = LUNORA_FUNCTIONS[functionPath];
1377
+ const allowsInternal = reason === "reactor" || (reason === "rpc" && this.isSystemDispatch());
1378
+
1379
+ if (registered?.visibility === "internal" && !allowsInternal) {
1380
+ return;
1381
+ }
1382
+
1383
+ if (getLoadedFunction(functionPath) !== undefined) {
1384
+ return;
1385
+ }
1386
+
1387
+ return loadFunction(functionPath).then(() => undefined);
1388
+ }
1389
+ `:"",Lt=ie===""?`
1390
+
1391
+ `:`${ie}
1392
+ `,It=xr(c),Pt=c?` const preparation = this.prepareFunction(functionPath, "subscription");
1393
+ if (preparation !== undefined) await preparation;
1394
+ `:"",Nt=Ar.replace("__PREPARE_FUNCTION__",Pt),Mt=Tr(l,c),$t=z?`
1395
+ const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1396
+ ${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFacade(db, ${JSON.stringify(s.name)});`).join(`
1397
+ `)}
1398
+ `:"",qt=`${y.everyBuild}${T.build}${H.build}
1399
+ const secrets = createSecrets(env);
1400
+ `,Ft=`${y.everyFields}${T.contextField}${W.contextField}${H.contextField}
1401
+ secrets,`,Ut=W.build,Bt=R?`
1402
+ const live = {
1403
+ publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
1404
+ await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
1405
+ },
1406
+ };
1407
+ `:"",jt=[...y.actionFields,...x.length>0?["services"]:[],...R?["live"]:[]],Wt=`${y.actionBuild}${V.build}${Bt}`;return`${fr}${_.join(`
1408
+ `)}
1409
+
1410
+ type FunctionKind = "action" | "mutation" | "query";
1411
+
1412
+ interface FunctionReference {
1413
+ __lunoraRef: string;
1414
+ }
1415
+
1416
+ /** 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>>")};
1418
+
1419
+ /** 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 }>>')};
1421
+
1422
+ /** 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<
1424
+ string,
1425
+ Array<{
1426
+ bucket?: string;
1427
+ enumValues?: string[];
1428
+ isStorage?: boolean;
1429
+ name: string;
1430
+ nullable?: boolean;
1431
+ onDelete?: "cascade" | "restrict" | "set null";
1432
+ optional: boolean;
1433
+ pk?: boolean;
1434
+ ref?: string;
1435
+ type: string;
1436
+ }>
1437
+ >`)};
1438
+
1439
+ /** 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[]>")};
1441
+
1442
+ /** 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 }>")};
1444
+
1445
+ /** 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>>")};
1447
+
1448
+ /** 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 }>")};
1450
+
1451
+ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1452
+ let cached: AdvisoryFinding[] | undefined;
1453
+ return () => (cached ??= LUNORA_ADVISORY_ROWS().map((row) => ({ ...LUNORA_ADVISORY_RULES()[row.name], ...row }) as AdvisoryFinding));
1454
+ })();
1455
+
1456
+ /** 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[]")};
1458
+
1459
+ /** 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}
1462
+ /** 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")};
1464
+
1465
+ /** 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")};
1467
+
1468
+ /** 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}
1471
+ export interface ShardDOConfig {
1472
+ /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1473
+ cdc?: boolean;
1474
+ /** Current authority for RPC and ordinary subscription deliveries; other live delivery modes are refused. */
1475
+ deliveryAuthorization?: (env: Record<string, unknown>) => DeliveryAuthorization;
1476
+ /** Ceiling on the join keys one relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
1477
+ maxRelationKeys?: number;
1478
+ /** Enable the per-shard reactive query cache: \`true\` for the defaults, or an options object to tune the caps. Query results are memoized by \`(functionPath, args, identity)\` and invalidated by the ctx-db write hooks before the subscription broadcast, so subscribers never observe a pre-write value. Omitted (or \`false\`) keeps every dispatch re-running its handler. */
1479
+ reactiveCache?: boolean | { maxBytes?: number; maxEntries?: number };
1480
+ /** Resolution policy for a relation-crossing \`where\` whose child is co-located in this shard: \`"auto"\` (cost-based, the engine default), \`"always"\` (inline correlated EXISTS) or \`"never"\` (universal semijoin). All three return identical rows. */
1481
+ relationExistsPushDown?: "always" | "auto" | "never";
1482
+ /** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
1483
+ observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1484
+ /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1485
+ scheduler?: (env: Record<string, unknown>) => unknown;
1486
+ /** \`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}
1488
+ }
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}
1491
+
1492
+ /**
1493
+ * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1494
+ * from the worker entry so wrangler binds it by name.
1495
+ */
1496
+ 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}
1502
+ protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1503
+ return LUNORA_LIFECYCLE_HOOKS[event];
1504
+ }
1505
+ ${xt}${Ot}${se}${G.override}${Ct}
1506
+ // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1507
+ // socket-terminated half of the same reactivity — and differs only in who
1508
+ // consumes the result: the base's \`dispatchReactors\` stores the digest as
1509
+ // the new baseline and the footprint as the "should I even re-run this"
1510
+ // gate, instead of pushing a frame down a socket.
1511
+ //
1512
+ // Dispatched through \`runMutationTransaction\` because a reactor handler is
1513
+ // a mutation: its writes must commit all-or-nothing, the jobs it schedules
1514
+ // must wait for that commit, and the objects its row deletes orphaned must
1515
+ // be flushed once it lands. Safe to open a span here: the refresh drain
1516
+ // runs OUTSIDE any dispatch transaction (it is post-flush background work),
1517
+ // so this never nests.
1518
+ //
1519
+ // NO identity is threaded, and the ctx is built \`trusted\`. A reactor fires
1520
+ // because data moved, not because anyone asked, so there is no user for RLS
1521
+ // to scope to — it runs in the same system tier as migrations and the
1522
+ // external-source poll loop. Inheriting the shared per-request identity
1523
+ // would instead run an app's reactor as whichever user happened to write
1524
+ // last, which is worse than running it as nobody.
1525
+ protected override async runReactor(functionPath: string, previousDigest?: string): Promise<{ digest: string; ran: boolean; tables: readonly string[] } | undefined> {
1526
+ ${c?` const requestScope = this.captureRequestScope();
1527
+ const preparation = this.prepareFunction(functionPath, "reactor");
1528
+
1529
+ if (preparation !== undefined) {
1530
+ try {
1531
+ await preparation;
1532
+ } finally {
1533
+ this.restoreRequestScope(requestScope);
1534
+ }
1535
+ }
1536
+
1537
+ `:""} const registered = LUNORA_FUNCTIONS[functionPath];
1538
+
1539
+ if (!registered || registered.kind !== "mutation") {
1540
+ return undefined;
1541
+ }
1542
+
1543
+ this.ensureMigrated();
1544
+
1545
+ const footprint = createReadFootprint();
1546
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), onRead: footprint.onRead, onReadRange: footprint.onReadRange, trusted: true });
1547
+ const outcome = (await this.runMutationTransaction(ctx, async () =>
1548
+ registered.handler(ctx, { previousDigest } as unknown as Record<string, unknown>),
1549
+ )) as {
1550
+ digest: string;
1551
+ ran: boolean;
1552
+ };
1553
+
1554
+ return { digest: outcome.digest, ran: outcome.ran, tables: [...footprint.tables] };
1555
+ }
1556
+
1557
+
1558
+ protected override tableRefs(table: string): Record<string, string> | undefined {
1559
+ return LUNORA_TABLE_REFS()[table];
1560
+ }
1561
+
1562
+ protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> {
1563
+ return LUNORA_TABLE_INDEXES()[table] ?? [];
1564
+ }
1565
+
1566
+ protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> {
1567
+ return LUNORA_TTL_SWEEPS;
1568
+ }
1569
+
1570
+ protected override tableColumns(table: string): Array<{
1571
+ bucket?: string;
1572
+ enumValues?: string[];
1573
+ isStorage?: boolean;
1574
+ name: string;
1575
+ nullable?: boolean;
1576
+ onDelete?: "cascade" | "restrict" | "set null";
1577
+ optional: boolean;
1578
+ pk?: boolean;
1579
+ ref?: string;
1580
+ type: string;
1581
+ }> {
1582
+ return LUNORA_TABLE_COLUMNS()[table] ?? [];
1583
+ }
1584
+
1585
+ protected override storageColumns(): Record<string, string[]> {
1586
+ return LUNORA_STORAGE_COLUMNS();
1587
+ }
1588
+
1589
+ protected override rlsMetadata(): RlsPoliciesResult {
1590
+ return LUNORA_RLS_METADATA();
1591
+ }
1592
+
1593
+ protected override maskMetadata(): MaskPoliciesResult {
1594
+ return LUNORA_MASK_METADATA();
1595
+ }
1596
+
1597
+ protected override storageRulesMetadata(): StorageRulesResult {
1598
+ return LUNORA_STORAGE_RULES();
1599
+ }
1600
+
1601
+ protected override studioFeatures(): StudioFeaturesResult {
1602
+ return LUNORA_STUDIO_FEATURES();
1603
+ }
1604
+ ${j.evaluateOverride}${j.subscriptionOverride}${Ge}${Je}
1605
+ protected override advisories(): AdvisoryFinding[] {
1606
+ return LUNORA_ADVISORIES();
1607
+ }
1608
+
1609
+ protected override advisorProcedures(): AdvisorProcedure[] {
1610
+ return LUNORA_ADVISOR_PROCEDURES();
1611
+ }
1612
+
1613
+ ${Sr}
1614
+
1615
+ protected override ensureMigrated(): void {
1616
+ if (this.migrated) {
1617
+ return;
1618
+ }
1619
+
1620
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${pe} });
1621
+ this.migrated = true;
1622
+ }
1623
+ ${J?`
1624
+ protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1625
+ // Migrations create the fts5 companions; without them every backfill
1626
+ // statement would raise "no such table" on a shard that has never
1627
+ // served a request.
1628
+ this.ensureMigrated();
1629
+
1630
+ return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1631
+ }
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})}
1634
+ };
1635
+ `};export{_r as b,Xr as e};