@lunora/codegen 1.0.0-alpha.31 → 1.0.0-alpha.311

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 (122) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +4467 -2142
  4. package/dist/index.d.ts +4467 -2142
  5. package/dist/index.mjs +1 -35
  6. package/dist/packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs +1 -0
  7. package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
  8. package/dist/packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs +1 -0
  9. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_TARGET-BnQiNNKu.mjs +1 -0
  11. package/dist/packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs +1 -0
  12. package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +1 -0
  13. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  14. package/dist/packem_shared/MUTATORS_FILENAME-qVDmv8st.mjs +1 -0
  15. package/dist/packem_shared/NOTIFY_FILENAME-CLoeWMb5.mjs +1 -0
  16. package/dist/packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs +3 -0
  17. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  18. package/dist/packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs +1 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CSjCtmZi.mjs +11 -0
  20. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  21. package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
  22. package/dist/packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs +1 -0
  23. package/dist/packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs +18 -0
  24. package/dist/packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs +1 -0
  25. package/dist/packem_shared/attribution-hVBriwzy.mjs +1 -0
  26. package/dist/packem_shared/buildOpenApiDocument-DFv-RYZU.mjs +3 -0
  27. package/dist/packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs +1 -0
  28. package/dist/packem_shared/chain-CRDaTj2c.mjs +1 -0
  29. package/dist/packem_shared/classify-procedure-call-BAj0D1u2.mjs +1 -0
  30. package/dist/packem_shared/context-property-calls-CQWCNUVH.mjs +1 -0
  31. package/dist/packem_shared/context-root-LyOsqj_o.mjs +1 -0
  32. package/dist/packem_shared/createCodegenProject-V51_yBw3.mjs +1 -0
  33. package/dist/packem_shared/database-calls-BPpefKqO.mjs +1 -0
  34. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  35. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  36. package/dist/packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs +1 -0
  37. package/dist/packem_shared/discoverCrons-DBnCama4.mjs +1 -0
  38. package/dist/packem_shared/discoverFunctions-CbxZGGj0.mjs +1 -0
  39. package/dist/packem_shared/discoverHttpRoutes-DgfoyNcf.mjs +1 -0
  40. package/dist/packem_shared/discoverHyperdriveCalls-CwnXgjFJ.mjs +1 -0
  41. package/dist/packem_shared/discoverInserts-mHOX_dJR.mjs +1 -0
  42. package/dist/packem_shared/discoverMaskProcedures-BTePIpmk.mjs +1 -0
  43. package/dist/packem_shared/discoverMigrations-C9mLIhGZ.mjs +1 -0
  44. package/dist/packem_shared/discoverNondeterministicCalls-9ZDpRptb.mjs +1 -0
  45. package/dist/packem_shared/discoverQueries-CfxkjP5X.mjs +1 -0
  46. package/dist/packem_shared/discoverR2sqlCalls-XBhs4XRZ.mjs +1 -0
  47. package/dist/packem_shared/discoverRlsMetadata-Cb8JR1b4.mjs +1 -0
  48. package/dist/packem_shared/discoverRlsProcedures-TskedRMh.mjs +1 -0
  49. package/dist/packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs +1 -0
  50. package/dist/packem_shared/discoverSchema-BtsX-CN9.mjs +1 -0
  51. package/dist/packem_shared/discoverStorageRulesMetadata-BPJplDfz.mjs +1 -0
  52. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  53. package/dist/packem_shared/emitAgents-CVN1D17z.mjs +1 -0
  54. package/dist/packem_shared/emitApi-Zx6VPN-7.mjs +135 -0
  55. package/dist/packem_shared/emitApp-BOUdd-2R.mjs +955 -0
  56. package/dist/packem_shared/emitCrons-BQW2lviZ.mjs +96 -0
  57. package/dist/packem_shared/emitDataModel-BskFt9Wv.mjs +114 -0
  58. package/dist/packem_shared/emitDrizzleSchema-DitcRZ1a.mjs +15 -0
  59. package/dist/packem_shared/emitFunctions-BeKgL3dl.mjs +241 -0
  60. package/dist/packem_shared/emitServer-D1vA5_X1.mjs +1 -0
  61. package/dist/packem_shared/emitShard-D_dkDtuY.mjs +1 -0
  62. package/dist/packem_shared/exported-procedure-chains-DKK5HoK3.mjs +1 -0
  63. package/dist/packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs +1 -0
  64. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
  65. package/dist/packem_shared/handler-reference-vIeqkhV_.mjs +1 -0
  66. package/dist/packem_shared/index-CkS96b8a.mjs +1 -0
  67. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  68. package/dist/packem_shared/isTestPath-B81lOULB.mjs +1 -0
  69. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  70. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  71. package/dist/packem_shared/loadProjectConfig-NO0dVJSl.mjs +1 -0
  72. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  73. package/dist/packem_shared/modules-CjOcuQnK.mjs +1 -0
  74. package/dist/packem_shared/parse-validator-IDBKIT7M.mjs +1 -0
  75. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  76. package/dist/packem_shared/project-config-file-BV7RR-l6.mjs +1 -0
  77. package/dist/packem_shared/qualifiers-DEdXn5wP.mjs +1 -0
  78. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  79. package/dist/packem_shared/readServiceBindings-DvqIThzd.mjs +1 -0
  80. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  81. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  82. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  83. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  84. package/dist/packem_shared/server-DAvi_bv_.mjs +368 -0
  85. package/dist/packem_shared/shard-Av4rUyYS.mjs +1454 -0
  86. package/dist/packem_shared/shard-runtime-CkTgY8tL.mjs +326 -0
  87. package/dist/packem_shared/shared-DnCokNcE.mjs +13 -0
  88. package/dist/packem_shared/unwrap-handler-return-CJrkfrSH.mjs +1 -0
  89. package/package.json +17 -8
  90. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  91. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  92. package/dist/packem_shared/FLAGS_FILENAME-BjpS5w08.mjs +0 -139
  93. package/dist/packem_shared/GENERATED_HEADER-f6nMvllu.mjs +0 -3274
  94. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  95. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  96. package/dist/packem_shared/OPENRPC_VERSION-u5SqDDGk.mjs +0 -60
  97. package/dist/packem_shared/QUEUES_FILENAME-BF0iUmx7.mjs +0 -119
  98. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Ca-TlVEc.mjs +0 -3481
  99. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  100. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  101. package/dist/packem_shared/WORKFLOWS_FILENAME-CCC_42o3.mjs +0 -124
  102. package/dist/packem_shared/buildOpenApiDocument-AgKWmlry.mjs +0 -183
  103. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  104. package/dist/packem_shared/discoverAuthApiCalls-URDoTADN.mjs +0 -62
  105. package/dist/packem_shared/discoverCrons-DdZOeroL.mjs +0 -257
  106. package/dist/packem_shared/discoverFunctions-BJdF7lRs.mjs +0 -514
  107. package/dist/packem_shared/discoverHttpRoutes-CcwP-Rkr.mjs +0 -131
  108. package/dist/packem_shared/discoverInserts-BpFhM32L.mjs +0 -61
  109. package/dist/packem_shared/discoverMaskProcedures-DT-v8wvj.mjs +0 -273
  110. package/dist/packem_shared/discoverMigrations-cG1idBVM.mjs +0 -97
  111. package/dist/packem_shared/discoverNondeterministicCalls-CEOjmfk4.mjs +0 -122
  112. package/dist/packem_shared/discoverQueries-DeVBQVAG.mjs +0 -62
  113. package/dist/packem_shared/discoverR2sqlCalls-CWCAU-xJ.mjs +0 -80
  114. package/dist/packem_shared/discoverRlsMetadata-BL0oukaK.mjs +0 -280
  115. package/dist/packem_shared/discoverSchema-CeXJWVKV.mjs +0 -874
  116. package/dist/packem_shared/discoverStorageRulesMetadata-CFHByjIl.mjs +0 -97
  117. package/dist/packem_shared/emitApp-BUCrHOeI.mjs +0 -685
  118. package/dist/packem_shared/formatAdvisories-C9wNBNvL.mjs +0 -113
  119. package/dist/packem_shared/parse-validator-D6zI2i85.mjs +0 -134
  120. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  121. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  122. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,1454 @@
1
+ import{LunoraError as Rt}from"@lunora/errors";import{serializeSchemaSnapshot as xt,hashSchemaSnapshot as At}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Ot,isD1GlobalTable as Dt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Tt}from"./json-data-Chfs2Cz5.mjs";import{r as L,e as Et,a as Lt,b as Ct,c as It,d as _t,f as Mt,g as Pt,h as Nt,i as $t,j as qt,k as Ft,l as Ut,m as Bt,n as Wt,o as jt,p as Ht,q as Vt}from"./shard-runtime-CkTgY8tL.mjs";import{u as K,i as Kt,G as Gt,d as Qt}from"./shared-DnCokNcE.mjs";import{p as zt}from"./platform-8oj7iXQy.mjs";import{i as Jt}from"./schema-BgM8A3XV.mjs";const h=(n,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${e}); })()`,te=["categories","description","facing","level","remediation","title"],Yt=n=>{const e={};return{advisoryRows:n.map(a=>{let r=e[a.name];return r||(r=Object.fromEntries(te.filter(s=>s in a).map(s=>[s,a[s]])),e[a.name]=r),Object.fromEntries(Object.entries(a).filter(([s,d])=>!te.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},Xt=` /**
2
+ * 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,
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
+ }`,p=(n="")=>` const writer = this.adminWriter(${n});`,Zt=`${Xt}
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
+ ${p()}
51
+
52
+ return runDataMigration({
53
+ batchSize: args.batchSize,
54
+ direction: args.direction,
55
+ dryRun: args.dryRun,
56
+ 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
+ ${p("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
+ ${p()}
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, { batchSize: args.batchSize, tables: args.tables })) {
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
+ ${p()}
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, { rows: args.rows, startLine: args.startLine });
161
+ }
162
+
163
+ protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
164
+ this.ensureMigrated();
165
+
166
+ ${p()}
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
+ ${p()}
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
+ { cursor: args.cursor, depth: args.depth, direction: args.direction, edges: args.edges, limit: args.limit },
196
+ );
197
+ }
198
+
199
+ protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
200
+ this.ensureMigrated();
201
+
202
+ ${p()}
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
+ after: args.after,
214
+ cursor: args.cursor,
215
+ partitionKey: args.partitionKey,
216
+ take: args.take,
217
+ });
218
+ }
219
+
220
+ protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
221
+ this.ensureMigrated();
222
+
223
+ ${p()}
224
+
225
+ await applyCdcChanges(writer, args.changes);
226
+
227
+ return { applied: args.changes.length };
228
+ }`,er=({actionOnlyBuild:n,actionOnlyFields:e,agentsBuild:t,agentsContextField:a,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:m,everyContextField:f,facadeBlock:c,globalDatabaseLine:y,notifyBuild:S,ormContextField:w,paymentsBuild:C,paymentsContextField:i,queuesBuild:g,queuesContextField:I,topicsBuild:_,topicsContextField:M,vectorsBuild:A,vectorsContextField:P,workflowsBuild:N,workflowsContextField:R})=>{const l=e.length>0,O=l?`
229
+ // ActionCtx-only helpers (external, non-deterministic I/O): constructed
230
+ // and attached only for an \`action\` so query/mutation ctx never carry them.
231
+ if (isAction) {
232
+ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(k=>` ctx.${k} = ${k};`).join(`
233
+ `)}
234
+ }
235
+ `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; kind?: "query"; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
236
+ const env = (this.env ?? {}) as Record<string, unknown>;
237
+ // The caller context this ctx runs under, resolved ONCE on one
238
+ // discriminant. When the caller threads an explicit identity
239
+ // (subscription seed / refresh / stream pull / shape resolve — all
240
+ // deferred or interleaved), it is used by value and the shared
241
+ // per-request fields are never read, because a concurrent RPC owns
242
+ // them: a refresh in particular runs inside the writing dispatch's
243
+ // \`flushChangedTables\`, BEFORE its \`endDispatch\`, so \`getCurrentIp()\`
244
+ // there is the MUTATING caller's address. Otherwise (the synchronous
245
+ // RPC dispatch path) it falls back to those fields as before.
246
+ //
247
+ // One expression, not one per field: three parallel ternaries on the
248
+ // same discriminant is how \`ip\` came to be the only one still reading
249
+ // the shared field.
250
+ const caller: SubscriptionIdentity = options.identity ?? {
251
+ identity: this.getCurrentIdentity(),
252
+ ip: this.getCurrentIp(),
253
+ userId: this.getCurrentUserId(),
254
+ };
255
+ const { identity, ip, userId } = caller;
256
+ ${A}${m}${r}${N}${g}${_}${t}
257
+ // Which dispatch this ctx belongs to. Drives the two deferral facades
258
+ // below and the \`ctx.run*\` caller guard; a ctx built for an
259
+ // admin/lifecycle path has no registered function, and so no kind. An
260
+ // untracked \`ctx.runQuery\` overrides it with \`"query"\`: the sub-query
261
+ // keeps the caller's \`functionPath\` for attribution but runs as a query.
262
+ const contextKind = options.kind ?? LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind;
263
+ // \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
264
+ // reaches through, and pending jobs live in the SchedulerDO — nothing the
265
+ // CDC changelog records — so reading them must forfeit a delta resume.
266
+ // The scheduler's own \`runAfter\`/\`runAt\`/\`cancel\` are writes and stay unstamped.
267
+ const schedulerBase = markUnvouchableReads((config.scheduler?.(env) ?? schedulerStub) as SchedulerLike, options.onRead, ["get", "list"]);
268
+ // \`ctx.scheduler.runAfter(0, ...)\` is documented as the deterministic
269
+ // equivalent of an \`afterCommit\` hook, and the SchedulerDO persists the
270
+ // job the moment it is called — so inside a mutation the call is BUFFERED
271
+ // and replayed after the transaction commits (a rollback drops it).
272
+ // Wrapped on the same dispatches as the deferred-delete queue and for the
273
+ // same reason: \`ctx.runMutation\` hands the CALLER's ctx to the callee, so
274
+ // a mutation reached from an action schedules through the action's ctx.
275
+ // An action's own schedules stay immediate — the window is only open
276
+ // while a transaction is (see \`runMutationTransaction\`).
277
+ //
278
+ // Every kind but \`query\` is wrapped, because \`runMutationTransaction\`
279
+ // is installed on \`ctx.runMutation\` for every kind but \`query\`: a
280
+ // STREAM ctx, and an admin/lifecycle ctx with no registered kind at all,
281
+ // both get the BEGIN/COMMIT span for a mutation they compose, and used
282
+ // to get it with the deferral missing — so that mutation's job reached
283
+ // the SchedulerDO while its transaction was still open, and survived the
284
+ // rollback. A query cannot host a mutation handler (\`dispatchRun\`
285
+ // refuses it) and its ctx is built on the hot subscription path, so it
286
+ // stays unwrapped.
287
+ //
288
+ // Wrapped OUTSIDE the read-stamping facade so \`get\`/\`list\` stay stamped.
289
+ //
290
+ // \`this.scheduleOutbox()\` is what keeps the buffer honest. Everything
291
+ // between the COMMIT and the scheduler's acknowledgement is outside the
292
+ // transaction, so a failure there leaves writes that are durable and a
293
+ // job that exists nowhere — and the mutation's replay-dedup row committed
294
+ // inside the span, so the client's retry is answered from cache and told
295
+ // it succeeded. The outbox takes custody of each buffered call inside the
296
+ // transaction and releases it once the scheduler has the job; what
297
+ // survives is retried by \`pollScheduleOutbox\` on the shared poll alarm.
298
+ const scheduler = contextKind === "query" ? schedulerBase : withDeferredSchedules(schedulerBase, this.scheduleOutbox());
299
+ // Build the storage adapter once and share it between \`ctx.storage\`
300
+ // and \`ctx.db.system._storage\` so both read the same R2 binding. The
301
+ // \`storageStub\` fallback satisfies SystemReaderStorageLike structurally
302
+ // (its \`list\`/\`getMetadata\` throw the "no storage configured" error).
303
+ //
304
+ // Wrapped BEFORE the split so both consumers share one stamping facade.
305
+ // Only the methods that actually reach R2 are stamped: \`getUrl\` and
306
+ // \`getSignedUrl\` build a URL from the configured base (and an HMAC) and
307
+ // read nothing, and they are what handlers overwhelmingly call — stamping
308
+ // them would forfeit resumes for a dependency that cannot move the result.
309
+ // \`bucket\` IS stamped: it hands back a sub-facade this wrapper does not
310
+ // reach, so the selection is the last point at which the read can be seen.
311
+ //
312
+ // The request origin is the storage base fallback for mutations and
313
+ // actions on the synchronous dispatch only. A deferred caller
314
+ // (\`options.identity\` set) runs outside the dispatch that owns the
315
+ // field, the same hazard \`getCurrentIp\` has. A query never gets it: a
316
+ // live query re-runs with no request behind it, and the reactive
317
+ // cache does not key on the host, so a query that signs URLs needs a
318
+ // declared \`publicBaseUrl\` either way.
319
+ const requestOrigin = contextKind !== "query" && options.identity === undefined ? this.getCurrentOrigin() : undefined;
320
+ const makeStorage = (origin?: string): SystemReaderStorageLike =>
321
+ markUnvouchableReads(asBucketStorage(config.storage?.(env, origin) ?? storageStub) as SystemReaderStorageLike, options.onRead, [
322
+ "bucket",
323
+ "download",
324
+ "getMetadata",
325
+ "list",
326
+ ]);
327
+ const storage = makeStorage(requestOrigin);
328
+ // \`ctx.storage.deleteAfterCommit(key)\`, on every dispatch that can host
329
+ // a MUTATION handler — which is not only a mutation dispatch:
330
+ // \`ctx.runMutation\` hands the CALLER's ctx to the callee, so a mutation
331
+ // reached from an action runs on the action's ctx. Wrapping mutations
332
+ // alone made that composition throw a bare TypeError on a method the
333
+ // handler's own type promises. Queries stay unwrapped: they cannot host
334
+ // one, and their ctx is built on the hot subscription path.
335
+ //
336
+ // Every dispatch wrapped here also flushes (see \`handleRpc\` and
337
+ // \`runReactor\`) — a queue nothing drains leaks silently, which is worse
338
+ // than not having the method at all.
339
+ //
340
+ // Wrapped OUTSIDE the read-stamping facade so \`bucket(name)\` still
341
+ // resolves through it and stays stamped, and applied only to
342
+ // \`ctx.storage\` so \`ctx.db.system._storage\` (which shares the adapter
343
+ // above) is untouched.
344
+ const contextStorage = contextKind === "mutation" || contextKind === "action" ? withDeferredDeletes(storage) : storage;
345
+ // \`ctx.log\`: the DO base builds the attributed logger (structured
346
+ // fields + \`.with(...)\` child + trace correlation) and routes each call
347
+ // to the optional \`observability\` sink. It also buffers the line (studio
348
+ // Logs panel) and emits a structured console event the dev-server formats.
349
+ //
350
+ // Resolved BEFORE \`ctx.db\` below, because the database is wrapped in
351
+ // auto-instrumentation that needs the sink, the trace anchor, and the
352
+ // dispatch's wide-event handle.
353
+ const observability = config.observability?.(env);
354
+ const logFunctionPath = options.functionPath ?? "";
355
+ const log = this.makeLogger(logFunctionPath, observability);
356
+ const traceAnchor = this.resolveDispatchAnchor(Boolean(options.identity));
357
+
358
+ // \`ctx.span\`: the handle onto the DISPATCH's own span — the wide-event
359
+ // surface. Attributes attached here accumulate for the whole request
360
+ // and are folded into the one span it already emits, instead of
361
+ // becoming N separate log lines. Shares \`traceAnchor\` with \`ctx.trace\`
362
+ // so both write to the same trace.
363
+ const span = this.makeDispatchSpan(traceAnchor, observability);
364
+
365
+ ${y} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
366
+ // adds aggregate counters (call count, total time, per-operation
367
+ // breakdown) to the wide event rather than a span per call, so a
368
+ // handler making hundreds of queries stays readable. See
369
+ // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
370
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
371
+ ${c}${C}
372
+
373
+ // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
374
+ // The trace anchor is threaded explicitly for the same reason \`identity\`
375
+ // is — a deferred caller (a subscription re-run) must not inherit the
376
+ // writing mutation's trace from the shared per-request field.
377
+ const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
378
+ const metrics = this.makeMetrics(logFunctionPath, observability);
379
+ ${S}
380
+ // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
381
+ // captured ONCE so the whole handler body sees a single stable value.
382
+ // A \`query\` handler is re-run by every live subscription that reads it,
383
+ // so \`Date.now()\` there flickers between re-evaluations. A \`mutation\`
384
+ // handler does not replay under ordinary dispatch (an OCC conflict throws
385
+ // to the caller rather than retrying internally), but one called from a
386
+ // workflow step or queue consumer runs again when that step replays. Both
387
+ // read time through \`ctx.now\` — the \`nondeterministic_query_mutation\`
388
+ // advisor flags \`Date.now()\`. Actions may still use ambient \`Date.now()\`.
389
+ const now = Date.now();
390
+
391
+ const ctx: Record<string, unknown> = {
392
+ auth: {
393
+ getIdentity: async () => identity ?? null,
394
+ userId: userId ?? null,
395
+ },
396
+ db,
397
+ // \`ctx.newId()\`: a replay of the same top-level mutation gets the same ids. A nested or
398
+ // subscription-driven build (\`options.identity\`) is not a replay.
399
+ // A replay key only means something inside the caller's dedup namespace; without one the call is not
400
+ // deduplicated, so its ids stay random.
401
+ newId: createStableIdFactory(
402
+ options.identity === undefined && this.idempotencyNamespace() !== undefined ? this.getCurrentMutationId() : undefined,
403
+ JSON.stringify([this.currentShardKey(), options.functionPath ?? "", this.idempotencyNamespace() ?? "", userId ?? ""]),
404
+ ),
405
+ // Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
406
+ // \`traceparent\` propagation, so time spent in a downstream service
407
+ // is visible and its spans join this trace. Degrades to the bare
408
+ // global when no sink is configured.
409
+ fetch: this.makeFetch(logFunctionPath, traceAnchor, observability),
410
+ // A GETTER, not a plain field, so the reactive cache can tell a
411
+ // handler that reads the caller's address from the majority that
412
+ // never do. \`ctx.ip\` is per-request state the memo must be keyed
413
+ // by — otherwise two anonymous callers share one entry and the
414
+ // second is served the first's address — but keying every entry
415
+ // by address would shard the cache per client for every query.
416
+ // Reading it here marks the dispatch's scope; \`runCachedQuery\`
417
+ // folds the address into the key for this function from then on.
418
+ get ip() {
419
+ options.scope?.markIpRead();
420
+
421
+ return ip;
422
+ },
423
+ log,
424
+ metrics,
425
+ now,
426
+ // The same request origin the storage fallback above uses, handed
427
+ // to the handler so code that signs its own URLs (a copy-in
428
+ // \`createStorage\`) can fall back to it too. \`undefined\` for a
429
+ // query and for a deferred dispatch, for the reasons given there.
430
+ origin: requestOrigin,${w}
431
+ scheduler,
432
+ span,
433
+ storage: contextStorage,
434
+ trace,${P}${f}${i}${s}${R}${I}${M}${a}
435
+ };
436
+ ${l?` const isAction = contextKind === "action";
437
+ `:""}${O}
438
+ const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
439
+ target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind);
440
+ // The composed mutation runs under the SAME wrapper the top-level RPC
441
+ // uses, so "do the transactional work in a mutation and call it from the
442
+ // action" — the recipe the docs give for atomicity — actually is atomic.
443
+ target.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) =>
444
+ dispatchRun("mutation", reference.__lunoraRef, fnArgs, target, kind, async (work) => this.runMutationTransaction(target, work));
445
+ // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
446
+ // its OWN query context, built without the subscription's read-footprint
447
+ // hooks — so its reads never enter this subscription's footprint and a
448
+ // write to the tables it touched does not re-run us. Everything else is
449
+ // inherited: \`functionPath\` (log/metric attribution), \`headroom\` (the
450
+ // sub-query must not escape this dispatch's resource ceiling),
451
+ // \`scope\` (the reactive-cache capture — an untracked sub-query's reads
452
+ // must still be deps of the entry the OUTER query is memoized as, or
453
+ // the memo goes stale), and — load-bearing — the resolved \`caller\` BY VALUE
454
+ // (identity, userId AND ip). Omitting it would let \`buildCtx\` fall back
455
+ // to the shared per-request fields, which a concurrent RPC may have
456
+ // re-set, and an RLS-scoped sub-query would then read as the wrong user
457
+ // from the wrong address. A tracked call runs on \`queryContext()\` below.
458
+ target.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>, runOptions?: { untracked?: boolean }) =>
459
+ dispatchRun(
460
+ "query",
461
+ reference.__lunoraRef,
462
+ fnArgs,
463
+ runOptions?.untracked === true
464
+ ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope })
465
+ : queryContext(),
466
+ kind,
467
+ );
468
+ };
469
+
470
+ // A query composed from a mutation or action runs on a QUERY view of
471
+ // this ctx, so it behaves exactly as it does when called directly or
472
+ // live: same \`db\`, read hooks, trace and \`now\`, but every field that
473
+ // depends on the dispatch kind or the request origin is re-derived for a
474
+ // query — no \`ctx.origin\`, storage with no origin fallback (and no
475
+ // \`deleteAfterCommit\`), the unwrapped scheduler, no ActionCtx-only
476
+ // helpers, and a \`run*\` guard that refuses a mutation or action. A new
477
+ // kind- or origin-dependent ctx field must be overridden here too.
478
+ // Copied by descriptor so the \`ip\` getter is carried over, not read.
479
+ // Built on the first composed call only; a query ctx is its own view.
480
+ let queryView: Record<string, unknown> | undefined;
481
+ const queryContext = (): Record<string, unknown> => {
482
+ if (contextKind === "query") {
483
+ return ctx;
484
+ }
485
+
486
+ if (queryView === undefined) {
487
+ const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
488
+ ${e.map(k=>` delete descriptors.${k};
489
+ `).join("")} // Writable and configurable, like the plain fields they replace.
490
+ const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
491
+
492
+ queryView = Object.defineProperties({}, {
493
+ ...descriptors,
494
+ origin: field(undefined),
495
+ scheduler: field(schedulerBase),
496
+ storage: field(makeStorage()),
497
+ }) as Record<string, unknown>;
498
+ installRun(queryView, "query");
499
+ }
500
+
501
+ return queryView;
502
+ };
503
+
504
+ installRun(ctx, contextKind);
505
+
506
+ return ctx;
507
+ }`},tr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
508
+ // referencing call fails loudly with a clear error instead of overflowing the
509
+ // stack. Tracked across the awaited handler chain (one DO invocation is
510
+ // single-threaded), so the counter reflects true nesting depth.
511
+ const MAX_RUN_DEPTH = 32;
512
+ let runDepth = 0;
513
+
514
+ const dispatchRun = async (
515
+ expected: FunctionKind,
516
+ functionPath: string,
517
+ args: Record<string, unknown>,
518
+ ctx: unknown,
519
+ // The kind of the context making the call, and — for a mutation target — the
520
+ // transaction wrapper to run it under. Both are supplied by \`buildCtx\`, which
521
+ // is the only place that knows which dispatch this \`ctx\` belongs to. Widened
522
+ // past \`FunctionKind\` because the registry also carries \`"stream"\`, and
523
+ // \`undefined\` for a ctx built outside a registered function (admin, migration).
524
+ callerKind?: "stream" | FunctionKind,
525
+ runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
526
+ ): Promise<unknown> => {
527
+ // A query is read-only. The ctx object installs \`run*\` on every kind (one
528
+ // shape, built once), so the TYPE is all that stops a query from writing —
529
+ // and a cast walks straight past it, inside a subscription re-run that can
530
+ // execute many times per write. Checked on the CALLER, before the registry
531
+ // lookup, so \`ctx.runMutation\` from a query fails identically whatever it
532
+ // aimed at.
533
+ if (callerKind === "query" && expected !== "query") {
534
+ throw new LunoraError(
535
+ "RUN_KIND_FORBIDDEN",
536
+ \`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: a query may only compose other queries (tried to run "\${functionPath}")\`,
537
+ );
538
+ }
539
+
540
+ const registered = LUNORA_FUNCTIONS[functionPath];
541
+
542
+ if (!registered) {
543
+ throw new Error(\`unknown function: \${functionPath}\`);
544
+ }
545
+
546
+ if (registered.kind !== expected) {
547
+ throw new Error(\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: "\${functionPath}" is registered as a \${registered.kind}, not a \${expected}\`);
548
+ }
549
+
550
+ if (runDepth >= MAX_RUN_DEPTH) {
551
+ throw new LunoraError("RUN_DEPTH_EXCEEDED", \`ctx.run*: composition depth limit (\${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation\`);
552
+ }
553
+
554
+ runDepth += 1;
555
+
556
+ try {
557
+ // A mutation composed from an action (or an http action) is the shape the
558
+ // docs prescribe for atomicity — "do the transactional reads and writes in
559
+ // a mutation and call it from the action". It only holds if the composed
560
+ // dispatch gets the same BEGIN/COMMIT span and single-writer gate the
561
+ // top-level mutation path gets; without it every write autocommits and a
562
+ // mid-handler throw leaves the earlier ones durable. A \`runMutation\` from
563
+ // inside a mutation rides the enclosing span instead of opening a second
564
+ // one (see \`runMutationTransaction\`).
565
+ if (runTransactional) {
566
+ return await runTransactional(async () => registered.handler(ctx, args));
567
+ }
568
+
569
+ return await registered.handler(ctx, args);
570
+ } finally {
571
+ runDepth -= 1;
572
+ }
573
+ };`,rr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
574
+ const registered = LUNORA_FUNCTIONS[functionPath];
575
+
576
+ // Internal functions are reachable server-side only: via \`ctx.run*\`
577
+ // composition, or a trusted system dispatch (scheduler/cron, marked by
578
+ // \`isSystemDispatch()\`). A client RPC never carries that flag, so its
579
+ // internals stay not-found and never leak across the external boundary.
580
+ if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) {
581
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
582
+ }
583
+
584
+ this.ensureMigrated();
585
+
586
+ // \`headroom\`, when the caller supplied one, is threaded straight
587
+ // through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
588
+ // fallback (the racy shared-field read) entirely for THIS dispatch.
589
+ // The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
590
+ // \`handleRunAs\` don't mint their own and omit it, so they keep the
591
+ // prior fallback behavior unchanged.
592
+ //
593
+ // \`scope\` is the reactive cache's per-dispatch read capture, threaded
594
+ // the same way and for the same reason: the ctx-db read hooks resolve
595
+ // their tracker at READ time, so binding them to the scope THIS
596
+ // dispatch was handed is what keeps a concurrent query's reads out of
597
+ // our dep set — and ours out of theirs. A dispatch with no scope (a
598
+ // mutation, an action, a cache-less shard) builds unbound hooks that
599
+ // stamp no deps.
600
+ const ctx = this.buildCtx({ bookmarks, functionPath, headroom, scope, trusted: registered.lifecycle === "init" });
601
+
602
+ // A mutation's writes must commit all-or-nothing, so its dispatch runs
603
+ // under \`runMutationTransaction\` — the ONE place that opens the span,
604
+ // settles the deferred schedules and flushes the deferred deletes. The
605
+ // same helper backs \`ctx.runMutation\` and \`runReactor\`, because a
606
+ // mutation reached by composition is promised exactly these guarantees
607
+ // and used to get none of them.
608
+ //
609
+ // The replay bookkeeping (idempotency dedup row + custom-mutator
610
+ // watermark advance) commits INSIDE the span via
611
+ // \`commitMutationBookkeeping\`, so the writes, the dedup row, and the
612
+ // watermark are atomic — a crash can't leave the writes durable without
613
+ // the replay guard. It is deliberately NOT in the shared helper: it is
614
+ // per-REQUEST bookkeeping, and a composed sub-mutation has no request of
615
+ // its own to record.
616
+ if (registered.kind === "mutation") {
617
+ return await this.runMutationTransaction(ctx, async () => {
618
+ const value = await registered.handler(ctx, args);
619
+
620
+ this.commitMutationBookkeeping(value);
621
+
622
+ return value;
623
+ });
624
+ }
625
+
626
+ const result = await registered.handler(ctx, args);
627
+
628
+ // An action is not itself transactional, but \`ctx.runMutation\` runs its
629
+ // submutations on THIS ctx, so anything they queued after their own
630
+ // transaction settled lands here. A dispatch with nothing queued no-ops.
631
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
632
+
633
+ return result;
634
+ }
635
+
636
+ /**
637
+ * Run one mutation handler with the atomicity every caller of a mutation is
638
+ * promised: a BEGIN/COMMIT span (with the single-writer gate
639
+ * \`ShardRunner.runInTransaction\` composes in front of it), scheduled jobs
640
+ * held until that span commits, and the deferred object deletes flushed
641
+ * only once it has.
642
+ *
643
+ * Shared by the three entry points that dispatch a mutation handler — the
644
+ * top-level RPC, \`ctx.runMutation\` from an action or http action, and a
645
+ * reactor — because the guarantee is a property of the mutation, not of how
646
+ * it was reached. The docs tell users to put the transactional part in a
647
+ * mutation and call it from the action precisely so that composition is
648
+ * atomic.
649
+ *
650
+ * A \`ctx.runMutation\` issued from inside a mutation is NESTED: SQLite-in-DO
651
+ * has no savepoints and \`runInTransaction\` rejects a second open, so it
652
+ * rides the enclosing span, which also owns its commit and therefore its
653
+ * scheduler flush.
654
+ *
655
+ * Both deferral windows are opened here and settled against the SAME
656
+ * outcome. The delete window is what keeps a composed mutation's queued
657
+ * object deletes off the caller's flush when it rolls back: \`ctx\` is
658
+ * shared, so without a window the keys are indistinguishable from the
659
+ * action's own and the action's flush destroys objects whose rows the
660
+ * rollback put back.
661
+ */
662
+ private async runMutationTransaction<T>(ctx: unknown, work: () => Promise<T>): Promise<T> {
663
+ const settleSchedules = beginDeferredSchedules(ctx as { scheduler?: unknown });
664
+ // Synchronous and non-throwing (it only moves queue entries), so it can
665
+ // settle first on every path and cannot mask the outcome.
666
+ const settleDeletes = beginDeferredDeletes(ctx);
667
+
668
+ if (this.isInTransaction()) {
669
+ try {
670
+ const nested = await work();
671
+
672
+ settleDeletes(true);
673
+ await settleSchedules(true);
674
+
675
+ return nested;
676
+ } catch (error) {
677
+ settleDeletes(false);
678
+ await settleSchedules(false);
679
+
680
+ throw error;
681
+ }
682
+ }
683
+
684
+ let result: T;
685
+
686
+ try {
687
+ result = await this.runInTransaction(work);
688
+ } catch (error) {
689
+ // The span rolled back, so the rows are gone and the jobs that were
690
+ // to run "after I commit" must go with them. Dropping them is the
691
+ // whole point of buffering: a persisted job for a write that never
692
+ // landed fires against state that does not exist.
693
+ //
694
+ // The queued object deletes go the same way, and for a sharper
695
+ // reason: the rows they were to clean up after are still there, and
696
+ // an R2 delete cannot be undone.
697
+ settleDeletes(false);
698
+ await settleSchedules(false);
699
+
700
+ throw error;
701
+ }
702
+
703
+ // Committed, so this span's queued keys join whatever the flush below
704
+ // (or an enclosing span's) will drain.
705
+ settleDeletes(true);
706
+
707
+ // Committed. Schedules first and AWAITED: \`runAfter(0, ...)\` is
708
+ // documented as the deterministic equivalent of an \`afterCommit\` hook,
709
+ // so the job must be enqueued after the commit, and a failure to enqueue
710
+ // it must be visible rather than swallowed.
711
+ //
712
+ // In a \`finally\`, because both halves of this are post-commit cleanup
713
+ // and neither is allowed to cancel the other. \`settleSchedules\` drains
714
+ // its whole queue and then rethrows what failed, so a SchedulerDO that
715
+ // refused one job used to take the object cleanup down with it — the
716
+ // rows were durably gone and their objects leaked with nothing logged.
717
+ try {
718
+ await settleSchedules(true);
719
+ } finally {
720
+ // Then the objects whose rows are now durably gone. Deliberately AFTER
721
+ // the span, never inside it: an R2 delete cannot roll back, so a delete
722
+ // issued from within a transaction that later aborts destroys data the
723
+ // surviving row still points at.
724
+ //
725
+ // \`flushDeferredDeletes\` never rejects — the mutation has already
726
+ // succeeded, so a failed cleanup must not turn into a failed response.
727
+ // A leaked object is reported through \`ctx.log\` instead, with its key.
728
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
729
+ }
730
+
731
+ return result;
732
+ }
733
+
734
+ // Only a \`mutation\` may enter the base class's single-writer gate for
735
+ // mutation-replay dedup — it is \`blockConcurrencyWhile\`, so gating an
736
+ // action would stall every other dispatch on the shard for the length of
737
+ // its outbound I/O, on nothing but a caller-supplied header. Unregistered
738
+ // paths answer \`false\`; \`handleRpc\` above rejects them anyway.
739
+ protected override isMutationFunction(functionPath: string): boolean {
740
+ return LUNORA_FUNCTIONS[functionPath]?.kind === "mutation";
741
+ }
742
+
743
+ // The scheduler the deferred-schedule outbox retries through. Only the
744
+ // CONFIGURED one: falling back to \`schedulerStub\` would have an app with no
745
+ // scheduler retry every entry against a thrower until the attempt ceiling
746
+ // parked it, and there is nothing to park — an app with no scheduler has no
747
+ // \`ctx.scheduler\` call that reached the buffer in the first place.
748
+ protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
749
+ return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
750
+ }`,ar=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
751
+ const registered = LUNORA_FUNCTIONS[functionPath];
752
+
753
+ if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
754
+ return null;
755
+ }
756
+
757
+ this.ensureMigrated();
758
+
759
+ const footprint = createReadFootprint();
760
+ // Identity is threaded EXPLICITLY from the (deferred/interleaved)
761
+ // subscription caller — never read from the shared per-request field
762
+ // here — so a concurrent RPC can't leak its identity into this re-run.
763
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange });
764
+ const result = await registered.handler(ctx, args);
765
+
766
+ // Ranges come from THIS run's reads, never a shared field on the DO:
767
+ // a deferred re-run interleaves with unrelated dispatches.
768
+ return { ranges: footprint.ranges(), result, tables: footprint.tables };
769
+ }
770
+
771
+ protected override executeStream(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
772
+ const registered = LUNORA_FUNCTIONS[functionPath];
773
+
774
+ if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
775
+ return null;
776
+ }
777
+
778
+ this.ensureMigrated();
779
+
780
+ return {
781
+ ...(registered.durable ? { durable: registered.durable as { ttlMs?: number } } : {}),
782
+ // Identity threaded EXPLICITLY from the socket, exactly as
783
+ // \`executeSubscription\` above: the iterator is pulled after this
784
+ // frame returned, interleaved with unrelated dispatches, so
785
+ // \`buildCtx\`'s per-request fallback would run an \`rls()\` /
786
+ // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
787
+ iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
788
+ };
789
+ }`,nr=n=>{const e={};for(const t of n.tables){const a={};for(const[r,s]of Object.entries(t.shape)){const d=K(s);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(e[t.name]=a)}return e},sr=n=>{const e={};for(const t of n.tables){const a=[];for(const[r,s]of Object.entries(t.shape))K(s).kind==="storage"&&a.push(r);a.length>0&&(e[t.name]=a)}return e},or=n=>{const e={};for(const t of n.tables){const a=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(e[t.name]=a)}return e},ir=n=>{const e=[];for(const t of n.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},dr=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const e=[];for(const t of n.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const a=JSON.parse(t.literalValue);if(typeof a!="string")return;e.push(a)}catch{return}}return e},cr=(n,e,t)=>{const a=K(e),r={name:n,optional:Kt(e),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=t.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const s=dr(a);return s!==void 0&&(r.enumValues=s),a.column?.notNull===!1&&(r.nullable=!0),r},lr=n=>{const e={};for(const t of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))a.push(cr(s,d,r));e[t.name]=a}return e},hr=({hasMutators:n,hasShapes:e,rlsData:t})=>{const a=e?`
790
+ protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
791
+ const shape = LUNORA_SHAPES[name];
792
+
793
+ if (!shape) {
794
+ return undefined;
795
+ }
796
+
797
+ this.ensureMigrated();
798
+
799
+ // Trusted ctx from the socket's OWN verified identity — the client
800
+ // supplies only the shape name + args; \`compileWhere\` validates the
801
+ // args then runs the shape's \`where(ctx, args)\` under that identity,
802
+ // so which rows replicate is a server decision (reads-as-permissions).
803
+ const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity });
804
+ // \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
805
+ // \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
806
+ // rather than every shape restating the ownership check in its \`where\`.
807
+ const shapeWhere = shape.compileWhere(ctx, args, {
808
+ ownerField: (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField,
809
+ }) as unknown as WhereInput;
810
+
811
+ // AND-compose with the read policies this SHAPE declares
812
+ // (\`defineShape({ use: [guard] })\`, pre-indexed into
813
+ // \`shape.rlsRegistry\`). A shape runs no procedure, so the
814
+ // \`.use(rls(...))\` middleware never fires; without this merge its
815
+ // reads would bypass the read policies it opted into.
816
+ // \`composeShapeReadWhere\` evaluates them under this same trusted ctx
817
+ // and fails closed under a \`.rls("required")\` schema for a
818
+ // non-\`.public()\` table the shape declared no read policy for.
819
+ //
820
+ // The registry is the shape's OWN — never one folded from every
821
+ // registered function. A project-wide union let one admin-only
822
+ // procedure's allow-all read policy unrestrict every shape on the
823
+ // table; see the SCOPE note in \`shape-read-base.ts\`.
824
+ //
825
+ // It is NOT identical to the request-time path, and must not be
826
+ // described as such: roles come from the identity's \`roles\` claim
827
+ // only, because no middleware runs here to contribute
828
+ // \`ctx.auth.roles\`. Derive roles at the identity if a policy gates
829
+ // on them — see \`shape-read-base.ts\`.
830
+ const effectiveWhere = composeShapeReadWhere(shape.rlsRegistry, {
831
+ ctx,
832
+ identity: identity?.identity ?? null,
833
+ rlsRequired: (schema as unknown as { rlsMode?: string }).rlsMode === "required",
834
+ shapeWhere,
835
+ table: shape.table,
836
+ tablePublic: (schema as unknown as { tables: Record<string, { isPublic?: boolean }> }).tables[shape.table]?.isPublic === true,
837
+ userId: identity?.userId ?? null,
838
+ });
839
+
840
+ // A live shape pokes only from its OWN shard's op-log, so a \`where()\`
841
+ // that joins to a \`.shardBy()\` table (rows in another DO) is rejected
842
+ // here — the first point the compiled predicate + shard modes are both
843
+ // known. Remedy: denormalize, or move the joined table to \`.global()\`.
844
+ assertShapeShardable(effectiveWhere, schema as unknown as SchemaLike, shape.table);
845
+
846
+ // A \`.global()\` table lives in D1 (no per-DO op-log): flag it so the
847
+ // base serves it through the latency-tiered poll path (\`readGlobalShapeRows\`)
848
+ // instead of the CDC poke path.
849
+ const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global";
850
+
851
+ return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
852
+ }
853
+ `:"",r=e?[...new Set(t.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,y)=>c.localeCompare(y)):[],s=r.length>0?`
854
+ /** Refuses to boot a shape that would replicate around the read policies its table is governed by (\`defineShape({ use })\` is how a shape opts in; \`use: []\` acknowledges an ungoverned one). */
855
+ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
856
+ `:"";return{customMutatorOverride:n?`
857
+ protected override isCustomMutator(functionPath: string): boolean {
858
+ return LUNORA_MUTATOR_PATHS.has(functionPath);
859
+ }
860
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},ur=(n,e)=>n?`
861
+ protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
862
+ const env = this.env as Record<string, unknown>;
863
+ // A shape read performs no writes, so the widened request only needs
864
+ // the inbound bookmark (pin the membership drain to the caller's own
865
+ // prior writes) — no \`onBookmark\` here.
866
+ //
867
+ // The two identity members are named rather than spread, matching the
868
+ // dispatch-path request built in \`buildCtx\`. A spread would also hand
869
+ // the global writer \`ip\`, and \`globalShapeReadKey\` — the per-flush
870
+ // cache in front of this read — keys on identity + userId only. Equal
871
+ // keys must mean equal rows, so a field the writer can scope by has to
872
+ // be either in the key or out of the request; it is out.
873
+ const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity: identity?.identity, userId: identity?.userId };
874
+ const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
875
+ const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
876
+
877
+ let cursor: null | string = null;
878
+
879
+ // Drain every page of the global membership so the seed/diff sees the
880
+ // full rowset (D1 \`findMany\` is paginated). Stop one row past the cap:
881
+ // a broad \`.global()\` shape would otherwise materialize an unbounded
882
+ // array before the caller's \`withinGlobalShapeBound\` check rejects it,
883
+ // so bail early and let the caller fail it closed.
884
+ do {
885
+ // eslint-disable-next-line no-await-in-loop -- sequential page drain to assemble the full membership
886
+ const page = await globalDb.findMany(resolved.table, { cursor, where: resolved.effectiveWhere });
887
+
888
+ for (const doc of page.page) {
889
+ rows.push({ doc, id: String((doc as { _id?: unknown })._id) });
890
+
891
+ if (rows.length > ShardDOBase.GLOBAL_SHAPE_MAX_ROWS) {
892
+ return rows;
893
+ }
894
+ }
895
+
896
+ cursor = page.isDone ? null : page.continueCursor;
897
+ } while (cursor !== null);
898
+
899
+ return rows;
900
+ }
901
+
902
+ protected override async readGlobalChangedTables(sinceSeq: number, cursorOnly?: boolean): Promise<{ cursor: number; floor?: number; tables: string[] } | undefined> {
903
+ const env = this.env as Record<string, unknown>;
904
+ // Metadata-only: this asks the global changelog which TABLES moved,
905
+ // never what changed in them, so it costs one small read per poll tick
906
+ // for the whole shard — and a tick whose answer omits a shape's table
907
+ // skips that shape's membership drain entirely.
908
+ // Named local, not an inline object literal — same reason as the
909
+ // dispatch path and \`readGlobalShapeRows\`: \`bookmark\` is not declared
910
+ // on the narrower Hyperdrive thunk's \`request\` type, and an inline
911
+ // literal trips an excess-property error (TS2353) that makes the
912
+ // emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
913
+ // a \`defineShape\`. The Hyperdrive factory simply never reads it.
914
+ const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
915
+ const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
916
+
917
+ return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
918
+ }
919
+ `:"",pr=n=>({externalSourceOverride:n?`
920
+ protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
921
+ const env = (this.env ?? {}) as Record<string, unknown>;
922
+ const sourced = Object.entries((schema as unknown as SchemaLike).tables)
923
+ .map(([table, definition]) => [table, (definition as { externalSource?: ExternalSourceLike }).externalSource] as const)
924
+ .filter((entry): entry is [string, ExternalSourceLike] => entry[1] !== undefined);
925
+
926
+ if (sourced.length === 0) {
927
+ return undefined;
928
+ }
929
+
930
+ const shardKey = this.currentShardKey();
931
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
932
+
933
+ let clients = sourceClientCache.get(this);
934
+
935
+ if (clients === undefined) {
936
+ clients = new Map();
937
+ sourceClientCache.set(this, clients);
938
+ }
939
+
940
+ let polledAt = sourcePollAtCache.get(this);
941
+
942
+ if (polledAt === undefined) {
943
+ polledAt = new Map();
944
+ sourcePollAtCache.set(this, polledAt);
945
+ }
946
+
947
+ const now = Date.now();
948
+ // \`nextDueAt\` tracks the EARLIEST next-due timestamp across every
949
+ // non-manual source; the shared alarm re-arms there instead of the
950
+ // fixed 2 s global-shape floor, so a large \`refresh.everyMs\` actually
951
+ // sleeps until it's due. Stays \`undefined\` when every source is
952
+ // \`refresh: "manual"\`, so the shared alarm goes idle for this tier.
953
+ let nextDueAt: number | undefined;
954
+
955
+ for (const [table, source] of sourced) {
956
+ if (source.refresh === "manual") {
957
+ continue;
958
+ }
959
+
960
+ if (isSourceDue(source.refresh, polledAt.get(table), now)) {
961
+ try {
962
+ let client = clients.get(source.binding);
963
+
964
+ if (client === undefined) {
965
+ client = config.sourceClient?.(env, source.binding);
966
+
967
+ if (client !== undefined) {
968
+ clients.set(source.binding, client);
969
+ }
970
+ }
971
+
972
+ if (client === undefined) {
973
+ // No SqlClient resolved for this binding (host never wired
974
+ // \`config.sourceClient\`, or wired it wrong). Surface it in the
975
+ // Logs panel and stamp \`polledAt\` so a persistent misconfig backs
976
+ // off to \`refresh.everyMs\` instead of retrying every alarm tick.
977
+ this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`), trace);
978
+ } else {
979
+ // A FRESH tracker per TABLE, not one shared across the whole
980
+ // loop: one table's runaway pull must not spend a budget a
981
+ // sibling table needs, and a limit hit here must not block
982
+ // that sibling from getting its own full budget this tick.
983
+ const writer = createShardCtxDb({
984
+ // Admin and maintenance writes go through the SAME reactive-cache hooks as
985
+ // a user mutation. Without this, a studio row edit, a TTL sweep, an admin
986
+ // import, a CDC apply or a data-migration backfill writes without
987
+ // invalidating, and the next query answers from the pre-write snapshot.
988
+ ...this.ctxDbTuning(),
989
+ broadcast: (delta) => {
990
+ this.recordChangedTable(delta.table, delta.indexKeys);
991
+ },
992
+ cdc: config.cdc ?? false,
993
+ headroom: this.alarmHeadroom(),
994
+ scheduler,
995
+ schema: schema as unknown as SchemaLike,
996
+ sql: this.sql as SqlExec,
997
+ });
998
+
999
+ if (source.mode === "incremental") {
1000
+ // Incremental (plan 136): pull only rows past the durable
1001
+ // watermark (or a full-pull seed/reconcile), upsert-only.
1002
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
1003
+ await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
1004
+ } else {
1005
+ // 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
1006
+ await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
1007
+ }
1008
+ }
1009
+
1010
+ // Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
1011
+ // poll that outruns \`everyMs\` must not make \`nextDueAt\` (below)
1012
+ // stale-immediate and re-arm the alarm in a hammering loop.
1013
+ polledAt.set(table, Date.now());
1014
+ } catch (error) {
1015
+ if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
1016
+ // Batch full, not a genuine failure. Incremental mode only
1017
+ // persists its watermark AFTER a full apply (see
1018
+ // \`pullExternalSourceIncrementalTick\`), so this throw left it
1019
+ // untouched — the next tick safely re-pulls/re-applies the
1020
+ // SAME slice (idempotent upsert). Full-pull mode (and an
1021
+ // incremental source's own occasional full-pull/reconcile
1022
+ // sweep) has no resumable cursor at all — deliberately not
1023
+ // inventing one here; a retry just redoes the whole pull,
1024
+ // safe if wasteful. Either way: warn instead of
1025
+ // \`recordExternalSourceError\`, and leave \`polledAt\`
1026
+ // UNCHANGED (skip the stamp below via \`continue\`) so this
1027
+ // table stays "due" and \`nextPollAlarmTarget\`'s existing
1028
+ // due-now floor re-arms the shared alarm promptly — not a
1029
+ // fresh \`setAlarm(now)\`.
1030
+ this.recordExternalSourceWarning(
1031
+ table,
1032
+ \`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
1033
+ trace,
1034
+ );
1035
+
1036
+ nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
1037
+
1038
+ continue;
1039
+ }
1040
+
1041
+ this.recordExternalSourceError(table, error, trace);
1042
+ // Stamp on failure too, so a persistently failing source throttles
1043
+ // to \`refresh.everyMs\` rather than being hammered every tick.
1044
+ polledAt.set(table, Date.now());
1045
+ }
1046
+ }
1047
+
1048
+ // This source's own next-due time, read AFTER the poll-or-skip above
1049
+ // so a just-polled source reports \`now + everyMs\` (its FRESH due
1050
+ // time), not the stale pre-poll one. An omitted \`refresh\` (poll
1051
+ // every tick) is due again immediately.
1052
+ const sourceNextDueAt = source.refresh === undefined ? now : (polledAt.get(table) ?? now) + source.refresh.everyMs;
1053
+
1054
+ nextDueAt = nextDueAt === undefined ? sourceNextDueAt : Math.min(nextDueAt, sourceNextDueAt);
1055
+ }
1056
+
1057
+ return nextDueAt;
1058
+ }
1059
+ `:"",sourceBootstrap:n?`
1060
+ const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1061
+ const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1062
+
1063
+ return source !== undefined && source.refresh !== "manual";
1064
+ });
1065
+
1066
+ if (autoSourced) {
1067
+ void this.scheduleSourcePoll();
1068
+ }
1069
+ `:"",sourceClientCacheConst:n?`
1070
+ const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1071
+ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1072
+ `:""}),mr=(n,e)=>{const t=e.length>0,r=n?L("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
1073
+ `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",f=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=n?`
1074
+ const vectorSync = this.vectorSync(env);
1075
+ // Vectorize lives outside this shard's SQLite, so a query whose result
1076
+ // depends on a similarity search cannot be proven current on reconnect —
1077
+ // an unrelated upsert (or a re-index) moves the matches without touching
1078
+ // \`__cdc_log\`. Only \`ctx.vectors\` is wrapped: the write-through
1079
+ // vector-sync hook keeps calling the bare facade.
1080
+ const bareVectors = vectorSync?.vectors ?? vectorsStub;
1081
+ const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
1082
+ const onWrite = vectorSync?.onWrite;
1083
+ `:"";return{vectorSyncMethod:n?`
1084
+ private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
1085
+ if (!config.vectors) {
1086
+ return undefined;
1087
+ }
1088
+
1089
+ const lunora = createVectors({ indexes: config.vectors(env) });
1090
+ ${s} const vectors = createContextVectors(lunora${f});
1091
+
1092
+ return {
1093
+ backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
1094
+ onWrite: createVectorSyncHook({ ${d}schema: schema as unknown as VectorSchemaLike, vectors }),
1095
+ vectors,
1096
+ };
1097
+ }
1098
+
1099
+ // \`__lunora_admin__:backfillVectors\`: the rows that predate a vector index,
1100
+ // a page at a time, each page ordered on the after-commit chain so it
1101
+ // never lands over a newer write's vector.
1102
+ protected override async runShardVectorBackfill(options: { maxPages?: number; restart?: boolean }): Promise<VectorBackfillProgress> {
1103
+ this.ensureMigrated();
1104
+
1105
+ const vectorSync = this.vectorSync((this.env ?? {}) as Record<string, unknown>);
1106
+
1107
+ if (!vectorSync) {
1108
+ throw new LunoraError("NOT_IMPLEMENTED", "vector backfill is unavailable: no vectors configured. Pass \`vectors\` to createShardDO().");
1109
+ }
1110
+
1111
+ return backfillVectorIndexes(this.sql as SqlExec, vectorBackfillTargets(schema as unknown as VectorSchemaLike), vectorSync.backfill, {
1112
+ ...options,
1113
+ ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1114
+ });
1115
+ }
1116
+ `:"",vectorsBuild:c,vectorsStub:r}},Dr=({advisories:n=[],advisorProcedures:e=[],agents:t=[],capabilities:a=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasVectors:c=!0,maskMetadata:y,mutators:S=[],queues:w=[],rlsMetadata:C,schema:i,schemaSnapshot:g,shapes:I=[],storageRules:_,studioFeatures:M,services:A=[],topics:P=[],useUmbrella:N=!1,workflows:R=[]})=>{const l=Qt(N),O=S.length>0,v=I.length>0,k=g===void 0?"":xt(g),re=g===void 0?"":`
1117
+ /** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
1118
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(At(g))}, json: ${JSON.stringify(k)} };
1119
+ `,ae=g===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=Et(a),D=Lt(m,l.flags),$=Ct(d,m,l.flags),q=Vt(f),F=It(s),{build:ne,contextField:se,importLines:oe,specs:ie}=_t(zt(w)),{build:de,contextField:ce,importLines:le,specs:he}=Mt(P,w),U=Pt(A,l.server),{build:ue,contextField:pe,importLines:me,specs:ge}=Nt(r,i.jurisdiction),{build:be,contextField:fe,importLines:ye,specs:we}=$t(R),{build:ve,contextField:ke,importLines:Se,specs:Re}=qt(t),{build:xe,configField:Ae,contextField:Oe,imports:De,stub:Te}=Ft(a.has("payments")),Ee=n,{advisoryRules:Le,advisoryRows:Ce}=Yt(Ee),Ie=e,G=C??{policies:[],roles:[]},_e=y??{columns:[]},Me=_??{rules:[]},Pe=M??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ne,override:$e}=Ut(R),{constant:qe,override:Fe}=Bt(w),u=c&&i.vectorIndexes.length>0,B=new Set(i.tables.filter(o=>Jt(o)).map(o=>o.name)),Q=u&&i.vectorIndexes.some(o=>B.has(o.table)),x=i.tables.some(o=>o.shardMode==="global"),W=Wt(B),j=i.tables.some(o=>Ot(o)),z=i.tables.some(o=>Dt(o)),T=i.tables.some(o=>o.externalSource!==void 0),J=i.tables.some(o=>o.memory===!0),H=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(z&&j)throw new Rt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,Ue=nr(i),Be=or(i),We=lr(i),je=sr(i),Y=ir(i),X=jt(u,R.length>0,w.length>0,m,H);v&&X.push("WhereInput");const Z=Ht(x),{customMutatorOverride:He,shapeGuardImport:Ve,shapeReadPolicyAssertion:Ke,shapeReadPolicyImport:Ge,shapeResolveOverride:Qe}=hr({hasMutators:O,hasShapes:v,rlsData:G}),E=[`import type { ${X.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, ${H?"backfillSearchIndexes, ":""}${u?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${J?"clearMemoryTables, ":""}${Ve}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${T?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Q?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...T?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],v?`import { asBucketStorage, ${Ge}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&E.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),u&&E.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),E.push(...b.importLines,...D.importLines,...q.importLines,...F.importLines,...me,...ye,...oe,...le,...U.importLines,...Se,...De,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...O?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ze=u?`
1120
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Je=z?`
1121
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ye=j?`
1122
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Xe=T?`
1123
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Ze="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",et="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",tt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",rt=x?L("globalDbStub: DatabaseWriterLike",Ze,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:at,vectorsBuild:nt,vectorsStub:st}=mr(u,Q?i.vectorIndexes.filter(o=>B.has(o.table)).map(o=>o.name):[]),ot=`{
1124
+ ...this.ctxDbTuning(),
1125
+ auth: { identity: identity ?? null, userId: userId ?? null },
1126
+ broadcast: (delta) => {
1127
+ this.recordChangedTable(delta.table, delta.indexKeys);
1128
+ },
1129
+ // Read at call time, not captured: the baseline belongs to the
1130
+ // dispatch in flight, and a queued mutation admitted after a
1131
+ // sibling's prologue must be judged against ITS caller's cursor.
1132
+ baselineSeq: () => this.getCurrentBaselineSeq(),
1133
+ cdc: config.cdc ?? false,
1134
+ // A dispatch with NO caller identity runs system-trusted: RLS scopes
1135
+ // rows to a user, and these have no user to scope to. This is the tier
1136
+ // migrations, imports and the external-source poll loop already run in
1137
+ // (see \`adminWriterPrelude\`). Only \`onShardInit\` and \`onQueryChange\`
1138
+ // reach it; \`onConnect\`/\`onDisconnect\` carry a verified identity and
1139
+ // stay guarded like any request.
1140
+ enforceRls: options.trusted !== true,
1141
+ headroom: options.headroom ?? this.transactionHeadroom(),
1142
+ // A live predicate, not a flag: the transaction opens AFTER this ctx
1143
+ // is built (a mutation dispatch wraps the handler), so only a call-time
1144
+ // read reports the truth. \`_commitSeq\` reuses one sequence across
1145
+ // writes only while they commit together — an action is not wrapped, so
1146
+ // each of its writes allocates its own.
1147
+ inTransaction: () => this.isInTransaction(),
1148
+ onIndexUse: this.getCtxDbIndexUseHook(),
1149
+ onStalePatchDropped: (event) => {
1150
+ this.recordStalePatchDropped(event);
1151
+ },
1152
+ // Bound to THIS dispatch's reactive-cache read scope (\`handleRpc\`
1153
+ // threads it in), so two concurrent queries never stamp each
1154
+ // other's dep sets. \`executeSubscription\` overrides both with its
1155
+ // own \`ReadFootprint\` pair instead, and a dispatch with neither
1156
+ // gets an unbound hook that stamps no deps.
1157
+ onRead: options.onRead ?? this.getCtxDbReadHook(options.scope),
1158
+ // Left \`undefined\` when there is no scope so \`createShardCtxDb\`
1159
+ // keeps its own "degrade a provable slice to a whole-table dep"
1160
+ // fallback rather than reporting into a no-op.
1161
+ onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${u?`
1162
+ // Vectorize is outside this shard's SQLite and cannot roll back, so
1163
+ // the sync is held until the mutation's transaction has COMMITTED
1164
+ // (\`deferAfterCommit\`) instead of running inline. Inline, a write
1165
+ // that later aborted left a vector pointing at a row that does not
1166
+ // exist — which a search then surfaces — and a rolled-back delete
1167
+ // left the row with its vector already purged. Outside a
1168
+ // transaction (an action) nothing is open and it runs at once.
1169
+ onWrite: onWrite === undefined ? undefined : (event) => this.deferAfterCommit(() => onWrite(event)),`:""}
1170
+ scheduler,
1171
+ schema: schema as unknown as SchemaLike,
1172
+ sql: this.sql as SqlExec,
1173
+ storage,${x?`
1174
+ globalDb,`:""}
1175
+ }`,it=u?`
1176
+ vectors,`:"",dt=V?`
1177
+ orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",ct=x?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1178
+ const globalDb: DatabaseWriterLike = ${ee}?.(env, globalRequest) ?? globalDbStub;
1179
+ `:"",lt=ur(v&&x,ee),{externalSourceOverride:ht,sourceBootstrap:ut,sourceClientCacheConst:pt}=pr(T),mt=`
1180
+ protected override async runShardInit(): Promise<void> {
1181
+ this.ensureMigrated();
1182
+ ${J?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1183
+ `:""}
1184
+ await this.dispatchShardInit();
1185
+ }
1186
+ `,gt=Y.length>0?`
1187
+ if (LUNORA_TTL_SWEEPS.length > 0) {
1188
+ void this.scheduleTtlSweep();
1189
+ }
1190
+ `:"",bt=`
1191
+ public constructor(state: ShardDOState, env: unknown) {
1192
+ super(state, env, {
1193
+ // Every writer this file builds spreads the ctxDbTuning() slice —
1194
+ // the user-facing ctx and all three admin/maintenance writers — so
1195
+ // the base class can drop its coarse invalidation backstop. Only the
1196
+ // emitter can know that; a hand-written subclass leaves this unset
1197
+ // and keeps the backstop.
1198
+ ctxDbCacheWired: true,
1199
+ ...(config.maxRelationKeys === undefined ? {} : { maxRelationKeys: config.maxRelationKeys }),
1200
+ ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1201
+ ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1202
+ // The same sink \`buildCtx\` resolves, made reachable before any ctx
1203
+ // exists — a trigger that fails first still flushes and fuses.
1204
+ ...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
1205
+ });
1206
+ ${ut}${gt} }
1207
+
1208
+ protected override isCacheableQuery(functionPath: string): boolean {
1209
+ // NOT \`kind === "query"\` alone. A cache hit answers without running
1210
+ // \`handleRpc\`, so the \`internal\` refusal at the top of it is skipped —
1211
+ // and an \`internalQuery\` primed by a trusted system dispatch was then
1212
+ // served to an anonymous client that the refusal would have 404'd.
1213
+ //
1214
+ // \`perDispatch\` is the same argument one layer out: the procedure's
1215
+ // own \`.use()\` chain runs INSIDE \`handleRpc\`, so a hit skips it too.
1216
+ // A \`.use(rateLimit(...))\` query was therefore charged once and then
1217
+ // served from the memo to every later request — each of which still
1218
+ // reached this Durable Object and still cost it a dispatch, so only
1219
+ // the accounting was skipped. Metering and memoizing are mutually
1220
+ // exclusive; the author asking for the first is choosing against the
1221
+ // second.
1222
+ const registered = LUNORA_FUNCTIONS[functionPath];
1223
+
1224
+ return registered?.kind === "query" && registered.visibility !== "internal" && registered.perDispatch !== true;
1225
+ }
1226
+
1227
+ protected override isPaidFunction(functionPath: string): boolean {
1228
+ return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1229
+ }
1230
+ `,ft=V?`
1231
+ const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1232
+ ${i.tables.map(o=>` facade[${JSON.stringify(o.name)}] = bindTableFacade(db, ${JSON.stringify(o.name)});`).join(`
1233
+ `)}
1234
+ `:"",yt=`${b.everyBuild}${D.build}${F.build}
1235
+ const secrets = createSecrets(env);
1236
+ `,wt=`${b.everyFields}${D.contextField}${q.contextField}${F.contextField}
1237
+ secrets,`,vt=q.build,kt=[...b.actionFields,...A.length>0?["services"]:[]],St=`${b.actionBuild}${U.build}`;return`${Gt}${E.join(`
1238
+ `)}
1239
+
1240
+ type FunctionKind = "action" | "mutation" | "query";
1241
+
1242
+ interface FunctionReference {
1243
+ __lunoraRef: string;
1244
+ }
1245
+
1246
+ /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1247
+ const LUNORA_TABLE_REFS = ${h(Ue,"Record<string, Record<string, string>>")};
1248
+
1249
+ /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1250
+ const LUNORA_TABLE_INDEXES = ${h(Be,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1251
+
1252
+ /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1253
+ const LUNORA_TABLE_COLUMNS = ${h(We,`Record<
1254
+ string,
1255
+ Array<{
1256
+ bucket?: string;
1257
+ enumValues?: string[];
1258
+ isStorage?: boolean;
1259
+ name: string;
1260
+ nullable?: boolean;
1261
+ onDelete?: "cascade" | "restrict" | "set null";
1262
+ optional: boolean;
1263
+ pk?: boolean;
1264
+ ref?: string;
1265
+ type: string;
1266
+ }>
1267
+ >`)};
1268
+
1269
+ /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1270
+ const LUNORA_STORAGE_COLUMNS = ${h(je,"Record<string, string[]>")};
1271
+
1272
+ /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1273
+ const LUNORA_TTL_SWEEPS = ${Tt(Y,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1274
+
1275
+ /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1276
+ const LUNORA_ADVISORY_RULES = ${h(Le,"Record<string, Partial<AdvisoryFinding>>")};
1277
+
1278
+ /** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
1279
+ const LUNORA_ADVISORY_ROWS = ${h(Ce,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1280
+
1281
+ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1282
+ let cached: AdvisoryFinding[] | undefined;
1283
+ return () => (cached ??= LUNORA_ADVISORY_ROWS().map((row) => ({ ...LUNORA_ADVISORY_RULES()[row.name], ...row }) as AdvisoryFinding));
1284
+ })();
1285
+
1286
+ /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1287
+ const LUNORA_ADVISOR_PROCEDURES = ${h(Ie,"AdvisorProcedure[]")};
1288
+
1289
+ /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1290
+ const LUNORA_RLS_METADATA = ${h(G,"RlsPoliciesResult")};
1291
+ ${Ke}
1292
+ /** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
1293
+ const LUNORA_MASK_METADATA = ${h(_e,"MaskPoliciesResult")};
1294
+
1295
+ /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1296
+ const LUNORA_STORAGE_RULES = ${h(Me,"StorageRulesResult")};
1297
+
1298
+ /** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
1299
+ const LUNORA_STUDIO_FEATURES = ${h(Pe,"StudioFeaturesResult")};
1300
+ ${re}${W.constant}${$.constant}${Ne}${qe}${ge}${we}${ie}${he}${U.specs}${Re}
1301
+ export interface ShardDOConfig {
1302
+ /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1303
+ cdc?: boolean;
1304
+ /** Ceiling on the join keys one relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
1305
+ maxRelationKeys?: number;
1306
+ /** 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. */
1307
+ reactiveCache?: boolean | { maxBytes?: number; maxEntries?: number };
1308
+ /** 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. */
1309
+ relationExistsPushDown?: "always" | "auto" | "never";
1310
+ /** 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. */
1311
+ observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1312
+ /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1313
+ scheduler?: (env: Record<string, unknown>) => unknown;
1314
+ /** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
1315
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ze}${b.configFields}${D.configField}${Ae}${Je}${Ye}${Xe}${W.configField}
1316
+ }
1317
+ ${L("schedulerStub",et,["cancel","runAfter","runAt"])}${L("storageStub",tt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${rt}${pt}${st}${b.stubs}${Te}
1318
+ ${tr}
1319
+
1320
+ /**
1321
+ * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1322
+ * from the worker entry so wrangler binds it by name.
1323
+ */
1324
+ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1325
+ class extends ShardDOBase {${bt}
1326
+ private migrated = false;
1327
+
1328
+ ${rr}
1329
+ ${Z.override}
1330
+ ${ar}
1331
+ ${He}${Qe}${lt}${ht}
1332
+ protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1333
+ return LUNORA_LIFECYCLE_HOOKS[event];
1334
+ }
1335
+ ${W.override}${mt}
1336
+ // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1337
+ // socket-terminated half of the same reactivity — and differs only in who
1338
+ // consumes the result: the base's \`dispatchReactors\` stores the digest as
1339
+ // the new baseline and the footprint as the "should I even re-run this"
1340
+ // gate, instead of pushing a frame down a socket.
1341
+ //
1342
+ // Dispatched through \`runMutationTransaction\` because a reactor handler is
1343
+ // a mutation: its writes must commit all-or-nothing, the jobs it schedules
1344
+ // must wait for that commit, and the objects its row deletes orphaned must
1345
+ // be flushed once it lands. Safe to open a span here: the refresh drain
1346
+ // runs OUTSIDE any dispatch transaction (it is post-flush background work),
1347
+ // so this never nests.
1348
+ //
1349
+ // NO identity is threaded, and the ctx is built \`trusted\`. A reactor fires
1350
+ // because data moved, not because anyone asked, so there is no user for RLS
1351
+ // to scope to — it runs in the same system tier as migrations and the
1352
+ // external-source poll loop. Inheriting the shared per-request identity
1353
+ // would instead run an app's reactor as whichever user happened to write
1354
+ // last, which is worse than running it as nobody.
1355
+ protected override async runReactor(functionPath: string, previousDigest?: string): Promise<{ digest: string; ran: boolean; tables: readonly string[] } | undefined> {
1356
+ const registered = LUNORA_FUNCTIONS[functionPath];
1357
+
1358
+ if (!registered || registered.kind !== "mutation") {
1359
+ return undefined;
1360
+ }
1361
+
1362
+ this.ensureMigrated();
1363
+
1364
+ const footprint = createReadFootprint();
1365
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), onRead: footprint.onRead, onReadRange: footprint.onReadRange, trusted: true });
1366
+ const outcome = (await this.runMutationTransaction(ctx, async () =>
1367
+ registered.handler(ctx, { previousDigest } as unknown as Record<string, unknown>),
1368
+ )) as {
1369
+ digest: string;
1370
+ ran: boolean;
1371
+ };
1372
+
1373
+ return { digest: outcome.digest, ran: outcome.ran, tables: [...footprint.tables] };
1374
+ }
1375
+
1376
+
1377
+ protected override tableRefs(table: string): Record<string, string> | undefined {
1378
+ return LUNORA_TABLE_REFS()[table];
1379
+ }
1380
+
1381
+ protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> {
1382
+ return LUNORA_TABLE_INDEXES()[table] ?? [];
1383
+ }
1384
+
1385
+ protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> {
1386
+ return LUNORA_TTL_SWEEPS;
1387
+ }
1388
+
1389
+ protected override tableColumns(table: string): Array<{
1390
+ bucket?: string;
1391
+ enumValues?: string[];
1392
+ isStorage?: boolean;
1393
+ name: string;
1394
+ nullable?: boolean;
1395
+ onDelete?: "cascade" | "restrict" | "set null";
1396
+ optional: boolean;
1397
+ pk?: boolean;
1398
+ ref?: string;
1399
+ type: string;
1400
+ }> {
1401
+ return LUNORA_TABLE_COLUMNS()[table] ?? [];
1402
+ }
1403
+
1404
+ protected override storageColumns(): Record<string, string[]> {
1405
+ return LUNORA_STORAGE_COLUMNS();
1406
+ }
1407
+
1408
+ protected override rlsMetadata(): RlsPoliciesResult {
1409
+ return LUNORA_RLS_METADATA();
1410
+ }
1411
+
1412
+ protected override maskMetadata(): MaskPoliciesResult {
1413
+ return LUNORA_MASK_METADATA();
1414
+ }
1415
+
1416
+ protected override storageRulesMetadata(): StorageRulesResult {
1417
+ return LUNORA_STORAGE_RULES();
1418
+ }
1419
+
1420
+ protected override studioFeatures(): StudioFeaturesResult {
1421
+ return LUNORA_STUDIO_FEATURES();
1422
+ }
1423
+ ${$.evaluateOverride}${$.subscriptionOverride}${$e}${Fe}
1424
+ protected override advisories(): AdvisoryFinding[] {
1425
+ return LUNORA_ADVISORIES();
1426
+ }
1427
+
1428
+ protected override advisorProcedures(): AdvisorProcedure[] {
1429
+ return LUNORA_ADVISOR_PROCEDURES();
1430
+ }
1431
+
1432
+ ${Zt}
1433
+
1434
+ protected override ensureMigrated(): void {
1435
+ if (this.migrated) {
1436
+ return;
1437
+ }
1438
+
1439
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ae} });
1440
+ this.migrated = true;
1441
+ }
1442
+ ${H?`
1443
+ protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1444
+ // Migrations create the fts5 companions; without them every backfill
1445
+ // statement would raise "no such table" on a shard that has never
1446
+ // served a request.
1447
+ this.ensureMigrated();
1448
+
1449
+ return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1450
+ }
1451
+ `:""}${at}
1452
+ ${er({actionOnlyFields:kt,agentsBuild:ve,agentsContextField:ke,containersBuild:ue,containersContextField:pe,databaseOptions:ot,everyContextBuild:yt,everyContextField:wt,facadeBlock:ft,globalDatabaseLine:ct,notifyBuild:vt,ormContextField:dt,paymentsBuild:xe,paymentsContextField:Oe,queuesBuild:ne,queuesContextField:se,topicsBuild:de,topicsContextField:ce,vectorsBuild:nt,vectorsContextField:it,workflowsBuild:be,workflowsContextField:fe,actionOnlyBuild:St})}
1453
+ };
1454
+ `};export{sr as b,Dr as e};