@lunora/codegen 1.0.0-alpha.20 → 1.0.0-alpha.201

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 (94) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +3324 -1151
  4. package/dist/index.d.ts +3324 -1151
  5. package/dist/index.mjs +1 -34
  6. package/dist/packem_shared/AGENTS_FILENAME-DPIMTD_h.mjs +1 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-wDZs0S4p.mjs +1 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_TARGET-DtzlGawL.mjs +1 -0
  10. package/dist/packem_shared/FLAGS_FILENAME-CQofXgIf.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER-CEgr9fSF.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-B7EXNAFK.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-DbuOgja2.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-D6-0Hn3B.mjs +3 -0
  16. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-D29yBg5X.mjs +1 -0
  17. package/dist/packem_shared/QUEUES_FILENAME-Dd781zOQ.mjs +1 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CuZkv079.mjs +9 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  20. package/dist/packem_shared/SDK_LANGUAGES-CFyux-74.mjs +371 -0
  21. package/dist/packem_shared/SHAPES_FILENAME-Bvd5kgsF.mjs +1 -0
  22. package/dist/packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs +18 -0
  23. package/dist/packem_shared/WORKFLOWS_FILENAME-v3AJcUjy.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-DCGde3iO.mjs +3 -0
  25. package/dist/packem_shared/chain-u-8_P10m.mjs +1 -0
  26. package/dist/packem_shared/classify-procedure-call-RjsZg8AH.mjs +1 -0
  27. package/dist/packem_shared/context-property-calls-DV-Pt4KS.mjs +1 -0
  28. package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
  29. package/dist/packem_shared/discoverAuthApiCalls-EHm1O8uG.mjs +1 -0
  30. package/dist/packem_shared/discoverCrons-B2GXsB-m.mjs +1 -0
  31. package/dist/packem_shared/discoverFunctions-BwB7RhZd.mjs +1 -0
  32. package/dist/packem_shared/discoverHttpRoutes-B0EVnVgb.mjs +1 -0
  33. package/dist/packem_shared/discoverHyperdriveCalls-CzRlqv_N.mjs +1 -0
  34. package/dist/packem_shared/discoverInserts-BP0Gl37o.mjs +1 -0
  35. package/dist/packem_shared/discoverMaskProcedures-Cl2I3ycl.mjs +1 -0
  36. package/dist/packem_shared/discoverMigrations-BX86Fv9G.mjs +1 -0
  37. package/dist/packem_shared/discoverNondeterministicCalls-CJYIXWPw.mjs +1 -0
  38. package/dist/packem_shared/discoverQueries-COGaQPE5.mjs +1 -0
  39. package/dist/packem_shared/discoverR2sqlCalls-emIgm3TF.mjs +1 -0
  40. package/dist/packem_shared/discoverRlsMetadata-3Gs8U3ng.mjs +1 -0
  41. package/dist/packem_shared/discoverRlsProcedures-CU7YMR3P.mjs +1 -0
  42. package/dist/packem_shared/discoverSandboxUsage-pJ42YuvL.mjs +1 -0
  43. package/dist/packem_shared/discoverSchema-DoZtXwLg.mjs +1 -0
  44. package/dist/packem_shared/discoverStorageRulesMetadata-BFiKUo5m.mjs +1 -0
  45. package/dist/packem_shared/emit-BuaY_1hY.mjs +2659 -0
  46. package/dist/packem_shared/emitApp-nInCbDo8.mjs +838 -0
  47. package/dist/packem_shared/exported-procedure-chains-CjlBrFjo.mjs +1 -0
  48. package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
  49. package/dist/packem_shared/index-D6xfnMEE.mjs +1 -0
  50. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  51. package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -0
  52. package/dist/packem_shared/listLunoraSourceFiles-DsxeRYvh.mjs +1 -0
  53. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  54. package/dist/packem_shared/parse-validator-tdRHHDzh.mjs +1 -0
  55. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  56. package/dist/packem_shared/queries-TZaLWhWq.mjs +1 -0
  57. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  58. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  59. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  60. package/dist/packem_shared/unwrap-handler-return-Da99uRXX.mjs +1 -0
  61. package/package.json +16 -7
  62. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  63. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  64. package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
  65. package/dist/packem_shared/GENERATED_HEADER-CI272wRm.mjs +0 -3245
  66. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  67. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  68. package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
  69. package/dist/packem_shared/OPENRPC_VERSION-t5pV2NIN.mjs +0 -60
  70. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  71. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BMez-jgr.mjs +0 -1039
  72. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  73. package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
  74. package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
  75. package/dist/packem_shared/buildOpenApiDocument-Dx5QftUn.mjs +0 -183
  76. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  77. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  78. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  79. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  80. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  81. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  82. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  83. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  84. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  85. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  86. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  87. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  88. package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
  89. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  90. package/dist/packem_shared/emitApp-cOSypPuO.mjs +0 -659
  91. package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
  92. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  93. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  94. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,2659 @@
1
+ import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Nn,isD1GlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as A}from"./paths-C-9fwEgQ.mjs";import{acceptsAbsentIr as On}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const mt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access",requiredPackage:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai",requiredPackage:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
2
+ /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
3
+ readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",requiredPackage:"@lunora/browser",serverCtxField:{field:`
4
+ /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
5
+ readonly browser: import("@lunora/browser").Browser;`,tier:"action"}},{contextProperty:"containers",key:"container",moduleSpecifier:"@lunora/container"},{contextProperty:"flags",key:"flags",moduleSpecifier:"@lunora/flags"},{appMethod:{configKey:"sql",doc:"Wire the Hyperdrive SQL client backing `ctx.sql` — build it with `createHyperdrive` + `fromPostgresJs`/`fromNodePg`/`fromMysql2`.",method:"hyperdrive"},contextProperty:"sql",key:"hyperdrive",moduleSpecifier:"@lunora/hyperdrive",requiredPackage:"@lunora/hyperdrive",serverCtxField:{field:`
6
+ /**
7
+ * External database access via Hyperdrive. Non-deterministic — available only in actions. Writes here are NOT tracked by Lunora live queries; subscriptions will not re-run on external DB changes.
8
+ */
9
+ readonly sql: import("@lunora/hyperdrive").SqlClient;`,tier:"action"}},{appMethod:{configKey:"images",doc:"Override the Images binding backing `ctx.images` (defaults to `env.IMAGES`).",method:"images"},contextProperty:"images",key:"images",moduleSpecifier:"@lunora/bindings/images",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
10
+ /** Cloudflare Images transforms (resize/format/optimize). Non-deterministic — available only in actions. */
11
+ readonly images: import("@lunora/bindings/images").Images;`,tier:"action"}},{appMethod:{configKey:"kv",doc:"Override the Workers KV binding backing `ctx.kv` (defaults to `env.KV`).",method:"kv"},contextProperty:"kv",key:"kv",moduleSpecifier:"@lunora/bindings/kv",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
12
+ readonly kv: import("@lunora/bindings/kv").Kv;`,tier:"every"}},{key:"mail",moduleSpecifier:"@lunora/mail"},{contextProperty:"notify",key:"notify",moduleSpecifier:"@lunora/notify"},{appMethod:{configKey:"payment",doc:"Wire the payment options backing `ctx.payments`.",method:"payment"},contextProperty:"payments",key:"payments",moduleSpecifier:"@lunora/payment",requiredPackage:"@lunora/payment"},{appMethod:{configKey:"x402",doc:"Wire the x402 agent-wallet pay rail backing `ctx.x402` — a payment-enabled `fetch` that answers `402` challenges under a mandatory spend policy (ActionCtx-only; spends real funds).",method:"x402"},contextProperty:"x402",key:"x402",moduleSpecifier:"@lunora/x402/pay",requiredPackage:"@lunora/x402"},{contextProperty:"pipelines",key:"pipelines",moduleSpecifier:"@lunora/bindings/pipelines",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
13
+ /** Pipelines ingestion sink (durable, R2-backed). Fire-and-forget and batched; do not read it back in-handler. */
14
+ readonly pipelines: import("@lunora/bindings/pipelines").PipelineClient;`,tier:"action"}},{appMethod:{configKey:"r2sql",doc:"Wire the R2 SQL client backing `ctx.r2sql` — build it with `createR2Sql({ accountId, apiToken, bucket })` (defaults to env `R2_SQL_TOKEN` / `R2_SQL_ACCOUNT_ID` / `R2_SQL_BUCKET`).",method:"r2sql"},contextProperty:"r2sql",key:"r2sql",moduleSpecifier:"@lunora/bindings/r2sql",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
15
+ /**
16
+ * R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
17
+ */
18
+ readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],In=mt,Cn=new Map(In.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),da=mt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),gt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,Dn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),ft=e=>e.column!==void 0,Ln=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
19
+ `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
20
+ `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
21
+ `;case"null":return`if (${t} !== null) return DEFER;
22
+ `;default:return`if (typeof ${t} !== "string") return DEFER;
23
+ `}},En=(e,t)=>e.stringMaxLength===void 0?"":`if (${t}.length > ${String(e.stringMaxLength)}) return DEFER;
24
+ `,_n=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!gt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
25
+ `}},Ge=(e,t,n)=>{if(!ft(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if(Dn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Ln(e.kind,t)+En(e,t)};switch(e.kind){case"array":return Pn(e,t,n);case"literal":return _n(e,t);case"object":return Bn(e,t,n);default:return}}},Pn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const a=n.next(),o=`__arr${String(a)}`,i=`__i${String(a)}`,s=`__e${String(a)}`,c=Ge(r,s,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
26
+ const ${o} = new Array(${t}.length);
27
+ for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
28
+ const ${s} = ${t}[${i}];
29
+ ${c.pre}${o}[${i}] = ${c.out};
30
+ }
31
+ `;return{out:o,pre:d}},Mn=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||ft(t))return;const{inner:i}=t;if(!i)return;const s=Ge(i,n,r);if(!s)return;const c=r.next(),d=`__has${String(c)}`,h=`__val${String(c)}`,g=`let ${d} = false;
32
+ let ${h};
33
+ if (${n} !== undefined) {
34
+ ${s.pre}${h} = ${s.out};
35
+ ${d} = true;
36
+ }
37
+ `;return{entry:`...(${d} ? { ${a}: ${h} } : {})`,pre:g}}const o=Ge(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},Fn=new Set(Object.getOwnPropertyNames(Object.prototype)),bt=(e,t,n)=>{let r="";const a=[];for(const o of Object.keys(e)){const i=e[o];if(!i)return;const s=JSON.stringify(o);let c=`${t}[${s}]`;if(Fn.has(o)){const h=`__f${String(n.next())}`;r+=`const ${h} = Object.hasOwn(${t}, ${s}) ? ${t}[${s}] : undefined;
38
+ `,c=h}const d=Mn(o,i,c,n);if(!d)return;r+=d.pre,a.push(d.entry)}return{entries:a.join(", "),pre:r}},yt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
39
+ `},Bn=(e,t,n)=>{const r=e.shape??{},a=bt(r,t,n);if(!a)return;const o=n.next(),i=`__obj${String(o)}`,s=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
40
+ ${yt(t)}${a.pre}const ${i} = { ${a.entries} };
41
+ `;return{out:i,pre:s}},qn=e=>{let t=0;const r=bt(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
42
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
43
+ ${yt("source")}${r.pre}return { ${r.entries} };
44
+ }`},S=`// GENERATED by @lunora/codegen — do not edit.
45
+ // Run \`lunora codegen\` to regenerate.
46
+
47
+ `,oe=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},wt=/^[A-Za-z_$][\w$]*$/u,jn=/^[\w./-]+$/u,f=(e,t)=>{if(!wt.test(e))throw new X("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ve=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>wt.test(e)?e:JSON.stringify(e),Y=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),Wn={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},Un=e=>{if(e===void 0)return"unknown";if(!gt.test(e))throw new X("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},N=e=>{const t=Wn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?N(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return f(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Un(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,a])=>kt(r,a)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?N(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?N(e.keyType):"string",r=e.valueType?N(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>N(n)).join(" | "):"never";default:return"unknown"}},kt=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?N(t.inner):"unknown";return`${n}?: ${r}`}return On(t)?`${n}?: ${N(t)}`:`${n}: ${N(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>kt(n,r)).join("; ")} }`},xt=e=>e.kind==="optional"||!!e.column?.hasDefault,se=e=>e.kind==="optional"&&e.inner?e.inner:e,Kn=e=>{f(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=se(a),i=N(o),s=q(r);return xt(a)?` ${s}?: ${i};`:` ${s}: ${i};`}).join(`
48
+ `),n=t?`
49
+ ${t}
50
+ `:"";return`export interface Insert_${e.name} {
51
+ _id?: Id<"${e.name}">;
52
+ _creationTime?: number;${n}}`},Je="schema",ua=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const $=q(x);if(v.kind==="optional"){const T=v.inner?N(v.inner):"unknown";return` ${$}?: ${T};`}return` ${$}: ${N(v)};`}).join(`
53
+ `),b=l?`
54
+ ${l}
55
+ `:"",R=u.commitOrdered===!0?`
56
+ _commitSeq: number;`:"";return`export interface Doc_${u.name} {
57
+ _id: Id<"${u.name}">;
58
+ _creationTime: number;${R}${b}}`}).join(`
59
+
60
+ `),a=e.tables.map(u=>` ${u.name}: Doc_${u.name};`).join(`
61
+ `),o=e.tables.map(u=>{const l=u.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
62
+ `),i=e.tables.map(u=>{const l=u.searchIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
63
+ `),s=e.tables.map(u=>{const l=u.rankIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
64
+ `),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
65
+ `),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",h=e.tables.map(u=>Kn(u)).join(`
66
+
67
+ `),g=e.tables.map(u=>` ${u.name}: Insert_${u.name};`).join(`
68
+ `),y=e.tables.map(u=>{const l=u.relations.map(b=>(f(b.table,"relation target table"),` ${q(b.name)}: ${b.kind==="one"?"OneRelation":"ManyRelation"}<"${b.table}">;`)).join(`
69
+ `);return l?` ${u.name}: {
70
+ ${l}
71
+ };`:` ${u.name}: {};`}).join(`
72
+ `);return L(`${S}export type TableName = ${t};
73
+
74
+ /**
75
+ * The tables **this app declared** — every {@link TableName} except those an add-on
76
+ * contributed through \`defineSchema(...).extend(...)\`.
77
+ *
78
+ * An add-on's tables are real tables and stay in \`TableName\` (they are queryable,
79
+ * they appear in \`DataModel\`), but an app enumerating "my tables" should not have to
80
+ * know they exist: an account-deletion sweep, an export, a migration allowlist, or a
81
+ * helper generic over a table union is about the app's own data, and every add-on
82
+ * added or removed would otherwise silently change the correct answer.
83
+ *
84
+ * \`\`\`ts
85
+ * // Doesn't need to mention \`ratelimit_buckets\`, and won't drift when an add-on lands.
86
+ * const EXPORTED: readonly AppTableName[] = ["nodes", "tagColors"];
87
+ * \`\`\`
88
+ */
89
+ export type AppTableName = ${n};
90
+
91
+ export type Id<TName extends string> = string & { readonly __table: TName };
92
+
93
+ ${r}
94
+
95
+ export interface DataModel {
96
+ ${a}
97
+ }
98
+
99
+ export type Doc<T extends keyof DataModel> = DataModel[T];
100
+
101
+ /**
102
+ * Per-table index name union. \`never\` for tables without secondary indexes.
103
+ * Used by \`TableReader.withIndex()\` to constrain callers to declared names.
104
+ */
105
+ export interface IndexNamesByTable {
106
+ ${o}
107
+ }
108
+
109
+ export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
110
+
111
+ /** Per-table search-index name union. \`never\` for tables without searchIndex. */
112
+ export interface SearchIndexNamesByTable {
113
+ ${i}
114
+ }
115
+
116
+ export type SearchIndexName<T extends keyof DataModel> = SearchIndexNamesByTable[T];
117
+
118
+ /** Per-table rank-index name union. \`never\` for tables without a rankIndex. */
119
+ export interface RankIndexNamesByTable {
120
+ ${s}
121
+ }
122
+
123
+ export type RankIndexName<T extends keyof DataModel> = RankIndexNamesByTable[T];
124
+
125
+ /** Per-table geo-index name union. \`never\` for tables without a geoIndex. */
126
+ export interface GeoIndexNamesByTable {
127
+ ${c}
128
+ }
129
+
130
+ export type GeoIndexName<T extends keyof DataModel> = GeoIndexNamesByTable[T];
131
+
132
+ /** Union of declared vector index names. \`never\` when none are declared. */
133
+ export type VectorIndexName = ${d};
134
+
135
+ ${h}
136
+
137
+ /** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
138
+ export interface InsertModel {
139
+ ${g}
140
+ }
141
+
142
+ export type Insert<T extends keyof DataModel> = InsertModel[T];
143
+
144
+ /**
145
+ * Phantom relation descriptors. They carry the relation kind and target table
146
+ * as type parameters only — there is no runtime value — so the \`with\` argument
147
+ * and its return type can be inferred from {@link Relations}.
148
+ */
149
+ export interface OneRelation<Target extends keyof DataModel> {
150
+ readonly __relationKind: "one";
151
+ readonly __target: Target;
152
+ }
153
+
154
+ export interface ManyRelation<Target extends keyof DataModel> {
155
+ readonly __relationKind: "many";
156
+ readonly __target: Target;
157
+ }
158
+
159
+ /** Per-table relation map keyed by accessor name. \`{}\` for tables with none. */
160
+ export interface Relations {
161
+ ${y}
162
+ }
163
+
164
+ `,Je)},Qn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,vt=/^(?:\.\.?\/)*_generated\//u,St=/\.[A-Za-z]\w*$/u,Hn=e=>e.replaceAll(Qn,(t,n)=>{const r=n.replace(vt,"./");return`import("${St.test(r)?r:`${r}.js`}")`}),Vn=/import\("(?<spec>[^"]+)"\)/gu,dt="node_modules/",Gn=/^@types\//u,Jn=e=>e.replaceAll(Vn,(t,n)=>{const r=n.lastIndexOf(dt);if(r===-1||r>0&&n[r-1]!=="/")return t;const a=n.slice(r+dt.length);return a===""||Gn.test(a)?t:`import("${a}")`}),zn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Yn=/^(?:\.\.?\/)+/u,Xn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Zn=(e,t)=>e.replaceAll(zn,(n,r)=>{if(vt.test(r.replace(Yn,"")))return n;const a=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Xn(`${a}/${r}`)}`;return`import("${St.test(i)?i:`${i}.js`}")`}),L=(e,t)=>Hn(Zn(Jn(e),t)),er=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],tr=new RegExp(String.raw`import\("@lunora/(?<pkg>${er.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),nr={flags:new Set(["/web"]),platform:new Set},Rt=(e,t)=>t?e.replaceAll(tr,(n,r,a)=>{const o=nr[r];return a&&o&&!o.has(a)?n:`import("lunorash/${r}${a??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),$t=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:N(e.output),Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},ut=e=>{const t=([n,r])=>{const a=r.toSorted((o,i)=>o.exportName.localeCompare(i.exportName)).map(o=>{const i=L(xe(o.args),o.filePath),s=L($t(o),o.filePath);return` ${o.exportName}: FunctionReference<"${o.kind}", ${i}, ${s}>;`}).join(`
165
+ `);return` ${q(A(n))}: {
166
+ ${a}
167
+ };`};return Ye(e).map(n=>t(n)).join(`
168
+ `)},rr=(e,t)=>{if(e.length===0&&t.length===0)return{block:"",importLine:""};const n=[];let r="";if(e.length>0&&(r+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),r+=`
169
+ /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
170
+ export interface WorkflowReference<Params = Record<string, unknown>> {
171
+ readonly isLunoraWorkflow: true;
172
+ readonly __params?: Params;
173
+ readonly binding: string;
174
+ readonly name: string;
175
+ }
176
+ `,e.length>0){const a=[...e].toSorted((s,c)=>s.exportName.localeCompare(c.exportName)),o=a.map(s=>` ${s.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${s.exportName}>>;`).join(`
177
+ `),i=a.map(s=>` ${Y(s.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.exportName)} },`).join(`
178
+ `);r+=`
179
+ /** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
180
+ export interface WorkflowsRef {
181
+ ${o}
182
+ }
183
+
184
+ export const workflows: WorkflowsRef = {
185
+ ${i}
186
+ };
187
+ `,n.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
188
+ `)}if(t.length>0){const a=[...t].toSorted((s,c)=>s.exportName.localeCompare(c.exportName)),o=a.map(s=>` ${s.exportName}: WorkflowReference<AgentRunInput>;`).join(`
189
+ `),i=a.map(s=>` ${Y(s.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.name)} },`).join(`
190
+ `);r+=`
191
+ /** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
192
+ export interface AgentsRef {
193
+ ${o}
194
+ }
195
+
196
+ export const agents: AgentsRef = {
197
+ ${i}
198
+ };
199
+ `,n.push(`import type { AgentRunInput } from "@lunora/agent";
200
+ `)}return{block:r,importLine:n.join("")}},ar=()=>Object.keys(pt().functions).toSorted((e,t)=>e.localeCompare(t)),Tt=e=>new Set(e.filter(t=>A(t.filePath)==="agents").map(t=>t.exportName)),or=()=>new Set(Object.entries(pt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),sr=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Tt(t),a=or(),o=t.find(s=>A(s.filePath)==="agents"&&a.has(s.exportName));if(o)throw new X("INTERNAL",`@lunora/codegen: "agents:${o.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${o.exportName}" export in ${o.filePath}`);const i=ar().filter(s=>!r.has(s));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
201
+ `,lines:i.map(s=>` "agents:${s}": lunoraAgentRuntimeFunctions.${s} as unknown as RegisteredLunoraFunction,`).join(`
202
+ `),prelude:`
203
+ /**
204
+ * The \`@lunora/agent\` runtime component — auto-registered because \`lunora/agents.ts\`
205
+ * declares agents. The durable loop dispatches the internal mutations; clients
206
+ * subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
207
+ */
208
+ const lunoraAgentRuntimeFunctions = agentComponent().functions;
209
+ `}},ir=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>A(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new X("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
210
+ `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},lr=(e,t)=>{if(e.length===0)return[];const n=Tt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const a of e)a.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${a.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(a=>!n.has(a.exportName))},cr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>A(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},dr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,s])=>{const c=s.map(d=>{const h=L(d.chunkType??"unknown",d.filePath),g=L(xe(d.searchParams),d.filePath),y=L(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${h}, ${g}, ${y}>;`}).join(`
211
+ `);return` ${q(A(i))}: {
212
+ ${c}
213
+ };`}).join(`
214
+ `),a=n.map(([i,s])=>{const c=s.map(d=>` ${Y(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
215
+ `);return` ${Y(A(i))}: {
216
+ ${c}
217
+ },`}).join(`
218
+ `);return{block:`
219
+ /** This project's HTTP-SSE stream routes (\`httpRoute.<verb>(path).stream()\`), addressable as typed references for \`client.httpStream\` / \`useHttpStream\`. */
220
+ export interface HttpStreamsRef {
221
+ ${r}
222
+ }
223
+
224
+ export const httpStreams: HttpStreamsRef = {
225
+ ${a}
226
+ };
227
+ `,body:r}},ha=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=oe(o),c=[...n.filter(O=>O.visibility!=="internal"),...lr(t,n),...cr(a,n)],d=n.filter(O=>O.visibility==="internal"),h=ut(c),g=ut(d),y=dr(r),u=`${h}
228
+ ${g}
229
+ ${y.body}`,l=ze(u),b=l.length>0?`
230
+ import type { ${l.join(", ")} } from "./dataModel.js";
231
+ `:"",R=h?`
232
+ ${h}
233
+ `:"",x=g?`
234
+ ${g}
235
+ `:"",v=rr(i,t),$=`export interface ApiTypes {${R}}
236
+
237
+ export const api = anyApi as unknown as ApiTypes;
238
+
239
+ /** Internal functions — callable only server-side via \`ctx.run*\`, never from a client. */
240
+ export interface InternalApiTypes {${x}}
241
+
242
+ export const internal = anyApi as unknown as InternalApiTypes;
243
+ ${v.block}${y.block}`,T=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],H=T.length>0?`import type { ${T.join(", ")} } from "${s.client}";
244
+ `:"";return Rt(`${S}import { anyApi } from "${s.client}";
245
+ ${H}${v.importLine}${b}
246
+ ${$}`,o)},pa=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
247
+ import type { SeedClient, SeedClientOptions } from "@lunora/seed";
248
+
249
+ import schema from "../schema.js";
250
+ import type { InsertModel } from "./dataModel.js";
251
+
252
+ /**
253
+ * Schema-aware seed client with this project's \`InsertModel\` and runtime schema
254
+ * pre-bound. Each table is a method; call it with a count, a range, explicit
255
+ * partial rows, or per-field overrides. Foreign keys connect to rows seeded
256
+ * earlier in the run, and FK-parent tables are seeded automatically.
257
+ * @example
258
+ * const seed = createSeedClient({ seed: 1 });
259
+ * const { users } = await seed.users(5);
260
+ * const { posts } = await seed.posts((x) => x([10, 20]));
261
+ */
262
+ export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
263
+ `:"",ma=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=oe(n),a=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,o=e.map(c=>{f(c.exportName,"shape export name");const d=a(c),h=L(xe(c.args),c.filePath),g=Object.keys(c.args).length>0,y=g?` args: ${h};`:` args?: ${h};`,u=g?`(args: ${h}) => void`:`(args?: ${h}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
264
+ export interface ${Ve(l)} {
265
+ ${y}
266
+ /**
267
+ * Share the optimistic-overlay gate with other collections + mutators on this
268
+ * shard. Defaults to the shared per-shard registry, which is almost always what
269
+ * you want — pass one only to isolate this collection's gate.
270
+ */
271
+ checkpoints?: CheckpointRegistry;
272
+ /** The Lunora client to subscribe through. */
273
+ client: LunoraClient;
274
+ /** Row key extractor — defaults to \`row._id\`. Override when the app keys rows by a natural column. */
275
+ getKey?: (row: ${d}) => string;
276
+ /** \`"eager"\` starts syncing at creation; \`"lazy"\` (default) on the first subscriber. */
277
+ load?: "eager" | "lazy";
278
+ /** Notified when the underlying subscription errors; the collection always leaves \`loading\`. */
279
+ onError?: (error: SubscriptionError) => void;
280
+ /** Routes the subscription to a shard's DO. **Required for a \`.shardBy()\` table** — without it the watermark lands in the default bucket. */
281
+ shardKey?: string;
282
+ }
283
+
284
+ /**
285
+ * Collection options for the \`${c.exportName}\` replication shape: \`config\` for
286
+ * \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
287
+ * \`scope\` to re-point the subscription.
288
+ */
289
+ export const ${c.exportName}CollectionOptions = (options: ${Ve(l)}): LunoraCollectionOptions<${d}> =>
290
+ lunoraCollectionOptions<${d}>({
291
+ client: options.client,
292
+ ...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
293
+ ...(options.getKey === undefined ? {} : { getKey: options.getKey }),
294
+ ...(options.load === undefined ? {} : { load: options.load }),
295
+ ...(options.onError === undefined ? {} : { onError: options.onError }),
296
+ ...(options.shardKey === undefined ? {} : { shardKey: options.shardKey }),
297
+ shape: { args: options.args, name: ${JSON.stringify(c.exportName)}, ...(options.shardKey === undefined ? {} : { shardKey: options.shardKey }) },
298
+ });
299
+
300
+ /** Live collection for the \`${c.exportName}\` shape, with its sync controls. */
301
+ export const ${c.exportName}Collection = (
302
+ options: ${Ve(l)},
303
+ ): { checkpoints: CheckpointRegistry; collection: Collection<${d}, string>; scope: ${u} } => {
304
+ const { checkpoints, config, scope } = ${c.exportName}CollectionOptions(options);
305
+
306
+ return { checkpoints, collection: createCollection(config), scope };
307
+ };`}).join(`
308
+
309
+ `),i=ze(o),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
310
+ `:"";return`${S}import type { LunoraClient, SubscriptionError } from "${r.client}";
311
+ import { lunoraCollectionOptions } from "@lunora/db/collections";
312
+ import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
313
+ import type { Collection } from "@tanstack/db";
314
+ import { createCollection } from "@tanstack/db";
315
+ ${s}
316
+ ${o}
317
+ `},ur=(e,t)=>`lunora_${A(e)}_${String(t)}`,hr=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
318
+ const registered = LUNORA_FUNCTIONS[functionPath];
319
+
320
+ if (!registered) {
321
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
322
+ }
323
+
324
+ // A mutation is routed through the caller's own \`ctx.runMutation\` rather than
325
+ // invoked directly, so \`createCaller(ctx).ns.someMutation()\` gets exactly what
326
+ // \`ctx.runMutation(api.ns.someMutation)\` gets: the BEGIN/COMMIT span (or the
327
+ // enclosing one, when the caller is already inside a transaction), the jobs it
328
+ // schedules held until that span commits, and the deferred object deletes
329
+ // flushed only once it has. Called straight, a mutation composed from an action
330
+ // or a stream had none of the three — its writes autocommitted one row at a
331
+ // time and its \`ctx.scheduler\` calls dispatched immediately, so a mid-handler
332
+ // throw left the earlier writes durable and the job already enqueued.
333
+ //
334
+ // The fallback covers a context that is not a shard dispatch (\`runMutation\` is
335
+ // installed by \`buildCtx\` on every kind but a query's TYPE omits it); there is
336
+ // no transaction to join in that case, so a direct call is all there is.
337
+ if (registered.kind === "mutation") {
338
+ const { runMutation } = context as { runMutation?: (reference: { __lunoraRef: string }, args: Record<string, unknown>) => Promise<unknown> };
339
+
340
+ if (typeof runMutation === "function") {
341
+ return (await runMutation.call(context, { __lunoraRef: functionPath }, args ?? {})) as R;
342
+ }
343
+ }
344
+
345
+ return (await registered.handler(context, args ?? {})) as R;
346
+ };`,pr=(e,t,n=[],r=[])=>{const a=new Map,o=l=>{a.has(l)||a.set(l,ur(l,a.size))};for(const l of e)o(l.filePath);for(const l of t)o(l.filePath);for(const l of n)o(l.filePath);for(const l of r)o(l.filePath);const i=[...a.entries()].map(([l,b])=>{if(!jn.test(l))throw new X("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${b} from "../${l}.js";`}).join(`
347
+ `),s=e.map(l=>` "${A(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
348
+ `),c=t.map(l=>` ${JSON.stringify(l.id)}: ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
349
+ `),d=n.map(l=>` "${A(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
350
+ `),h=r.map(l=>` "${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
351
+ `),g=n.map(l=>`${A(l.filePath)}:${l.exportName}`),y=[s,d].filter(l=>l.length>0).join(`
352
+ `),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const b=qn(l.args);return b===void 0?void 0:`installCompiledValidatorMap(${a.get(l.filePath)??""}.${l.exportName}.args, ${b});`}).filter(l=>l!==void 0).join(`
353
+ `);return{dispatchBody:y.length>0?`
354
+ ${y}
355
+ `:"",importBlock:i.length>0?`${i}
356
+
357
+ `:"",installBlock:u,migrationBody:c.length>0?`
358
+ ${c}
359
+ `:"",mutatorPaths:g,shapeBody:h.length>0?`
360
+ ${h}
361
+ `:""}},mr=e=>{const t=Ye(e),n=t.map(([a,o])=>{const i=o.map(s=>{const c=L(xe(s.args),s.filePath),d=c==="{}"?"?":"",h=L($t(s),s.filePath);return s.kind==="stream"?` ${s.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${h}>>;`:` ${s.exportName}: (args${d}: ${c}) => Promise<${h}>;`}).join(`
362
+ `);return` ${q(A(a))}: {
363
+ ${i}
364
+ };`}).join(`
365
+ `);return{implementation:t.map(([a,o])=>{const i=A(a),s=o.map(c=>` ${Y(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
366
+ `);return` ${Y(i)}: {
367
+ ${s}
368
+ },`}).join(`
369
+ `),types:n}},gr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=se(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},ga=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasVectors:s=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:h=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:R=!1,identity:x,queues:v=[],schema:$,storageRuleBuckets:T=[],useUmbrella:H=!1,workflows:O=[]}={})=>{const C=oe(H),k=gr($??{tables:[]},T).map(p=>JSON.stringify(p)).join(" | "),P=a?`import type { LunoraAi } from "@lunora/ai";
370
+ `:"",M=a?`
371
+ readonly ai: LunoraAi;`:"",ie=u?`import type { LunoraPayment } from "@lunora/payment";
372
+ `:"",le=u?`
373
+ readonly payments: LunoraPayment;`:"",Z=R?`import type { X402Pay } from "@lunora/x402/pay";
374
+ `:"",V=R?`
375
+ readonly x402: X402Pay;`:"",D=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
376
+ `:"",ee=t.length>0?`
377
+ readonly containers: {${t.map(p=>`
378
+ readonly ${p.exportName}: ContainerAccessor;`).join("")}
379
+ };`:"",w=[...a?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(p=>(f(p.bindingName,`container binding "${p.bindingName}"`),` /** Durable Object namespace for the \`${p.exportName}\` container. */
380
+ readonly ${p.bindingName}?: unknown;`)),...O.map(p=>(f(p.bindingName,`workflow binding "${p.bindingName}"`),` /** Workflow binding for the \`${p.exportName}\` workflow. */
381
+ readonly ${p.bindingName}?: unknown;`)),...v.map(p=>(f(p.bindingName,`queue binding "${p.bindingName}"`),` /** Queue producer binding for the \`${p.exportName}\` queue. */
382
+ readonly ${p.bindingName}?: unknown;`)),...e.map(p=>(f(p.bindingName,`agent binding "${p.bindingName}"`),` /** Workflow binding for the \`${p.exportName}\` agent. */
383
+ readonly ${p.bindingName}?: unknown;`))].join(`
384
+ `),Ae=`
385
+
386
+ /**
387
+ * This project's Cloudflare bindings, as far as codegen can discover them from
388
+ * \`lunora/\` source — the container/workflow Durable Object namespaces and the
389
+ * conventional Workers AI binding. Bindings the config layer reconciles from
390
+ * user-named wrangler config (R2/KV/D1/\`services\`/queues/…) aren't statically
391
+ * visible here, so the open index signature keeps them reachable (cast at the
392
+ * use site). Service bindings (\`env.<SERVICE>.fetch(...)\` / RPC stubs) live
393
+ * under this signature too — Lunora can't type a third-party worker's RPC
394
+ * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
395
+ */
396
+ export interface CloudflareBindings {
397
+ readonly [binding: string]: unknown;${w?`
398
+ ${w}`:""}
399
+ }
400
+
401
+ /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
402
+ export type Env = CloudflareBindings;`,F=(p,We,Te)=>{const re=Cn.get(p);if(re!==void 0&&re.tier!==Te)throw new X("INTERNAL",`@lunora/codegen: capability "${p}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Te}" context — update whichever is wrong.`);return We?re?.field??"":""},ce=F("kv",g,"every"),de=F("analytics",o,"every"),Oe=F("hyperdrive",d,"action"),Ie=F("browser",i,"action"),Ce=F("images",h,"action"),ue=F("pipelines",l,"action"),G=F("r2sql",b,"action"),_=s&&($?.vectorIndexes.length??0)>0,J=_?' | "vectors"':"",te=_?`
403
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",he=_?`
404
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",z=_?`import type { VectorSearch, VectorSearchReader } from "${C.server}";
405
+ import type { VectorIndexName } from "./dataModel.js";
406
+ `:"",j=r?`
407
+ /** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
408
+ readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",W=c?`
409
+ /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
410
+ readonly flags: import("${C.flags}").LunoraFlags;`:"",U=y?`
411
+ /** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
412
+ readonly notify: import("@lunora/notify").LunoraNotify;
413
+ /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
414
+ readonly push: import("@lunora/notify").LunoraPush;`:"",B=O.length>0,ne=B?`import type { WorkflowHandle } from "@lunora/workflow";
415
+ import type * as lunoraWorkflowDefinitions from "../workflows.js";
416
+ `:"",De=B?`
417
+
418
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
419
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
420
+ ? unknown extends Params
421
+ ? Record<string, unknown>
422
+ : NonNullable<Params>
423
+ : Record<string, unknown>;
424
+
425
+ /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
426
+ export interface LunoraWorkflows {
427
+ ${O.map(p=>` get(name: ${JSON.stringify(p.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${p.exportName}>>;`).join(`
428
+ `)}
429
+ }`:"",ve=B?' | "workflows"':"",Se=B?`
430
+ readonly workflows: LunoraWorkflows;`:"",pe=v.length>0,Le=pe?`import type { QueueProducer } from "@lunora/queue";
431
+ import type * as lunoraQueueDefinitions from "../queues.js";
432
+ `:"",Ee=pe?`
433
+
434
+ /** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
435
+ type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
436
+
437
+ /** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
438
+ export interface LunoraQueues {
439
+ ${v.map(p=>` readonly ${p.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${p.exportName}>>;`).join(`
440
+ `)}
441
+ }`:"",Re=pe?`
442
+ readonly queues: LunoraQueues;`:"",me=e.length>0,_e=me?`import type { AgentHandle } from "@lunora/agent";
443
+ `:"",Pe=me?`
444
+
445
+ /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
446
+ export interface LunoraAgents {
447
+ ${e.map(p=>(f(p.exportName,`agent export "${p.exportName}"`),` readonly ${p.exportName}: AgentHandle;`)).join(`
448
+ `)}
449
+ }`:"",$e=me?`
450
+ readonly agents: LunoraAgents;`:"",Me=x?`import type { InferIdentity } from "${C.server}";
451
+ import type * as lunoraIdentityContract from "../identity.js";
452
+ `:"",Fe=x?`
453
+
454
+ /** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
455
+ export type Identity = InferIdentity<typeof lunoraIdentityContract.${x.exportName}>;
456
+
457
+ /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
458
+ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",ge=x?' | "auth"':"",fe=x?`
459
+ readonly auth: NarrowedAuth;`:"",Be=x?", Identity":"",qe=n?`import type * as lunoraEnvContract from "../env.js";
460
+ `:"",je=n?`
461
+
462
+ /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
463
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",be=n?' | "env"':"",ye=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${S}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${C.server}";
464
+ import type {
465
+ ActionBuilder,
466
+ ActionCtx as ActionCtxBase,
467
+ ColumnValidator,
468
+ DatabaseReader,
469
+ DatabaseWriter,
470
+ EmptyArgs,
471
+ InternalActionBuilder,
472
+ InternalMutationBuilder,
473
+ InternalQueryBuilder,
474
+ MutationBuilder,
475
+ MutationCtx as MutationCtxBase,
476
+ MutationStorage,
477
+ MutatorDefinition,
478
+ QueryBuilder,
479
+ QueryCtx as QueryCtxBase,
480
+ ReadOnlyStorage,
481
+ RegisteredMutator,
482
+ Storage as StorageBase,
483
+ TableReader,
484
+ Validator,
485
+ } from "${C.server}";
486
+
487
+ import type {
488
+ DatabaseReaderFacade as DatabaseReaderFacadeOf,
489
+ DatabaseWriterFacade as DatabaseWriterFacadeOf,
490
+ LoadWith as LoadWithOf,
491
+ TableReaderFacade as TableReaderFacadeOf,
492
+ TableWriterFacade as TableWriterFacadeOf,
493
+ WithArg as WithArgOf,
494
+ } from "${C.serverDataModel}";
495
+
496
+ export type {
497
+ AggregateOp,
498
+ GroupByEntry,
499
+ OrderBy,
500
+ QueryArgs,
501
+ QueryPage,
502
+ RankPage,
503
+ RankResult,
504
+ RestrictableQueryOptions,
505
+ RestrictableQueryOptionsOf,
506
+ SearchFilterBuilder,
507
+ SearchReader,
508
+ TableAggregateOptions,
509
+ TableAggregateOptionsOf,
510
+ TableGroupByOptions,
511
+ TableGroupByOptionsOf,
512
+ TableRankOptions,
513
+ TableRankPageOptions,
514
+ Where,
515
+ WhereOf,
516
+ WhereOperators,
517
+ } from "${C.serverDataModel}";
518
+
519
+ import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
520
+ ${z}${P}${ie}${Z}${D}${ne}${Le}${_e}${Me}${qe}
521
+ export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
522
+
523
+ /**
524
+ * The query-DSL bindings: \`@lunora/server/data-model\`'s generics parameterized
525
+ * over this project's \`DataModel\` / \`InsertModel\` / \`Relations\` / index maps.
526
+ *
527
+ * They live here rather than in \`dataModel.ts\` because they are the half that
528
+ * needs the SERVER package. Keeping \`dataModel.ts\` free of it lets a sibling
529
+ * package — a web app, another Worker — compile \`api.ts\` for its \`Doc\`/\`Id\`
530
+ * types without installing a server dependency to do it.
531
+ */
532
+
533
+ /** The \`with\` argument for table \`T\` — see \`@lunora/server/data-model\`. */
534
+ export type WithArg<T extends keyof DataModel> = WithArgOf<DataModel, Relations, T>;
535
+
536
+ /** \`Doc<T>\` narrowed to exactly the relations requested in the with-arg \`W\`. */
537
+ export type LoadWith<T extends keyof DataModel, W> = LoadWithOf<DataModel, Relations, T, W>;
538
+
539
+ /** Read-only typed table accessor exposed on \`QueryCtx.db.<table>\`. */
540
+ export type TableReaderFacade<T extends keyof DataModel> = TableReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
541
+
542
+ /** Read-write typed table accessor exposed on \`MutationCtx.db.<table>\` / \`ActionCtx.db.<table>\`. */
543
+ export type TableWriterFacade<T extends keyof DataModel> = TableWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
544
+
545
+ /** Per-table read facade — \`ctx.db.<table>\` on a \`QueryCtx\`. */
546
+ export type DatabaseReaderFacade = DatabaseReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
547
+
548
+ /** Per-table read-write facade — \`ctx.db.<table>\` on a \`MutationCtx\` / \`ActionCtx\`. */
549
+ export type DatabaseWriterFacade = DatabaseWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
550
+
551
+ /** Insert builder returned by \`ctx.orm.insert(table)\`. */
552
+ export interface OrmInsertBuilder<T extends keyof DataModel> {
553
+ values: (values: Insert<T>) => Promise<IdOfTable<T>>;
554
+ }
555
+
556
+ /** Replace builder returned by \`ctx.orm.replace(table, id)\` — swaps the whole document. */
557
+ export interface OrmReplaceBuilder<T extends keyof DataModel> {
558
+ with: (values: Insert<T>) => Promise<void>;
559
+ }
560
+
561
+ /** Update builder returned by \`ctx.orm.update(table, id)\` — patches the named fields. */
562
+ export interface OrmUpdateBuilder<T extends keyof DataModel> {
563
+ set: (values: Partial<Insert<T>>) => Promise<void>;
564
+ }
565
+
566
+ /** Read-only ORM surface — \`ctx.orm\` on a \`QueryCtx\`. Mirrors \`ctx.db\` reads under a kitcn-style \`query\` namespace. */
567
+ export interface OrmReader {
568
+ query: DatabaseReaderFacade;
569
+ }
570
+
571
+ /** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
572
+ export interface OrmWriter extends OrmReader {
573
+ delete: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => Promise<void>;
574
+ insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
575
+ replace: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmReplaceBuilder<T>;
576
+ update: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmUpdateBuilder<T>;
577
+ }
578
+
579
+ /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
580
+ export type StorageBucketName = ${k};${Ae}${De}${Ee}${Pe}${Fe}${je}
581
+
582
+ /**
583
+ * Project-typed contexts. The base contexts from \`@lunora/server\` are
584
+ * untyped against the schema; here \`db\` is widened to the generated per-table
585
+ * facade (\`ctx.db.<table>.findMany(...)\`) while keeping the legacy structural
586
+ * \`db.get\`/\`db.query\` surface for back-compat, and \`storage\` is narrowed so
587
+ * \`ctx.storage.bucket(name)\` autocompletes the declared buckets.
588
+ */
589
+ /**
590
+ * The Convex-style fluent reader \`ctx.db.query(table)\`, bound to this schema:
591
+ * a table-name literal narrows the row type, so \`.collect()\` / \`.first()\` /
592
+ * \`.take()\` (and the \`.withIndex()\` / \`.filter()\` / \`.order()\` chain) resolve
593
+ * as \`Doc<table>\` with no \`as unknown as Doc<...>\` casts. The per-table accessor
594
+ * \`ctx.db.<table>\` stays available alongside it via the facade.
595
+ *
596
+ * Intersected with the wide \`(string) => TableReader\` signature so the bound
597
+ * \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
598
+ * call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
599
+ *
600
+ * The three index-name unions are what make \`.withIndex("by_TYPO")\` a compile
601
+ * error: each resolves to the table's declared names, or \`never\` when it
602
+ * declares none of that kind. Without them a renamed or dropped index left
603
+ * every call site typechecking, and the query either threw at runtime or
604
+ * degraded silently to a full table scan.
605
+ */
606
+ type TypedTableQuery = (<T extends TableName>(
607
+ table: T,
608
+ ) => TableReader<Doc<T>, IndexNamesByTable[T], SearchIndexNamesByTable[T], GeoIndexNamesByTable[T]>) &
609
+ ((table: string) => TableReader);
610
+
611
+ /**
612
+ * The point read \`ctx.db.get(id)\`, bound to this schema: an \`Id<"table">\`
613
+ * carries its table name, so the resolved document is typed \`Doc<table>\` (or
614
+ * \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
615
+ */
616
+ type TypedTableGet = <T extends TableName>(id: IdOfTable<T>) => Promise<Doc<T> | null>;
617
+
618
+ /**
619
+ * Resolves the \`asId\` table argument: a literal in {@link TableName} passes through, a
620
+ * genuinely-wide \`string\` (a computed name) passes through, and any OTHER literal
621
+ * collapses to \`never\` so it fails to typecheck.
622
+ *
623
+ * The \`string extends T\` arm is what distinguishes "the caller passed a computed
624
+ * string" from "the caller passed a misspelled literal" — only the wide \`string\` type
625
+ * is a supertype of \`string\`.
626
+ */
627
+ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ? T : never;
628
+
629
+ /**
630
+ * The id parse boundary \`ctx.db.asId(table, id)\`, bound to this schema: a misspelled
631
+ * table literal is a compile error rather than a call that hands back a confidently-
632
+ * branded id for a table that does not exist. Mirrors {@link TypedTableQuery} /
633
+ * {@link TypedTableGet}.
634
+ *
635
+ * Deliberately NOT an intersection with a wide \`(string, string) => string\` overload:
636
+ * overload resolution would fall through to it for a bad literal, silently restoring
637
+ * the very typo hole this narrowing exists to close. {@link AsIdTable} instead keeps a
638
+ * computed table name working — and keeps \`ctx.db\` structurally assignable to
639
+ * schema-agnostic consumers — without accepting an invalid literal.
640
+ */
641
+ type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
642
+
643
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${J}${ge}${be}> {
644
+ readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
645
+ readonly orm: OrmReader;
646
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${he}${j}${ce}${W}${U}${de}${ye}${fe}
647
+ }
648
+
649
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${J}${ve}${ge}${be}> {
650
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
651
+ readonly orm: OrmWriter;
652
+ readonly storage: MutationStorage<StorageBucketName>;${te}${j}${ce}${W}${U}${de}${ye}${Se}${Re}${$e}${fe}
653
+ }
654
+
655
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${J}${ve}${ge}${be}> {
656
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
657
+ readonly orm: OrmWriter;
658
+ readonly storage: StorageBase<StorageBucketName>;${te}${j}${M}${le}${V}${ee}${ce}${W}${U}${Oe}${Ie}${Ce}${de}${ue}${G}${ye}${Se}${Re}${$e}${fe}
659
+ }
660
+
661
+ /**
662
+ * Procedure builders bound to this project's typed contexts. Chain
663
+ * \`.input({...})\` to declare args, \`.use(middleware)\` for rate limiting / RLS /
664
+ * masking (each middleware may refine \`ctx\`), then the terminal
665
+ * \`.query()\` / \`.mutation()\` / \`.action()\` with a \`({ ctx, args }) => ...\`
666
+ * handler. \`.output(validator)\` and (queries) \`.stream()\` are also available.
667
+ */
668
+ const lunoraBuilders = initLunora.dataModel<DataModel>().create();
669
+
670
+ /** \`query\` builder bound to this project's typed {@link QueryCtx}. */
671
+ export const query = lunoraBuilders.query as unknown as QueryBuilder<QueryCtx, EmptyArgs>;
672
+
673
+ /** \`mutation\` builder bound to this project's typed {@link MutationCtx}. */
674
+ export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder<MutationCtx, EmptyArgs>;
675
+
676
+ /** \`action\` builder bound to this project's typed {@link ActionCtx}. */
677
+ export const action = lunoraBuilders.action as unknown as ActionBuilder<ActionCtx, EmptyArgs>;
678
+
679
+ /** \`internalQuery\` builder bound to this project's typed {@link QueryCtx} — never exposed on \`api\`. */
680
+ export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder<QueryCtx, EmptyArgs>;
681
+
682
+ /** \`internalMutation\` builder bound to this project's typed {@link MutationCtx} — never exposed on \`api\`. */
683
+ export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder<MutationCtx, EmptyArgs>;
684
+
685
+ /** \`internalAction\` builder bound to this project's typed {@link ActionCtx} — never exposed on \`api\`. */
686
+ export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder<ActionCtx, EmptyArgs>;
687
+
688
+ /**
689
+ * \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
690
+ * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
691
+ * \`${C.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
692
+ * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
693
+ * \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
694
+ * no \`as unknown as\` cast. Runtime-identical to the package export; only the
695
+ * context type narrows, so discovery finds a mutator authored either way.
696
+ * @example
697
+ * export const setText = defineMutator({
698
+ * args: { id: v.id("nodes"), text: v.string() },
699
+ * server: async (ctx, args) => { await ctx.db.patch(args.id, { text: args.text }); },
700
+ * });
701
+ */
702
+ export const defineMutator = defineMutatorBase as unknown as <Args extends Record<string, Validator> = Record<string, Validator>, ClientTx = unknown, R = unknown>(
703
+ definition: MutatorDefinition<Args, MutationCtx, ClientTx, R>,
704
+ ) => RegisteredMutator<Args, MutationCtx, ClientTx, R>;
705
+
706
+ /**
707
+ * \`definePolicy\` bound to THIS schema's {@link DataModel} + {@link Relations}.
708
+ * Import it from here (\`./_generated/server\`) instead of \`@lunora/server\` to get
709
+ * a relation-aware RLS authoring surface: \`table\` autocompletes to a real table
710
+ * name and the \`when\` predicate type-checks against the table's columns **and**
711
+ * its declared relations — \`{ author: { is: {...} } }\`, \`{ posts: { some: {...} } }\`,
712
+ * etc. (the \`@lunora/do\` pre-resolver resolves relation predicates on reads).
713
+ * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
714
+ * so the \`rls()\` chain discovers a policy authored either way the same.
715
+ */
716
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Be}>();
717
+
718
+ /**
719
+ * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
720
+ * table names — so the argument autocompletes and returns a precise
721
+ * \`Id<"table">\`. Identical to \`@lunora/server\`'s \`v\` at runtime; the only
722
+ * difference is the tightened \`id\` type.
723
+ *
724
+ * Import \`v\` from here (\`./_generated/server\`) in your queries/mutations/actions
725
+ * to get table-name autocomplete. \`lunora/schema.ts\` can't use it — it is the
726
+ * file that defines the table names, so they aren't known yet there; pass the
727
+ * names as string literals and the generated \`Id<"table">\` types still catch a
728
+ * typo wherever the id is used.
729
+ */
730
+ export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
731
+ id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
732
+ };
733
+ `},fr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${A(n.filePath)}:${n.exportName}`);return t},fa=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,c=n.length>0,d=oe(i),{dispatchBody:h,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=pr(n,r,a,o),R=sr(t,n),x=ir(s,n),v=[R.lines,x.lines].filter(w=>w.length>0).join(`
734
+ `);let $=h;v.length>0&&($=h.length>0?`${h.trimEnd()}
735
+ ${v}
736
+ `:`
737
+ ${v}
738
+ `);const T=fr(n),H=o.length>0?`import type { RegisteredShape } from "${d.server}";
739
+ `:"",O=o.length>0?`
740
+ /**
741
+ * Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
742
+ * The generated ShardDO's \`resolveShape\` override looks a shape up by name and
743
+ * evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
744
+ * \`shape_subscribe\` (reads-as-permissions).
745
+ */
746
+ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${b}};
747
+ `:"",C=l.length>0?`
748
+ /**
749
+ * Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
750
+ * ShardDO's \`isCustomMutator\` override routes through the client-watermark push
751
+ * protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
752
+ */
753
+ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(w=>JSON.stringify(w)).join(", ")}]);
754
+ `:"",k=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
755
+ `:"",P=y.length>0?`
756
+ /**
757
+ * AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
758
+ * onto its function's live \`.args\` object and consulted by the interpreted
759
+ * parser as a zero-allocation fast path; anything it can't model is deferred.
760
+ */
761
+ ${y}
762
+ `:"",M=mr(n),ie=M.types?`
763
+ ${M.types}
764
+ `:"",le=M.implementation?`
765
+ ${M.implementation}
766
+ `:"",Z=ze(M.types),V=Z.length>0?`import type { ${Z.join(", ")} } from "./dataModel.js";
767
+ `:"",D=c?"context":"_context",ee=c?`${hr}
768
+
769
+ `:"";return Rt(`${S}${g}${R.importLine}${x.importLine}${k}${H}import { LunoraError } from "${d.server}";
770
+ import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
771
+ ${V}
772
+ /**
773
+ * Single registered function, narrowed to the shape \`handleRpc\` needs.
774
+ * The real argument validators / return types are checked elsewhere — at
775
+ * the dispatch site we erase to \`unknown\` so a single map can host every
776
+ * registered function.
777
+ */
778
+ export interface RegisteredLunoraFunction {
779
+ kind: "action" | "mutation" | "query" | "stream";
780
+ args: Record<string, unknown>;
781
+ /**
782
+ * Present on a \`"stream"\` declared \`durable\`: its run is persisted and
783
+ * survives the socket that opened it. Absent on every other kind, and on an
784
+ * ephemeral stream.
785
+ */
786
+ durable?: { ttlMs?: number };
787
+ /**
788
+ * For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
789
+ * For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
790
+ * \`AbortSignal\` as a third argument — the runtime drives it frame-by-frame.
791
+ */
792
+ handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
793
+ /**
794
+ * The lifecycle moment a hook fires on, when this registration came from
795
+ * \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`/\`onWhisper\`.
796
+ * Read at dispatch to decide whether the function runs system-trusted:
797
+ * \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
798
+ * to. \`whisper\` does have one — it runs under the asking socket's identity.
799
+ */
800
+ lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper";
801
+ /**
802
+ * Hoisted by the builder when the \`.use()\` chain carries a step with a
803
+ * per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
804
+ * captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
805
+ * inside the dispatch callback, and a reactive-cache HIT skips that
806
+ * callback, so such a query must never be memoized.
807
+ */
808
+ perDispatch?: boolean;
809
+ /** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
810
+ visibility?: "internal" | "public";
811
+ /**
812
+ * \`.x402({ price })\` tag on a paid public procedure. The origin worker
813
+ * paywalls it; the shard refuses to subscribe it (\`isPaidFunction\`).
814
+ */
815
+ x402?: { readonly price: number | string };
816
+ }
817
+ ${R.prelude}${x.prelude}
818
+ /**
819
+ * Static dispatch table. The key matches the \`__lunoraRef\` the client
820
+ * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
821
+ */
822
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${$}};
823
+ ${P}${O}${C}
824
+ /**
825
+ * Lifecycle manifest: the function paths the generated ShardDO dispatches when a
826
+ * client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
827
+ * per Durable Object instance before any handler runs (\`init\`), after a
828
+ * write flush when a watched read's result changed (\`reactor\`), and before a
829
+ * socket joins or broadcasts to a whisper topic (\`whisper\`). Each path also
830
+ * resolves through {@link LUNORA_FUNCTIONS}. The socket-scoped moments run under
831
+ * the socket's verified identity; \`init\` and \`reactor\` have no caller, so they
832
+ * run anonymous — all via system dispatch.
833
+ */
834
+ export const LUNORA_LIFECYCLE_HOOKS: {
835
+ connect: readonly string[];
836
+ disconnect: readonly string[];
837
+ init: readonly string[];
838
+ reactor: readonly string[];
839
+ whisper: readonly string[];
840
+ } = {
841
+ connect: [${T.connect.map(w=>JSON.stringify(w)).join(", ")}],
842
+ disconnect: [${T.disconnect.map(w=>JSON.stringify(w)).join(", ")}],
843
+ init: [${T.init.map(w=>JSON.stringify(w)).join(", ")}],
844
+ reactor: [${T.reactor.map(w=>JSON.stringify(w)).join(", ")}],
845
+ whisper: [${T.whisper.map(w=>JSON.stringify(w)).join(", ")}],
846
+ };
847
+
848
+ /**
849
+ * Resolve and invoke a registered function from an external caller. Throws a
850
+ * LunoraError-shaped object (404) when the path is unknown — the runtime's
851
+ * structural error mapper turns that into the right HTTP status. Internal
852
+ * functions are treated as not-found so their existence never leaks to clients.
853
+ */
854
+ export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
855
+ const registered = LUNORA_FUNCTIONS[functionPath];
856
+
857
+ if (!registered || registered.visibility === "internal") {
858
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
859
+ }
860
+
861
+ return registered.handler(context, args);
862
+ };
863
+
864
+ /**
865
+ * A handler context accepted by {@link createCaller}. The runtime context the
866
+ * shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
867
+ */
868
+ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
869
+
870
+ /**
871
+ * Typed, in-process server-to-server caller. Every registered function — public
872
+ * *and* internal — is reachable; each call dispatches against the same shard
873
+ * with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
874
+ * \`runAction\` but without re-stating the function path.
875
+ */
876
+ export interface Caller {${ie}}
877
+
878
+ ${ee}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
879
+ export const createCaller = (${D}: CallerCtx): Caller => ({${le}});
880
+
881
+ /**
882
+ * Single registered data migration, narrowed to the shape the per-shard runner
883
+ * consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
884
+ * validation lives in \`defineMigration\`.
885
+ */
886
+ export interface RegisteredDataMigration {
887
+ batchSize?: number;
888
+ down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
889
+ id: string;
890
+ table: string;
891
+ up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
892
+ }
893
+
894
+ /**
895
+ * Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
896
+ * shard DO's admin RPC and the CLI resolve migrations to run through this map.
897
+ */
898
+ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
899
+ `,i)},br=e=>{const t={};for(const n of e.tables){const r={};for(const[a,o]of Object.entries(n.shape)){const i=se(o);i.kind==="id"&&i.tableName!==void 0&&(r[a]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},yr=e=>{const t={};for(const n of e.tables){const r=[];for(const[a,o]of Object.entries(n.shape))se(o).kind==="storage"&&r.push(a);r.length>0&&(t[n.name]=r)}return t},wr=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(a=>({fields:[...a.fields],name:a.name,type:"index",...a.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(a=>({fields:[a.field,...a.filterFields??[]],name:a.name,type:"search"})),...(n.geoIndexes??[]).map(a=>({fields:[a.field],name:a.name,type:"geo"})),...n.rankIndexes.map(a=>({fields:a.sortBy.map(o=>o.field),name:a.name,type:"rank"})),...n.vectorIndexes.map(a=>({fields:a.field===void 0?[]:[a.field],name:a.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},kr=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},xr=e=>{if(e.kind!=="union"||e.members===void 0||e.members.length===0)return;const t=[];for(const n of e.members){if(n.kind!=="literal"||n.literalValue===void 0)return;try{const r=JSON.parse(n.literalValue);if(typeof r!="string")return;t.push(r)}catch{return}}return t},vr=(e,t,n)=>{const r=se(t),a={name:e,optional:xt(t),type:r.kind};if(r.kind==="id"&&r.tableName!==void 0){a.ref=r.tableName;const i=n.get(e);i!==void 0&&(a.onDelete=i)}r.kind==="storage"&&(a.isStorage=!0,r.bucket!==void 0&&(a.bucket=r.bucket));const o=xr(r);return o!==void 0&&(a.enumValues=o),r.column?.notNull===!1&&(a.nullable=!0),a},Sr=e=>{const t={};for(const n of e.tables){const r=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...n.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],a=new Map(n.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,i]of Object.entries(n.shape))r.push(vr(o,i,a));t[n.name]=r}return t},Rr=e=>e?{importFragment:"serveRelationFanout, ",override:`
900
+ protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
901
+ this.ensureMigrated();
902
+
903
+ const { db } = this.buildCtx({ functionPath }) as { db: DatabaseWriterLike };
904
+
905
+ return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
906
+ }
907
+ `}:{importFragment:"",override:""},$r=e=>{if(!e)return{build:"",configField:"",contextField:"",stub:""};const t='throw new Error("ctx.ai: no AI binding found. Add an \\`ai\\` binding (env.AI) to wrangler.jsonc, or pass \\`ai\\` to createShardDO().");';return{build:`
908
+ const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
909
+ // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
910
+ // function path + trace id into createAi, which folds them into the
911
+ // gateway's native \`metadata\` only when a gateway is configured (absent
912
+ // otherwise). Mirror the tracer's anchor guard — a deferred subscription
913
+ // re-run must not borrow a concurrent dispatch's trace, so read
914
+ // \`getCurrentTrace()\` only on the synchronous (non-threaded-identity) path.
915
+ const aiTrace = options.identity ? undefined : this.getCurrentTrace();
916
+ const ai: LunoraAi = aiBinding
917
+ ? createAi({ binding: aiBinding as AiBindingLike, env: env as Record<string, unknown>, metadata: { functionPath: options.functionPath, traceId: aiTrace?.traceId } })
918
+ : aiStub;
919
+ `,configField:`
920
+ ai?: (env: Record<string, unknown>) => AiBindingLike;`,contextField:`
921
+ ai,`,stub:`
922
+ const aiStub: LunoraAi = {
923
+ embeddingModel: () => {
924
+ ${t}
925
+ },
926
+ model: () => {
927
+ ${t}
928
+ },
929
+ run: async () => {
930
+ ${t}
931
+ },
932
+ // workersai is a callable-with-properties; a bare throwing arrow isn't
933
+ // structurally assignable, so cast it. Never invoked (the stub throws first).
934
+ workersai: (() => {
935
+ ${t}
936
+ }) as unknown as LunoraAi["workersai"],
937
+ };
938
+ `}},I=(e,t,n,{cast:r="",sync:a=[]}={})=>{const o=n.map(i=>` ${i}: ${a.includes(i)?"":"async "}() => {
939
+ ${t}
940
+ },`).join(`
941
+ `);return`
942
+ const ${e} = {
943
+ ${o}
944
+ }${r};
945
+ `},E={build:"",configField:"",contextField:"",importLines:[],stub:""},Tr=e=>e?{build:`
946
+ const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
947
+ // KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
948
+ // when a value changes — a subscription that read one can never be proven
949
+ // current on reconnect and must re-snapshot. Reads only; \`put\`/\`delete\`
950
+ // are writes and stay unstamped.
951
+ const kv: Kv = markUnvouchableReads(kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub, options.onRead, [
952
+ "get",
953
+ "getRaw",
954
+ "getWithMetadata",
955
+ "list",
956
+ ]);
957
+ `,configField:`
958
+ kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
959
+ kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:I("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:E,Nr=(e,t)=>e?{build:`
960
+ const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
961
+ provider: () => config.flags?.(env),
962
+ targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
963
+ });
964
+ `,configField:`
965
+ flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
966
+ flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:E,Ar=e=>e?{build:`
967
+ const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
968
+ `,configField:"",contextField:`
969
+ notify,
970
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:E,Or=e=>e?{build:`
971
+ const envConfig = lunoraEnvContract.${e.exportName}(env);
972
+ `,configField:"",contextField:`
973
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:E,Ir=e=>e?{build:`
974
+ const access = accessFacade(identity, userId);
975
+ `,configField:"",contextField:`
976
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:E,Cr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
977
+ const env = (this.env ?? {}) as Record<string, unknown>;
978
+ const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
979
+ provider: () => config.flags?.(env),
980
+ targetingKey: ${s},
981
+ });`,a=`
982
+ /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
983
+ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }> = ${JSON.stringify(e,void 0,4)};
984
+ `,o=`
985
+ protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${r("undefined")}
986
+ const evalContext = context as import("${n}").EvaluationContext | undefined;
987
+ const evaluations: FlagsResult["flags"] = [];
988
+
989
+ for (const entry of LUNORA_FLAG_KEYS) {
990
+ // eslint-disable-next-line no-await-in-loop -- flags evaluate sequentially; each shares the single memoized provider client
991
+ const details =
992
+ entry.type === "boolean"
993
+ ? await flags.details.boolean(entry.key, false, evalContext)
994
+ : entry.type === "number"
995
+ ? await flags.details.number(entry.key, 0, evalContext)
996
+ : entry.type === "string"
997
+ ? await flags.details.string(entry.key, "", evalContext)
998
+ : await flags.details.object(entry.key, {}, evalContext);
999
+
1000
+ evaluations.push({ errorCode: details.errorCode, key: entry.key, reason: details.reason, type: entry.type, value: details.value, variant: details.variant });
1001
+ }
1002
+
1003
+ return { configured: true, flags: evaluations };
1004
+ }
1005
+ `,i=`
1006
+ protected override runFlagSubscriptionRead(_functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<unknown> {${r("() => flagsConfig.identify?.({ identity: identity?.identity ?? null, userId: identity?.userId ?? null })")}
1007
+ const key = typeof args.key === "string" ? args.key : "";
1008
+
1009
+ // SECURITY: the reactive channel is public (any socket, no auth). Serve
1010
+ // ONLY statically-discovered flag keys — an arbitrary client-supplied key
1011
+ // would let a subscriber probe the value of internal/unreleased flags the
1012
+ // app never exposes. Unknown key ⇒ the "nothing to deliver" sentinel.
1013
+ // eslint-disable-next-line unicorn/no-null -- the base hook's "nothing to deliver" sentinel
1014
+ if (key.length === 0 || !LUNORA_FLAG_KEYS.some((entry) => entry.key === key)) {
1015
+ return Promise.resolve(null);
1016
+ }
1017
+
1018
+ // SECURITY: evaluate under the socket's server-verified identity ONLY
1019
+ // (the targetingKey resolved above). Client-supplied targeting context is
1020
+ // NOT honored on this public channel — otherwise a subscriber could spoof
1021
+ // targeting attributes (e.g. plan/role) to unlock a flag gated on them.
1022
+ const context = undefined;
1023
+
1024
+ if (args.type === "number") {
1025
+ return flags.number(key, typeof args.default === "number" ? args.default : 0, context);
1026
+ }
1027
+
1028
+ if (args.type === "string") {
1029
+ return flags.string(key, typeof args.default === "string" ? args.default : "", context);
1030
+ }
1031
+
1032
+ if (args.type === "object") {
1033
+ return flags.object(key, (args.default ?? {}) as import("${n}").JsonValue, context);
1034
+ }
1035
+
1036
+ return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
1037
+ }
1038
+ `;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},Dr=e=>e?{build:`
1039
+ const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
1040
+ const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
1041
+ `,configField:`
1042
+ analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
1043
+ analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:I("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:E,Lr=e=>e?{build:`
1044
+ const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
1045
+ const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
1046
+ `,configField:`
1047
+ images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
1048
+ images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:I("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:E,Er=e=>e?{build:`
1049
+ const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
1050
+ `,configField:`
1051
+ sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
1052
+ sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:I("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:E,_r=e=>e?{build:`
1053
+ const browser: Browser = config.browser ? config.browser(env) : browserStub;
1054
+ `,configField:`
1055
+ browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
1056
+ browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:I("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:E,Pr=e=>e?{build:`
1057
+ const r2sqlEnv = env as Record<string, unknown>;
1058
+ const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
1059
+ const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
1060
+ const r2sqlBucket = r2sqlEnv.R2_SQL_BUCKET as string | undefined;
1061
+ const r2sql: R2SqlClient = config.r2sql
1062
+ ? config.r2sql(env)
1063
+ : r2sqlAccountId && r2sqlToken && r2sqlBucket
1064
+ ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
1065
+ : r2sqlStub;
1066
+ `,configField:`
1067
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:I("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:E,Mr=e=>e?{build:`
1068
+ const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
1069
+ const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
1070
+ `,configField:`
1071
+ pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,ba=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(o=>(f(o.exportName,`container export "${o.exportName}"`),f(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
1072
+ export class ${o.className} extends LunoraContainer {
1073
+ public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1074
+ super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
1075
+ }
1076
+ }
1077
+ `)).join(`
1078
+ `),a=e.map(o=>o.exportName).join(", ");return`${S}/**
1079
+ * Container-enabled Durable Object classes for the containers declared in
1080
+ * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
1081
+ * requires each \`containers[].class_name\` to be exported by the worker:
1082
+ *
1083
+ * \`export * from "./lunora/_generated/containers.js";\`
1084
+ *
1085
+ * \`ContainerProxy\` is re-exported alongside them: the egress-interception path
1086
+ * (\`allowedHosts\`/\`deniedHosts\`/\`interceptHttps\` and the runtime
1087
+ * \`handle.egress\` controls) routes container outbound traffic through this
1088
+ * WorkerEntrypoint, so it too must be exported by the deployed worker.
1089
+ */
1090
+ import { LunoraContainer } from "@lunora/container/do";
1091
+
1092
+ import { ${a} } from "../containers.js";
1093
+
1094
+ export { ContainerProxy } from "@lunora/container/do";
1095
+
1096
+ ${r}`},Fr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)f(r.exportName,`container export "${r.exportName}"`),f(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const a=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${a} },`}).join(`
1097
+ `);return{build:`
1098
+ const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
1099
+ `,contextField:`
1100
+ containers,`,importLines:['import type { ContainerBindingSpec } from "@lunora/container";','import { createContainerContext } from "@lunora/container";'],specs:`
1101
+ /** Wiring specs for \`ctx.containers\` (codegen-derived from \`lunora/containers.ts\`). */
1102
+ const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
1103
+ ${n}
1104
+ ];
1105
+ `}},ya=e=>{if(e.length===0)return"";const t=e.map(r=>(f(r.exportName,`workflow export "${r.exportName}"`),f(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
1106
+ export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
1107
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1108
+ super(ctx, env, ${r.exportName}, "${r.exportName}");
1109
+ }
1110
+ }
1111
+ `)).join(`
1112
+ `),n=e.map(r=>r.exportName).join(", ");return`${S}/**
1113
+ * WorkflowEntrypoint classes for the workflows declared in
1114
+ * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
1115
+ * requires each \`workflows[].class_name\` to be exported by the worker:
1116
+ *
1117
+ * \`export * from "./lunora/_generated/workflows.js";\`
1118
+ */
1119
+ import LunoraWorkflow from "@lunora/workflow/do";
1120
+
1121
+ import { ${n} } from "../workflows.js";
1122
+
1123
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`), so each entrypoint keeps the authored \`ctx.params\` type. */
1124
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
1125
+ ? unknown extends Params
1126
+ ? Record<string, unknown>
1127
+ : NonNullable<Params>
1128
+ : Record<string, unknown>;
1129
+
1130
+ /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
1131
+ type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
1132
+
1133
+ ${t}`},wa=e=>{if(e.length===0)return"";const n=e.filter(s=>s.voice).length>0,r=e.map(s=>{f(s.exportName,`agent export "${s.exportName}"`),f(s.className,`agent class "${s.className}"`);const c=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent (binding \`${s.bindingName}\`). */
1134
+ export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1135
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1136
+ super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
1137
+ }
1138
+ }
1139
+ `;if(!s.voice)return c;const d=s.voiceClassName??"",h=s.voiceBindingName??"";f(d,`agent voice class "${d}"`);const g=`
1140
+ /** Voice-session Durable Object for the \`${s.exportName}\` agent (binding \`${h}\`). */
1141
+ export class ${d} extends VoiceSessionDO {
1142
+ public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
1143
+ super(ctx, env, ${s.exportName}, "${s.exportName}");
1144
+ }
1145
+ }
1146
+ `;return`${c}${g}`}).join(`
1147
+ `),a=e.map(s=>s.exportName).join(", ");return`${S}/**
1148
+ * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
1149
+ * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
1150
+ * Workflow. Re-export them from your worker entry — wrangler requires each
1151
+ * \`workflows[].class_name\` to be exported by the worker:
1152
+ *
1153
+ * \`export * from "./lunora/_generated/agents.js";\`${n?"\n *\n * Voice-enabled agents ALSO get a `VoiceSessionDO` subclass here — a real\n * Durable Object (unlike the Workflow), so wrangler needs both its\n * `durable_objects` binding and its `class_name` export (the same re-export\n * line covers it).":""}
1154
+ */
1155
+ import LunoraWorkflow from "@lunora/workflow/do";
1156
+ ${n?'import { compileAgentWorkflow, VoiceSessionDO } from "@lunora/agent";':'import { compileAgentWorkflow } from "@lunora/agent";'}
1157
+ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
1158
+
1159
+ import { ${a} } from "../agents.js";
1160
+
1161
+ ${r}`},ka=e=>{const t=e.filter(a=>a.mode==="push");if(t.length===0)return"";for(const a of t)f(a.exportName,`queue export "${a.exportName}"`);const n=t.map(a=>a.exportName).join(", "),r=t.map(a=>` ${JSON.stringify(a.name)}: { definition: ${a.exportName}, exportName: ${JSON.stringify(a.exportName)} },`).join(`
1162
+ `);return`${S}/**
1163
+ * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
1164
+ * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
1165
+ * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
1166
+ * by \`defineApp\` — you don't import this directly.
1167
+ */
1168
+ import type { QueueRegistry } from "@lunora/queue";
1169
+
1170
+ import { ${n} } from "../queues.js";
1171
+
1172
+ /** Stable wrangler queue name → { definition, exportName } for batch routing. */
1173
+ export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
1174
+ ${r}
1175
+ };
1176
+ `},Br=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)f(n.exportName,`workflow export "${n.exportName}"`),f(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
1177
+ `);return{build:`
1178
+ const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
1179
+ `,contextField:`
1180
+ workflows,`,importLines:['import type { WorkflowBindingSpec } from "@lunora/workflow";','import { createWorkflowContext } from "@lunora/workflow";'],specs:`
1181
+ /** Wiring specs for \`ctx.workflows\` (codegen-derived from \`lunora/workflows.ts\`). */
1182
+ const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
1183
+ ${t}
1184
+ ];
1185
+ `}},qr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)f(n.exportName,`queue export "${n.exportName}"`),f(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
1186
+ `);return{build:`
1187
+ const queues = createQueueContext(env, LUNORA_QUEUES);
1188
+ `,contextField:`
1189
+ queues,`,importLines:['import type { QueueBindingSpec } from "@lunora/queue";','import { createQueueContext } from "@lunora/queue";'],specs:`
1190
+ /** Wiring specs for \`ctx.queues\` (codegen-derived from \`lunora/queues.ts\`). */
1191
+ const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
1192
+ ${t}
1193
+ ];
1194
+ `}},jr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)f(n.exportName,`agent export "${n.exportName}"`),f(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
1195
+ `);return{build:`
1196
+ const agents = createAgentContext(env, LUNORA_AGENTS);
1197
+ `,contextField:`
1198
+ agents,`,importLines:['import { createAgentContext } from "@lunora/agent";','import type { AgentBindingSpec } from "@lunora/agent";'],specs:`
1199
+ /** Wiring specs for \`ctx.agents\` (codegen-derived from \`lunora/agents.ts\`). */
1200
+ const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
1201
+ ${t}
1202
+ ];
1203
+ `}},Nt=(e,t,n,r,a)=>({constant:`
1204
+ ${a}
1205
+ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1206
+ `,override:`
1207
+ protected override ${n}(): ${t} {
1208
+ return ${e};
1209
+ }
1210
+ `}),Wr=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return Nt("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Ur=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return Nt("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Kr=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
1211
+ const payments: LunoraPayment = config.payment
1212
+ ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
1213
+ : paymentStub;
1214
+ `,configField:`
1215
+ payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
1216
+ payments,`,stub:I("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},Qr=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
1217
+ const x402: X402Pay = config.x402
1218
+ ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1219
+ : x402Stub;
1220
+ `,configField:`
1221
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Hr=(e,t,n,r,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],xa=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:$=!1,maskMetadata:T,mutators:H=[],queues:O=[],rlsMetadata:C,schema:k,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const D=oe(Z),ee=H.length>0,w=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
1222
+ /** 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. */
1223
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Tn(P))}, json: ${JSON.stringify(Ae)} };
1224
+ `,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=$r(s),ue=Ir(i),G=Tr(u),_=Nr(h,D.flags),J=Cr(o,h,D.flags),te=Ar(l),he=Or(a),z=Dr(c),j=Lr(y),W=Er(g),U=_r(d),B=Pr(x),ne=Mr(R),{build:De,contextField:ve,importLines:Se,specs:pe}=qr(O),{build:Le,contextField:Ee,importLines:Re,specs:me}=Fr(r,k.jurisdiction),{build:_e,contextField:Pe,importLines:$e,specs:Me}=Br(V),{build:Fe,contextField:ge,importLines:fe,specs:Be}=jr(n),{build:qe,configField:je,contextField:be,imports:ye,stub:Ze}=Kr(b),{build:p,configField:We,imports:Te,stub:re}=Qr($),Ot=e,It=t,et=C??{policies:[],roles:[]},Ct=T??{columns:[]},Dt=ie??{rules:[]},Lt=le??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Et,override:_t}=Wr(V),{constant:Pt,override:Mt}=Ur(O),K=v&&k.vectorIndexes.length>0,tt=new Set(k.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&k.vectorIndexes.some(m=>tt.has(m.table)),we=k.tables.some(m=>m.shardMode==="global"),Ue=k.tables.some(m=>Nn(m)),nt=k.tables.some(m=>An(m)),ae=k.tables.some(m=>m.externalSource!==void 0),rt=k.tables.some(m=>m.memory===!0),Ke=k.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(nt&&Ue)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=k.tables.length>0,Ft=br(k),Bt=wr(k),qt=Sr(k),jt=yr(k),at=kr(k),ot=Hr(K,V.length>0,O.length>0,h,Ke);w&&ot.push("WhereInput");const st=Rr(we),Wt=w?`
1225
+ protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
1226
+ const shape = LUNORA_SHAPES[name];
1227
+
1228
+ if (!shape) {
1229
+ return undefined;
1230
+ }
1231
+
1232
+ this.ensureMigrated();
1233
+
1234
+ // Trusted ctx from the socket's OWN verified identity — the client
1235
+ // supplies only the shape name + args; \`compileWhere\` validates the
1236
+ // args then runs the shape's \`where(ctx, args)\` under that identity,
1237
+ // so which rows replicate is a server decision (reads-as-permissions).
1238
+ const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity });
1239
+ // \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
1240
+ // \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
1241
+ // rather than every shape restating the ownership check in its \`where\`.
1242
+ const shapeWhere = shape.compileWhere(ctx, args, {
1243
+ ownerField: (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField,
1244
+ }) as unknown as WhereInput;
1245
+
1246
+ // AND-compose with the read policies this SHAPE declares
1247
+ // (\`defineShape({ use: [guard] })\`, pre-indexed into
1248
+ // \`shape.rlsRegistry\`). A shape runs no procedure, so the
1249
+ // \`.use(rls(...))\` middleware never fires; without this merge its
1250
+ // reads would bypass the read policies it opted into.
1251
+ // \`composeShapeReadWhere\` evaluates them under this same trusted ctx
1252
+ // and fails closed under a \`.rls("required")\` schema for a
1253
+ // non-\`.public()\` table the shape declared no read policy for.
1254
+ //
1255
+ // The registry is the shape's OWN — never one folded from every
1256
+ // registered function. A project-wide union let one admin-only
1257
+ // procedure's allow-all read policy unrestrict every shape on the
1258
+ // table; see the SCOPE note in \`shape-read-base.ts\`.
1259
+ //
1260
+ // It is NOT identical to the request-time path, and must not be
1261
+ // described as such: roles come from the identity's \`roles\` claim
1262
+ // only, because no middleware runs here to contribute
1263
+ // \`ctx.auth.roles\`. Derive roles at the identity if a policy gates
1264
+ // on them — see \`shape-read-base.ts\`.
1265
+ const effectiveWhere = composeShapeReadWhere(shape.rlsRegistry, {
1266
+ ctx,
1267
+ identity: identity?.identity ?? null,
1268
+ rlsRequired: (schema as unknown as { rlsMode?: string }).rlsMode === "required",
1269
+ shapeWhere,
1270
+ table: shape.table,
1271
+ tablePublic: (schema as unknown as { tables: Record<string, { isPublic?: boolean }> }).tables[shape.table]?.isPublic === true,
1272
+ userId: identity?.userId ?? null,
1273
+ });
1274
+
1275
+ // A live shape pokes only from its OWN shard's op-log, so a \`where()\`
1276
+ // that joins to a \`.shardBy()\` table (rows in another DO) is rejected
1277
+ // here — the first point the compiled predicate + shard modes are both
1278
+ // known. Remedy: denormalize, or move the joined table to \`.global()\`.
1279
+ assertShapeShardable(effectiveWhere, schema as unknown as SchemaLike, shape.table);
1280
+
1281
+ // A \`.global()\` table lives in D1 (no per-DO op-log): flag it so the
1282
+ // base serves it through the latency-tiered poll path (\`readGlobalShapeRows\`)
1283
+ // instead of the CDC poke path.
1284
+ const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global";
1285
+
1286
+ return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
1287
+ }
1288
+ `:"",it=w?[...new Set(et.policies.filter(m=>m.on==="read"&&m.table!=="").map(m=>m.table))].toSorted((m,Rn)=>m.localeCompare(Rn)):[],lt=it.length>0?`
1289
+ /** 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). */
1290
+ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(it)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
1291
+ `:"",Ut=ee?`
1292
+ protected override isCustomMutator(functionPath: string): boolean {
1293
+ return LUNORA_MUTATOR_PATHS.has(functionPath);
1294
+ }
1295
+ `:"",Kt=w?"assertShapeShardable, ":"",Qt=lt===""?"":"assertShapesDeclareReadPolicies, ",ke=[`import type { ${ot.join(", ")} } from "${D.do}";`,`import { applyCdcChanges, ${Ke?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${rt?"clearMemoryTables, ":""}${Kt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${ae?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Ne?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${st.importFragment}ShardDO as ShardDOBase } from "${D.do}";`,...ae?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${D.do}";`]:[],w?`import { asBucketStorage, ${Qt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${D.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${D.server}";`];Qe&&ke.push(`import { bindOrm, bindTableFacade } from "${D.server}";`),K&&ke.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&ke.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ke.push(...ue.importLines,...G.importLines,..._.importLines,...te.importLines,...he.importLines,...z.importLines,...j.importLines,...W.importLines,...U.importLines,...B.importLines,...ne.importLines,...Re,...$e,...Se,...fe,...ye,...Te,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ee?["LUNORA_MUTATOR_PATHS"]:[],...w?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ht=K?`
1296
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Vt=nt?`
1297
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Gt=Ue?`
1298
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Jt=ae?`
1299
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",zt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Yt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Xt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Zt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',en=we?I("globalDbStub: DatabaseWriterLike",zt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",tn=K?I("vectorsStub: VectorSearchLike",Yt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",nn=Ne?`
1300
+ const vectorShardKey = this.currentShardKey();
1301
+ `:"",rn=Ne?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",an=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...Ne?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${k.vectorIndexes.filter(m=>tt.has(m.table)).map(m=>JSON.stringify(m.name)).join(", ")}]`]:[]].join(", ")} }`,on=K?`
1302
+ let vectors: VectorSearchLike;
1303
+ let onWrite: WriteHook | undefined;
1304
+
1305
+ if (config.vectors) {
1306
+ const lunora = createVectors({ indexes: config.vectors(env) });
1307
+ ${nn}
1308
+ vectors = createContextVectors(lunora${an});
1309
+ onWrite = createVectorSyncHook({ ${rn}schema: schema as unknown as VectorSchemaLike, vectors });
1310
+ } else {
1311
+ vectors = vectorsStub;
1312
+ onWrite = undefined;
1313
+ }
1314
+
1315
+ // Vectorize lives outside this shard's SQLite, so a query whose result
1316
+ // depends on a similarity search cannot be proven current on reconnect —
1317
+ // an unrelated upsert (or a re-index) moves the matches without touching
1318
+ // \`__cdc_log\`. Wrapped AFTER \`onWrite\` is built so the write-through
1319
+ // vector-sync hook keeps calling the bare facade.
1320
+ vectors = markUnvouchableReads(vectors, options.onRead, ["getByIds", "query"]);
1321
+ `:"",sn=`{
1322
+ ...this.ctxDbTuning(),
1323
+ auth: { identity: identity ?? null, userId: userId ?? null },
1324
+ broadcast: (delta) => {
1325
+ this.recordChangedTable(delta.table, delta.indexKeys);
1326
+ },
1327
+ // Read at call time, not captured: the baseline belongs to the
1328
+ // dispatch in flight, and a queued mutation admitted after a
1329
+ // sibling's prologue must be judged against ITS caller's cursor.
1330
+ baselineSeq: () => this.getCurrentBaselineSeq(),
1331
+ cdc: config.cdc ?? false,
1332
+ // A dispatch with NO caller identity runs system-trusted: RLS scopes
1333
+ // rows to a user, and these have no user to scope to. This is the tier
1334
+ // migrations, imports and the external-source poll loop already run in
1335
+ // (see \`adminWriterPrelude\`). Only \`onShardInit\` and \`onQueryChange\`
1336
+ // reach it; \`onConnect\`/\`onDisconnect\` carry a verified identity and
1337
+ // stay guarded like any request.
1338
+ enforceRls: options.trusted !== true,
1339
+ headroom: options.headroom ?? this.transactionHeadroom(),
1340
+ // A live predicate, not a flag: the transaction opens AFTER this ctx
1341
+ // is built (a mutation dispatch wraps the handler), so only a call-time
1342
+ // read reports the truth. \`_commitSeq\` reuses one sequence across
1343
+ // writes only while they commit together — an action is not wrapped, so
1344
+ // each of its writes allocates its own.
1345
+ inTransaction: () => this.isInTransaction(),
1346
+ onIndexUse: this.getCtxDbIndexUseHook(),
1347
+ onStalePatchDropped: (event) => {
1348
+ this.recordStalePatchDropped(event);
1349
+ },
1350
+ // Bound to THIS dispatch's reactive-cache read scope (\`handleRpc\`
1351
+ // threads it in), so two concurrent queries never stamp each
1352
+ // other's dep sets. \`executeSubscription\` overrides both with its
1353
+ // own \`ReadFootprint\` pair instead, and a dispatch with neither
1354
+ // gets an unbound hook that stamps no deps.
1355
+ onRead: options.onRead ?? this.getCtxDbReadHook(options.scope),
1356
+ // Left \`undefined\` when there is no scope so \`createShardCtxDb\`
1357
+ // keeps its own "degrade a provable slice to a whole-table dep"
1358
+ // fallback rather than reporting into a no-op.
1359
+ onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${K?`
1360
+ // Vectorize is outside this shard's SQLite and cannot roll back, so
1361
+ // the sync is held until the mutation's transaction has COMMITTED
1362
+ // (\`deferAfterCommit\`) instead of running inline. Inline, a write
1363
+ // that later aborted left a vector pointing at a row that does not
1364
+ // exist — which a search then surfaces — and a rolled-back delete
1365
+ // left the row with its vector already purged. Outside a
1366
+ // transaction (an action) nothing is open and it runs at once.
1367
+ onWrite: onWrite === undefined ? undefined : (event) => this.deferAfterCommit(() => onWrite(event)),`:""}
1368
+ scheduler,
1369
+ schema: schema as unknown as SchemaLike,
1370
+ sql: this.sql as SqlExec,
1371
+ storage,${we?`
1372
+ globalDb,`:""}
1373
+ }`,ln=` /**
1374
+ * The bare writer every admin/maintenance entry point writes through.
1375
+ *
1376
+ * Admin and maintenance writes go through the SAME reactive-cache hooks as a
1377
+ * user mutation. Without this, a studio row edit, a TTL sweep, an admin
1378
+ * import, a CDC apply or a data-migration backfill writes without
1379
+ * invalidating, and the next query answers from the pre-write snapshot.
1380
+ *
1381
+ * \`headroom\` meters the transaction. An admin \`/rpc\` caller passes nothing
1382
+ * and falls back to \`this.transactionHeadroom()\`, which for an admin RPC is
1383
+ * \`undefined\` — \`handleAdminRpc\` answers before \`beginDispatch\`, so no
1384
+ * per-dispatch meter is in flight and a bulk loop is bounded by its per-call
1385
+ * row cap alone. The TTL sweep (an alarm work item, no dispatch) passes its
1386
+ * own by-value tracker explicitly instead.
1387
+ */
1388
+ private adminWriter(headroom?: TransactionHeadroomTracker): DatabaseWriterLike {
1389
+ const env = (this.env ?? {}) as Record<string, unknown>;
1390
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1391
+
1392
+ return createShardCtxDb({
1393
+ ...this.ctxDbTuning(),
1394
+ broadcast: (delta) => {
1395
+ this.recordChangedTable(delta.table, delta.indexKeys);
1396
+ },
1397
+ cdc: config.cdc ?? false,
1398
+ headroom,
1399
+ // Live predicate, same as the user-facing ctx — see \`databaseOptions\`.
1400
+ inTransaction: () => this.isInTransaction(),
1401
+ scheduler,
1402
+ schema: schema as unknown as SchemaLike,
1403
+ sql: this.sql as SqlExec,
1404
+ });
1405
+ }`,Q=(m="")=>` const writer = this.adminWriter(${m});`,cn=K?`
1406
+ vectors,`:"",dn=Qe?`
1407
+ orm: bindOrm(facade),`:"",He=Ue?"config.hyperdriveGlobal":"config.d1",un=we?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1408
+ const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
1409
+ `:"",hn=w&&we?`
1410
+ protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1411
+ const env = this.env as Record<string, unknown>;
1412
+ // A shape read performs no writes, so the widened request only needs
1413
+ // the inbound bookmark (pin the membership drain to the caller's own
1414
+ // prior writes) — no \`onBookmark\` here.
1415
+ //
1416
+ // The two identity members are named rather than spread, matching the
1417
+ // dispatch-path request built in \`buildCtx\`. A spread would also hand
1418
+ // the global writer \`ip\`, and \`globalShapeReadKey\` — the per-flush
1419
+ // cache in front of this read — keys on identity + userId only. Equal
1420
+ // keys must mean equal rows, so a field the writer can scope by has to
1421
+ // be either in the key or out of the request; it is out.
1422
+ const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity: identity?.identity, userId: identity?.userId };
1423
+ const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
1424
+ const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
1425
+
1426
+ let cursor: null | string = null;
1427
+
1428
+ // Drain every page of the global membership so the seed/diff sees the
1429
+ // full rowset (D1 \`findMany\` is paginated). Stop one row past the cap:
1430
+ // a broad \`.global()\` shape would otherwise materialize an unbounded
1431
+ // array before the caller's \`withinGlobalShapeBound\` check rejects it,
1432
+ // so bail early and let the caller fail it closed.
1433
+ do {
1434
+ // eslint-disable-next-line no-await-in-loop -- sequential page drain to assemble the full membership
1435
+ const page = await globalDb.findMany(resolved.table, { cursor, where: resolved.effectiveWhere });
1436
+
1437
+ for (const doc of page.page) {
1438
+ rows.push({ doc, id: String((doc as { _id?: unknown })._id) });
1439
+
1440
+ if (rows.length > ShardDOBase.GLOBAL_SHAPE_MAX_ROWS) {
1441
+ return rows;
1442
+ }
1443
+ }
1444
+
1445
+ cursor = page.isDone ? null : page.continueCursor;
1446
+ } while (cursor !== null);
1447
+
1448
+ return rows;
1449
+ }
1450
+
1451
+ protected override async readGlobalChangedTables(sinceSeq: number, cursorOnly?: boolean): Promise<{ cursor: number; floor?: number; tables: string[] } | undefined> {
1452
+ const env = this.env as Record<string, unknown>;
1453
+ // Metadata-only: this asks the global changelog which TABLES moved,
1454
+ // never what changed in them, so it costs one small read per poll tick
1455
+ // for the whole shard — and a tick whose answer omits a shape's table
1456
+ // skips that shape's membership drain entirely.
1457
+ // Named local, not an inline object literal — same reason as the
1458
+ // dispatch path and \`readGlobalShapeRows\`: \`bookmark\` is not declared
1459
+ // on the narrower Hyperdrive thunk's \`request\` type, and an inline
1460
+ // literal trips an excess-property error (TS2353) that makes the
1461
+ // emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
1462
+ // a \`defineShape\`. The Hyperdrive factory simply never reads it.
1463
+ const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
1464
+ const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
1465
+
1466
+ return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
1467
+ }
1468
+ `:"",pn=ae?`
1469
+ const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1470
+ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1471
+ `:"",mn=`
1472
+ protected override async runShardInit(): Promise<void> {
1473
+ this.ensureMigrated();
1474
+ ${rt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1475
+ `:""}
1476
+ await this.dispatchShardInit();
1477
+ }
1478
+ `,gn=ae?`
1479
+ protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1480
+ const env = (this.env ?? {}) as Record<string, unknown>;
1481
+ const sourced = Object.entries((schema as unknown as SchemaLike).tables)
1482
+ .map(([table, definition]) => [table, (definition as { externalSource?: ExternalSourceLike }).externalSource] as const)
1483
+ .filter((entry): entry is [string, ExternalSourceLike] => entry[1] !== undefined);
1484
+
1485
+ if (sourced.length === 0) {
1486
+ return undefined;
1487
+ }
1488
+
1489
+ const shardKey = this.currentShardKey();
1490
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1491
+
1492
+ let clients = sourceClientCache.get(this);
1493
+
1494
+ if (clients === undefined) {
1495
+ clients = new Map();
1496
+ sourceClientCache.set(this, clients);
1497
+ }
1498
+
1499
+ let polledAt = sourcePollAtCache.get(this);
1500
+
1501
+ if (polledAt === undefined) {
1502
+ polledAt = new Map();
1503
+ sourcePollAtCache.set(this, polledAt);
1504
+ }
1505
+
1506
+ const now = Date.now();
1507
+ // \`nextDueAt\` tracks the EARLIEST next-due timestamp across every
1508
+ // non-manual source; the shared alarm re-arms there instead of the
1509
+ // fixed 2 s global-shape floor, so a large \`refresh.everyMs\` actually
1510
+ // sleeps until it's due. Stays \`undefined\` when every source is
1511
+ // \`refresh: "manual"\`, so the shared alarm goes idle for this tier.
1512
+ let nextDueAt: number | undefined;
1513
+
1514
+ for (const [table, source] of sourced) {
1515
+ if (source.refresh === "manual") {
1516
+ continue;
1517
+ }
1518
+
1519
+ if (isSourceDue(source.refresh, polledAt.get(table), now)) {
1520
+ try {
1521
+ let client = clients.get(source.binding);
1522
+
1523
+ if (client === undefined) {
1524
+ client = config.sourceClient?.(env, source.binding);
1525
+
1526
+ if (client !== undefined) {
1527
+ clients.set(source.binding, client);
1528
+ }
1529
+ }
1530
+
1531
+ if (client === undefined) {
1532
+ // No SqlClient resolved for this binding (host never wired
1533
+ // \`config.sourceClient\`, or wired it wrong). Surface it in the
1534
+ // Logs panel and stamp \`polledAt\` so a persistent misconfig backs
1535
+ // off to \`refresh.everyMs\` instead of retrying every alarm tick.
1536
+ this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`), trace);
1537
+ } else {
1538
+ // A FRESH tracker per TABLE, not one shared across the whole
1539
+ // loop: one table's runaway pull must not spend a budget a
1540
+ // sibling table needs, and a limit hit here must not block
1541
+ // that sibling from getting its own full budget this tick.
1542
+ const writer = createShardCtxDb({
1543
+ // Admin and maintenance writes go through the SAME reactive-cache hooks as
1544
+ // a user mutation. Without this, a studio row edit, a TTL sweep, an admin
1545
+ // import, a CDC apply or a data-migration backfill writes without
1546
+ // invalidating, and the next query answers from the pre-write snapshot.
1547
+ ...this.ctxDbTuning(),
1548
+ broadcast: (delta) => {
1549
+ this.recordChangedTable(delta.table, delta.indexKeys);
1550
+ },
1551
+ cdc: config.cdc ?? false,
1552
+ headroom: this.alarmHeadroom(),
1553
+ scheduler,
1554
+ schema: schema as unknown as SchemaLike,
1555
+ sql: this.sql as SqlExec,
1556
+ });
1557
+
1558
+ if (source.mode === "incremental") {
1559
+ // Incremental (plan 136): pull only rows past the durable
1560
+ // watermark (or a full-pull seed/reconcile), upsert-only.
1561
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
1562
+ await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
1563
+ } else {
1564
+ // 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
1565
+ await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
1566
+ }
1567
+ }
1568
+
1569
+ // Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
1570
+ // poll that outruns \`everyMs\` must not make \`nextDueAt\` (below)
1571
+ // stale-immediate and re-arm the alarm in a hammering loop.
1572
+ polledAt.set(table, Date.now());
1573
+ } catch (error) {
1574
+ if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
1575
+ // Batch full, not a genuine failure. Incremental mode only
1576
+ // persists its watermark AFTER a full apply (see
1577
+ // \`pullExternalSourceIncrementalTick\`), so this throw left it
1578
+ // untouched — the next tick safely re-pulls/re-applies the
1579
+ // SAME slice (idempotent upsert). Full-pull mode (and an
1580
+ // incremental source's own occasional full-pull/reconcile
1581
+ // sweep) has no resumable cursor at all — deliberately not
1582
+ // inventing one here; a retry just redoes the whole pull,
1583
+ // safe if wasteful. Either way: warn instead of
1584
+ // \`recordExternalSourceError\`, and leave \`polledAt\`
1585
+ // UNCHANGED (skip the stamp below via \`continue\`) so this
1586
+ // table stays "due" and \`nextPollAlarmTarget\`'s existing
1587
+ // due-now floor re-arms the shared alarm promptly — not a
1588
+ // fresh \`setAlarm(now)\`.
1589
+ this.recordExternalSourceWarning(
1590
+ table,
1591
+ \`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
1592
+ trace,
1593
+ );
1594
+
1595
+ nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
1596
+
1597
+ continue;
1598
+ }
1599
+
1600
+ this.recordExternalSourceError(table, error, trace);
1601
+ // Stamp on failure too, so a persistently failing source throttles
1602
+ // to \`refresh.everyMs\` rather than being hammered every tick.
1603
+ polledAt.set(table, Date.now());
1604
+ }
1605
+ }
1606
+
1607
+ // This source's own next-due time, read AFTER the poll-or-skip above
1608
+ // so a just-polled source reports \`now + everyMs\` (its FRESH due
1609
+ // time), not the stale pre-poll one. An omitted \`refresh\` (poll
1610
+ // every tick) is due again immediately.
1611
+ const sourceNextDueAt = source.refresh === undefined ? now : (polledAt.get(table) ?? now) + source.refresh.everyMs;
1612
+
1613
+ nextDueAt = nextDueAt === undefined ? sourceNextDueAt : Math.min(nextDueAt, sourceNextDueAt);
1614
+ }
1615
+
1616
+ return nextDueAt;
1617
+ }
1618
+ `:"",fn=at.length>0,bn=`
1619
+ public constructor(state: ShardDOState, env: unknown) {
1620
+ super(state, env, {
1621
+ // Every writer this file builds spreads the ctxDbTuning() slice —
1622
+ // the user-facing ctx and all three admin/maintenance writers — so
1623
+ // the base class can drop its coarse invalidation backstop. Only the
1624
+ // emitter can know that; a hand-written subclass leaves this unset
1625
+ // and keeps the backstop.
1626
+ ctxDbCacheWired: true,
1627
+ ...(config.maxRelationKeys === undefined ? {} : { maxRelationKeys: config.maxRelationKeys }),
1628
+ ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1629
+ ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1630
+ });
1631
+ ${ae?`
1632
+ const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1633
+ const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1634
+
1635
+ return source !== undefined && source.refresh !== "manual";
1636
+ });
1637
+
1638
+ if (autoSourced) {
1639
+ void this.scheduleSourcePoll();
1640
+ }
1641
+ `:""}${fn?`
1642
+ if (LUNORA_TTL_SWEEPS.length > 0) {
1643
+ void this.scheduleTtlSweep();
1644
+ }
1645
+ `:""} }
1646
+
1647
+ protected override isCacheableQuery(functionPath: string): boolean {
1648
+ // NOT \`kind === "query"\` alone. A cache hit answers without running
1649
+ // \`handleRpc\`, so the \`internal\` refusal at the top of it is skipped —
1650
+ // and an \`internalQuery\` primed by a trusted system dispatch was then
1651
+ // served to an anonymous client that the refusal would have 404'd.
1652
+ //
1653
+ // \`perDispatch\` is the same argument one layer out: the procedure's
1654
+ // own \`.use()\` chain runs INSIDE \`handleRpc\`, so a hit skips it too.
1655
+ // A \`.use(rateLimit(...))\` query was therefore charged once and then
1656
+ // served from the memo to every later request — each of which still
1657
+ // reached this Durable Object and still cost it a dispatch, so only
1658
+ // the accounting was skipped. Metering and memoizing are mutually
1659
+ // exclusive; the author asking for the first is choosing against the
1660
+ // second.
1661
+ const registered = LUNORA_FUNCTIONS[functionPath];
1662
+
1663
+ return registered?.kind === "query" && registered.visibility !== "internal" && registered.perDispatch !== true;
1664
+ }
1665
+
1666
+ protected override isPaidFunction(functionPath: string): boolean {
1667
+ return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1668
+ }
1669
+ `,yn=Qe?`
1670
+ const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1671
+ ${k.tables.map(m=>` facade[${JSON.stringify(m.name)}] = bindTableFacade(db, ${JSON.stringify(m.name)});`).join(`
1672
+ `)}
1673
+ `:"",wn=`${ue.build}${G.build}${_.build}${z.build}${he.build}
1674
+ const secrets = createSecrets(env);
1675
+ `,kn=`${ue.contextField}${G.contextField}${_.contextField}${te.contextField}${z.contextField}${he.contextField}
1676
+ secrets,`,xn=te.build,ct=y||g||d||x||R||$,vn=ct?`
1677
+ // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1678
+ // and attached only for an \`action\` so query/mutation ctx never carry them.
1679
+ if (isAction) {
1680
+ ${j.build}${W.build}${U.build}${B.build}${ne.build}${p}${[...y?[" ctx.images = images;"]:[],...g?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...x?[" ctx.r2sql = r2sql;"]:[],...R?[" ctx.pipelines = pipelines;"]:[],...$?[" ctx.x402 = x402;"]:[]].join(`
1681
+ `)}
1682
+ }
1683
+ `:"",Sn=ct?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1684
+ `:"";return`${S}${ke.join(`
1685
+ `)}
1686
+
1687
+ type FunctionKind = "action" | "mutation" | "query";
1688
+
1689
+ interface FunctionReference {
1690
+ __lunoraRef: string;
1691
+ }
1692
+
1693
+ /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1694
+ const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(Ft,void 0,4)};
1695
+
1696
+ /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1697
+ const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(Bt,void 0,4)};
1698
+
1699
+ /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1700
+ const LUNORA_TABLE_COLUMNS: Record<
1701
+ string,
1702
+ Array<{
1703
+ bucket?: string;
1704
+ enumValues?: string[];
1705
+ isStorage?: boolean;
1706
+ name: string;
1707
+ nullable?: boolean;
1708
+ onDelete?: "cascade" | "restrict" | "set null";
1709
+ optional: boolean;
1710
+ pk?: boolean;
1711
+ ref?: string;
1712
+ type: string;
1713
+ }>
1714
+ > = ${JSON.stringify(qt,void 0,4)};
1715
+
1716
+ /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1717
+ const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(jt,void 0,4)};
1718
+
1719
+ /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1720
+ const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(at,void 0,4)};
1721
+
1722
+ /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1723
+ const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(Ot,void 0,4)};
1724
+
1725
+ /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1726
+ const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(It,void 0,4)};
1727
+
1728
+ /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1729
+ const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(et,void 0,4)};
1730
+ ${lt}
1731
+ /** 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. */
1732
+ const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(Ct,void 0,4)};
1733
+
1734
+ /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1735
+ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Dt,void 0,4)};
1736
+
1737
+ /** 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. */
1738
+ const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(Lt,void 0,4)};
1739
+ ${F}${J.constant}${Et}${Pt}${me}${Me}${pe}${Be}
1740
+ export interface ShardDOConfig {
1741
+ /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1742
+ cdc?: boolean;
1743
+ /** Ceiling on the join keys one relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
1744
+ maxRelationKeys?: number;
1745
+ /** 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. */
1746
+ reactiveCache?: boolean | { maxBytes?: number; maxEntries?: number };
1747
+ /** 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. */
1748
+ relationExistsPushDown?: "always" | "auto" | "never";
1749
+ /** 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. */
1750
+ observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1751
+ /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1752
+ scheduler?: (env: Record<string, unknown>) => unknown;
1753
+ storage?: (env: Record<string, unknown>) => unknown;${Ht}${Oe}${G.configField}${_.configField}${z.configField}${j.configField}${W.configField}${U.configField}${B.configField}${ne.configField}${je}${We}${Vt}${Gt}${Jt}
1754
+ }
1755
+ ${I("schedulerStub",Xt,["cancel","runAfter","runAt"])}${I("storageStub",Zt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${en}${pn}${tn}${Ce}${G.stub}${_.stub}${z.stub}${j.stub}${W.stub}${U.stub}${B.stub}${ne.stub}${Ze}${re}
1756
+ // Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
1757
+ // referencing call fails loudly with a clear error instead of overflowing the
1758
+ // stack. Tracked across the awaited handler chain (one DO invocation is
1759
+ // single-threaded), so the counter reflects true nesting depth.
1760
+ const MAX_RUN_DEPTH = 32;
1761
+ let runDepth = 0;
1762
+
1763
+ const dispatchRun = async (
1764
+ expected: FunctionKind,
1765
+ functionPath: string,
1766
+ args: Record<string, unknown>,
1767
+ ctx: unknown,
1768
+ // The kind of the context making the call, and — for a mutation target — the
1769
+ // transaction wrapper to run it under. Both are supplied by \`buildCtx\`, which
1770
+ // is the only place that knows which dispatch this \`ctx\` belongs to. Widened
1771
+ // past \`FunctionKind\` because the registry also carries \`"stream"\`, and
1772
+ // \`undefined\` for a ctx built outside a registered function (admin, migration).
1773
+ callerKind?: "stream" | FunctionKind,
1774
+ runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
1775
+ ): Promise<unknown> => {
1776
+ // A query is read-only. The ctx object installs \`run*\` on every kind (one
1777
+ // shape, built once), so the TYPE is all that stops a query from writing —
1778
+ // and a cast walks straight past it, inside a subscription re-run that can
1779
+ // execute many times per write. Checked on the CALLER, before the registry
1780
+ // lookup, so \`ctx.runMutation\` from a query fails identically whatever it
1781
+ // aimed at.
1782
+ if (callerKind === "query" && expected !== "query") {
1783
+ throw new LunoraError(
1784
+ "RUN_KIND_FORBIDDEN",
1785
+ \`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: a query may only compose other queries (tried to run "\${functionPath}")\`,
1786
+ );
1787
+ }
1788
+
1789
+ const registered = LUNORA_FUNCTIONS[functionPath];
1790
+
1791
+ if (!registered) {
1792
+ throw new Error(\`unknown function: \${functionPath}\`);
1793
+ }
1794
+
1795
+ if (registered.kind !== expected) {
1796
+ throw new Error(\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: "\${functionPath}" is registered as a \${registered.kind}, not a \${expected}\`);
1797
+ }
1798
+
1799
+ if (runDepth >= MAX_RUN_DEPTH) {
1800
+ throw new LunoraError("RUN_DEPTH_EXCEEDED", \`ctx.run*: composition depth limit (\${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation\`);
1801
+ }
1802
+
1803
+ runDepth += 1;
1804
+
1805
+ try {
1806
+ // A mutation composed from an action (or an http action) is the shape the
1807
+ // docs prescribe for atomicity — "do the transactional reads and writes in
1808
+ // a mutation and call it from the action". It only holds if the composed
1809
+ // dispatch gets the same BEGIN/COMMIT span and single-writer gate the
1810
+ // top-level mutation path gets; without it every write autocommits and a
1811
+ // mid-handler throw leaves the earlier ones durable. A \`runMutation\` from
1812
+ // inside a mutation rides the enclosing span instead of opening a second
1813
+ // one (see \`runMutationTransaction\`).
1814
+ if (runTransactional) {
1815
+ return await runTransactional(async () => registered.handler(ctx, args));
1816
+ }
1817
+
1818
+ return await registered.handler(ctx, args);
1819
+ } finally {
1820
+ runDepth -= 1;
1821
+ }
1822
+ };
1823
+
1824
+ /**
1825
+ * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1826
+ * from the worker entry so wrangler binds it by name.
1827
+ */
1828
+ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1829
+ class extends ShardDOBase {${bn}
1830
+ private migrated = false;
1831
+
1832
+ public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
1833
+ const registered = LUNORA_FUNCTIONS[functionPath];
1834
+
1835
+ // Internal functions are reachable server-side only: via \`ctx.run*\`
1836
+ // composition, or a trusted system dispatch (scheduler/cron, marked by
1837
+ // \`isSystemDispatch()\`). A client RPC never carries that flag, so its
1838
+ // internals stay not-found and never leak across the external boundary.
1839
+ if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) {
1840
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
1841
+ }
1842
+
1843
+ this.ensureMigrated();
1844
+
1845
+ // \`headroom\`, when the caller supplied one, is threaded straight
1846
+ // through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
1847
+ // fallback (the racy shared-field read) entirely for THIS dispatch.
1848
+ // The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
1849
+ // \`handleRunAs\` don't mint their own and omit it, so they keep the
1850
+ // prior fallback behavior unchanged.
1851
+ //
1852
+ // \`scope\` is the reactive cache's per-dispatch read capture, threaded
1853
+ // the same way and for the same reason: the ctx-db read hooks resolve
1854
+ // their tracker at READ time, so binding them to the scope THIS
1855
+ // dispatch was handed is what keeps a concurrent query's reads out of
1856
+ // our dep set — and ours out of theirs. A dispatch with no scope (a
1857
+ // mutation, an action, a cache-less shard) builds unbound hooks that
1858
+ // stamp no deps.
1859
+ const ctx = this.buildCtx({ bookmarks, functionPath, headroom, scope, trusted: registered.lifecycle === "init" });
1860
+
1861
+ // A mutation's writes must commit all-or-nothing, so its dispatch runs
1862
+ // under \`runMutationTransaction\` — the ONE place that opens the span,
1863
+ // settles the deferred schedules and flushes the deferred deletes. The
1864
+ // same helper backs \`ctx.runMutation\` and \`runReactor\`, because a
1865
+ // mutation reached by composition is promised exactly these guarantees
1866
+ // and used to get none of them.
1867
+ //
1868
+ // The replay bookkeeping (idempotency dedup row + custom-mutator
1869
+ // watermark advance) commits INSIDE the span via
1870
+ // \`commitMutationBookkeeping\`, so the writes, the dedup row, and the
1871
+ // watermark are atomic — a crash can't leave the writes durable without
1872
+ // the replay guard. It is deliberately NOT in the shared helper: it is
1873
+ // per-REQUEST bookkeeping, and a composed sub-mutation has no request of
1874
+ // its own to record.
1875
+ if (registered.kind === "mutation") {
1876
+ return await this.runMutationTransaction(ctx, async () => {
1877
+ const value = await registered.handler(ctx, args);
1878
+
1879
+ this.commitMutationBookkeeping(value);
1880
+
1881
+ return value;
1882
+ });
1883
+ }
1884
+
1885
+ const result = await registered.handler(ctx, args);
1886
+
1887
+ // An action is not itself transactional, but \`ctx.runMutation\` runs its
1888
+ // submutations on THIS ctx, so anything they queued after their own
1889
+ // transaction settled lands here. A dispatch with nothing queued no-ops.
1890
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
1891
+
1892
+ return result;
1893
+ }
1894
+
1895
+ /**
1896
+ * Run one mutation handler with the atomicity every caller of a mutation is
1897
+ * promised: a BEGIN/COMMIT span (with the single-writer gate
1898
+ * \`ShardRunner.runInTransaction\` composes in front of it), scheduled jobs
1899
+ * held until that span commits, and the deferred object deletes flushed
1900
+ * only once it has.
1901
+ *
1902
+ * Shared by the three entry points that dispatch a mutation handler — the
1903
+ * top-level RPC, \`ctx.runMutation\` from an action or http action, and a
1904
+ * reactor — because the guarantee is a property of the mutation, not of how
1905
+ * it was reached. The docs tell users to put the transactional part in a
1906
+ * mutation and call it from the action precisely so that composition is
1907
+ * atomic.
1908
+ *
1909
+ * A \`ctx.runMutation\` issued from inside a mutation is NESTED: SQLite-in-DO
1910
+ * has no savepoints and \`runInTransaction\` rejects a second open, so it
1911
+ * rides the enclosing span, which also owns its commit and therefore its
1912
+ * scheduler flush.
1913
+ *
1914
+ * Both deferral windows are opened here and settled against the SAME
1915
+ * outcome. The delete window is what keeps a composed mutation's queued
1916
+ * object deletes off the caller's flush when it rolls back: \`ctx\` is
1917
+ * shared, so without a window the keys are indistinguishable from the
1918
+ * action's own and the action's flush destroys objects whose rows the
1919
+ * rollback put back.
1920
+ */
1921
+ private async runMutationTransaction<T>(ctx: unknown, work: () => Promise<T>): Promise<T> {
1922
+ const settleSchedules = beginDeferredSchedules(ctx as { scheduler?: unknown });
1923
+ // Synchronous and non-throwing (it only moves queue entries), so it can
1924
+ // settle first on every path and cannot mask the outcome.
1925
+ const settleDeletes = beginDeferredDeletes(ctx);
1926
+
1927
+ if (this.isInTransaction()) {
1928
+ try {
1929
+ const nested = await work();
1930
+
1931
+ settleDeletes(true);
1932
+ await settleSchedules(true);
1933
+
1934
+ return nested;
1935
+ } catch (error) {
1936
+ settleDeletes(false);
1937
+ await settleSchedules(false);
1938
+
1939
+ throw error;
1940
+ }
1941
+ }
1942
+
1943
+ let result: T;
1944
+
1945
+ try {
1946
+ result = await this.runInTransaction(work);
1947
+ } catch (error) {
1948
+ // The span rolled back, so the rows are gone and the jobs that were
1949
+ // to run "after I commit" must go with them. Dropping them is the
1950
+ // whole point of buffering: a persisted job for a write that never
1951
+ // landed fires against state that does not exist.
1952
+ //
1953
+ // The queued object deletes go the same way, and for a sharper
1954
+ // reason: the rows they were to clean up after are still there, and
1955
+ // an R2 delete cannot be undone.
1956
+ settleDeletes(false);
1957
+ await settleSchedules(false);
1958
+
1959
+ throw error;
1960
+ }
1961
+
1962
+ // Committed, so this span's queued keys join whatever the flush below
1963
+ // (or an enclosing span's) will drain.
1964
+ settleDeletes(true);
1965
+
1966
+ // Committed. Schedules first and AWAITED: \`runAfter(0, ...)\` is
1967
+ // documented as the deterministic equivalent of an \`afterCommit\` hook,
1968
+ // so the job must be enqueued after the commit, and a failure to enqueue
1969
+ // it must be visible rather than swallowed.
1970
+ //
1971
+ // In a \`finally\`, because both halves of this are post-commit cleanup
1972
+ // and neither is allowed to cancel the other. \`settleSchedules\` drains
1973
+ // its whole queue and then rethrows what failed, so a SchedulerDO that
1974
+ // refused one job used to take the object cleanup down with it — the
1975
+ // rows were durably gone and their objects leaked with nothing logged.
1976
+ try {
1977
+ await settleSchedules(true);
1978
+ } finally {
1979
+ // Then the objects whose rows are now durably gone. Deliberately AFTER
1980
+ // the span, never inside it: an R2 delete cannot roll back, so a delete
1981
+ // issued from within a transaction that later aborts destroys data the
1982
+ // surviving row still points at.
1983
+ //
1984
+ // \`flushDeferredDeletes\` never rejects — the mutation has already
1985
+ // succeeded, so a failed cleanup must not turn into a failed response.
1986
+ // A leaked object is reported through \`ctx.log\` instead, with its key.
1987
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
1988
+ }
1989
+
1990
+ return result;
1991
+ }
1992
+
1993
+ // Only a \`mutation\` may enter the base class's single-writer gate for
1994
+ // mutation-replay dedup — it is \`blockConcurrencyWhile\`, so gating an
1995
+ // action would stall every other dispatch on the shard for the length of
1996
+ // its outbound I/O, on nothing but a caller-supplied header. Unregistered
1997
+ // paths answer \`false\`; \`handleRpc\` above rejects them anyway.
1998
+ protected override isMutationFunction(functionPath: string): boolean {
1999
+ return LUNORA_FUNCTIONS[functionPath]?.kind === "mutation";
2000
+ }
2001
+
2002
+ // The scheduler the deferred-schedule outbox retries through. Only the
2003
+ // CONFIGURED one: falling back to \`schedulerStub\` would have an app with no
2004
+ // scheduler retry every entry against a thrower until the attempt ceiling
2005
+ // parked it, and there is nothing to park — an app with no scheduler has no
2006
+ // \`ctx.scheduler\` call that reached the buffer in the first place.
2007
+ protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
2008
+ return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
2009
+ }
2010
+ ${st.override}
2011
+ protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
2012
+ const registered = LUNORA_FUNCTIONS[functionPath];
2013
+
2014
+ if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
2015
+ return null;
2016
+ }
2017
+
2018
+ this.ensureMigrated();
2019
+
2020
+ const footprint = createReadFootprint();
2021
+ // Identity is threaded EXPLICITLY from the (deferred/interleaved)
2022
+ // subscription caller — never read from the shared per-request field
2023
+ // here — so a concurrent RPC can't leak its identity into this re-run.
2024
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange });
2025
+ const result = await registered.handler(ctx, args);
2026
+
2027
+ // Ranges come from THIS run's reads, never a shared field on the DO:
2028
+ // a deferred re-run interleaves with unrelated dispatches.
2029
+ return { ranges: footprint.ranges(), result, tables: footprint.tables };
2030
+ }
2031
+
2032
+ protected override executeStream(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
2033
+ const registered = LUNORA_FUNCTIONS[functionPath];
2034
+
2035
+ if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
2036
+ return null;
2037
+ }
2038
+
2039
+ this.ensureMigrated();
2040
+
2041
+ return {
2042
+ ...(registered.durable ? { durable: registered.durable as { ttlMs?: number } } : {}),
2043
+ // Identity threaded EXPLICITLY from the socket, exactly as
2044
+ // \`executeSubscription\` above: the iterator is pulled after this
2045
+ // frame returned, interleaved with unrelated dispatches, so
2046
+ // \`buildCtx\`'s per-request fallback would run an \`rls()\` /
2047
+ // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
2048
+ iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
2049
+ };
2050
+ }
2051
+ ${Ut}${Wt}${hn}${gn}
2052
+ protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
2053
+ return LUNORA_LIFECYCLE_HOOKS[event];
2054
+ }
2055
+ ${mn}
2056
+ // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
2057
+ // socket-terminated half of the same reactivity — and differs only in who
2058
+ // consumes the result: the base's \`dispatchReactors\` stores the digest as
2059
+ // the new baseline and the footprint as the "should I even re-run this"
2060
+ // gate, instead of pushing a frame down a socket.
2061
+ //
2062
+ // Dispatched through \`runMutationTransaction\` because a reactor handler is
2063
+ // a mutation: its writes must commit all-or-nothing, the jobs it schedules
2064
+ // must wait for that commit, and the objects its row deletes orphaned must
2065
+ // be flushed once it lands. Safe to open a span here: the refresh drain
2066
+ // runs OUTSIDE any dispatch transaction (it is post-flush background work),
2067
+ // so this never nests.
2068
+ //
2069
+ // NO identity is threaded, and the ctx is built \`trusted\`. A reactor fires
2070
+ // because data moved, not because anyone asked, so there is no user for RLS
2071
+ // to scope to — it runs in the same system tier as migrations and the
2072
+ // external-source poll loop. Inheriting the shared per-request identity
2073
+ // would instead run an app's reactor as whichever user happened to write
2074
+ // last, which is worse than running it as nobody.
2075
+ protected override async runReactor(functionPath: string, previousDigest?: string): Promise<{ digest: string; ran: boolean; tables: readonly string[] } | undefined> {
2076
+ const registered = LUNORA_FUNCTIONS[functionPath];
2077
+
2078
+ if (!registered || registered.kind !== "mutation") {
2079
+ return undefined;
2080
+ }
2081
+
2082
+ this.ensureMigrated();
2083
+
2084
+ const footprint = createReadFootprint();
2085
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), onRead: footprint.onRead, onReadRange: footprint.onReadRange, trusted: true });
2086
+ const outcome = (await this.runMutationTransaction(ctx, async () =>
2087
+ registered.handler(ctx, { previousDigest } as unknown as Record<string, unknown>),
2088
+ )) as {
2089
+ digest: string;
2090
+ ran: boolean;
2091
+ };
2092
+
2093
+ return { digest: outcome.digest, ran: outcome.ran, tables: [...footprint.tables] };
2094
+ }
2095
+
2096
+
2097
+ protected override tableRefs(table: string): Record<string, string> | undefined {
2098
+ return LUNORA_TABLE_REFS[table];
2099
+ }
2100
+
2101
+ protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> {
2102
+ return LUNORA_TABLE_INDEXES[table] ?? [];
2103
+ }
2104
+
2105
+ protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> {
2106
+ return LUNORA_TTL_SWEEPS;
2107
+ }
2108
+
2109
+ protected override tableColumns(table: string): Array<{
2110
+ bucket?: string;
2111
+ enumValues?: string[];
2112
+ isStorage?: boolean;
2113
+ name: string;
2114
+ nullable?: boolean;
2115
+ onDelete?: "cascade" | "restrict" | "set null";
2116
+ optional: boolean;
2117
+ pk?: boolean;
2118
+ ref?: string;
2119
+ type: string;
2120
+ }> {
2121
+ return LUNORA_TABLE_COLUMNS[table] ?? [];
2122
+ }
2123
+
2124
+ protected override storageColumns(): Record<string, string[]> {
2125
+ return LUNORA_STORAGE_COLUMNS;
2126
+ }
2127
+
2128
+ protected override rlsMetadata(): RlsPoliciesResult {
2129
+ return LUNORA_RLS_METADATA;
2130
+ }
2131
+
2132
+ protected override maskMetadata(): MaskPoliciesResult {
2133
+ return LUNORA_MASK_METADATA;
2134
+ }
2135
+
2136
+ protected override storageRulesMetadata(): StorageRulesResult {
2137
+ return LUNORA_STORAGE_RULES;
2138
+ }
2139
+
2140
+ protected override studioFeatures(): StudioFeaturesResult {
2141
+ return LUNORA_STUDIO_FEATURES;
2142
+ }
2143
+ ${J.evaluateOverride}${J.subscriptionOverride}${_t}${Mt}
2144
+ protected override advisories(): AdvisoryFinding[] {
2145
+ return LUNORA_ADVISORIES;
2146
+ }
2147
+
2148
+ protected override advisorProcedures(): AdvisorProcedure[] {
2149
+ return LUNORA_ADVISOR_PROCEDURES;
2150
+ }
2151
+
2152
+ ${ln}
2153
+
2154
+ protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
2155
+ this.ensureMigrated();
2156
+
2157
+ // Falls back to the framework's reserved re-projection backfill
2158
+ // (\`__lunora_reproject__<table>\`), which rewrites rows whose
2159
+ // v.bigint()/v.bytes() columns are still stored in the pre-projection
2160
+ // tagged form. Built here rather than at module scope because it
2161
+ // needs this shard's \`sql\` handle to tell a legacy row from a
2162
+ // current one.
2163
+ const migration = LUNORA_MIGRATIONS[args.id] ?? buildReprojectionMigration(args.id, schema as unknown as SchemaLike, this.sql as SqlExec);
2164
+
2165
+ if (!migration) {
2166
+ throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
2167
+ }
2168
+
2169
+ ${Q()}
2170
+
2171
+ return runDataMigration({
2172
+ batchSize: args.batchSize,
2173
+ direction: args.direction,
2174
+ dryRun: args.dryRun,
2175
+ maxBatches: args.maxBatches,
2176
+ migration: migration as unknown as DataMigrationLike,
2177
+ // Flush after each batch so live migrationStatus subscribers see
2178
+ // progress mid-run (the base method records the reserved state
2179
+ // table the raw-SQL progress write is invisible to the tracker).
2180
+ onBatch: () => this.flushMigrationProgress(),
2181
+ sql: this.sql as SqlExec,
2182
+ writer,
2183
+ });
2184
+ }
2185
+
2186
+ protected override async runShardWrite(args: RunShardWriteArgs, headroom?: TransactionHeadroomTracker): Promise<RunShardWriteResult> {
2187
+ const definition = (schema as unknown as SchemaLike).tables[args.table];
2188
+
2189
+ if (!definition) {
2190
+ throw new LunoraError("UNKNOWN_TABLE", \`unknown table: \${args.table}\`, { status: 404 });
2191
+ }
2192
+
2193
+ // \`.global()\` tables live in D1, not this DO's SQLite — editing them
2194
+ // here would corrupt nothing but would fail confusingly, so reject up
2195
+ // front with a clear code the studio can surface.
2196
+ if (definition.shardMode?.kind === "global") {
2197
+ throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", \`table "\${args.table}" is global; edit it through D1, not the shard\`, { status: 400 });
2198
+ }
2199
+
2200
+ this.ensureMigrated();
2201
+
2202
+ ${Q("headroom ?? this.transactionHeadroom()")}
2203
+
2204
+ if (args.op === "insert") {
2205
+ const id = await writer.insert(args.table, args.doc ?? {});
2206
+
2207
+ return { id, op: "insert" };
2208
+ }
2209
+
2210
+ // Every by-id op PINS \`args.table\`. Unpinned, \`locateRowById\` probes
2211
+ // every non-global table for the id, so a request naming table A with an
2212
+ // id belonging to table B locates and mutates B's row — the by-id IDOR
2213
+ // the per-table \`ctx.db.<table>\` facade pins against. Pinning also stops
2214
+ // an absent row falling through to the \`.global()\` D1 twin, though that
2215
+ // branch is already unreachable here: \`adminWriter\` is built without a
2216
+ // \`globalDb\`, so a miss throws \`NOT_FOUND\` either way.
2217
+ // \`hard\` is set only by the BULK delete arm, which needs the row gone
2218
+ // from the physical table for its next batch's scan to make progress.
2219
+ // A single-row \`writeRow\` delete never carries it, so it keeps the
2220
+ // table's declared \`.softDelete()\` behaviour.
2221
+ if (args.op === "delete") {
2222
+ await writer.delete(args.id ?? "", args.table, { hard: args.hard === true });
2223
+
2224
+ return { id: args.id ?? null, op: "delete" };
2225
+ }
2226
+
2227
+ if (args.op === "replace") {
2228
+ await writer.replace(args.id ?? "", args.doc ?? {}, args.table);
2229
+
2230
+ return { id: args.id ?? null, op: "replace" };
2231
+ }
2232
+
2233
+ await writer.patch(args.id ?? "", args.doc ?? {}, args.table);
2234
+
2235
+ return { id: args.id ?? null, op: "patch" };
2236
+ }
2237
+
2238
+ // The base \`ShardDO\` cannot build a schema-aware writer, so its
2239
+ // \`runShardExport\`/\`runShardImport\` return \`[]\` and \`{inserted:{}}\`.
2240
+ // Those are success-shaped: an empty export is what a correct export of
2241
+ // an empty shard looks like, so a backup of a populated sharded schema
2242
+ // reported success and wrote nothing, and an import reported success and
2243
+ // dropped every row. Overriding both here is what makes the two admin
2244
+ // RPCs real for a \`.shardBy()\` table.
2245
+ //
2246
+ // NOTE: the admin export RPC is not paginated — \`parseExportShardArgs\`
2247
+ // takes \`tables\`/\`batchSize\` but no cursor, and the coordinator issues
2248
+ // one call per shard — so the rows are collected into a single response.
2249
+ // \`batchSize\` bounds the SQLite scan page, not the reply. A shard holding
2250
+ // more rows than fit in the DO's memory budget will therefore fail the
2251
+ // export rather than stream it. That is a loud failure where the bug this
2252
+ // replaces was a silent empty one, but a cursor on the RPC is what makes
2253
+ // this a complete backup path for large shards.
2254
+ protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
2255
+ this.ensureMigrated();
2256
+
2257
+ ${Q()}
2258
+
2259
+ const rows: ExportRow[] = [];
2260
+
2261
+ // \`exportShardRows\` walks in keyset batches so a large table does not
2262
+ // materialize at once inside the generator; the admin RPC's response
2263
+ // is a single array, so it is collected here rather than streamed.
2264
+ for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, { batchSize: args.batchSize, tables: args.tables })) {
2265
+ rows.push(row);
2266
+ }
2267
+
2268
+ return rows;
2269
+ }
2270
+
2271
+ protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
2272
+ this.ensureMigrated();
2273
+
2274
+ ${Q()}
2275
+
2276
+ // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
2277
+ // database's \`_id\`s carry across verbatim and every foreign key
2278
+ // referencing them stays valid without a second remapping pass.
2279
+ return importShardRows(writer, schema as unknown as SchemaLike, { rows: args.rows, startLine: args.startLine });
2280
+ }
2281
+
2282
+ protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
2283
+ this.ensureMigrated();
2284
+
2285
+ ${Q()}
2286
+
2287
+ // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2288
+ // but the shard writer from \`createShardCtxDb\` always defines it.
2289
+ if (!writer.rankBefore) {
2290
+ throw new LunoraError("NOT_IMPLEMENTED", "rankBefore is unavailable on the shard writer", { status: 500 });
2291
+ }
2292
+
2293
+ return writer.rankBefore(args.table, args.index, {
2294
+ partitionKey: args.partitionKey,
2295
+ rowId: args.rowId,
2296
+ sortValues: args.sortValues,
2297
+ });
2298
+ }
2299
+
2300
+ protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
2301
+ this.ensureMigrated();
2302
+
2303
+ ${Q()}
2304
+
2305
+ // \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2306
+ // but the shard writer from \`createShardCtxDb\` always defines it — it
2307
+ // derives the edge set from this app's schema.
2308
+ if (!writer.related) {
2309
+ throw new LunoraError("NOT_IMPLEMENTED", "findRelated is unavailable on the shard writer", { status: 500 });
2310
+ }
2311
+
2312
+ return writer.related(
2313
+ { id: args.id, table: args.table },
2314
+ { cursor: args.cursor, depth: args.depth, direction: args.direction, edges: args.edges, limit: args.limit },
2315
+ );
2316
+ }
2317
+
2318
+ protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
2319
+ this.ensureMigrated();
2320
+
2321
+ ${Q()}
2322
+
2323
+ // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2324
+ // but the shard writer from \`createShardCtxDb\` always defines it. The sort
2325
+ // directions live in the schema's rankIndex, so the shard reads them itself;
2326
+ // \`args.directions\` is only the coordinator's comparator hint and isn't forwarded.
2327
+ if (!writer.rankPageRows) {
2328
+ throw new LunoraError("NOT_IMPLEMENTED", "rankPage is unavailable on the shard writer", { status: 500 });
2329
+ }
2330
+
2331
+ return writer.rankPageRows(args.table, args.index, {
2332
+ after: args.after,
2333
+ cursor: args.cursor,
2334
+ partitionKey: args.partitionKey,
2335
+ take: args.take,
2336
+ });
2337
+ }
2338
+
2339
+ protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
2340
+ this.ensureMigrated();
2341
+
2342
+ ${Q()}
2343
+
2344
+ await applyCdcChanges(writer, args.changes);
2345
+
2346
+ return { applied: args.changes.length };
2347
+ }
2348
+
2349
+ protected override ensureMigrated(): void {
2350
+ if (this.migrated) {
2351
+ return;
2352
+ }
2353
+
2354
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ce} });
2355
+ this.migrated = true;
2356
+ }
2357
+ ${Ke?`
2358
+ protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
2359
+ // Migrations create the fts5 companions; without them every backfill
2360
+ // statement would raise "no such table" on a shard that has never
2361
+ // served a request.
2362
+ this.ensureMigrated();
2363
+
2364
+ return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
2365
+ }
2366
+ `:""}
2367
+ private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
2368
+ const env = (this.env ?? {}) as Record<string, unknown>;
2369
+ // The caller context this ctx runs under, resolved ONCE on one
2370
+ // discriminant. When the caller threads an explicit identity
2371
+ // (subscription seed / refresh / stream pull / shape resolve — all
2372
+ // deferred or interleaved), it is used by value and the shared
2373
+ // per-request fields are never read, because a concurrent RPC owns
2374
+ // them: a refresh in particular runs inside the writing dispatch's
2375
+ // \`flushChangedTables\`, BEFORE its \`endDispatch\`, so \`getCurrentIp()\`
2376
+ // there is the MUTATING caller's address. Otherwise (the synchronous
2377
+ // RPC dispatch path) it falls back to those fields as before.
2378
+ //
2379
+ // One expression, not one per field: three parallel ternaries on the
2380
+ // same discriminant is how \`ip\` came to be the only one still reading
2381
+ // the shared field.
2382
+ const caller: SubscriptionIdentity = options.identity ?? {
2383
+ identity: this.getCurrentIdentity(),
2384
+ ip: this.getCurrentIp(),
2385
+ userId: this.getCurrentUserId(),
2386
+ };
2387
+ const { identity, ip, userId } = caller;
2388
+ ${on}${de}${wn}${Le}${_e}${De}${Fe}
2389
+ // Which dispatch this ctx belongs to. Drives the two deferral facades
2390
+ // below and the \`ctx.run*\` caller guard; a ctx built for an
2391
+ // admin/lifecycle path has no registered function, and so no kind.
2392
+ const contextKind = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind;
2393
+ // \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
2394
+ // reaches through, and pending jobs live in the SchedulerDO — nothing the
2395
+ // CDC changelog records — so reading them must forfeit a delta resume.
2396
+ // The scheduler's own \`runAfter\`/\`runAt\`/\`cancel\` are writes and stay unstamped.
2397
+ const schedulerBase = markUnvouchableReads((config.scheduler?.(env) ?? schedulerStub) as SchedulerLike, options.onRead, ["get", "list"]);
2398
+ // \`ctx.scheduler.runAfter(0, ...)\` is documented as the deterministic
2399
+ // equivalent of an \`afterCommit\` hook, and the SchedulerDO persists the
2400
+ // job the moment it is called — so inside a mutation the call is BUFFERED
2401
+ // and replayed after the transaction commits (a rollback drops it).
2402
+ // Wrapped on the same dispatches as the deferred-delete queue and for the
2403
+ // same reason: \`ctx.runMutation\` hands the CALLER's ctx to the callee, so
2404
+ // a mutation reached from an action schedules through the action's ctx.
2405
+ // An action's own schedules stay immediate — the window is only open
2406
+ // while a transaction is (see \`runMutationTransaction\`).
2407
+ //
2408
+ // Every kind but \`query\` is wrapped, because \`runMutationTransaction\`
2409
+ // is installed on \`ctx.runMutation\` for every kind but \`query\`: a
2410
+ // STREAM ctx, and an admin/lifecycle ctx with no registered kind at all,
2411
+ // both get the BEGIN/COMMIT span for a mutation they compose, and used
2412
+ // to get it with the deferral missing — so that mutation's job reached
2413
+ // the SchedulerDO while its transaction was still open, and survived the
2414
+ // rollback. A query cannot host a mutation handler (\`dispatchRun\`
2415
+ // refuses it) and its ctx is built on the hot subscription path, so it
2416
+ // stays unwrapped.
2417
+ //
2418
+ // Wrapped OUTSIDE the read-stamping facade so \`get\`/\`list\` stay stamped.
2419
+ //
2420
+ // \`this.scheduleOutbox()\` is what keeps the buffer honest. Everything
2421
+ // between the COMMIT and the scheduler's acknowledgement is outside the
2422
+ // transaction, so a failure there leaves writes that are durable and a
2423
+ // job that exists nowhere — and the mutation's replay-dedup row committed
2424
+ // inside the span, so the client's retry is answered from cache and told
2425
+ // it succeeded. The outbox takes custody of each buffered call inside the
2426
+ // transaction and releases it once the scheduler has the job; what
2427
+ // survives is retried by \`pollScheduleOutbox\` on the shared poll alarm.
2428
+ const scheduler = contextKind === "query" ? schedulerBase : withDeferredSchedules(schedulerBase, this.scheduleOutbox());
2429
+ // Build the storage adapter once and share it between \`ctx.storage\`
2430
+ // and \`ctx.db.system._storage\` so both read the same R2 binding. The
2431
+ // \`storageStub\` fallback satisfies SystemReaderStorageLike structurally
2432
+ // (its \`list\`/\`getMetadata\` throw the "no storage configured" error).
2433
+ //
2434
+ // Wrapped BEFORE the split so both consumers share one stamping facade.
2435
+ // Only the methods that actually reach R2 are stamped: \`getUrl\` and
2436
+ // \`getSignedUrl\` build a URL from the configured base (and an HMAC) and
2437
+ // read nothing, and they are what handlers overwhelmingly call — stamping
2438
+ // them would forfeit resumes for a dependency that cannot move the result.
2439
+ // \`bucket\` IS stamped: it hands back a sub-facade this wrapper does not
2440
+ // reach, so the selection is the last point at which the read can be seen.
2441
+ const storage = markUnvouchableReads(asBucketStorage(config.storage?.(env) ?? storageStub) as SystemReaderStorageLike, options.onRead, [
2442
+ "bucket",
2443
+ "download",
2444
+ "getMetadata",
2445
+ "list",
2446
+ ]);
2447
+ // \`ctx.storage.deleteAfterCommit(key)\`, on every dispatch that can host
2448
+ // a MUTATION handler — which is not only a mutation dispatch:
2449
+ // \`ctx.runMutation\` hands the CALLER's ctx to the callee, so a mutation
2450
+ // reached from an action runs on the action's ctx. Wrapping mutations
2451
+ // alone made that composition throw a bare TypeError on a method the
2452
+ // handler's own type promises. Queries stay unwrapped: they cannot host
2453
+ // one, and their ctx is built on the hot subscription path.
2454
+ //
2455
+ // Every dispatch wrapped here also flushes (see \`handleRpc\` and
2456
+ // \`runReactor\`) — a queue nothing drains leaks silently, which is worse
2457
+ // than not having the method at all.
2458
+ //
2459
+ // Wrapped OUTSIDE the read-stamping facade so \`bucket(name)\` still
2460
+ // resolves through it and stays stamped, and applied only to
2461
+ // \`ctx.storage\` so \`ctx.db.system._storage\` (which shares the adapter
2462
+ // above) is untouched.
2463
+ const contextStorage = contextKind === "mutation" || contextKind === "action" ? withDeferredDeletes(storage) : storage;
2464
+ // \`ctx.log\`: the DO base builds the attributed logger (structured
2465
+ // fields + \`.with(...)\` child + trace correlation) and routes each call
2466
+ // to the optional \`observability\` sink. It also buffers the line (studio
2467
+ // Logs panel) and emits a structured console event the dev-server formats.
2468
+ //
2469
+ // Resolved BEFORE \`ctx.db\` below, because the database is wrapped in
2470
+ // auto-instrumentation that needs the sink, the trace anchor, and the
2471
+ // dispatch's wide-event handle.
2472
+ const observability = config.observability?.(env);
2473
+ const logFunctionPath = options.functionPath ?? "";
2474
+ const log = this.makeLogger(logFunctionPath, observability);
2475
+ const traceAnchor = this.resolveDispatchAnchor(Boolean(options.identity));
2476
+
2477
+ // \`ctx.span\`: the handle onto the DISPATCH's own span — the wide-event
2478
+ // surface. Attributes attached here accumulate for the whole request
2479
+ // and are folded into the one span it already emits, instead of
2480
+ // becoming N separate log lines. Shares \`traceAnchor\` with \`ctx.trace\`
2481
+ // so both write to the same trace.
2482
+ const span = this.makeDispatchSpan(traceAnchor, observability);
2483
+
2484
+ ${un} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
2485
+ // adds aggregate counters (call count, total time, per-operation
2486
+ // breakdown) to the wide event rather than a span per call, so a
2487
+ // handler making hundreds of queries stays readable. See
2488
+ // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
2489
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${sn}), logFunctionPath, traceAnchor, observability);
2490
+ ${yn}${qe}
2491
+
2492
+ // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
2493
+ // The trace anchor is threaded explicitly for the same reason \`identity\`
2494
+ // is — a deferred caller (a subscription re-run) must not inherit the
2495
+ // writing mutation's trace from the shared per-request field.
2496
+ const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
2497
+ const metrics = this.makeMetrics(logFunctionPath, observability);
2498
+ ${xn}
2499
+ // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
2500
+ // captured ONCE so the whole handler body sees a single stable value.
2501
+ // A \`query\` handler is re-run by every live subscription that reads it,
2502
+ // so \`Date.now()\` there flickers between re-evaluations. A \`mutation\`
2503
+ // handler does not replay under ordinary dispatch (an OCC conflict throws
2504
+ // to the caller rather than retrying internally), but one called from a
2505
+ // workflow step or queue consumer runs again when that step replays. Both
2506
+ // read time through \`ctx.now\` — the \`nondeterministic_query_mutation\`
2507
+ // advisor flags \`Date.now()\`. Actions may still use ambient \`Date.now()\`.
2508
+ const now = Date.now();
2509
+
2510
+ const ctx: Record<string, unknown> = {
2511
+ auth: {
2512
+ getIdentity: async () => identity ?? null,
2513
+ userId: userId ?? null,
2514
+ },
2515
+ db,
2516
+ // Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
2517
+ // \`traceparent\` propagation, so time spent in a downstream service
2518
+ // is visible and its spans join this trace. Degrades to the bare
2519
+ // global when no sink is configured.
2520
+ fetch: this.makeFetch(logFunctionPath, traceAnchor, observability),
2521
+ // A GETTER, not a plain field, so the reactive cache can tell a
2522
+ // handler that reads the caller's address from the majority that
2523
+ // never do. \`ctx.ip\` is per-request state the memo must be keyed
2524
+ // by — otherwise two anonymous callers share one entry and the
2525
+ // second is served the first's address — but keying every entry
2526
+ // by address would shard the cache per client for every query.
2527
+ // Reading it here marks the dispatch's scope; \`runCachedQuery\`
2528
+ // folds the address into the key for this function from then on.
2529
+ get ip() {
2530
+ options.scope?.markIpRead();
2531
+
2532
+ return ip;
2533
+ },
2534
+ log,
2535
+ metrics,
2536
+ now,${dn}
2537
+ scheduler,
2538
+ span,
2539
+ storage: contextStorage,
2540
+ trace,${cn}${Ie}${kn}${be}${Ee}${Pe}${ve}${ge}
2541
+ };
2542
+ ${Sn}${vn}
2543
+ ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx, contextKind);
2544
+ // The composed mutation runs under the SAME wrapper the top-level RPC
2545
+ // uses, so "do the transactional work in a mutation and call it from the
2546
+ // action" — the recipe the docs give for atomicity — actually is atomic.
2547
+ ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) =>
2548
+ dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx, contextKind, async (work) => this.runMutationTransaction(ctx, work));
2549
+ // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
2550
+ // its OWN context, built without the subscription's read-footprint
2551
+ // hooks — so its reads never enter this subscription's footprint and a
2552
+ // write to the tables it touched does not re-run us. Everything else is
2553
+ // inherited: \`functionPath\` (log/metric attribution), \`headroom\` (the
2554
+ // sub-query must not escape this dispatch's resource ceiling),
2555
+ // \`scope\` (the reactive-cache capture — an untracked sub-query's reads
2556
+ // must still be deps of the entry the OUTER query is memoized as, or
2557
+ // the memo goes stale), and — load-bearing — the resolved \`caller\` BY VALUE
2558
+ // (identity, userId AND ip). Omitting it would let \`buildCtx\` fall back
2559
+ // to the shared per-request fields, which a concurrent RPC may have
2560
+ // re-set, and an RLS-scoped sub-query would then read as the wrong user
2561
+ // from the wrong address. A tracked call keeps sharing \`ctx\` exactly as
2562
+ // before.
2563
+ ctx.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>, runOptions?: { untracked?: boolean }) =>
2564
+ dispatchRun(
2565
+ "query",
2566
+ reference.__lunoraRef,
2567
+ fnArgs,
2568
+ runOptions?.untracked === true
2569
+ ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, scope: options.scope })
2570
+ : ctx,
2571
+ contextKind,
2572
+ );
2573
+
2574
+ return ctx;
2575
+ }
2576
+ };
2577
+ `},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:N(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:N(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Xe(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},At=(e,t)=>{const n=se(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Vr=(e,t,n)=>{f(e,"drizzle column name");const r=Xe(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const i=At(t,n);return i!==void 0&&(o+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(o+=".notNull()"),o},Gr=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(f(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${Y(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},Jr=(e,t)=>{f(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([a,o])=>` ${a}: ${Vr(a,o,t)},`)].join(`
2578
+ `),r=e.indexes.length>0?`, (t) => ({
2579
+ ${e.indexes.map(a=>Gr(a)).join(`
2580
+ `)}
2581
+ })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
2582
+ ${n}
2583
+ }${r});`},zr=e=>e.typeAnnotation?.includes('Id<"')??!1,Yr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let a=!1,o=!1;for(const i of e){for(const s of Object.values(i.shape)){const c=Xe(s);n.add(c.builder),o=o||zr(c),a=a||At(s,t)!==void 0}for(const s of i.indexes)r.add(s.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,s)=>i.localeCompare(s)),indexes:[...r].toSorted((i,s)=>i.localeCompare(s)),needsAnyColumn:a,needsId:o}},ht=(e,t=!1)=>{if(e.length===0)return`${S}export {};
2584
+ `;const n=oe(t),r=new Set(e.map(g=>g.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=Yr(e,r),c=[...o,...a].toSorted((g,y)=>g.localeCompare(y)),d=e.map(g=>Jr(g,r)).join(`
2585
+
2586
+ `),h=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
2587
+ `:"",s?`import type { Id } from "./dataModel.js";
2588
+ `:""].join("");return`${S}import { ${c.join(", ")} } from "${n.serverDrizzle}";
2589
+ ${h}
2590
+ ${d}
2591
+ `},va=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:L(ht(n,t),Je),shard:L(ht(r,t),Je)}},Sa=e=>e?`${S}/**
2592
+ * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
2593
+ * forward it — wrangler binds only what the entry exports:
2594
+ *
2595
+ * \`export * from "./lunora/_generated/scheduler.js";\`
2596
+ *
2597
+ * A Vite-first (class-A) app needs no such line: the generated worker entry
2598
+ * forwards this module for you whenever it exists.
2599
+ */
2600
+ export { SchedulerDO } from "@lunora/scheduler";
2601
+ `:"",Ra=e=>{const t=new Map;for(const i of e){const s=t.get(i.cron);s?s.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
2602
+ `),r=n.length>0?`
2603
+ ${n}
2604
+ `:"",a=[...t.entries()].map(([i,s])=>{const c=s.map(d=>{const h=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${h}, args: ${JSON.stringify(d.args)} },`}).join(`
2605
+ `);return` ${JSON.stringify(i)}: [
2606
+ ${c}
2607
+ ],`}).join(`
2608
+ `),o=a.length>0?`
2609
+ ${a}
2610
+ `:"";return`${S}/**
2611
+ * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
2612
+ * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
2613
+ * shard; \`workflow\` is a \`WORKFLOW_*\` binding name whose durable workflow is
2614
+ * started fresh per fire. \`args\` are forwarded verbatim (a workflow's become
2615
+ * its \`params\`).
2616
+ */
2617
+ export interface LunoraCronJob {
2618
+ args: Record<string, unknown>;
2619
+ functionPath?: string;
2620
+ name: string;
2621
+ workflow?: string;
2622
+ }
2623
+
2624
+ /**
2625
+ * Deduplicated cron schedules — mirror of wrangler's \`triggers.crons\`. The
2626
+ * Lunora vite plugin keeps \`wrangler.jsonc\` in sync with this array.
2627
+ */
2628
+ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
2629
+
2630
+ /**
2631
+ * Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
2632
+ * looks up \`event.cron\` here and dispatches every job in the list.
2633
+ */
2634
+ export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${o}};
2635
+ `},$a=e=>{const t=[...e].toSorted((r,a)=>r.name.localeCompare(a.name)).map(r=>{const a=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&a.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&a.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&a.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&a.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${a.join(", ")} },`}).join(`
2636
+ `),n=t.length>0?`
2637
+ ${t}
2638
+ `:"";return`${S}/**
2639
+ * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
2640
+ * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
2641
+ * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
2642
+ * mirrored into Vectorize for filtering.
2643
+ */
2644
+ export interface LunoraVectorIndex {
2645
+ dimensions?: number;
2646
+ field?: string;
2647
+ metadata?: ReadonlyArray<string>;
2648
+ metric?: "cosine" | "dot-product" | "euclidean";
2649
+ name: string;
2650
+ table: string;
2651
+ }
2652
+
2653
+ /**
2654
+ * Static registry of every vector index in the schema, sorted by name.
2655
+ * Vectorize cannot enumerate indexes at runtime, so the worker passes this to
2656
+ * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2657
+ */
2658
+ export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
2659
+ `},Ta=e=>[...new Set(e.map(t=>t.cron))];export{da as A,In as C,S as G,er as U,ha as a,ma as b,ba as c,Ra as d,wa as e,ua as f,va as g,fa as h,Sa as i,ga as j,xa as k,$a as l,ya as m,Ta as n,yr as o,ka as p,pa as q};