@lunora/codegen 1.0.0-alpha.42 → 1.0.0-alpha.420

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 (130) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +4 -4
  3. package/dist/index.d.mts +4583 -2045
  4. package/dist/index.d.ts +4583 -2045
  5. package/dist/index.mjs +1 -35
  6. package/dist/packem_shared/AGENTS_FILENAME-C4tHmiZZ.mjs +1 -0
  7. package/dist/packem_shared/ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs +1 -0
  8. package/dist/packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs +25 -0
  9. package/dist/packem_shared/COMPANION_BINDING-Da_v9XpC.mjs +1 -0
  10. package/dist/packem_shared/CONTAINERS_FILENAME-d3XTFcqV.mjs +1 -0
  11. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  12. package/dist/packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs +1 -0
  13. package/dist/packem_shared/ENV_FILENAME-DJ11PXN5.mjs +1 -0
  14. package/dist/packem_shared/FLAGS_FILENAME-DeSjFBWq.mjs +1 -0
  15. package/dist/packem_shared/GENERATED_HEADER-DgrhC3Iv.mjs +1 -0
  16. package/dist/packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs +1 -0
  17. package/dist/packem_shared/MUTATORS_FILENAME-C0ZV0hh6.mjs +1 -0
  18. package/dist/packem_shared/OPENRPC_VERSION-BOBo0zdQ.mjs +3 -0
  19. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
  20. package/dist/packem_shared/QUEUES_FILENAME-DbuJZnrY.mjs +1 -0
  21. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BljJJD8u.mjs +56 -0
  22. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
  23. package/dist/packem_shared/SHAPES_FILENAME-C-hrGfJ2.mjs +1 -0
  24. package/dist/packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs +17 -0
  25. package/dist/packem_shared/WORKFLOWS_FILENAME-7FysJsMZ.mjs +1 -0
  26. package/dist/packem_shared/attribution-Cwt30DDJ.mjs +1 -0
  27. package/dist/packem_shared/buildOpenApiDocument-DmV_PBFv.mjs +3 -0
  28. package/dist/packem_shared/capabilitiesUsedBy-BNvoiCu1.mjs +1 -0
  29. package/dist/packem_shared/classify-procedure-call-BmEirzc_.mjs +1 -0
  30. package/dist/packem_shared/companionServiceBinding-BZjm486n.mjs +1 -0
  31. package/dist/packem_shared/context-property-calls-BT1J7BqY.mjs +1 -0
  32. package/dist/packem_shared/context-root-BpDEhvNE.mjs +1 -0
  33. package/dist/packem_shared/createCodegenProject-dC6oJh5H.mjs +1 -0
  34. package/dist/packem_shared/database-calls-d-Sssc-3.mjs +1 -0
  35. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  36. package/dist/packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs +1 -0
  37. package/dist/packem_shared/discoverAuthApiCalls-CuqaLRa0.mjs +1 -0
  38. package/dist/packem_shared/discoverCrons-bT8F5GyL.mjs +1 -0
  39. package/dist/packem_shared/discoverFunctions-C9HUlfiV.mjs +1 -0
  40. package/dist/packem_shared/discoverHttpRoutes-CesuhqW1.mjs +1 -0
  41. package/dist/packem_shared/discoverHyperdriveCalls-BmAoOGGq.mjs +1 -0
  42. package/dist/packem_shared/discoverInserts-DIarYU2P.mjs +1 -0
  43. package/dist/packem_shared/discoverMaskProcedures-jkRrWS86.mjs +1 -0
  44. package/dist/packem_shared/discoverMigrations-C9AlZYFi.mjs +1 -0
  45. package/dist/packem_shared/discoverNondeterministicCalls-ZeZDQJAI.mjs +1 -0
  46. package/dist/packem_shared/discoverQueries-DLZHcDzB.mjs +1 -0
  47. package/dist/packem_shared/discoverR2sqlCalls-D_HWbbky.mjs +1 -0
  48. package/dist/packem_shared/discoverRlsMetadata-C0UkQkWd.mjs +1 -0
  49. package/dist/packem_shared/discoverRlsProcedures-BbSdCvmA.mjs +1 -0
  50. package/dist/packem_shared/discoverSandboxUsage-Dgvv6F_7.mjs +1 -0
  51. package/dist/packem_shared/discoverSchema-BLTROO8Z.mjs +1 -0
  52. package/dist/packem_shared/discoverStorageRulesMetadata-DeBgC7po.mjs +1 -0
  53. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  54. package/dist/packem_shared/emitAgents-vWoT8-Yb.mjs +1 -0
  55. package/dist/packem_shared/emitApi-lwadq5G7.mjs +147 -0
  56. package/dist/packem_shared/emitApp-LFKtDRYu.mjs +1162 -0
  57. package/dist/packem_shared/emitCrons-CCRKs482.mjs +138 -0
  58. package/dist/packem_shared/emitDataModel-BvCZS4Yq.mjs +114 -0
  59. package/dist/packem_shared/emitDrizzleSchema-BzOChEYW.mjs +15 -0
  60. package/dist/packem_shared/emitFunctions-ppMX7E3X.mjs +528 -0
  61. package/dist/packem_shared/emitServer-CGRV_uIq.mjs +1 -0
  62. package/dist/packem_shared/emitShard-CDWgekIG.mjs +1 -0
  63. package/dist/packem_shared/exported-procedure-chains-CfH5jrzD.mjs +1 -0
  64. package/dist/packem_shared/fingerprintSchemaSources-TN-rU6Of.mjs +1 -0
  65. package/dist/packem_shared/formatAdvisories-Bue5tbp6.mjs +2 -0
  66. package/dist/packem_shared/handler-reference-BkOkxxg8.mjs +1 -0
  67. package/dist/packem_shared/index-CfSmiylg.mjs +1 -0
  68. package/dist/packem_shared/index-DtJBMdZ4.mjs +1 -0
  69. package/dist/packem_shared/ip-reads-D2qhKEb6.mjs +1 -0
  70. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  71. package/dist/packem_shared/isTestPath-Uwb5a6Kq.mjs +1 -0
  72. package/dist/packem_shared/isTypedSchema-CDv3pJB6.mjs +4 -0
  73. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  74. package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
  75. package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
  76. package/dist/packem_shared/modules-DdOd-7Wp.mjs +1 -0
  77. package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
  78. package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
  79. package/dist/packem_shared/policies-Dn_tuTZd.mjs +1 -0
  80. package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
  81. package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
  82. package/dist/packem_shared/qualifiers-qqH8fRTo.mjs +1 -0
  83. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  84. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  85. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  86. package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
  87. package/dist/packem_shared/schemaFromIr-CByOxuZb.mjs +1 -0
  88. package/dist/packem_shared/server-Dfxmm5Zw.mjs +377 -0
  89. package/dist/packem_shared/shard-CWAD5mYy.mjs +1897 -0
  90. package/dist/packem_shared/shard-runtime-G5mZQjY0.mjs +351 -0
  91. package/dist/packem_shared/shared-Cn7dMQ_u.mjs +13 -0
  92. package/dist/packem_shared/unwrap-handler-return-DvbyiLjc.mjs +1 -0
  93. package/dist/sdk/index.d.mts +288 -0
  94. package/dist/sdk/index.d.ts +288 -0
  95. package/dist/sdk/index.mjs +394 -0
  96. package/package.json +22 -9
  97. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  98. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  99. package/dist/packem_shared/FLAGS_FILENAME-fEZtzWXi.mjs +0 -139
  100. package/dist/packem_shared/GENERATED_HEADER-D6RK1WF1.mjs +0 -3
  101. package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
  102. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  103. package/dist/packem_shared/OPENRPC_VERSION-CzhfvCIQ.mjs +0 -60
  104. package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
  105. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cl1EBMdR.mjs +0 -3438
  106. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  107. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  108. package/dist/packem_shared/WORKFLOWS_FILENAME-B2By8S4s.mjs +0 -152
  109. package/dist/packem_shared/buildOpenApiDocument-bg-NnLka.mjs +0 -183
  110. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  111. package/dist/packem_shared/discoverAuthApiCalls-WMx8L2FG.mjs +0 -62
  112. package/dist/packem_shared/discoverCrons-D-jrpm97.mjs +0 -256
  113. package/dist/packem_shared/discoverFunctions-CZ91aenA.mjs +0 -518
  114. package/dist/packem_shared/discoverHttpRoutes-DNZLDCmm.mjs +0 -131
  115. package/dist/packem_shared/discoverInserts-DFRJhmCv.mjs +0 -61
  116. package/dist/packem_shared/discoverMaskProcedures-B5iFnZ-X.mjs +0 -273
  117. package/dist/packem_shared/discoverMigrations-CdKtMlBc.mjs +0 -97
  118. package/dist/packem_shared/discoverNondeterministicCalls-C_PrQPkA.mjs +0 -122
  119. package/dist/packem_shared/discoverQueries-B8W9UPrt.mjs +0 -62
  120. package/dist/packem_shared/discoverR2sqlCalls-Bm7Rfnf4.mjs +0 -80
  121. package/dist/packem_shared/discoverRlsMetadata-B4GL4ZKm.mjs +0 -280
  122. package/dist/packem_shared/discoverSchema-DFWVgU5o.mjs +0 -874
  123. package/dist/packem_shared/discoverStorageRulesMetadata-nosjYcvN.mjs +0 -97
  124. package/dist/packem_shared/emit-31Yg1Ee5.mjs +0 -3474
  125. package/dist/packem_shared/emitApp-DCP7Pr6M.mjs +0 -668
  126. package/dist/packem_shared/formatAdvisories-DRhEiJUz.mjs +0 -114
  127. package/dist/packem_shared/parse-validator-BSJo1HGP.mjs +0 -144
  128. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  129. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  130. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,1897 @@
1
+ import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Zt,hashSchemaSnapshot as er}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{isHyperdriveGlobalTable as tr,isD1GlobalTable as rr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as nr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as ar,a as sr,b as or,c as ir,d as dr,f as cr,g as lr,h as ur,i as hr,j as pr,k as mr,l as fr,m as gr,n as br,o as yr,p as wr,q as vr,s as kr}from"./shard-runtime-G5mZQjY0.mjs";import{u as U,h as Sr,s as Rr,a as xr,I as Ar,c as Or,G as Tr,d as _r}from"./shared-Cn7dMQ_u.mjs";import{p as Dr}from"./platform-8oj7iXQy.mjs";import{i as Ir}from"./schema-BgM8A3XV.mjs";const m=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,me=["categories","description","facing","level","remediation","title"],Er=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(me.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!me.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Cr=` /**
2
+ * The bare writer every admin/maintenance entry point writes through.
3
+ *
4
+ * Admin and maintenance writes go through the SAME reactive-cache hooks as a
5
+ * user mutation. Without this, a studio row edit, a TTL sweep, an admin
6
+ * import, a CDC apply or a data-migration backfill writes without
7
+ * invalidating, and the next query answers from the pre-write snapshot.
8
+ *
9
+ * \`headroom\` meters the transaction. An admin \`/rpc\` caller passes nothing
10
+ * and falls back to \`this.transactionHeadroom()\`, which for an admin RPC is
11
+ * \`undefined\` — \`handleAdminRpc\` answers before \`beginDispatch\`, so no
12
+ * per-dispatch meter is in flight and a bulk loop is bounded by its per-call
13
+ * row cap alone. The TTL sweep (an alarm work item, no dispatch) passes its
14
+ * own by-value tracker explicitly instead.
15
+ */
16
+ private adminWriter(headroom?: TransactionHeadroomTracker): DatabaseWriterLike {
17
+ const env = (this.env ?? {}) as Record<string, unknown>;
18
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
19
+
20
+ return createShardCtxDb({
21
+ ...this.ctxDbTuning(),
22
+ broadcast: (delta) => {
23
+ this.recordChangedTable(delta.table, delta.indexKeys);
24
+ },
25
+ cdc: config.cdc ?? false,
26
+ ...(headroom === undefined ? {} : { headroom }),
27
+ // Live predicate, same as the user-facing ctx — see \`databaseOptions\`.
28
+ inTransaction: () => this.isInTransaction(),
29
+ scheduler,
30
+ schema: schema as unknown as SchemaLike,
31
+ sql: this.sql as SqlExec,
32
+ });
33
+ }`,y=(r="")=>` const writer = this.adminWriter(${r});`,Lr=`${Cr}
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
+ ${y()}
51
+
52
+ try {
53
+ return await runDataMigration({
54
+ ...(args.batchSize === undefined ? {} : { batchSize: args.batchSize }),
55
+ ...(args.direction === undefined ? {} : { direction: args.direction }),
56
+ ...(args.dryRun === undefined ? {} : { dryRun: args.dryRun }),
57
+ ...(args.maxBatches === undefined ? {} : { maxBatches: args.maxBatches }),
58
+ migration: migration as unknown as DataMigrationLike,
59
+ // Flush after each batch so live migrationStatus subscribers see
60
+ // progress mid-run (the base method records the reserved state
61
+ // table the raw-SQL progress write is invisible to the tracker).
62
+ onBatch: () => this.flushMigrationProgress(),
63
+ sql: this.sql as SqlExec,
64
+ writer,
65
+ });
66
+ } finally {
67
+ // The de-dup that unblocks a deferred UNIQUE index runs through here;
68
+ // let the next call rebuild it now instead of after the retry interval.
69
+ this.migrationRetryAt = 0;
70
+ }
71
+ }
72
+
73
+ protected override async runShardWrite(args: RunShardWriteArgs, headroom?: TransactionHeadroomTracker): Promise<RunShardWriteResult> {
74
+ const definition = (schema as unknown as SchemaLike).tables[args.table];
75
+
76
+ if (!definition) {
77
+ throw new LunoraError("UNKNOWN_TABLE", \`unknown table: \${args.table}\`, { status: 404 });
78
+ }
79
+
80
+ // \`.global()\` tables live in D1, not this DO's SQLite — editing them
81
+ // here would corrupt nothing but would fail confusingly, so reject up
82
+ // front with a clear code the studio can surface.
83
+ if (definition.shardMode?.kind === "global") {
84
+ throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", \`table "\${args.table}" is global; edit it through D1, not the shard\`, { status: 400 });
85
+ }
86
+
87
+ this.ensureMigrated();
88
+
89
+ ${y("headroom ?? this.transactionHeadroom()")}
90
+
91
+ if (args.op === "insert") {
92
+ const id = await writer.insert(args.table, args.doc ?? {});
93
+
94
+ return { id, op: "insert" };
95
+ }
96
+
97
+ // Every by-id op PINS \`args.table\`. Unpinned, \`locateRowById\` probes
98
+ // every non-global table for the id, so a request naming table A with an
99
+ // id belonging to table B locates and mutates B's row — the by-id IDOR
100
+ // the per-table \`ctx.db.<table>\` facade pins against. Pinning also stops
101
+ // an absent row falling through to the \`.global()\` D1 twin, though that
102
+ // branch is already unreachable here: \`adminWriter\` is built without a
103
+ // \`globalDb\`, so a miss throws \`NOT_FOUND\` either way.
104
+ // \`hard\` is set only by the BULK delete arm, which needs the row gone
105
+ // from the physical table for its next batch's scan to make progress.
106
+ // A single-row \`writeRow\` delete never carries it, so it keeps the
107
+ // table's declared \`.softDelete()\` behaviour.
108
+ if (args.op === "delete") {
109
+ await writer.delete(args.table, args.id ?? "", { hard: args.hard === true });
110
+
111
+ return { id: args.id ?? null, op: "delete" };
112
+ }
113
+
114
+ if (args.op === "replace") {
115
+ await writer.replace(args.table, args.id ?? "", args.doc ?? {});
116
+
117
+ return { id: args.id ?? null, op: "replace" };
118
+ }
119
+
120
+ await writer.patch(args.table, args.id ?? "", args.doc ?? {});
121
+
122
+ return { id: args.id ?? null, op: "patch" };
123
+ }
124
+
125
+ // The base \`ShardDO\` cannot build a schema-aware writer, so its
126
+ // \`runShardExport\`/\`runShardImport\` return \`[]\` and \`{inserted:{}}\`.
127
+ // Those are success-shaped: an empty export is what a correct export of
128
+ // an empty shard looks like, so a backup of a populated sharded schema
129
+ // reported success and wrote nothing, and an import reported success and
130
+ // dropped every row. Overriding both here is what makes the two admin
131
+ // RPCs real for a \`.shardBy()\` table.
132
+ //
133
+ // NOTE: the admin export RPC is not paginated — \`parseExportShardArgs\`
134
+ // takes \`tables\`/\`batchSize\` but no cursor, and the coordinator issues
135
+ // one call per shard — so the rows are collected into a single response.
136
+ // \`batchSize\` bounds the SQLite scan page, not the reply. A shard holding
137
+ // more rows than fit in the DO's memory budget will therefore fail the
138
+ // export rather than stream it. That is a loud failure where the bug this
139
+ // replaces was a silent empty one, but a cursor on the RPC is what makes
140
+ // this a complete backup path for large shards.
141
+ protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
142
+ this.ensureMigrated();
143
+
144
+ ${y()}
145
+
146
+ const rows: ExportRow[] = [];
147
+
148
+ // \`exportShardRows\` walks in keyset batches so a large table does not
149
+ // materialize at once inside the generator; the admin RPC's response
150
+ // is a single array, so it is collected here rather than streamed.
151
+ for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, args)) {
152
+ rows.push(row);
153
+ }
154
+
155
+ return rows;
156
+ }
157
+
158
+ protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
159
+ // A dry run checks row shapes and never writes. Migrating first would write the schema ledger and create tables on a cold shard.
160
+ if (args.dryRun !== true) {
161
+ this.ensureMigrated();
162
+ }
163
+
164
+ ${y()}
165
+
166
+ // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
167
+ // database's \`_id\`s carry across verbatim and every foreign key
168
+ // referencing them stays valid without a second remapping pass.
169
+ return importShardRows(writer, schema as unknown as SchemaLike, args);
170
+ }
171
+
172
+ protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
173
+ this.ensureMigrated();
174
+
175
+ ${y()}
176
+
177
+ // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
178
+ // but the shard writer from \`createShardCtxDb\` always defines it.
179
+ if (!writer.rankBefore) {
180
+ throw new LunoraError("NOT_IMPLEMENTED", "rankBefore is unavailable on the shard writer", { status: 500 });
181
+ }
182
+
183
+ return writer.rankBefore(args.table, args.index, {
184
+ partitionKey: args.partitionKey,
185
+ rowId: args.rowId,
186
+ sortValues: args.sortValues,
187
+ });
188
+ }
189
+
190
+ protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
191
+ this.ensureMigrated();
192
+
193
+ ${y()}
194
+
195
+ // \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
196
+ // but the shard writer from \`createShardCtxDb\` always defines it — it
197
+ // derives the edge set from this app's schema.
198
+ if (!writer.related) {
199
+ throw new LunoraError("NOT_IMPLEMENTED", "findRelated is unavailable on the shard writer", { status: 500 });
200
+ }
201
+
202
+ return writer.related(
203
+ { id: args.id, table: args.table },
204
+ args,
205
+ );
206
+ }
207
+
208
+ protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
209
+ this.ensureMigrated();
210
+
211
+ ${y()}
212
+
213
+ // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
214
+ // but the shard writer from \`createShardCtxDb\` always defines it. The sort
215
+ // directions live in the schema's rankIndex, so the shard reads them itself;
216
+ // \`args.directions\` is only the coordinator's comparator hint and isn't forwarded.
217
+ if (!writer.rankPageRows) {
218
+ throw new LunoraError("NOT_IMPLEMENTED", "rankPage is unavailable on the shard writer", { status: 500 });
219
+ }
220
+
221
+ return writer.rankPageRows(args.table, args.index, {
222
+ ...(args.after === undefined ? {} : { after: args.after }),
223
+ ...(args.cursor === undefined ? {} : { cursor: args.cursor }),
224
+ ...(args.partitionKey === undefined ? {} : { partitionKey: args.partitionKey }),
225
+ ...(args.take === undefined ? {} : { take: args.take }),
226
+ });
227
+ }
228
+
229
+ protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
230
+ this.ensureMigrated();
231
+
232
+ ${y()}
233
+
234
+ await applyCdcChanges(writer, args.changes);
235
+
236
+ return { applied: args.changes.length };
237
+ }`,Pr=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,agentsSchedulerSource:n,containersBuild:a,containersContextField:i,databaseOptions:f,everyContextBuild:c,everyContextField:g,facadeBlock:A,globalDatabaseLine:w,hasSensitiveArgs:u=!1,lazyFunctions:l=!1,notifyBuild:O,ormContextField:v,paymentsBuild:F,paymentsContextField:B,queuesBuild:R,queuesContextField:j,topicsBuild:d,topicsContextField:k,vectorsBuild:I,vectorsContextField:W,workflowsBuild:K,workflowsContextField:E})=>{const T=t.length>0,H=v===""?"{ db }":"{ db, orm: bindOrm(facade) }",V=v===""?"":`
238
+ orm: databaseContext.orm,`,C=v===""?"":`
239
+ orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,x=T?`
240
+ // ActionCtx-only helpers (external, non-deterministic I/O): constructed
241
+ // and attached only for an \`action\` so query/mutation ctx never carry them.
242
+ if (isAction) {
243
+ ${r.replaceAll(/^(?=.)/gmu," ")}${t.map(p=>` ctx.${p} = ${p};`).join(`
244
+ `)}
245
+ }
246
+ `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark | undefined; functionPath?: string | undefined; headroom?: TransactionHeadroomTracker | undefined; identity?: SubscriptionIdentity | undefined; kind?: "query" | undefined; onRead?: ((table: string, idOrScan?: string) => void) | undefined; onReadRange?: ((range: KeyRange) => void) | undefined; replayKey?: boolean | undefined; scope?: QueryReadScope | undefined; sensitive?: SensitiveScope | undefined; trusted?: boolean | undefined } = {}): unknown {
247
+ const env = (this.env ?? {}) as Record<string, unknown>;
248
+ // The caller context this ctx runs under, resolved ONCE on one
249
+ // discriminant. When the caller threads an explicit identity
250
+ // (subscription seed / refresh / stream pull / shape resolve — all
251
+ // deferred or interleaved), it is used by value and the shared
252
+ // per-request fields are never read, because a concurrent RPC owns
253
+ // them: a refresh in particular runs inside the writing dispatch's
254
+ // \`flushChangedTables\`, BEFORE its \`endDispatch\`, so \`getCurrentIp()\`
255
+ // there is the MUTATING caller's address. Otherwise (the synchronous
256
+ // RPC dispatch path) it falls back to those fields as before.
257
+ //
258
+ // One expression, not one per field: three parallel ternaries on the
259
+ // same discriminant is how \`ip\` came to be the only one still reading
260
+ // the shared field.
261
+ const caller: SubscriptionIdentity = options.identity ?? (() => {
262
+ const identity = this.getCurrentIdentity();
263
+ const ip = this.getCurrentIp();
264
+ const userId = this.getCurrentUserId();
265
+
266
+ return {
267
+ ...(identity === undefined ? {} : { identity }),
268
+ ...(ip === undefined ? {} : { ip }),
269
+ ...(userId === undefined ? {} : { userId }),
270
+ };
271
+ })();
272
+ // The ONLY way to the caller: there are deliberately no \`identity\` /
273
+ // \`userId\` / \`ip\` locals. Each reader marks this function path as
274
+ // reading its caller, which is what keeps a live query that reads it from
275
+ // sharing one run across subscribers (see \`noteIdentityRead\`). A consumer
276
+ // that copies a value at build time marks every ctx of the app; one that
277
+ // reads it lazily marks only the handlers that reach it.
278
+ //
279
+ // Only a registered path is marked: only one can ever be shared, and a
280
+ // client-chosen name (a shape, a relation fan-out) must not grow the set.
281
+ const identityPath = Object.hasOwn(LUNORA_FUNCTIONS, options.functionPath ?? "") ? options.functionPath : undefined;
282
+ const noteCallerRead = (): void => {
283
+ if (identityPath !== undefined) {
284
+ this.noteIdentityRead(identityPath);
285
+ }
286
+ };
287
+ const readIdentity = (): Record<string, unknown> | undefined => {
288
+ noteCallerRead();
289
+
290
+ return caller.identity;
291
+ };
292
+ const readUserId = (): string | undefined => {
293
+ noteCallerRead();
294
+
295
+ return caller.userId;
296
+ };
297
+ const readIp = (): string | undefined => {
298
+ noteCallerRead();
299
+ options.scope?.markIpRead();
300
+
301
+ return caller.ip;
302
+ };
303
+ ${I}${c}${a}${K}${R}${d}${e}
304
+ // Which dispatch this ctx belongs to. Drives the two deferral facades
305
+ // below and the \`ctx.run*\` caller guard; a ctx built for an
306
+ // admin/lifecycle path has no registered function, and so no kind. An
307
+ // untracked \`ctx.runQuery\` overrides it with \`"query"\`: the sub-query
308
+ // keeps the caller's \`functionPath\` for attribution but runs as a query.
309
+ const contextKind = options.kind ?? LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind;
310
+ // \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
311
+ // reaches through, and pending jobs live in the SchedulerDO — nothing the
312
+ // CDC changelog records — so reading them must forfeit a delta resume.
313
+ // The scheduler's own \`runAfter\`/\`runAt\`/\`cancel\` are writes and stay unstamped.
314
+ const schedulerBase = markUnvouchableReads(${n}, options.onRead, ["get", "list"]);
315
+ // \`ctx.scheduler.runAfter(0, ...)\` is documented as the deterministic
316
+ // equivalent of an \`afterCommit\` hook, and the SchedulerDO persists the
317
+ // job the moment it is called — so inside a mutation the call is BUFFERED
318
+ // and replayed after the transaction commits (a rollback drops it).
319
+ // Composed mutations get their own facade when the caller is outside
320
+ // a transaction. True nested calls share the enclosing facade and open
321
+ // a nested window. The action's own schedules stay immediate.
322
+ //
323
+ // Every kind but \`query\` is wrapped, because \`runMutationTransaction\`
324
+ // is installed on \`ctx.runMutation\` for every kind but \`query\`: a
325
+ // STREAM ctx, and an admin/lifecycle ctx with no registered kind at all,
326
+ // both get the BEGIN/COMMIT span for a mutation they compose, and used
327
+ // to get it with the deferral missing — so that mutation's job reached
328
+ // the SchedulerDO while its transaction was still open, and survived the
329
+ // rollback. A query cannot host a mutation handler (\`dispatchRun\`
330
+ // refuses it) and its ctx is built on the hot subscription path, so it
331
+ // stays unwrapped.
332
+ //
333
+ // Wrapped OUTSIDE the read-stamping facade so \`get\`/\`list\` stay stamped.
334
+ //
335
+ // \`this.scheduleOutbox()\` is what keeps the buffer honest. Everything
336
+ // between the COMMIT and the scheduler's acknowledgement is outside the
337
+ // transaction, so a failure there leaves writes that are durable and a
338
+ // job that exists nowhere — and the mutation's replay-dedup row committed
339
+ // inside the span, so the client's retry is answered from cache and told
340
+ // it succeeded. The outbox takes custody of each buffered call inside the
341
+ // transaction and releases it once the scheduler has the job; what
342
+ // survives is retried by \`pollScheduleOutbox\` on the shared poll alarm.
343
+ const scheduler = contextKind === "query" ? schedulerBase : withDeferredSchedules(schedulerBase, this.scheduleOutbox());
344
+ // Build the storage adapter once and share it between \`ctx.storage\`
345
+ // and \`ctx.db.system._storage\` so both read the same R2 binding. The
346
+ // \`storageStub\` fallback satisfies SystemReaderStorageLike structurally
347
+ // (its \`list\`/\`getMetadata\` throw the "no storage configured" error).
348
+ //
349
+ // Wrapped BEFORE the split so both consumers share one stamping facade.
350
+ // Only the methods that actually reach R2 are stamped: \`getUrl\` and
351
+ // \`getSignedUrl\` build a URL from the configured base (and an HMAC) and
352
+ // read nothing, and they are what handlers overwhelmingly call — stamping
353
+ // them would forfeit resumes for a dependency that cannot move the result.
354
+ // \`bucket\` IS stamped: it hands back a sub-facade this wrapper does not
355
+ // reach, so the selection is the last point at which the read can be seen.
356
+ //
357
+ // The request origin is the storage base fallback for mutations and
358
+ // actions on the synchronous dispatch only. A deferred caller
359
+ // (\`options.identity\` set) runs outside the dispatch that owns the
360
+ // field, the same hazard \`getCurrentIp\` has. A query never gets it: a
361
+ // live query re-runs with no request behind it, and the reactive
362
+ // cache does not key on the host, so a query that signs URLs needs a
363
+ // declared \`publicBaseUrl\` either way.
364
+ const requestOrigin = contextKind !== "query" && options.identity === undefined ? this.getCurrentOrigin() : undefined;
365
+ const makeStorage = (origin?: string): SystemReaderStorageLike =>
366
+ markUnvouchableReads(asBucketStorage(config.storage?.(env, origin) ?? storageStub) as SystemReaderStorageLike, options.onRead, [
367
+ "bucket",
368
+ "download",
369
+ "getMetadata",
370
+ "list",
371
+ ]);
372
+ const storage = makeStorage(requestOrigin);
373
+ // \`ctx.storage.deleteAfterCommit(key)\`, on every dispatch that can host
374
+ // a MUTATION handler — which is not only a mutation dispatch. An
375
+ // action's composed mutation gets a child ctx with its own deferred
376
+ // delete queue, while mutations reuse the admitted ctx. Queries stay
377
+ // unwrapped: they cannot host one, and their ctx is built on the hot
378
+ // subscription path.
379
+ //
380
+ // Every dispatch wrapped here also flushes (see \`handleRpc\` and
381
+ // \`runReactor\`) — a queue nothing drains leaks silently, which is worse
382
+ // than not having the method at all.
383
+ //
384
+ // Wrapped OUTSIDE the read-stamping facade so \`bucket(name)\` still
385
+ // resolves through it and stays stamped, and applied only to
386
+ // \`ctx.storage\` so \`ctx.db.system._storage\` (which shares the adapter
387
+ // above) is untouched.
388
+ const contextStorage = contextKind === "mutation" || contextKind === "action" ? withDeferredDeletes(storage) : storage;
389
+ // \`ctx.log\`: the DO base builds the attributed logger (structured
390
+ // fields + \`.with(...)\` child + trace correlation) and routes each call
391
+ // to the optional \`observability\` sink. It also buffers the line (studio
392
+ // Logs panel) and emits a structured console event the dev-server formats.
393
+ //
394
+ // Resolved BEFORE \`ctx.db\` below, because the database is wrapped in
395
+ // auto-instrumentation that needs the sink, the trace anchor, and the
396
+ // dispatch's wide-event handle.
397
+ const observability = config.observability?.(env);
398
+ const logFunctionPath = options.functionPath ?? "";
399
+ const log = this.makeLogger(logFunctionPath, observability, undefined, options.sensitive);
400
+ const traceAnchor = this.resolveDispatchAnchor(Boolean(options.identity));
401
+
402
+ // \`ctx.span\`: the handle onto the DISPATCH's own span — the wide-event
403
+ // surface. Attributes attached here accumulate for the whole request
404
+ // and are folded into the one span it already emits, instead of
405
+ // becoming N separate log lines. Shares \`traceAnchor\` with \`ctx.trace\`
406
+ // so both write to the same trace.
407
+ const span = this.makeDispatchSpan(traceAnchor, observability, options.sensitive);
408
+
409
+ ${w} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
410
+ // adds aggregate counters (call count, total time, per-operation
411
+ // breakdown) to the wide event rather than a span per call, so a
412
+ // handler making hundreds of queries stays readable. See
413
+ // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
414
+ // Schema triggers close over this DB's scheduler, so a composed
415
+ // mutation must rebuild its DB and table/ORM views with its own queue.
416
+ const makeDatabaseContext = (scheduler: SchedulerLike) => {
417
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${f}), logFunctionPath, traceAnchor, observability, options.sensitive);
418
+ ${A} return ${H};
419
+ };
420
+ const databaseContext = makeDatabaseContext(scheduler);
421
+ const db = databaseContext.db;
422
+ ${F}
423
+
424
+ // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
425
+ // The trace anchor is threaded explicitly for the same reason \`identity\`
426
+ // is — a deferred caller (a subscription re-run) must not inherit the
427
+ // writing mutation's trace from the shared per-request field.
428
+ const trace = this.makeTracer(logFunctionPath, observability, traceAnchor, options.sensitive);
429
+ const metrics = this.makeMetrics(logFunctionPath, observability, options.sensitive);
430
+ ${O}
431
+ // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
432
+ // captured ONCE so the whole handler body sees a single stable value.
433
+ // A \`query\` handler is re-run by every live subscription that reads it,
434
+ // so \`Date.now()\` there flickers between re-evaluations. A \`mutation\`
435
+ // handler does not replay under ordinary dispatch (an OCC conflict throws
436
+ // to the caller rather than retrying internally), but one called from a
437
+ // workflow step or queue consumer runs again when that step replays. Both
438
+ // read time through \`ctx.now\` — the \`nondeterministic_query_mutation\`
439
+ // advisor flags \`Date.now()\`. Actions may still use ambient \`Date.now()\`.
440
+ const now = Date.now();
441
+
442
+ // A reactor run is driven by the writer's inline refresh, not replayed by the writer, so it must not
443
+ // inherit the writer's key: every run would restart the same id and random sequence.
444
+ const stableKey = options.replayKey !== false && options.identity === undefined && this.idempotencyNamespace() !== undefined ? this.getCurrentMutationId() : undefined;
445
+ // The scope reads the caller, so a factory is only built (and the read only made) on its first draw: a
446
+ // query that carries a replay key but never draws must not count as reading its caller. Both factories
447
+ // ignore the scope without a replay key, and most dispatches have none.
448
+ // The request-scoped parts are captured now: instance state may belong to another request by the first draw.
449
+ const scopeHead = stableKey === undefined ? [] : [this.currentShardKey(), options.functionPath ?? "", this.idempotencyNamespace() ?? ""];
450
+ let scopeText: string | undefined;
451
+ const stableScope = (): string => (scopeText ??= JSON.stringify([...scopeHead, readUserId() ?? ""]));
452
+ const scoped = <T>(create: (scope: string) => () => T): (() => T) => {
453
+ if (stableKey === undefined) {
454
+ return create("");
455
+ }
456
+
457
+ let made: (() => T) | undefined;
458
+
459
+ return () => (made ??= create(stableScope()))();
460
+ };
461
+ // One sequence for every mutation this run composes: their ids share one counter (the copied \`newId\`), so their draws must too.
462
+ // Created on the first composed mutation that gets a ctx of its own; most dispatches compose none.
463
+ let composedRandom: (() => number) | undefined;
464
+
465
+ const ctx: Record<string, unknown> = {
466
+ auth: {
467
+ getIdentity: async () => readIdentity() ?? null,
468
+ get userId() {
469
+ return readUserId() ?? null;
470
+ },
471
+ },
472
+ db,
473
+ // \`ctx.newId()\`: a replay of the same top-level mutation gets the same ids. A nested or
474
+ // subscription-driven build (\`options.identity\`) is not a replay.
475
+ // A replay key only means something inside the caller's dedup namespace; without one the call is not
476
+ // deduplicated, so its ids stay random.
477
+ // \`ctx.random()\` shares the replay key and scope, so a replay reproduces both sequences.
478
+ // A query is never replayed, so its ids skip \`scoped\` (whose first draw reads the caller) and stay random.
479
+ newId: contextKind === "query" ? createStableIdFactory(undefined, "") : scoped((scope) => createStableIdFactory(stableKey, scope)),
480
+ // Only a mutation is a replay the key reproduces; a query or action carrying the header draws Math.random,
481
+ // and never goes through \`scoped\`, whose first draw reads the caller.
482
+ random: contextKind === "mutation" ? scoped((scope) => createStableRandomFactory(stableKey, scope)) : createStableRandomFactory(undefined, ""),
483
+ shardKey: this.currentShardKey(),
484
+ // Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
485
+ // \`traceparent\` propagation, so time spent in a downstream service
486
+ // is visible and its spans join this trace. Degrades to the bare
487
+ // global when no sink is configured. Not built for a query or a
488
+ // mutation: those refuse network I/O (see \`refuseFetch\`).
489
+ fetch: contextKind === "query" || contextKind === "mutation" ? refuseFetch : this.makeFetch(logFunctionPath, traceAnchor, observability, options.sensitive),
490
+ // A GETTER, not a plain field, so the reactive cache can tell a
491
+ // handler that reads the caller's address from the majority that
492
+ // never do. \`ctx.ip\` is per-request state the memo must be keyed
493
+ // by — otherwise two anonymous callers share one entry and the
494
+ // second is served the first's address — but keying every entry
495
+ // by address would shard the cache per client for every query.
496
+ // Reading it here marks the dispatch's scope; \`runCachedQuery\`
497
+ // folds the address into the key for this function from then on.
498
+ get ip() {
499
+ return readIp();
500
+ },
501
+ log,
502
+ metrics,
503
+ now,
504
+ // The same request origin the storage fallback above uses, handed
505
+ // to the handler so code that signs its own URLs (a copy-in
506
+ // \`createStorage\`) can fall back to it too. \`undefined\` for a
507
+ // query and for a deferred dispatch, for the reasons given there.
508
+ origin: requestOrigin,${V}
509
+ scheduler,
510
+ span,
511
+ storage: contextStorage,
512
+ trace,${W}${g}${B}${i}${E}${j}${k}${o}${u?`
513
+ [Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
514
+ };
515
+ ${T?` const isAction = contextKind === "action";
516
+ `:""}${x}
517
+ ${l?` const captureScope = (): (() => void) => {
518
+ const requestScope = this.captureRequestScope();
519
+ return () => this.restoreRequestScope(requestScope);
520
+ };
521
+
522
+ `:""} const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
523
+ target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => {
524
+ // The callee runs inside this invocation, so its marked arguments are scrubbed here too.
525
+ this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
526
+
527
+ return dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${l?", undefined, captureScope":""});
528
+ };
529
+ // The composed mutation runs under the SAME wrapper the top-level RPC
530
+ // uses, so "do the transactional work in a mutation and call it from the
531
+ // action" — the recipe the docs give for atomicity — actually is atomic.
532
+ target.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => {
533
+ this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
534
+ // An action can start sibling mutations concurrently. Each owns its
535
+ // context and deferral queues; only calls from an admitted mutation
536
+ // inherit that mutation's transaction.
537
+ const mutationCtx: Record<string, unknown> = this.mutationContexts.has(target)
538
+ ? target
539
+ : (() => {
540
+ const mutationScheduler = withDeferredSchedules(schedulerBase, this.scheduleOutbox());
541
+ const mutationDatabase = makeDatabaseContext(mutationScheduler);
542
+ // The composed mutation's ids come from the action's replay key and counter, so its draws do too; a
543
+ // fresh factory per call would repeat the same draws across sibling mutations.
544
+ const mutationRandom = (composedRandom ??= scoped((scope) => createStableRandomFactory(stableKey, scope)));
545
+
546
+ // Copied from an action's ctx, which carries the real \`fetch\`; a mutation
547
+ // refuses network I/O wherever it runs, so its \`fetch\` is overridden here.
548
+ return Object.defineProperties({}, {
549
+ ...Object.getOwnPropertyDescriptors(target),
550
+ db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${C}
551
+ fetch: { configurable: true, enumerable: true, value: refuseFetch, writable: true },
552
+ random: { configurable: true, enumerable: true, value: mutationRandom, writable: true },
553
+ scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
554
+ storage: { configurable: true, enumerable: true, value: withDeferredDeletes(storage), writable: true },
555
+ });
556
+ })();
557
+
558
+ if (mutationCtx !== target) {
559
+ installRun(mutationCtx, kind);
560
+ }
561
+
562
+ return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${l?", captureScope":""});
563
+ };
564
+ // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
565
+ // its OWN query context, built without the subscription's read-footprint
566
+ // hooks — so its reads never enter this subscription's footprint and a
567
+ // write to the tables it touched does not re-run us. Everything else is
568
+ // inherited: \`functionPath\` (log/metric attribution), \`headroom\` (the
569
+ // sub-query must not escape this dispatch's resource ceiling),
570
+ // \`scope\` (the reactive-cache capture — an untracked sub-query's reads
571
+ // must still be deps of the entry the OUTER query is memoized as, or
572
+ // the memo goes stale), and — load-bearing — the resolved \`caller\` BY VALUE
573
+ // (identity, userId AND ip). Omitting it would let \`buildCtx\` fall back
574
+ // to the shared per-request fields, which a concurrent RPC may have
575
+ // re-set, and an RLS-scoped sub-query would then read as the wrong user
576
+ // from the wrong address. A tracked call runs on \`queryContext()\` below.
577
+ target.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>, runOptions?: { untracked?: boolean }) => {
578
+ this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
579
+
580
+ return dispatchRun(
581
+ "query",
582
+ reference.__lunoraRef,
583
+ fnArgs,
584
+ runOptions?.untracked === true
585
+ ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope, sensitive: options.sensitive })
586
+ : queryContext(),
587
+ kind,${l?`
588
+ undefined,
589
+ captureScope,`:""}
590
+ );
591
+ };
592
+ };
593
+
594
+ // A query composed from a mutation or action runs on a QUERY view of
595
+ // this ctx, so it behaves exactly as it does when called directly or
596
+ // live: same \`db\`, read hooks, trace and \`now\`, but every field that
597
+ // depends on the dispatch kind or the request origin is re-derived for a
598
+ // query — no \`ctx.origin\`, storage with no origin fallback (and no
599
+ // \`deleteAfterCommit\`), the unwrapped scheduler, no ActionCtx-only
600
+ // helpers, no \`fetch\` (a query is re-run, see \`refuseFetch\`), and a \`run*\` guard
601
+ // that refuses a mutation or action. A new kind- or origin-dependent ctx field must
602
+ // be overridden here too.
603
+ // Copied by descriptor so the \`ip\` getter is carried over, not read.
604
+ // Built on the first composed call only; a query ctx is its own view.
605
+ let queryView: Record<string, unknown> | undefined;
606
+ const queryContext = (): Record<string, unknown> => {
607
+ if (contextKind === "query") {
608
+ return ctx;
609
+ }
610
+
611
+ if (queryView === undefined) {
612
+ const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
613
+ ${t.map(p=>` delete descriptors.${p};
614
+ `).join("")} // Writable and configurable, like the plain fields they replace.
615
+ const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
616
+
617
+ queryView = Object.defineProperties({}, {
618
+ ...descriptors,
619
+ fetch: field(refuseFetch),
620
+ origin: field(undefined),
621
+ // A composed query is not a mutation replay, so it must not advance the mutation's random sequence.
622
+ random: field(scoped((scope) => createStableRandomFactory(undefined, scope))),
623
+ scheduler: field(schedulerBase),
624
+ storage: field(makeStorage()),
625
+ }) as Record<string, unknown>;
626
+ installRun(queryView, "query");
627
+ }
628
+
629
+ return queryView;
630
+ };
631
+
632
+ installRun(ctx, contextKind);
633
+
634
+ return ctx;
635
+ }`},fe=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
636
+ // referencing call fails loudly with a clear error instead of overflowing the
637
+ // stack. Tracked across the awaited handler chain (one DO invocation is
638
+ // single-threaded), so the counter reflects true nesting depth.
639
+ const MAX_RUN_DEPTH = 32;
640
+ let runDepth = 0;
641
+
642
+ const dispatchRun = async (
643
+ expected: FunctionKind,
644
+ functionPath: string,
645
+ args: Record<string, unknown>,
646
+ ctx: unknown,
647
+ // The kind of the context making the call, and — for a mutation target — the
648
+ // transaction wrapper to run it under. Both are supplied by \`buildCtx\`, which
649
+ // is the only place that knows which dispatch this \`ctx\` belongs to. Widened
650
+ // past \`FunctionKind\` because the registry also carries \`"stream"\`, and
651
+ // \`undefined\` for a ctx built outside a registered function (admin, migration).
652
+ callerKind?: "stream" | FunctionKind,
653
+ runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
654
+ ): Promise<unknown> => {
655
+ // A query and a stream are read-only: their declared ctx is the query ctx. The
656
+ // ctx object installs \`run*\` on every kind (one shape, built once), so the
657
+ // TYPE is all that stops them writing — and a cast walks straight past it,
658
+ // inside a subscription re-run that can execute many times per write. Checked
659
+ // on the CALLER, before the registry lookup, so \`ctx.runMutation\` from a
660
+ // query or stream fails identically whatever it aimed at.
661
+ if ((callerKind === "query" || callerKind === "stream") && expected !== "query") {
662
+ throw new LunoraError(
663
+ "RUN_KIND_FORBIDDEN",
664
+ \`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: a \${callerKind} may only compose other queries (tried to run "\${functionPath}")\`,
665
+ );
666
+ }
667
+
668
+ const registered = LUNORA_FUNCTIONS[functionPath];
669
+
670
+ if (!registered) {
671
+ throw new Error(\`unknown function: \${functionPath}\`);
672
+ }
673
+
674
+ if (registered.kind !== expected) {
675
+ throw new Error(\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: "\${functionPath}" is registered as a \${registered.kind}, not a \${expected}\`);
676
+ }
677
+
678
+ if (runDepth >= MAX_RUN_DEPTH) {
679
+ throw new LunoraError("RUN_DEPTH_EXCEEDED", \`ctx.run*: composition depth limit (\${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation\`);
680
+ }
681
+
682
+ runDepth += 1;
683
+
684
+ try {
685
+ // A mutation composed from an action (or an http action) is the shape the
686
+ // docs prescribe for atomicity — "do the transactional reads and writes in
687
+ // a mutation and call it from the action". It only holds if the composed
688
+ // dispatch gets the same BEGIN/COMMIT span and single-writer gate the
689
+ // top-level mutation path gets; without it every write autocommits and a
690
+ // mid-handler throw leaves the earlier ones durable. A \`runMutation\` from
691
+ // inside a mutation rides the enclosing span instead of opening a second
692
+ // one (see \`runMutationTransaction\`).
693
+ if (runTransactional) {
694
+ return await runTransactional(async () => registered.handler(ctx, args));
695
+ }
696
+
697
+ return await registered.handler(ctx, args);
698
+ } finally {
699
+ runDepth -= 1;
700
+ }
701
+ };`,Nr=r=>r?fe.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
702
+ captureScope?: () => () => void,`).replace(` try {
703
+ // A mutation composed from an action`,` try {
704
+ let loaded = getLoadedFunction(functionPath);
705
+
706
+ if (loaded === undefined) {
707
+ const restoreScope = captureScope?.();
708
+
709
+ try {
710
+ loaded = await loadFunction(functionPath);
711
+ } finally {
712
+ restoreScope?.();
713
+ }
714
+ }
715
+
716
+ if (!loaded) {
717
+ throw new Error(\`unknown function: \${functionPath}\`);
718
+ }
719
+
720
+ const loadedFunction = loaded;
721
+
722
+ // A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):fe,$r=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark, sensitive?: SensitiveScope): Promise<unknown> {
723
+ // A dispatch that did not come through the shard's \`/rpc\` (a scheduled call,
724
+ // a lifecycle hook, an admin run) has no scope of its own, so it opens one here
725
+ // and releases it when the handler settles.
726
+ if (sensitive === undefined) {
727
+ const own = this.openSensitiveScope(functionPath, args);
728
+
729
+ try {
730
+ return await this.handleRpc(functionPath, args, headroom, scope, bookmarks, own);
731
+ } finally {
732
+ own.clear();
733
+ }
734
+ }
735
+
736
+ __PREPARE_FUNCTION__ const registered = LUNORA_FUNCTIONS[functionPath];
737
+
738
+ // Internal functions are reachable server-side only: via \`ctx.run*\`
739
+ // composition, or a trusted system dispatch (scheduler/cron, marked by
740
+ // \`isSystemDispatch()\`). A client RPC never carries that flag, so its
741
+ // internals stay not-found and never leak across the external boundary.
742
+ if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) {
743
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
744
+ }
745
+
746
+ // A stream yields chunks over its WebSocket procedure stream. Run here it
747
+ // would return an async iterator, which the wire encoder cannot carry as a
748
+ // single result, so refuse it before the handler runs.
749
+ if (registered.kind === "stream") {
750
+ throw new LunoraError("BAD_REQUEST", \`"\${functionPath}" is a stream: open it over the WebSocket, not RPC\`);
751
+ }
752
+
753
+ this.ensureServable();
754
+
755
+ // \`headroom\`, when the caller supplied one, is threaded straight
756
+ // through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
757
+ // fallback (the racy shared-field read) entirely for THIS dispatch.
758
+ // The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
759
+ // \`handleRunAs\` don't mint their own and omit it, so they keep the
760
+ // prior fallback behavior unchanged.
761
+ //
762
+ // \`scope\` is the reactive cache's per-dispatch read capture, threaded
763
+ // the same way and for the same reason: the ctx-db read hooks resolve
764
+ // their tracker at READ time, so binding them to the scope THIS
765
+ // dispatch was handed is what keeps a concurrent query's reads out of
766
+ // our dep set — and ours out of theirs. A dispatch with no scope (a
767
+ // mutation, an action, a cache-less shard) builds unbound hooks that
768
+ // stamp no deps.
769
+ const ctx = this.buildCtx({ bookmarks, functionPath, headroom, scope, sensitive, trusted: registered.lifecycle === "init" });
770
+
771
+ // A mutation's writes must commit all-or-nothing, so its dispatch runs
772
+ // under \`runMutationTransaction\` — the ONE place that opens the span,
773
+ // settles the deferred schedules and flushes the deferred deletes. The
774
+ // same helper backs \`ctx.runMutation\` and \`runReactor\`, because a
775
+ // mutation reached by composition is promised exactly these guarantees
776
+ // and used to get none of them.
777
+ //
778
+ // The replay bookkeeping (idempotency dedup row + custom-mutator
779
+ // watermark advance) commits INSIDE the span via
780
+ // \`commitMutationBookkeeping\`, so the writes, the dedup row, and the
781
+ // watermark are atomic — a crash can't leave the writes durable without
782
+ // the replay guard. It is deliberately NOT in the shared helper: it is
783
+ // per-REQUEST bookkeeping, and a composed sub-mutation has no request of
784
+ // its own to record.
785
+ if (registered.kind === "mutation") {
786
+ return await this.runMutationTransaction(ctx, async () => {
787
+ const value = await registered.handler(ctx, args);
788
+
789
+ this.commitMutationBookkeeping(value);
790
+
791
+ return value;
792
+ });
793
+ }
794
+
795
+ // An action's unawaited I/O can be cancelled after the response, so its
796
+ // ctx counts what is still in flight when the handler returns.
797
+ // Reported on a throw too: the pending calls are just as abandoned.
798
+ const finishActionWork = registered.kind === "action" ? this.watchActionWork(functionPath, ctx) : undefined;
799
+ let result: unknown;
800
+
801
+ try {
802
+ result = await registered.handler(ctx, args);
803
+ } finally {
804
+ finishActionWork?.();
805
+ }
806
+
807
+ // Composed mutations settle their own delete queues. An action can
808
+ // also queue deletes outside those mutations; drain its own queue here.
809
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
810
+
811
+ return result;
812
+ }
813
+
814
+ private readonly mutationContexts = new WeakSet<object>();
815
+
816
+ /**
817
+ * Run one mutation handler with the atomicity every caller of a mutation is
818
+ * promised: a BEGIN/COMMIT span (with the single-writer gate
819
+ * \`ShardRunner.runInTransaction\` composes in front of it), scheduled jobs
820
+ * held until that span commits, and the deferred object deletes flushed
821
+ * only once it has.
822
+ *
823
+ * Shared by the three entry points that dispatch a mutation handler — the
824
+ * top-level RPC, \`ctx.runMutation\` from an action or http action, and a
825
+ * reactor — because the guarantee is a property of the mutation, not of how
826
+ * it was reached. The docs tell users to put the transactional part in a
827
+ * mutation and call it from the action precisely so that composition is
828
+ * atomic.
829
+ *
830
+ * A \`ctx.runMutation\` issued from inside a mutation is NESTED: SQLite-in-DO
831
+ * has no savepoints and \`runInTransaction\` rejects a second open, so it
832
+ * rides the enclosing span, which also owns its commit and therefore its
833
+ * scheduler flush.
834
+ *
835
+ * Both deferral windows are opened here and settled against the SAME
836
+ * outcome. True nested calls share their caller's context, so each window
837
+ * must discard its own failed delete and schedule intents even when the
838
+ * outer handler catches the error and commits.
839
+ */
840
+ private async runMutationTransaction<T>(ctx: unknown, work: () => Promise<T>): Promise<T> {
841
+ const settleSchedules = beginDeferredSchedules(ctx as { scheduler?: unknown });
842
+ // Synchronous and non-throwing (it only moves queue entries), so it can
843
+ // settle first on every path and cannot mask the outcome.
844
+ const settleDeletes = beginDeferredDeletes(ctx);
845
+
846
+ if (this.mutationContexts.has(ctx as object)) {
847
+ try {
848
+ const nested = await work();
849
+
850
+ settleDeletes(true);
851
+ await settleSchedules(true);
852
+
853
+ return nested;
854
+ } catch (error) {
855
+ settleDeletes(false);
856
+ await settleSchedules(false);
857
+
858
+ throw error;
859
+ }
860
+ }
861
+
862
+ let result: T;
863
+
864
+ try {
865
+ result = await this.runInTransaction(async () => {
866
+ this.mutationContexts.add(ctx as object);
867
+
868
+ try {
869
+ return await work();
870
+ } finally {
871
+ this.mutationContexts.delete(ctx as object);
872
+ }
873
+ }, { independent: true });
874
+ } catch (error) {
875
+ // The span rolled back, so the rows are gone and the jobs that were
876
+ // to run "after I commit" must go with them. Dropping them is the
877
+ // whole point of buffering: a persisted job for a write that never
878
+ // landed fires against state that does not exist.
879
+ //
880
+ // The queued object deletes go the same way, and for a sharper
881
+ // reason: the rows they were to clean up after are still there, and
882
+ // an R2 delete cannot be undone.
883
+ settleDeletes(false);
884
+ await settleSchedules(false);
885
+
886
+ throw error;
887
+ }
888
+
889
+ // Committed, so this span's queued keys join whatever the flush below
890
+ // (or an enclosing span's) will drain.
891
+ settleDeletes(true);
892
+
893
+ // Committed. Schedules first and AWAITED: \`runAfter(0, ...)\` is
894
+ // documented as the deterministic equivalent of an \`afterCommit\` hook,
895
+ // so the job must be enqueued after the commit, and a failure to enqueue
896
+ // it must be visible rather than swallowed.
897
+ //
898
+ // In a \`finally\`, because both halves of this are post-commit cleanup
899
+ // and neither is allowed to cancel the other. \`settleSchedules\` drains
900
+ // its whole queue and then rethrows what failed, so a SchedulerDO that
901
+ // refused one job used to take the object cleanup down with it — the
902
+ // rows were durably gone and their objects leaked with nothing logged.
903
+ try {
904
+ await settleSchedules(true);
905
+ __COMMITTED_CATCH__ } finally {
906
+ // Then the objects whose rows are now durably gone. Deliberately AFTER
907
+ // the span, never inside it: an R2 delete cannot roll back, so a delete
908
+ // issued from within a transaction that later aborts destroys data the
909
+ // surviving row still points at.
910
+ //
911
+ // \`flushDeferredDeletes\` never rejects — the mutation has already
912
+ // succeeded, so a failed cleanup must not turn into a failed response.
913
+ // A leaked object is reported through \`ctx.log\` instead, with its key.
914
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
915
+ }
916
+
917
+ return result;
918
+ }
919
+
920
+ // Only a \`mutation\` may enter the base class's single-writer gate for
921
+ // mutation-replay dedup — it is \`blockConcurrencyWhile\`, so gating an
922
+ // action would stall every other dispatch on the shard for the length of
923
+ // its outbound I/O, on nothing but a caller-supplied header. Unregistered
924
+ // paths answer \`false\`; \`handleRpc\` above rejects them anyway.
925
+ protected override isMutationFunction(functionPath: string): boolean {
926
+ return LUNORA_FUNCTIONS[functionPath]?.kind === "mutation";
927
+ }
928
+
929
+ // The scheduler the deferred-schedule outbox retries through. Only the
930
+ // CONFIGURED one: falling back to \`schedulerStub\` would have an app with no
931
+ // scheduler retry every entry against a thrower until the attempt ceiling
932
+ // parked it, and there is nothing to park — an app with no scheduler has no
933
+ // \`ctx.scheduler\` call that reached the buffer in the first place.
934
+ protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
935
+ __OUTBOX_SCHEDULER__ }`,Mr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ identityTracked?: boolean; ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
936
+ const registered = LUNORA_FUNCTIONS[functionPath];
937
+
938
+ if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
939
+ return null;
940
+ }
941
+
942
+ __PREPARE_FUNCTION__ this.ensureServable();
943
+
944
+ const footprint = createReadFootprint();
945
+ // Identity is threaded EXPLICITLY from the (deferred/interleaved)
946
+ // subscription caller — never read from the shared per-request field
947
+ // here — so a concurrent RPC can't leak its identity into this re-run.
948
+ __SUBSCRIPTION_RUN__
949
+ // Ranges come from THIS run's reads, never a shared field on the DO:
950
+ // a deferred re-run interleaves with unrelated dispatches.
951
+ const ranges = footprint.ranges();
952
+
953
+ // \`identityTracked\`: this ctx reports every read of its caller through
954
+ // \`noteIdentityRead\`, so the base may share the run across subscribers
955
+ // of a path observed never reading it.
956
+ return { identityTracked: true, ...(ranges === undefined ? {} : { ranges }), result, tables: footprint.tables };
957
+ }
958
+
959
+ protected override executeStream(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
960
+ const registered = LUNORA_FUNCTIONS[functionPath];
961
+
962
+ if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
963
+ return null;
964
+ }
965
+
966
+ this.ensureServable();
967
+
968
+ return {
969
+ ...(registered.durable ? { durable: registered.durable as { ttlMs?: number } } : {}),
970
+ // Identity threaded EXPLICITLY from the socket, exactly as
971
+ // \`executeSubscription\` above: the iterator is pulled after this
972
+ // frame returned, interleaved with unrelated dispatches, so
973
+ // \`buildCtx\`'s per-request fallback would run an \`rls()\` /
974
+ // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
975
+ iterator: (signal) => {
976
+ const headroom = this.streamHeadroom(functionPath, identity);
977
+
978
+ return this.windowStreamReads(headroom, (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, headroom, identity }), args, signal));
979
+ },
980
+ };
981
+ }`,qr=` } catch (error) {
982
+ // The write committed before this failed. Mark the error so the caller can tell
983
+ // a durable write from a rollback: the rethrow still reaches the caller unchanged.
984
+ if (typeof error === "object" && error !== null) {
985
+ Object.assign(error, { committed: true });
986
+ }
987
+
988
+ throw error;
989
+ `,Ur=(r,t=!1,e=!1)=>{const o=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
990
+
991
+ if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
992
+ throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
993
+ }
994
+
995
+ `:"",n=t?` const requestScope = this.captureRequestScope();
996
+ const preparation = this.prepareFunction(functionPath, "rpc");
997
+
998
+ if (preparation !== undefined) {
999
+ try {
1000
+ await preparation;
1001
+ } finally {
1002
+ this.restoreRequestScope(requestScope);
1003
+ }
1004
+ }
1005
+
1006
+ `:"",a=e?` const configured = config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
1007
+ return configured === undefined ? undefined : withAgentScheduleShard(configured, LUNORA_AGENTS, this.currentShardKey());
1008
+ `:` return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
1009
+ `;return $r.replace("__COMMITTED_CATCH__",r?qr:"").replace("__PREPARE_FUNCTION__",`${o}${n}`).replace("__OUTBOX_SCHEDULER__",a)},Fr=` const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(functionPath, identity), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange });
1010
+ const result = await registered.handler(ctx, args);
1011
+ `,Br=` const sensitive = this.openSensitiveScope(functionPath, args);
1012
+ let result: unknown;
1013
+
1014
+ try {
1015
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(functionPath, identity), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange, sensitive });
1016
+
1017
+ result = await registered.handler(ctx, args);
1018
+ } catch (error) {
1019
+ throw this.maskSensitiveError(error, sensitive);
1020
+ } finally {
1021
+ sensitive.clear();
1022
+ }
1023
+ `,jr=r=>Mr.replace("__SUBSCRIPTION_RUN__",r?Br:Fr),Wr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,a]of Object.entries(e.shape)){const i=U(a);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},Kr=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,a]of Object.entries(e.shape))U(a).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Hr=r=>{const t={};for(const e of r.tables){const o=[...e.indexes.map(n=>({fields:[...n.fields],name:n.name,type:"index",...n.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(n=>({fields:[n.field,...n.filterFields??[]],name:n.name,type:"search"})),...(e.geoIndexes??[]).map(n=>({fields:[n.field],name:n.name,type:"geo"})),...e.rankIndexes.map(n=>({fields:n.sortBy.map(a=>a.field),name:n.name,type:"rank"})),...e.vectorIndexes.map(n=>({fields:n.field===void 0?[]:[n.field],name:n.name,type:"vector"}))];o.length>0&&(t[e.name]=o)}return t},Vr=r=>{const t=[];for(const e of r.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Gr=r=>{if(r.kind!=="union"||r.members===void 0||r.members.length===0)return;const t=[];for(const e of r.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const o=JSON.parse(e.literalValue);if(typeof o!="string")return;t.push(o)}catch{return}}return t},Qr=new Set(["bigint","boolean","date","number","timestamp"]),zr=r=>{const[t,e]=r.kind==="union"?r.members??[]:[];if(t===void 0||e===void 0||r.members?.length!==2)return;const o=a=>a.kind==="null"||a.kind==="literal"&&a.literalValue==="null",n=U(o(e)?t:e);return o(t)!==o(e)&&Qr.has(n.kind)?n:void 0},Jr=(r,t,e)=>{const o=U(t),n=zr(o),a=n??o,i={name:r,optional:Sr(t),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){i.ref=a.tableName;const c=e.get(r);c!==void 0&&(i.onDelete=c)}a.kind==="storage"&&(i.isStorage=!0,a.bucket!==void 0&&(i.bucket=a.bucket));const f=Gr(a);return f!==void 0&&(i.enumValues=f),(a.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Yr=r=>{const t={};for(const e of r.tables){const o=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],n=new Map(e.relations.flatMap(a=>a.kind==="one"?[[a.field,a.onDelete]]:[]));for(const[a,i]of Object.entries(e.shape))o.push(Jr(a,i,n));t[e.name]=o}return t},Xr=({hasMutators:r,hasSensitiveShapes:t,hasShapes:e,rlsData:o})=>{const n="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",a=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {
1024
+ const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
1025
+
1026
+ try {
1027
+ return this.resolveShapeWithScope(name, args, identity, sensitive);
1028
+ } catch (error) {
1029
+ throw this.maskSensitiveError(error, sensitive);
1030
+ } finally {
1031
+ sensitive.clear();
1032
+ }
1033
+ }
1034
+
1035
+ private resolveShapeWithScope(name: string, args: Record<string, unknown>, identity: SubscriptionIdentity | undefined, sensitive: SensitiveScope): ${n} {`:` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {`,f=e?`
1036
+ ${a}
1037
+ const shape = LUNORA_SHAPES[name];
1038
+
1039
+ if (!shape) {
1040
+ return undefined;
1041
+ }
1042
+
1043
+ this.ensureServable();
1044
+
1045
+ // Trusted ctx from the socket's OWN verified identity — the client
1046
+ // supplies only the shape name + args; \`compileWhere\` validates the
1047
+ // args then runs the shape's \`where(ctx, args)\` under that identity,
1048
+ // so which rows replicate is a server decision (reads-as-permissions).
1049
+ const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity${t?", sensitive":""} });
1050
+ // \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
1051
+ // \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
1052
+ // rather than every shape restating the ownership check in its \`where\`.
1053
+ const ownerField = (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField;
1054
+ const shapeWhere = shape.compileWhere(ctx, args, ownerField === undefined ? {} : { ownerField }) as unknown as WhereInput;
1055
+
1056
+ // AND-compose with the read policies this SHAPE declares
1057
+ // (\`defineShape({ use: [guard] })\`, pre-indexed into
1058
+ // \`shape.rlsRegistry\`). A shape runs no procedure, so the
1059
+ // \`.use(rls(...))\` middleware never fires; without this merge its
1060
+ // reads would bypass the read policies it opted into.
1061
+ // \`composeShapeReadWhere\` evaluates them under this same trusted ctx
1062
+ // and fails closed under a \`.rls("required")\` schema for a
1063
+ // non-\`.public()\` table the shape declared no read policy for.
1064
+ //
1065
+ // The registry is the shape's OWN — never one folded from every
1066
+ // registered function. A project-wide union let one admin-only
1067
+ // procedure's allow-all read policy unrestrict every shape on the
1068
+ // table; see the SCOPE note in \`shape-read-base.ts\`.
1069
+ //
1070
+ // It is NOT identical to the request-time path, and must not be
1071
+ // described as such: roles come from the identity's \`roles\` claim
1072
+ // only, because no middleware runs here to contribute
1073
+ // \`ctx.auth.roles\`. Derive roles at the identity if a policy gates
1074
+ // on them — see \`shape-read-base.ts\`.
1075
+ const effectiveWhere = composeShapeReadWhere(shape.rlsRegistry, {
1076
+ ctx,
1077
+ identity: identity?.identity ?? null,
1078
+ rlsRequired: (schema as unknown as { rlsMode?: string }).rlsMode === "required",
1079
+ shapeWhere,
1080
+ table: shape.table,
1081
+ tablePublic: (schema as unknown as { tables: Record<string, { isPublic?: boolean }> }).tables[shape.table]?.isPublic === true,
1082
+ userId: identity?.userId ?? null,
1083
+ });
1084
+
1085
+ // A live shape pokes only from its OWN shard's op-log, so a \`where()\`
1086
+ // that joins to a \`.shardBy()\` table (rows in another DO) is rejected
1087
+ // here — the first point the compiled predicate + shard modes are both
1088
+ // known. Remedy: denormalize, or move the joined table to \`.global()\`.
1089
+ assertShapeShardable(effectiveWhere, schema as unknown as SchemaLike, shape.table);
1090
+
1091
+ // A \`.global()\` table lives in D1 (no per-DO op-log): flag it so the
1092
+ // base serves it through the latency-tiered poll path (\`readGlobalShapeRows\`)
1093
+ // instead of the CDC poke path.
1094
+ const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global";
1095
+
1096
+ return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
1097
+ }
1098
+ `:"",c=e?[...new Set(o.policies.filter(l=>l.on==="read"&&l.table!=="").map(l=>l.table))].toSorted((l,O)=>l.localeCompare(O)):[],g=c.length>0?`
1099
+ /** 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). */
1100
+ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(c)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
1101
+ `:"";return{customMutatorOverride:r?`
1102
+ protected override isCustomMutator(functionPath: string): boolean {
1103
+ return LUNORA_MUTATOR_PATHS.has(functionPath);
1104
+ }
1105
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:g,shapeReadPolicyImport:g===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:f}},Zr=(r,t)=>r?`
1106
+ protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1107
+ const env = this.env as Record<string, unknown>;
1108
+ // A shape read performs no writes, so the widened request only needs
1109
+ // the inbound bookmark (pin the membership drain to the caller's own
1110
+ // prior writes) — no \`onBookmark\` here.
1111
+ //
1112
+ // The two identity members are named rather than spread, matching the
1113
+ // dispatch-path request built in \`buildCtx\`. A spread would also hand
1114
+ // the global writer \`ip\`, and \`globalShapeReadKey\` — the per-flush
1115
+ // cache in front of this read — keys on identity + userId only. Equal
1116
+ // keys must mean equal rows, so a field the writer can scope by has to
1117
+ // be either in the key or out of the request; it is out.
1118
+ const bookmark = this.getInboundBookmark();
1119
+ const globalRequest = {
1120
+ ...this.globalCdcOptions(config.cdc ?? false),
1121
+ ...(bookmark === undefined ? {} : { bookmark }),
1122
+ ...(identity?.identity === undefined ? {} : { identity: identity.identity }),
1123
+ ...(identity?.userId === undefined ? {} : { userId: identity.userId }),
1124
+ };
1125
+ const globalDb: DatabaseWriterLike = ${t}?.(env, globalRequest) ?? globalDbStub;
1126
+ const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
1127
+
1128
+ let cursor: null | string = null;
1129
+
1130
+ // Drain every page of the global membership so the seed/diff sees the
1131
+ // full rowset (D1 \`findMany\` is paginated). Stop one row past the cap:
1132
+ // a broad \`.global()\` shape would otherwise materialize an unbounded
1133
+ // array before the caller's \`withinGlobalShapeBound\` check rejects it,
1134
+ // so bail early and let the caller fail it closed.
1135
+ do {
1136
+ // eslint-disable-next-line no-await-in-loop -- sequential page drain to assemble the full membership
1137
+ const page = await globalDb.findMany(resolved.table, { cursor, ...(resolved.effectiveWhere === undefined ? {} : { where: resolved.effectiveWhere }) });
1138
+
1139
+ for (const doc of page.page) {
1140
+ rows.push({ doc, id: String((doc as { _id?: unknown })._id) });
1141
+
1142
+ if (rows.length > ShardDOBase.GLOBAL_SHAPE_MAX_ROWS) {
1143
+ return rows;
1144
+ }
1145
+ }
1146
+
1147
+ cursor = page.isDone ? null : page.continueCursor;
1148
+ } while (cursor !== null);
1149
+
1150
+ return rows;
1151
+ }
1152
+
1153
+ protected override async readGlobalChangedTables(sinceSeq: number, cursorOnly?: boolean): Promise<{ cursor: number; floor?: number; tables: string[] } | undefined> {
1154
+ const env = this.env as Record<string, unknown>;
1155
+ // Metadata-only: this asks the global changelog which TABLES moved,
1156
+ // never what changed in them, so it costs one small read per poll tick
1157
+ // for the whole shard — and a tick whose answer omits a shape's table
1158
+ // skips that shape's membership drain entirely.
1159
+ // Named local, not an inline object literal — same reason as the
1160
+ // dispatch path and \`readGlobalShapeRows\`: \`bookmark\` is not declared
1161
+ // on the narrower Hyperdrive thunk's \`request\` type, and an inline
1162
+ // literal trips an excess-property error (TS2353) that makes the
1163
+ // emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
1164
+ // a \`defineShape\`. The Hyperdrive factory simply never reads it.
1165
+ const bookmark = this.getInboundBookmark();
1166
+ const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), ...(bookmark === undefined ? {} : { bookmark }) };
1167
+ const globalDb: DatabaseWriterLike = ${t}?.(env, globalRequest) ?? globalDbStub;
1168
+
1169
+ return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
1170
+ }
1171
+ `:"",en=r=>({externalSourceOverride:r?`
1172
+ protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1173
+ const env = (this.env ?? {}) as Record<string, unknown>;
1174
+ const sourced = Object.entries((schema as unknown as SchemaLike).tables)
1175
+ .map(([table, definition]) => [table, (definition as { externalSource?: ExternalSourceLike }).externalSource] as const)
1176
+ .filter((entry): entry is [string, ExternalSourceLike] => entry[1] !== undefined);
1177
+
1178
+ if (sourced.length === 0) {
1179
+ return undefined;
1180
+ }
1181
+
1182
+ // A blocked unique index refuses user writes; ingest must not write rows the missing constraint would have rejected.
1183
+ // The alarm tier records the refusal and retries on its poll interval.
1184
+ this.ensureServable();
1185
+
1186
+ const shardKey = this.currentShardKey();
1187
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1188
+
1189
+ let clients = sourceClientCache.get(this);
1190
+
1191
+ if (clients === undefined) {
1192
+ clients = new Map();
1193
+ sourceClientCache.set(this, clients);
1194
+ }
1195
+
1196
+ let polledAt = sourcePollAtCache.get(this);
1197
+
1198
+ if (polledAt === undefined) {
1199
+ polledAt = new Map();
1200
+ sourcePollAtCache.set(this, polledAt);
1201
+ }
1202
+
1203
+ const now = Date.now();
1204
+ // \`nextDueAt\` tracks the EARLIEST next-due timestamp across every
1205
+ // non-manual source; the shared alarm re-arms there instead of the
1206
+ // fixed 2 s global-shape floor, so a large \`refresh.everyMs\` actually
1207
+ // sleeps until it's due. Stays \`undefined\` when every source is
1208
+ // \`refresh: "manual"\`, so the shared alarm goes idle for this tier.
1209
+ let nextDueAt: number | undefined;
1210
+
1211
+ for (const [table, source] of sourced) {
1212
+ if (source.refresh === "manual") {
1213
+ continue;
1214
+ }
1215
+
1216
+ if (isSourceDue(source.refresh, polledAt.get(table), now)) {
1217
+ try {
1218
+ let client = clients.get(source.binding);
1219
+
1220
+ if (client === undefined) {
1221
+ client = config.sourceClient?.(env, source.binding);
1222
+
1223
+ if (client !== undefined) {
1224
+ clients.set(source.binding, client);
1225
+ }
1226
+ }
1227
+
1228
+ if (client === undefined) {
1229
+ // No SqlClient resolved for this binding (host never wired
1230
+ // \`config.sourceClient\`, or wired it wrong). Surface it in the
1231
+ // Logs panel and stamp \`polledAt\` so a persistent misconfig backs
1232
+ // off to \`refresh.everyMs\` instead of retrying every alarm tick.
1233
+ this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`), trace);
1234
+ } else {
1235
+ // A FRESH tracker per TABLE, not one shared across the whole
1236
+ // loop: one table's runaway pull must not spend a budget a
1237
+ // sibling table needs, and a limit hit here must not block
1238
+ // that sibling from getting its own full budget this tick.
1239
+ const writer = createShardCtxDb({
1240
+ // Admin and maintenance writes go through the SAME reactive-cache hooks as
1241
+ // a user mutation. Without this, a studio row edit, a TTL sweep, an admin
1242
+ // import, a CDC apply or a data-migration backfill writes without
1243
+ // invalidating, and the next query answers from the pre-write snapshot.
1244
+ ...this.ctxDbTuning(),
1245
+ broadcast: (delta) => {
1246
+ this.recordChangedTable(delta.table, delta.indexKeys);
1247
+ },
1248
+ cdc: config.cdc ?? false,
1249
+ headroom: this.alarmHeadroom(),
1250
+ scheduler,
1251
+ schema: schema as unknown as SchemaLike,
1252
+ sql: this.sql as SqlExec,
1253
+ });
1254
+
1255
+ if (source.mode === "incremental") {
1256
+ // Incremental (plan 136): pull only rows past the durable
1257
+ // watermark (or a full-pull seed/reconcile), upsert-only.
1258
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
1259
+ await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
1260
+ } else {
1261
+ // 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
1262
+ await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
1263
+ }
1264
+ }
1265
+
1266
+ // Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
1267
+ // poll that outruns \`everyMs\` must not make \`nextDueAt\` (below)
1268
+ // stale-immediate and re-arm the alarm in a hammering loop.
1269
+ polledAt.set(table, Date.now());
1270
+ } catch (error) {
1271
+ if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
1272
+ // Batch full, not a genuine failure. Incremental mode only
1273
+ // persists its watermark AFTER a full apply (see
1274
+ // \`pullExternalSourceIncrementalTick\`), so this throw left it
1275
+ // untouched — the next tick safely re-pulls/re-applies the
1276
+ // SAME slice (idempotent upsert). Full-pull mode (and an
1277
+ // incremental source's own occasional full-pull/reconcile
1278
+ // sweep) has no resumable cursor at all — deliberately not
1279
+ // inventing one here; a retry just redoes the whole pull,
1280
+ // safe if wasteful. Either way: warn instead of
1281
+ // \`recordExternalSourceError\`, and leave \`polledAt\`
1282
+ // UNCHANGED (skip the stamp below via \`continue\`) so this
1283
+ // table stays "due" and \`nextPollAlarmTarget\`'s existing
1284
+ // due-now floor re-arms the shared alarm promptly — not a
1285
+ // fresh \`setAlarm(now)\`.
1286
+ this.recordExternalSourceWarning(
1287
+ table,
1288
+ \`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
1289
+ trace,
1290
+ );
1291
+
1292
+ nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
1293
+
1294
+ continue;
1295
+ }
1296
+
1297
+ this.recordExternalSourceError(table, error, trace);
1298
+ // Stamp on failure too, so a persistently failing source throttles
1299
+ // to \`refresh.everyMs\` rather than being hammered every tick.
1300
+ polledAt.set(table, Date.now());
1301
+ }
1302
+ }
1303
+
1304
+ // This source's own next-due time, read AFTER the poll-or-skip above
1305
+ // so a just-polled source reports \`now + everyMs\` (its FRESH due
1306
+ // time), not the stale pre-poll one. An omitted \`refresh\` (poll
1307
+ // every tick) is due again immediately.
1308
+ const sourceNextDueAt = source.refresh === undefined ? now : (polledAt.get(table) ?? now) + source.refresh.everyMs;
1309
+
1310
+ nextDueAt = nextDueAt === undefined ? sourceNextDueAt : Math.min(nextDueAt, sourceNextDueAt);
1311
+ }
1312
+
1313
+ return nextDueAt;
1314
+ }
1315
+ `:"",sourceBootstrap:r?`
1316
+ const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1317
+ const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1318
+
1319
+ return source !== undefined && source.refresh !== "manual";
1320
+ });
1321
+
1322
+ if (autoSourced) {
1323
+ void this.scheduleSourcePoll();
1324
+ }
1325
+ `:"",sourceClientCacheConst:r?`
1326
+ const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1327
+ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1328
+ `:""}),tn=(r,t)=>{const e=t.length>0,n=r?q("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",a=e?` const vectorShardKey = this.currentShardKey();
1329
+ `:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",c=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(w=>JSON.stringify(w)).join(", ")}]`]:[]].join(", ")} }`,g=r?`
1330
+ const vectorSync = this.vectorSync(env);
1331
+ // Vectorize lives outside this shard's SQLite, so a query whose result
1332
+ // depends on a similarity search cannot be proven current on reconnect —
1333
+ // an unrelated upsert (or a re-index) moves the matches without touching
1334
+ // \`__cdc_log\`. Only \`ctx.vectors\` is wrapped: the write-through
1335
+ // vector-sync hook keeps calling the bare facade.
1336
+ const bareVectors = vectorSync?.vectors ?? vectorsStub;
1337
+ const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
1338
+ const onWrite = vectorSync?.onWrite;
1339
+ `:"";return{vectorSyncMethod:r?`
1340
+ private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
1341
+ if (!config.vectors) {
1342
+ return undefined;
1343
+ }
1344
+
1345
+ const lunora = createVectors({ indexes: config.vectors(env) });
1346
+ ${a} const vectors = createContextVectors(lunora${c});
1347
+
1348
+ return {
1349
+ backfill: createVectorBackfillSync({ ${i}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
1350
+ onWrite: createVectorSyncHook({ ${i}schema: schema as unknown as VectorSchemaLike, vectors }),
1351
+ vectors,
1352
+ };
1353
+ }
1354
+
1355
+ // \`__lunora_admin__:backfillVectors\`: the rows that predate a vector index,
1356
+ // a page at a time, each page ordered on the after-commit chain so it
1357
+ // never lands over a newer write's vector.
1358
+ protected override async runShardVectorBackfill(options: { maxPages?: number; restart?: boolean }): Promise<VectorBackfillProgress> {
1359
+ this.ensureMigrated();
1360
+
1361
+ const vectorSync = this.vectorSync((this.env ?? {}) as Record<string, unknown>);
1362
+
1363
+ if (!vectorSync) {
1364
+ throw new LunoraError("NOT_IMPLEMENTED", "vector backfill is unavailable: no vectors configured. Pass \`vectors\` to createShardDO().");
1365
+ }
1366
+
1367
+ return backfillVectorIndexes(this.sql as SqlExec, vectorBackfillTargets(schema as unknown as VectorSchemaLike), vectorSync.backfill, {
1368
+ ...options,
1369
+ ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1370
+ });
1371
+ }
1372
+ `:"",vectorsBuild:g,vectorsStub:n}},vn=({advisories:r=[],agents:t=[],capabilities:e=new Set,containers:o=[],env:n,flagKeys:a=[],hasFlags:i=!1,hasNotify:f=!1,hasRooms:c=!1,hasSecretValues:g=!1,hasSensitiveArgs:A=!1,hasSockets:w=!1,lazyFunctions:u=!1,hasVectors:l=!0,liveStreamDeclarations:O=[],liveStreams:v=!1,maskMetadata:F,mutators:B=[],queues:R=[],rlsMetadata:j,schema:d,schemaSnapshot:k,shapes:I=[],storageRules:W,studioFeatures:K,hasIpReaders:E=!1,services:T=[],topics:H=[],useUmbrella:V=!1,workflowEvents:C=[],workflows:x=[]})=>{const h=_r(V),G=B.length>0,p=I.length>0,L=I.some(s=>Rr(s.args).length>0),P=A||L,ge=k===void 0?"":Zt(k),be=k===void 0?"":`
1373
+ /** 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. */
1374
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(er(k))}, json: ${JSON.stringify(ge)} };
1375
+ `,ye=k===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",S=ar(e),N=sr(i,h.flags),Q=or(a,i,h.flags),z=kr(f),J=ir(n),{build:we,contextField:ve,importLines:ke,specs:Se}=dr(Dr(R)),{build:Re,contextField:xe,importLines:Ae,specs:Oe}=cr(H,R),Y=lr(T,h.server),{build:Te,contextField:_e,importLines:De,specs:Ie}=ur(o,d.jurisdiction),{build:Ee,contextField:Ce,importLines:Le,specs:Pe}=hr(x),{build:Ne,contextField:$e,importLines:Me,schedulerSource:qe,specs:Ue,stampsOutbox:Fe}=pr(t,g&&t.length>0),{build:Be,configField:je,contextField:We,imports:Ke,stub:He}=mr(e.has("payments")),Ve=r,{advisoryRules:Ge,advisoryRows:Qe}=Er(Ve),ne=j??{policies:[],roles:[]},ze=F??{columns:[]},Je=W??{rules:[]},Ye=K??{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:Xe,override:Ze}=fr(x,C),{constant:et,override:tt}=gr(x,C),{constant:rt,override:nt}=br(R),b=l&&d.vectorIndexes.length>0,X=new Set(d.tables.filter(s=>Ir(s)).map(s=>s.name)),ae=b&&d.vectorIndexes.some(s=>X.has(s.table)),_=d.tables.some(s=>s.shardMode==="global"),Z=yr(X),ee=d.tables.some(s=>tr(s)),se=d.tables.some(s=>rr(s)),$=d.tables.some(s=>s.externalSource!==void 0),oe=d.tables.some(s=>s.memory===!0),te=d.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&ee)throw new pe("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const re=d.tables.length>0,at=Wr(d),st=Hr(d),ot=Yr(d),it=Kr(d),ie=Vr(d),de=wr(b,x.length>0,R.length>0,i,te);p&&de.push("WhereInput");const ce=vr(_),{customMutatorOverride:dt,shapeGuardImport:ct,shapeReadPolicyAssertion:lt,shapeReadPolicyImport:ut,shapeResolveOverride:ht}=Xr({hasMutators:G,hasSensitiveShapes:L,hasShapes:p,rlsData:ne}),D=v?O:[];for(const s of D)if(xr(s.exportName,"live stream export name"),!Ar.test(s.filePath))throw new pe("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const pt=u?[]:D.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),mt=` protected override liveStreams() {
1376
+ return { ${D.map(s=>`${Or(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1377
+ }
1378
+ `,ft=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
1379
+ ${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1380
+ `)}
1381
+ ]);
1382
+
1383
+ private readonly loadedLiveStreams = new Map<string, { validatePublish: (topic: string, payload: unknown) => unknown }>();
1384
+
1385
+ protected override loadLiveStream(stream: string): Promise<void> | undefined {
1386
+ const load = this.loadedLiveStreams.has(stream) ? undefined : this.liveStreamLoaders.get(stream);
1387
+
1388
+ return load === undefined
1389
+ ? undefined
1390
+ : load().then((declaration) => {
1391
+ this.loadedLiveStreams.set(stream, declaration);
1392
+ });
1393
+ }
1394
+
1395
+ // Only the streams a publish has already loaded: a stream not yet loaded was either never published to or is
1396
+ // unknown, and either way \`declaredLivePayload\` refuses what this does not hold.
1397
+ protected override liveStreams() {
1398
+ return Object.fromEntries(this.loadedLiveStreams);
1399
+ }
1400
+ `;let le="";D.length>0&&(le=u?ft:mt);const M=[`import type { ${de.join(", ")} } from "${h.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${te?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${ct}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${$?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ce.importFragment}ShardDO as ShardDOBase } from "${h.do}";`,...$?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${h.do}";`]:[],p?`import { asBucketStorage, ${ut}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`];re&&M.push(`import type { FacadeEntry } from "${h.server}";`,`import { bindOrm, defineLazyFacade } from "${h.server}";`),b&&M.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),M.push(...S.importLines,...N.importLines,...z.importLines,...J.importLines,...De,...Le,...ke,...Ae,...Y.importLines,...Me,...Ke,...P?[`import { sensitiveArgumentNames } from "${h.values}";`]:[],"",'import schema from "../schema.js";',...pt,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...u?["getLoadedFunction","loadFunction"]:[],...G?["LUNORA_MUTATOR_PATHS"]:[],...E?["LUNORA_IP_READER_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...w?["LUNORA_SOCKETS"]:[],...p?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const gt=b?`
1401
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",bt=se?`
1402
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",yt=ee?`
1403
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",wt=$?`
1404
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",vt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",kt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",St="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Rt=_?q("globalDbStub: DatabaseWriterLike",vt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:xt,vectorsBuild:At,vectorsStub:Ot}=tn(b,ae?d.vectorIndexes.filter(s=>X.has(s.table)).map(s=>s.name):[]),Tt=`{
1405
+ ...this.ctxDbTuning(),
1406
+ auth: {
1407
+ get identity() {
1408
+ return readIdentity() ?? null;
1409
+ },
1410
+ get userId() {
1411
+ return readUserId() ?? null;
1412
+ },
1413
+ },
1414
+ broadcast: (delta) => {
1415
+ this.recordChangedTable(delta.table, delta.indexKeys);
1416
+ },
1417
+ // Read at call time, not captured: the baseline belongs to the
1418
+ // dispatch in flight, and a queued mutation admitted after a
1419
+ // sibling's prologue must be judged against ITS caller's cursor.
1420
+ baselineSeq: () => this.getCurrentBaselineSeq(),
1421
+ cdc: config.cdc ?? false,
1422
+ // A dispatch with NO caller identity runs system-trusted: RLS scopes
1423
+ // rows to a user, and these have no user to scope to. This is the tier
1424
+ // migrations, imports and the external-source poll loop already run in
1425
+ // (see \`adminWriterPrelude\`). Only \`onShardInit\` and \`onQueryChange\`
1426
+ // reach it; \`onConnect\`/\`onDisconnect\` carry a verified identity and
1427
+ // stay guarded like any request.
1428
+ enforceRls: options.trusted !== true,
1429
+ headroom: options.headroom ?? this.transactionHeadroom(options.functionPath),
1430
+ // A live predicate, not a flag: the transaction opens AFTER this ctx
1431
+ // is built (a mutation dispatch wraps the handler), so only a call-time
1432
+ // read reports the truth. \`_commitSeq\` reuses one sequence across
1433
+ // writes only while they commit together — an action is not wrapped, so
1434
+ // each of its writes allocates its own.
1435
+ inTransaction: () => this.isInTransaction(),
1436
+ onIndexUse: this.getCtxDbIndexUseHook(),
1437
+ onStalePatchDropped: (event) => {
1438
+ this.recordStalePatchDropped(event);
1439
+ },
1440
+ // Bound to THIS dispatch's reactive-cache read scope (\`handleRpc\`
1441
+ // threads it in), so two concurrent queries never stamp each
1442
+ // other's dep sets. \`executeSubscription\` overrides both with its
1443
+ // own \`ReadFootprint\` pair instead, and a dispatch with neither
1444
+ // gets an unbound hook that stamps no deps.
1445
+ onRead: options.onRead ?? this.getCtxDbReadHook(options.scope),
1446
+ // Omitted when there is no scope so \`createShardCtxDb\`
1447
+ // keeps its own "degrade a provable slice to a whole-table dep"
1448
+ // fallback rather than reporting into a no-op.
1449
+ ...(options.onReadRange !== undefined
1450
+ ? { onReadRange: options.onReadRange }
1451
+ : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${b?`
1452
+ // Vectorize is outside this shard's SQLite and cannot roll back, so
1453
+ // the sync is held until the mutation's transaction has COMMITTED
1454
+ // (\`deferAfterCommit\`) instead of running inline. Inline, a write
1455
+ // that later aborted left a vector pointing at a row that does not
1456
+ // exist — which a search then surfaces — and a rolled-back delete
1457
+ // left the row with its vector already purged. Outside a
1458
+ // transaction (an action) nothing is open and it runs at once.
1459
+ ...(onWrite === undefined ? {} : { onWrite: (event) => this.deferAfterCommit(() => onWrite(event)) }),`:""}
1460
+ scheduler,
1461
+ schema: schema as unknown as SchemaLike,
1462
+ sql: this.sql as SqlExec,
1463
+ storage,${_?`
1464
+ globalDb,`:""}
1465
+ }`,_t=b?`
1466
+ vectors,`:"",Dt=re?`
1467
+ orm: bindOrm(facade),`:"",ue=ee?"config.hyperdriveGlobal":"config.d1",It=_?` const bookmark = this.getInboundBookmark();
1468
+ const globalRequest = {
1469
+ ...this.globalCdcOptions(config.cdc ?? false),
1470
+ ...(bookmark === undefined ? {} : { bookmark }),
1471
+ get identity(): Record<string, unknown> | undefined {
1472
+ return readIdentity();
1473
+ },
1474
+ onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
1475
+ get userId(): string | undefined {
1476
+ return readUserId();
1477
+ },
1478
+ };
1479
+ const globalDb: DatabaseWriterLike = ${ue}?.(env, globalRequest) ?? globalDbStub;
1480
+ `:"",Et=Zr(p&&_,ue),Ct=c?` protected override roomHandlerPath(topic: string): string | undefined {
1481
+ // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1482
+ return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1483
+ }
1484
+ `:"",Lt=w?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1485
+ return LUNORA_SOCKETS[path];
1486
+ }
1487
+ `:"",{externalSourceOverride:Pt,sourceBootstrap:Nt,sourceClientCacheConst:$t}=en($),Mt=`
1488
+ private shardInitDeferred = false;
1489
+ private deferredShardInit?: Promise<void>;
1490
+
1491
+ protected override async runShardInit(): Promise<void> {
1492
+ this.ensureMigrated();
1493
+ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1494
+ `:""}
1495
+ if (this.blockedUniqueIndexes.length > 0) {
1496
+ this.shardInitDeferred = true;
1497
+
1498
+ return;
1499
+ }
1500
+
1501
+ await this.dispatchShardInit();
1502
+ }
1503
+
1504
+ protected override async ensureShardInit(): Promise<void> {
1505
+ await super.ensureShardInit();
1506
+
1507
+ if (!this.shardInitDeferred) {
1508
+ return;
1509
+ }
1510
+
1511
+ try {
1512
+ this.ensureMigrated();
1513
+ } catch (error: unknown) {
1514
+ this.recordShardInitError("__shard_init__", error);
1515
+
1516
+ return;
1517
+ }
1518
+
1519
+ if (this.blockedUniqueIndexes.length > 0) {
1520
+ return;
1521
+ }
1522
+
1523
+ this.deferredShardInit ??= (async (): Promise<void> => {
1524
+ try {
1525
+ await this.dispatchShardInit();
1526
+ } finally {
1527
+ this.shardInitDeferred = false;
1528
+ }
1529
+ })();
1530
+
1531
+ await this.deferredShardInit;
1532
+ }
1533
+ `,qt=ie.length>0?`
1534
+ if (LUNORA_TTL_SWEEPS.length > 0) {
1535
+ void this.scheduleTtlSweep();
1536
+ }
1537
+ `:"",Ut=`
1538
+ public constructor(state: ShardDOState, env: unknown) {
1539
+ super(state, env, {
1540
+ // Every writer this file builds spreads the ctxDbTuning() slice —
1541
+ // the user-facing ctx and all three admin/maintenance writers — so
1542
+ // the base class can drop its coarse invalidation backstop. Only the
1543
+ // emitter can know that; a hand-written subclass leaves this unset
1544
+ // and keeps the backstop.
1545
+ ctxDbCacheWired: true,
1546
+ ...(config.deliveryAuthorization === undefined ? {} : { deliveryAuthorization: config.deliveryAuthorization((env ?? {}) as Record<string, unknown>) }),
1547
+ ...(config.maxRelationKeys === undefined ? {} : { maxRelationKeys: config.maxRelationKeys }),
1548
+ ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1549
+ ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1550
+ // The same sink \`buildCtx\` resolves, made reachable before any ctx
1551
+ // exists — a trigger that fails first still flushes and fuses.
1552
+ ...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
1553
+ });
1554
+ ${E?` for (const path of LUNORA_IP_READER_PATHS) {
1555
+ this.ipKeyedFunctionPaths.add(path);
1556
+ }
1557
+ `:""}${Nt}${qt} }
1558
+
1559
+ protected override isCacheableQuery(functionPath: string): boolean {
1560
+ // NOT \`kind === "query"\` alone. A cache hit answers without running
1561
+ // \`handleRpc\`, so the \`internal\` refusal at the top of it is skipped —
1562
+ // and an \`internalQuery\` primed by a trusted system dispatch was then
1563
+ // served to an anonymous client that the refusal would have 404'd.
1564
+ //
1565
+ // \`perDispatch\` is the same argument one layer out: the procedure's
1566
+ // own \`.use()\` chain runs INSIDE \`handleRpc\`, so a hit skips it too.
1567
+ // A \`.use(rateLimit(...))\` query was therefore charged once and then
1568
+ // served from the memo to every later request — each of which still
1569
+ // reached this Durable Object and still cost it a dispatch, so only
1570
+ // the accounting was skipped. Metering and memoizing are mutually
1571
+ // exclusive; the author asking for the first is choosing against the
1572
+ // second.
1573
+ const registered = LUNORA_FUNCTIONS[functionPath];
1574
+
1575
+ return registered?.kind === "query" && registered.visibility !== "internal" && registered.perDispatch !== true;
1576
+ }
1577
+
1578
+ protected override isPaidFunction(functionPath: string): boolean {
1579
+ return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1580
+ }
1581
+ `,he=u?`
1582
+ protected override prepareFunction(functionPath: string, reason: "rpc" | "subscription" | "stream" | "reactor"): Promise<void> | undefined {
1583
+ const registered = LUNORA_FUNCTIONS[functionPath];
1584
+ const allowsInternal = reason === "reactor" || (reason === "rpc" && this.isSystemDispatch());
1585
+
1586
+ if (registered?.visibility === "internal" && !allowsInternal) {
1587
+ return;
1588
+ }
1589
+
1590
+ if (getLoadedFunction(functionPath) !== undefined) {
1591
+ return;
1592
+ }
1593
+
1594
+ return this.holdShardWhileLoading(() => loadFunction(functionPath));
1595
+ }
1596
+ `:"",Ft=he===""?`
1597
+
1598
+ `:`${he}
1599
+ `,Bt=P?`
1600
+ protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
1601
+ const registered = LUNORA_FUNCTIONS[functionPath];${L?`
1602
+ const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
1603
+ const fromValidators = sensitiveArgumentNames(registered?.args ?? ${L?"shape?.args ?? ":""}{});
1604
+
1605
+ if (registered?.sensitiveArgs === undefined) {
1606
+ return fromValidators;
1607
+ }
1608
+
1609
+ return new Set([...registered.sensitiveArgs, ...fromValidators]);
1610
+ }
1611
+
1612
+ `:"",jt=Nr(u),Wt=u?` const preparation = this.prepareFunction(functionPath, "subscription");
1613
+ if (preparation !== undefined) await preparation;
1614
+ `:"",Kt=jr(P).replace("__PREPARE_FUNCTION__",Wt),Ht=Ur(c,u,Fe),Vt=re?`
1615
+ const facade = db as unknown as Record<string, FacadeEntry>;
1616
+ ${d.tables.map(s=>` defineLazyFacade(db, ${JSON.stringify(s.name)});`).join(`
1617
+ `)}
1618
+ `:"",Gt=`${S.everyBuild}${N.build}${J.build}
1619
+ const secrets = createSecrets(env);
1620
+ `,Qt=`${S.everyFields}${N.contextField}${z.contextField}${J.contextField}
1621
+ secrets,`,zt=z.build,Jt=v?`
1622
+ const live = {
1623
+ publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
1624
+ await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
1625
+ },
1626
+ };
1627
+ `:"",Yt=[...S.actionFields,...T.length>0?["services"]:[],...v?["live"]:[]],Xt=`${S.actionBuild}${Y.build}${Jt}`;return`${Tr}${M.join(`
1628
+ `)}
1629
+
1630
+ type FunctionKind = "action" | "mutation" | "query";
1631
+
1632
+ interface FunctionReference {
1633
+ __lunoraRef: string;
1634
+ }
1635
+
1636
+ /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1637
+ const LUNORA_TABLE_REFS = ${m(at,"Record<string, Record<string, string>>")};
1638
+
1639
+ /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1640
+ const LUNORA_TABLE_INDEXES = ${m(st,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1641
+
1642
+ /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1643
+ const LUNORA_TABLE_COLUMNS = ${m(ot,`Record<
1644
+ string,
1645
+ Array<{
1646
+ bucket?: string;
1647
+ enumValues?: string[];
1648
+ isStorage?: boolean;
1649
+ name: string;
1650
+ nullable?: boolean;
1651
+ onDelete?: "cascade" | "restrict" | "set null";
1652
+ optional: boolean;
1653
+ pk?: boolean;
1654
+ ref?: string;
1655
+ type: string;
1656
+ }>
1657
+ >`)};
1658
+
1659
+ /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1660
+ const LUNORA_STORAGE_COLUMNS = ${m(it,"Record<string, string[]>")};
1661
+
1662
+ /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1663
+ const LUNORA_TTL_SWEEPS = ${nr(ie,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1664
+
1665
+ /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1666
+ const LUNORA_ADVISORY_RULES = ${m(Ge,"Record<string, Partial<AdvisoryFinding>>")};
1667
+
1668
+ /** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
1669
+ const LUNORA_ADVISORY_ROWS = ${m(Qe,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1670
+
1671
+ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1672
+ let cached: AdvisoryFinding[] | undefined;
1673
+ return () => (cached ??= LUNORA_ADVISORY_ROWS().map((row) => ({ ...LUNORA_ADVISORY_RULES()[row.name], ...row }) as AdvisoryFinding));
1674
+ })();
1675
+
1676
+ /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1677
+ const LUNORA_RLS_METADATA = ${m(ne,"RlsPoliciesResult")};
1678
+ ${lt}
1679
+ /** 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. */
1680
+ const LUNORA_MASK_METADATA = ${m(ze,"MaskPoliciesResult")};
1681
+
1682
+ /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1683
+ const LUNORA_STORAGE_RULES = ${m(Je,"StorageRulesResult")};
1684
+
1685
+ /** 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. */
1686
+ const LUNORA_STUDIO_FEATURES = ${m(Ye,"StudioFeaturesResult")};
1687
+
1688
+ /** How long a shard with a UNIQUE index blocked by duplicate rows serves the cached diagnostic before re-attempting the build. */
1689
+ const BLOCKED_MIGRATION_RETRY_MS = 5000;
1690
+ ${be}${Z.constant}${Q.constant}${Xe}${et}${rt}${Ie}${Pe}${Se}${Oe}${Y.specs}${Ue}
1691
+ export interface ShardDOConfig {
1692
+ /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1693
+ cdc?: boolean;
1694
+ /** Current authority for RPC and ordinary subscription deliveries; other live delivery modes are refused. */
1695
+ deliveryAuthorization?: (env: Record<string, unknown>) => DeliveryAuthorization;
1696
+ /** Ceiling on the join keys one relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
1697
+ maxRelationKeys?: number;
1698
+ /** 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. */
1699
+ reactiveCache?: boolean | { maxBytes?: number; maxEntries?: number };
1700
+ /** 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. */
1701
+ relationExistsPushDown?: "always" | "auto" | "never";
1702
+ /** 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. */
1703
+ observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1704
+ /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1705
+ scheduler?: (env: Record<string, unknown>) => unknown;
1706
+ /** \`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. */
1707
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${gt}${S.configFields}${N.configField}${je}${bt}${yt}${wt}${Z.configField}
1708
+ }
1709
+ ${q("schedulerStub",kt,["cancel","runAfter","runAt"])}${q("storageStub",St,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${Rt}${$t}${Ot}${S.stubs}${He}
1710
+ // \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
1711
+ // mutation may be replayed, so a network call in either returns a different answer
1712
+ // on each run. Refused at runtime, not only linted: the advisor sees just the call
1713
+ // sites it can read, and a call inside a dependency is invisible to it.
1714
+ // Synchronous on purpose: an async refusal only rejects a promise the handler may
1715
+ // discard, and the handler would then return normally. A sync throw surfaces at the call.
1716
+ // Module scope: it captures nothing, so one instance serves every dispatch.
1717
+ const refuseFetch = (): never => {
1718
+ throw new LunoraError("FORBIDDEN", "ctx.fetch is action-only: network I/O belongs in an action, not a query or mutation");
1719
+ };
1720
+
1721
+ ${jt}
1722
+
1723
+ /**
1724
+ * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1725
+ * from the worker entry so wrangler binds it by name.
1726
+ */
1727
+ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1728
+ class extends ShardDOBase {${Ut}
1729
+ private blockedUniqueIndexes: readonly string[] = [];
1730
+ private migrated = false;
1731
+ private migrationRetryAt = 0;${Ft}${Bt}${Ht}
1732
+ ${ce.override}
1733
+ ${Kt}
1734
+ ${dt}${ht}${Et}${Pt}
1735
+ protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1736
+ return LUNORA_LIFECYCLE_HOOKS[event];
1737
+ }
1738
+ ${Ct}${Lt}${le}${Z.override}${Mt}
1739
+ // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1740
+ // socket-terminated half of the same reactivity — and differs only in who
1741
+ // consumes the result: the base's \`dispatchReactors\` stores the digest as
1742
+ // the new baseline and the footprint as the "should I even re-run this"
1743
+ // gate, instead of pushing a frame down a socket.
1744
+ //
1745
+ // Dispatched through \`runMutationTransaction\` because a reactor handler is
1746
+ // a mutation: its writes must commit all-or-nothing, the jobs it schedules
1747
+ // must wait for that commit, and the objects its row deletes orphaned must
1748
+ // be flushed once it lands. Safe to open a span here: the refresh drain
1749
+ // runs OUTSIDE any dispatch transaction (it is post-flush background work),
1750
+ // so this never nests.
1751
+ //
1752
+ // NO identity is threaded, and the ctx is built \`trusted\`. A reactor fires
1753
+ // because data moved, not because anyone asked, so there is no user for RLS
1754
+ // to scope to — it runs in the same system tier as migrations and the
1755
+ // external-source poll loop. Inheriting the shared per-request identity
1756
+ // would instead run an app's reactor as whichever user happened to write
1757
+ // last, which is worse than running it as nobody.
1758
+ protected override async runReactor(functionPath: string, previousDigest?: string): Promise<{ digest: string; ran: boolean; tables: readonly string[] } | undefined> {
1759
+ ${u?` const requestScope = this.captureRequestScope();
1760
+ const preparation = this.prepareFunction(functionPath, "reactor");
1761
+
1762
+ if (preparation !== undefined) {
1763
+ try {
1764
+ await preparation;
1765
+ } finally {
1766
+ this.restoreRequestScope(requestScope);
1767
+ }
1768
+ }
1769
+
1770
+ `:""} const registered = LUNORA_FUNCTIONS[functionPath];
1771
+
1772
+ if (!registered || registered.kind !== "mutation") {
1773
+ return undefined;
1774
+ }
1775
+
1776
+ this.ensureServable();
1777
+
1778
+ const footprint = createReadFootprint();
1779
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(functionPath), onRead: footprint.onRead, onReadRange: footprint.onReadRange, replayKey: false, trusted: true });
1780
+ const outcome = (await this.runMutationTransaction(ctx, async () =>
1781
+ registered.handler(ctx, { previousDigest } as unknown as Record<string, unknown>),
1782
+ )) as {
1783
+ digest: string;
1784
+ ran: boolean;
1785
+ };
1786
+
1787
+ return { digest: outcome.digest, ran: outcome.ran, tables: [...footprint.tables] };
1788
+ }
1789
+
1790
+
1791
+ protected override tableRefs(table: string): Record<string, string> | undefined {
1792
+ return LUNORA_TABLE_REFS()[table];
1793
+ }
1794
+
1795
+ protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> {
1796
+ return LUNORA_TABLE_INDEXES()[table] ?? [];
1797
+ }
1798
+
1799
+ protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> {
1800
+ return LUNORA_TTL_SWEEPS;
1801
+ }
1802
+
1803
+ protected override tableColumns(table: string): Array<{
1804
+ bucket?: string;
1805
+ enumValues?: string[];
1806
+ isStorage?: boolean;
1807
+ name: string;
1808
+ nullable?: boolean;
1809
+ onDelete?: "cascade" | "restrict" | "set null";
1810
+ optional: boolean;
1811
+ pk?: boolean;
1812
+ ref?: string;
1813
+ type: string;
1814
+ }> {
1815
+ return LUNORA_TABLE_COLUMNS()[table] ?? [];
1816
+ }
1817
+
1818
+ protected override storageColumns(): Record<string, string[]> {
1819
+ return LUNORA_STORAGE_COLUMNS();
1820
+ }
1821
+
1822
+ protected override rlsMetadata(): RlsPoliciesResult {
1823
+ return LUNORA_RLS_METADATA();
1824
+ }
1825
+
1826
+ protected override maskMetadata(): MaskPoliciesResult {
1827
+ return LUNORA_MASK_METADATA();
1828
+ }
1829
+
1830
+ protected override storageRulesMetadata(): StorageRulesResult {
1831
+ return LUNORA_STORAGE_RULES();
1832
+ }
1833
+
1834
+ protected override studioFeatures(): StudioFeaturesResult {
1835
+ return LUNORA_STUDIO_FEATURES();
1836
+ }
1837
+ ${Q.evaluateOverride}${Q.subscriptionOverride}${Ze}${tt}${nt}
1838
+ protected override advisories(): AdvisoryFinding[] {
1839
+ return LUNORA_ADVISORIES();
1840
+ }
1841
+
1842
+ ${Lr}
1843
+
1844
+ /**
1845
+ * Migrate the base schema. A UNIQUE index that existing duplicate rows block
1846
+ * is deferred, not thrown: the rest of the pass completes so the admin path
1847
+ * (including the data migration that de-duplicates the table) keeps working.
1848
+ * User dispatch goes through \`ensureServable\`, which refuses until the
1849
+ * index exists. \`migrated\` stays false while one is outstanding, but the
1850
+ * retry (a schema-ledger write plus a full-table duplicate scan per blocked
1851
+ * index) runs at most once per \`BLOCKED_MIGRATION_RETRY_MS\`; in between,
1852
+ * callers see the cached diagnostics. The first call after a cold start
1853
+ * always migrates, and an admin data migration resets the clock so the
1854
+ * de-dup that unblocks the index takes effect on the next call.
1855
+ */
1856
+ protected override ensureMigrated(): void {
1857
+ if (this.migrated) {
1858
+ return;
1859
+ }
1860
+
1861
+ const now = Date.now();
1862
+
1863
+ if (this.blockedUniqueIndexes.length > 0 && now < this.migrationRetryAt) {
1864
+ return;
1865
+ }
1866
+
1867
+ this.blockedUniqueIndexes = runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false, deferBlockedUniqueIndexes: true${ye} });
1868
+ this.invalidateCompanionMemo();
1869
+ this.migrated = this.blockedUniqueIndexes.length === 0;
1870
+ this.migrationRetryAt = now + BLOCKED_MIGRATION_RETRY_MS;
1871
+
1872
+ if (this.blockedUniqueIndexes.length > 0) {
1873
+ // Once per retry window: the wire message only reaches the caller, and operators need it in the log.
1874
+ console.error(\`[lunora] unique index blocked by duplicate rows: \${this.blockedUniqueIndexes.join("; ")}\`);
1875
+ }
1876
+ }
1877
+
1878
+ private ensureServable(): void {
1879
+ this.ensureMigrated();
1880
+
1881
+ if (this.blockedUniqueIndexes.length > 0) {
1882
+ throw new LunoraError("UNIQUE_INDEX_DUPLICATES", this.blockedUniqueIndexes.join("; "));
1883
+ }
1884
+ }
1885
+ ${te?`
1886
+ protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1887
+ // Migrations create the fts5 companions; without them every backfill
1888
+ // statement would raise "no such table" on a shard that has never
1889
+ // served a request.
1890
+ this.ensureMigrated();
1891
+
1892
+ return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1893
+ }
1894
+ `:""}${xt}
1895
+ ${Pr({hasSensitiveArgs:P,lazyFunctions:u,actionOnlyFields:Yt,agentsBuild:Ne,agentsContextField:$e,agentsSchedulerSource:qe,containersBuild:Te,containersContextField:_e,databaseOptions:Tt,everyContextBuild:Gt,everyContextField:Qt,facadeBlock:Vt,globalDatabaseLine:It,notifyBuild:zt,ormContextField:Dt,paymentsBuild:Be,paymentsContextField:We,queuesBuild:we,queuesContextField:ve,topicsBuild:Re,topicsContextField:xe,vectorsBuild:At,vectorsContextField:_t,workflowsBuild:Ee,workflowsContextField:Ce,actionOnlyBuild:Xt})}
1896
+ };
1897
+ `};export{Kr as b,vn as e};