@lunora/codegen 1.0.0-alpha.19 → 1.0.0-alpha.190

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 +3277 -1132
  4. package/dist/index.d.ts +3277 -1132
  5. package/dist/index.mjs +1 -34
  6. package/dist/packem_shared/AGENTS_FILENAME-B78F7DuQ.mjs +1 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-CQoUu7n7.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-CoTJH0-7.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER-DycP5oCG.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-CTHlZ1j6.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-CZh4jN4q.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-BNobmd0k.mjs +3 -0
  16. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-D29yBg5X.mjs +1 -0
  17. package/dist/packem_shared/QUEUES_FILENAME-Q3CF3uYr.mjs +1 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DLqvtzGf.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-BaSbufF2.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-BomWVHVV.mjs +3 -0
  25. package/dist/packem_shared/chain-Dp_6wzI9.mjs +1 -0
  26. package/dist/packem_shared/classify-procedure-call-C8jbo0IJ.mjs +1 -0
  27. package/dist/packem_shared/context-property-calls-Ce9xGl_o.mjs +1 -0
  28. package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
  29. package/dist/packem_shared/discoverAuthApiCalls-DoblmzUW.mjs +1 -0
  30. package/dist/packem_shared/discoverCrons-CMu0sA8k.mjs +1 -0
  31. package/dist/packem_shared/discoverFunctions-DB9G_XrW.mjs +1 -0
  32. package/dist/packem_shared/discoverHttpRoutes-S81Iv_iB.mjs +1 -0
  33. package/dist/packem_shared/discoverHyperdriveCalls-DgAYcZRD.mjs +1 -0
  34. package/dist/packem_shared/discoverInserts-COk-Sm_n.mjs +1 -0
  35. package/dist/packem_shared/discoverMaskProcedures-BLAzNB90.mjs +1 -0
  36. package/dist/packem_shared/discoverMigrations-B_sYrTyE.mjs +1 -0
  37. package/dist/packem_shared/discoverNondeterministicCalls-DkVVHe3U.mjs +1 -0
  38. package/dist/packem_shared/discoverQueries-BQXP4BZ0.mjs +1 -0
  39. package/dist/packem_shared/discoverR2sqlCalls-6u0OKy2N.mjs +1 -0
  40. package/dist/packem_shared/discoverRlsMetadata-CwWRPb8N.mjs +1 -0
  41. package/dist/packem_shared/discoverRlsProcedures-vJZq3yhb.mjs +1 -0
  42. package/dist/packem_shared/discoverSandboxUsage-DskdDbkM.mjs +1 -0
  43. package/dist/packem_shared/discoverSchema-DoZtXwLg.mjs +1 -0
  44. package/dist/packem_shared/discoverStorageRulesMetadata-xhxu-mkS.mjs +1 -0
  45. package/dist/packem_shared/emit-B_n-PvH3.mjs +2639 -0
  46. package/dist/packem_shared/emitApp-DvDGeMCt.mjs +823 -0
  47. package/dist/packem_shared/exported-procedure-chains-C9FHwphy.mjs +1 -0
  48. package/dist/packem_shared/formatAdvisories-CkEu1eye.mjs +2 -0
  49. package/dist/packem_shared/index-D_Z8rX-f.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-D4xthUf-.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-CPlxXagL.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-CmIWbykC.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-D-AbhmRh.mjs +0 -3134
  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-DDT4mIzD.mjs +0 -60
  70. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  71. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BZH-O4uh.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-DoK7_x1g.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-BnWHHJ4T.mjs +0 -822
  89. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  90. package/dist/packem_shared/emitApp-CV81L74c.mjs +0 -659
  91. package/dist/packem_shared/formatAdvisories-LM8-Ixjw.mjs +0 -75
  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,2639 @@
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 N}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]]:[])),ca=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},T=e=>{const t=Wn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?T(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?T(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?T(e.keyType):"string",r=e.valueType?T(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>T(n)).join(" | "):"never";default:return"unknown"}},kt=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?T(t.inner):"unknown";return`${n}?: ${r}`}return On(t)?`${n}?: ${T(t)}`:`${n}: ${T(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=T(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",da=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 A=v.inner?T(v.inner):"unknown";return` ${$}?: ${A};`}return` ${$}: ${T(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:T(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(N(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=>N(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=>N(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=>N(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=>N(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(N(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(N(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}},ua=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}`,A=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],H=A.length>0?`import type { ${A.join(", ")} } from "${s.client}";
244
+ `:"";return Rt(`${S}import { anyApi } from "${s.client}";
245
+ ${H}${v.importLine}${b}
246
+ ${$}`,o)},ha=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
+ `:"",pa=(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_${N(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=>` "${N(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=>` "${N(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=>`${N(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(N(a))}: {
363
+ ${i}
364
+ };`}).join(`
365
+ `);return{implementation:t.map(([a,o])=>{const i=N(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))]},ma=({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:A=[],useUmbrella:H=!1,workflows:O=[]}={})=>{const C=oe(H),w=gr($??{tables:[]},A).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
+ };`:"",k=[...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;${k?`
398
+ ${k}`:""}
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 = ${w};${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:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${N(n.filePath)}:${n.exportName}`);return t},ga=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(k=>k.length>0).join(`
734
+ `);let $=h;v.length>0&&($=h.length>0?`${h.trimEnd()}
735
+ ${v}
736
+ `:`
737
+ ${v}
738
+ `);const A=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(k=>JSON.stringify(k)).join(", ")}]);
754
+ `:"",w=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}${w}${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\`. Read at
796
+ * dispatch to decide whether the function runs system-trusted: \`init\` and
797
+ * \`reactor\` have no caller identity, so RLS has no user to scope to.
798
+ */
799
+ lifecycle?: "connect" | "disconnect" | "init" | "reactor";
800
+ /**
801
+ * Hoisted by the builder when the \`.use()\` chain carries a step with a
802
+ * per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
803
+ * captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
804
+ * inside the dispatch callback, and a reactive-cache HIT skips that
805
+ * callback, so such a query must never be memoized.
806
+ */
807
+ perDispatch?: boolean;
808
+ /** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
809
+ visibility?: "internal" | "public";
810
+ /**
811
+ * \`.x402({ price })\` tag on a paid public procedure. The origin worker
812
+ * paywalls it; the shard refuses to subscribe it (\`isPaidFunction\`).
813
+ */
814
+ x402?: { readonly price: number | string };
815
+ }
816
+ ${R.prelude}${x.prelude}
817
+ /**
818
+ * Static dispatch table. The key matches the \`__lunoraRef\` the client
819
+ * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
820
+ */
821
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${$}};
822
+ ${P}${O}${C}
823
+ /**
824
+ * Lifecycle manifest: the function paths the generated ShardDO dispatches when a
825
+ * client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
826
+ * per Durable Object instance before any handler runs (\`init\`), and after a
827
+ * write flush when a watched read's result changed (\`reactor\`). Each path also
828
+ * resolves through {@link LUNORA_FUNCTIONS}. The socket sides run under the
829
+ * socket's verified identity; \`init\` and \`reactor\` have no caller, so they run
830
+ * anonymous — all via system dispatch.
831
+ */
832
+ export const LUNORA_LIFECYCLE_HOOKS: { connect: readonly string[]; disconnect: readonly string[]; init: readonly string[]; reactor: readonly string[] } = {
833
+ connect: [${A.connect.map(k=>JSON.stringify(k)).join(", ")}],
834
+ disconnect: [${A.disconnect.map(k=>JSON.stringify(k)).join(", ")}],
835
+ init: [${A.init.map(k=>JSON.stringify(k)).join(", ")}],
836
+ reactor: [${A.reactor.map(k=>JSON.stringify(k)).join(", ")}],
837
+ };
838
+
839
+ /**
840
+ * Resolve and invoke a registered function from an external caller. Throws a
841
+ * LunoraError-shaped object (404) when the path is unknown — the runtime's
842
+ * structural error mapper turns that into the right HTTP status. Internal
843
+ * functions are treated as not-found so their existence never leaks to clients.
844
+ */
845
+ export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
846
+ const registered = LUNORA_FUNCTIONS[functionPath];
847
+
848
+ if (!registered || registered.visibility === "internal") {
849
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
850
+ }
851
+
852
+ return registered.handler(context, args);
853
+ };
854
+
855
+ /**
856
+ * A handler context accepted by {@link createCaller}. The runtime context the
857
+ * shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
858
+ */
859
+ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
860
+
861
+ /**
862
+ * Typed, in-process server-to-server caller. Every registered function — public
863
+ * *and* internal — is reachable; each call dispatches against the same shard
864
+ * with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
865
+ * \`runAction\` but without re-stating the function path.
866
+ */
867
+ export interface Caller {${ie}}
868
+
869
+ ${ee}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
870
+ export const createCaller = (${D}: CallerCtx): Caller => ({${le}});
871
+
872
+ /**
873
+ * Single registered data migration, narrowed to the shape the per-shard runner
874
+ * consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
875
+ * validation lives in \`defineMigration\`.
876
+ */
877
+ export interface RegisteredDataMigration {
878
+ batchSize?: number;
879
+ down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
880
+ id: string;
881
+ table: string;
882
+ up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
883
+ }
884
+
885
+ /**
886
+ * Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
887
+ * shard DO's admin RPC and the CLI resolve migrations to run through this map.
888
+ */
889
+ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
890
+ `,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:`
891
+ protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
892
+ this.ensureMigrated();
893
+
894
+ const { db } = this.buildCtx({ functionPath }) as { db: DatabaseWriterLike };
895
+
896
+ return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
897
+ }
898
+ `}:{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:`
899
+ const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
900
+ // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
901
+ // function path + trace id into createAi, which folds them into the
902
+ // gateway's native \`metadata\` only when a gateway is configured (absent
903
+ // otherwise). Mirror the tracer's anchor guard — a deferred subscription
904
+ // re-run must not borrow a concurrent dispatch's trace, so read
905
+ // \`getCurrentTrace()\` only on the synchronous (non-threaded-identity) path.
906
+ const aiTrace = options.identity ? undefined : this.getCurrentTrace();
907
+ const ai: LunoraAi = aiBinding
908
+ ? createAi({ binding: aiBinding as AiBindingLike, env: env as Record<string, unknown>, metadata: { functionPath: options.functionPath, traceId: aiTrace?.traceId } })
909
+ : aiStub;
910
+ `,configField:`
911
+ ai?: (env: Record<string, unknown>) => AiBindingLike;`,contextField:`
912
+ ai,`,stub:`
913
+ const aiStub: LunoraAi = {
914
+ embeddingModel: () => {
915
+ ${t}
916
+ },
917
+ model: () => {
918
+ ${t}
919
+ },
920
+ run: async () => {
921
+ ${t}
922
+ },
923
+ // workersai is a callable-with-properties; a bare throwing arrow isn't
924
+ // structurally assignable, so cast it. Never invoked (the stub throws first).
925
+ workersai: (() => {
926
+ ${t}
927
+ }) as unknown as LunoraAi["workersai"],
928
+ };
929
+ `}},I=(e,t,n,{cast:r="",sync:a=[]}={})=>{const o=n.map(i=>` ${i}: ${a.includes(i)?"":"async "}() => {
930
+ ${t}
931
+ },`).join(`
932
+ `);return`
933
+ const ${e} = {
934
+ ${o}
935
+ }${r};
936
+ `},E={build:"",configField:"",contextField:"",importLines:[],stub:""},Tr=e=>e?{build:`
937
+ const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
938
+ // KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
939
+ // when a value changes — a subscription that read one can never be proven
940
+ // current on reconnect and must re-snapshot. Reads only; \`put\`/\`delete\`
941
+ // are writes and stay unstamped.
942
+ const kv: Kv = markUnvouchableReads(kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub, options.onRead, [
943
+ "get",
944
+ "getRaw",
945
+ "getWithMetadata",
946
+ "list",
947
+ ]);
948
+ `,configField:`
949
+ kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
950
+ 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:`
951
+ const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
952
+ provider: () => config.flags?.(env),
953
+ targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
954
+ });
955
+ `,configField:`
956
+ flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
957
+ flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:E,Ar=e=>e?{build:`
958
+ const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
959
+ `,configField:"",contextField:`
960
+ notify,
961
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:E,Or=e=>e?{build:`
962
+ const envConfig = lunoraEnvContract.${e.exportName}(env);
963
+ `,configField:"",contextField:`
964
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:E,Ir=e=>e?{build:`
965
+ const access = accessFacade(identity, userId);
966
+ `,configField:"",contextField:`
967
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:E,Cr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
968
+ const env = (this.env ?? {}) as Record<string, unknown>;
969
+ const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
970
+ provider: () => config.flags?.(env),
971
+ targetingKey: ${s},
972
+ });`,a=`
973
+ /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
974
+ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }> = ${JSON.stringify(e,void 0,4)};
975
+ `,o=`
976
+ protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${r("undefined")}
977
+ const evalContext = context as import("${n}").EvaluationContext | undefined;
978
+ const evaluations: FlagsResult["flags"] = [];
979
+
980
+ for (const entry of LUNORA_FLAG_KEYS) {
981
+ // eslint-disable-next-line no-await-in-loop -- flags evaluate sequentially; each shares the single memoized provider client
982
+ const details =
983
+ entry.type === "boolean"
984
+ ? await flags.details.boolean(entry.key, false, evalContext)
985
+ : entry.type === "number"
986
+ ? await flags.details.number(entry.key, 0, evalContext)
987
+ : entry.type === "string"
988
+ ? await flags.details.string(entry.key, "", evalContext)
989
+ : await flags.details.object(entry.key, {}, evalContext);
990
+
991
+ evaluations.push({ errorCode: details.errorCode, key: entry.key, reason: details.reason, type: entry.type, value: details.value, variant: details.variant });
992
+ }
993
+
994
+ return { configured: true, flags: evaluations };
995
+ }
996
+ `,i=`
997
+ protected override runFlagSubscriptionRead(_functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<unknown> {${r("() => flagsConfig.identify?.({ identity: identity?.identity ?? null, userId: identity?.userId ?? null })")}
998
+ const key = typeof args.key === "string" ? args.key : "";
999
+
1000
+ // SECURITY: the reactive channel is public (any socket, no auth). Serve
1001
+ // ONLY statically-discovered flag keys — an arbitrary client-supplied key
1002
+ // would let a subscriber probe the value of internal/unreleased flags the
1003
+ // app never exposes. Unknown key ⇒ the "nothing to deliver" sentinel.
1004
+ // eslint-disable-next-line unicorn/no-null -- the base hook's "nothing to deliver" sentinel
1005
+ if (key.length === 0 || !LUNORA_FLAG_KEYS.some((entry) => entry.key === key)) {
1006
+ return Promise.resolve(null);
1007
+ }
1008
+
1009
+ // SECURITY: evaluate under the socket's server-verified identity ONLY
1010
+ // (the targetingKey resolved above). Client-supplied targeting context is
1011
+ // NOT honored on this public channel — otherwise a subscriber could spoof
1012
+ // targeting attributes (e.g. plan/role) to unlock a flag gated on them.
1013
+ const context = undefined;
1014
+
1015
+ if (args.type === "number") {
1016
+ return flags.number(key, typeof args.default === "number" ? args.default : 0, context);
1017
+ }
1018
+
1019
+ if (args.type === "string") {
1020
+ return flags.string(key, typeof args.default === "string" ? args.default : "", context);
1021
+ }
1022
+
1023
+ if (args.type === "object") {
1024
+ return flags.object(key, (args.default ?? {}) as import("${n}").JsonValue, context);
1025
+ }
1026
+
1027
+ return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
1028
+ }
1029
+ `;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},Dr=e=>e?{build:`
1030
+ const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
1031
+ const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
1032
+ `,configField:`
1033
+ analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
1034
+ 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:`
1035
+ const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
1036
+ const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
1037
+ `,configField:`
1038
+ images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
1039
+ 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:`
1040
+ const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
1041
+ `,configField:`
1042
+ sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
1043
+ 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:`
1044
+ const browser: Browser = config.browser ? config.browser(env) : browserStub;
1045
+ `,configField:`
1046
+ browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
1047
+ 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:`
1048
+ const r2sqlEnv = env as Record<string, unknown>;
1049
+ const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
1050
+ const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
1051
+ const r2sqlBucket = r2sqlEnv.R2_SQL_BUCKET as string | undefined;
1052
+ const r2sql: R2SqlClient = config.r2sql
1053
+ ? config.r2sql(env)
1054
+ : r2sqlAccountId && r2sqlToken && r2sqlBucket
1055
+ ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
1056
+ : r2sqlStub;
1057
+ `,configField:`
1058
+ 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:`
1059
+ const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
1060
+ const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
1061
+ `,configField:`
1062
+ 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,fa=(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}\`). */
1063
+ export class ${o.className} extends LunoraContainer {
1064
+ public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1065
+ super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
1066
+ }
1067
+ }
1068
+ `)).join(`
1069
+ `),a=e.map(o=>o.exportName).join(", ");return`${S}/**
1070
+ * Container-enabled Durable Object classes for the containers declared in
1071
+ * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
1072
+ * requires each \`containers[].class_name\` to be exported by the worker:
1073
+ *
1074
+ * \`export * from "./lunora/_generated/containers.js";\`
1075
+ *
1076
+ * \`ContainerProxy\` is re-exported alongside them: the egress-interception path
1077
+ * (\`allowedHosts\`/\`deniedHosts\`/\`interceptHttps\` and the runtime
1078
+ * \`handle.egress\` controls) routes container outbound traffic through this
1079
+ * WorkerEntrypoint, so it too must be exported by the deployed worker.
1080
+ */
1081
+ import { LunoraContainer } from "@lunora/container/do";
1082
+
1083
+ import { ${a} } from "../containers.js";
1084
+
1085
+ export { ContainerProxy } from "@lunora/container/do";
1086
+
1087
+ ${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(`
1088
+ `);return{build:`
1089
+ const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
1090
+ `,contextField:`
1091
+ containers,`,importLines:['import type { ContainerBindingSpec } from "@lunora/container";','import { createContainerContext } from "@lunora/container";'],specs:`
1092
+ /** Wiring specs for \`ctx.containers\` (codegen-derived from \`lunora/containers.ts\`). */
1093
+ const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
1094
+ ${n}
1095
+ ];
1096
+ `}},ba=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}\`). */
1097
+ export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
1098
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1099
+ super(ctx, env, ${r.exportName}, "${r.exportName}");
1100
+ }
1101
+ }
1102
+ `)).join(`
1103
+ `),n=e.map(r=>r.exportName).join(", ");return`${S}/**
1104
+ * WorkflowEntrypoint classes for the workflows declared in
1105
+ * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
1106
+ * requires each \`workflows[].class_name\` to be exported by the worker:
1107
+ *
1108
+ * \`export * from "./lunora/_generated/workflows.js";\`
1109
+ */
1110
+ import LunoraWorkflow from "@lunora/workflow/do";
1111
+
1112
+ import { ${n} } from "../workflows.js";
1113
+
1114
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`), so each entrypoint keeps the authored \`ctx.params\` type. */
1115
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
1116
+ ? unknown extends Params
1117
+ ? Record<string, unknown>
1118
+ : NonNullable<Params>
1119
+ : Record<string, unknown>;
1120
+
1121
+ /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
1122
+ type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
1123
+
1124
+ ${t}`},ya=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}\`). */
1125
+ export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1126
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1127
+ super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
1128
+ }
1129
+ }
1130
+ `;if(!s.voice)return c;const d=s.voiceClassName??"",h=s.voiceBindingName??"";f(d,`agent voice class "${d}"`);const g=`
1131
+ /** Voice-session Durable Object for the \`${s.exportName}\` agent (binding \`${h}\`). */
1132
+ export class ${d} extends VoiceSessionDO {
1133
+ public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
1134
+ super(ctx, env, ${s.exportName}, "${s.exportName}");
1135
+ }
1136
+ }
1137
+ `;return`${c}${g}`}).join(`
1138
+ `),a=e.map(s=>s.exportName).join(", ");return`${S}/**
1139
+ * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
1140
+ * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
1141
+ * Workflow. Re-export them from your worker entry — wrangler requires each
1142
+ * \`workflows[].class_name\` to be exported by the worker:
1143
+ *
1144
+ * \`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).":""}
1145
+ */
1146
+ import LunoraWorkflow from "@lunora/workflow/do";
1147
+ ${n?'import { compileAgentWorkflow, VoiceSessionDO } from "@lunora/agent";':'import { compileAgentWorkflow } from "@lunora/agent";'}
1148
+ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
1149
+
1150
+ import { ${a} } from "../agents.js";
1151
+
1152
+ ${r}`},wa=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(`
1153
+ `);return`${S}/**
1154
+ * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
1155
+ * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
1156
+ * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
1157
+ * by \`defineApp\` — you don't import this directly.
1158
+ */
1159
+ import type { QueueRegistry } from "@lunora/queue";
1160
+
1161
+ import { ${n} } from "../queues.js";
1162
+
1163
+ /** Stable wrangler queue name → { definition, exportName } for batch routing. */
1164
+ export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
1165
+ ${r}
1166
+ };
1167
+ `},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(`
1168
+ `);return{build:`
1169
+ const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
1170
+ `,contextField:`
1171
+ workflows,`,importLines:['import type { WorkflowBindingSpec } from "@lunora/workflow";','import { createWorkflowContext } from "@lunora/workflow";'],specs:`
1172
+ /** Wiring specs for \`ctx.workflows\` (codegen-derived from \`lunora/workflows.ts\`). */
1173
+ const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
1174
+ ${t}
1175
+ ];
1176
+ `}},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(`
1177
+ `);return{build:`
1178
+ const queues = createQueueContext(env, LUNORA_QUEUES);
1179
+ `,contextField:`
1180
+ queues,`,importLines:['import type { QueueBindingSpec } from "@lunora/queue";','import { createQueueContext } from "@lunora/queue";'],specs:`
1181
+ /** Wiring specs for \`ctx.queues\` (codegen-derived from \`lunora/queues.ts\`). */
1182
+ const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
1183
+ ${t}
1184
+ ];
1185
+ `}},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(`
1186
+ `);return{build:`
1187
+ const agents = createAgentContext(env, LUNORA_AGENTS);
1188
+ `,contextField:`
1189
+ agents,`,importLines:['import { createAgentContext } from "@lunora/agent";','import type { AgentBindingSpec } from "@lunora/agent";'],specs:`
1190
+ /** Wiring specs for \`ctx.agents\` (codegen-derived from \`lunora/agents.ts\`). */
1191
+ const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
1192
+ ${t}
1193
+ ];
1194
+ `}},Nt=(e,t,n,r,a)=>({constant:`
1195
+ ${a}
1196
+ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1197
+ `,override:`
1198
+ protected override ${n}(): ${t} {
1199
+ return ${e};
1200
+ }
1201
+ `}),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:`
1202
+ const payments: LunoraPayment = config.payment
1203
+ ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
1204
+ : paymentStub;
1205
+ `,configField:`
1206
+ payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
1207
+ 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:`
1208
+ const x402: X402Pay = config.x402
1209
+ ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1210
+ : x402Stub;
1211
+ `,configField:`
1212
+ 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"]:[]],ka=({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:A,mutators:H=[],queues:O=[],rlsMetadata:C,schema:w,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const D=oe(Z),ee=H.length>0,k=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
1213
+ /** 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. */
1214
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Tn(P))}, json: ${JSON.stringify(Ae)} };
1215
+ `,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,w.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=A??{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&&w.vectorIndexes.length>0,tt=new Set(w.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&w.vectorIndexes.some(m=>tt.has(m.table)),we=w.tables.some(m=>m.shardMode==="global"),Ue=w.tables.some(m=>Nn(m)),nt=w.tables.some(m=>An(m)),ae=w.tables.some(m=>m.externalSource!==void 0),rt=w.tables.some(m=>m.memory===!0),Ke=w.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=w.tables.length>0,Ft=br(w),Bt=wr(w),qt=Sr(w),jt=yr(w),at=kr(w),ot=Hr(K,V.length>0,O.length>0,h,Ke);k&&ot.push("WhereInput");const st=Rr(we),Wt=k?`
1216
+ protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
1217
+ const shape = LUNORA_SHAPES[name];
1218
+
1219
+ if (!shape) {
1220
+ return undefined;
1221
+ }
1222
+
1223
+ this.ensureMigrated();
1224
+
1225
+ // Trusted ctx from the socket's OWN verified identity — the client
1226
+ // supplies only the shape name + args; \`compileWhere\` validates the
1227
+ // args then runs the shape's \`where(ctx, args)\` under that identity,
1228
+ // so which rows replicate is a server decision (reads-as-permissions).
1229
+ const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity });
1230
+ // \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
1231
+ // \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
1232
+ // rather than every shape restating the ownership check in its \`where\`.
1233
+ const shapeWhere = shape.compileWhere(ctx, args, {
1234
+ ownerField: (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField,
1235
+ }) as unknown as WhereInput;
1236
+
1237
+ // AND-compose with the read policies this SHAPE declares
1238
+ // (\`defineShape({ use: [guard] })\`, pre-indexed into
1239
+ // \`shape.rlsRegistry\`). A shape runs no procedure, so the
1240
+ // \`.use(rls(...))\` middleware never fires; without this merge its
1241
+ // reads would bypass the read policies it opted into.
1242
+ // \`composeShapeReadWhere\` evaluates them under this same trusted ctx
1243
+ // and fails closed under a \`.rls("required")\` schema for a
1244
+ // non-\`.public()\` table the shape declared no read policy for.
1245
+ //
1246
+ // The registry is the shape's OWN — never one folded from every
1247
+ // registered function. A project-wide union let one admin-only
1248
+ // procedure's allow-all read policy unrestrict every shape on the
1249
+ // table; see the SCOPE note in \`shape-read-base.ts\`.
1250
+ //
1251
+ // It is NOT identical to the request-time path, and must not be
1252
+ // described as such: roles come from the identity's \`roles\` claim
1253
+ // only, because no middleware runs here to contribute
1254
+ // \`ctx.auth.roles\`. Derive roles at the identity if a policy gates
1255
+ // on them — see \`shape-read-base.ts\`.
1256
+ const effectiveWhere = composeShapeReadWhere(shape.rlsRegistry, {
1257
+ ctx,
1258
+ identity: identity?.identity ?? null,
1259
+ rlsRequired: (schema as unknown as { rlsMode?: string }).rlsMode === "required",
1260
+ shapeWhere,
1261
+ table: shape.table,
1262
+ tablePublic: (schema as unknown as { tables: Record<string, { isPublic?: boolean }> }).tables[shape.table]?.isPublic === true,
1263
+ userId: identity?.userId ?? null,
1264
+ });
1265
+
1266
+ // A live shape pokes only from its OWN shard's op-log, so a \`where()\`
1267
+ // that joins to a \`.shardBy()\` table (rows in another DO) is rejected
1268
+ // here — the first point the compiled predicate + shard modes are both
1269
+ // known. Remedy: denormalize, or move the joined table to \`.global()\`.
1270
+ assertShapeShardable(effectiveWhere, schema as unknown as SchemaLike, shape.table);
1271
+
1272
+ // A \`.global()\` table lives in D1 (no per-DO op-log): flag it so the
1273
+ // base serves it through the latency-tiered poll path (\`readGlobalShapeRows\`)
1274
+ // instead of the CDC poke path.
1275
+ const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global";
1276
+
1277
+ return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
1278
+ }
1279
+ `:"",it=k?[...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?`
1280
+ /** 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). */
1281
+ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(it)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
1282
+ `:"",Ut=ee?`
1283
+ protected override isCustomMutator(functionPath: string): boolean {
1284
+ return LUNORA_MUTATOR_PATHS.has(functionPath);
1285
+ }
1286
+ `:"",Kt=k?"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}";`]:[],k?`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"]:[],...k?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ht=K?`
1287
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Vt=nt?`
1288
+ 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?`
1289
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Jt=ae?`
1290
+ 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?`
1291
+ const vectorShardKey = this.currentShardKey();
1292
+ `:"",rn=Ne?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",an=Ne?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${w.vectorIndexes.filter(m=>tt.has(m.table)).map(m=>JSON.stringify(m.name)).join(", ")}] }`:"",on=K?`
1293
+ let vectors: VectorSearchLike;
1294
+ let onWrite: WriteHook | undefined;
1295
+
1296
+ if (config.vectors) {
1297
+ const lunora = createVectors({ indexes: config.vectors(env) });
1298
+ ${nn}
1299
+ vectors = createContextVectors(lunora${an});
1300
+ onWrite = createVectorSyncHook({ ${rn}schema: schema as unknown as VectorSchemaLike, vectors });
1301
+ } else {
1302
+ vectors = vectorsStub;
1303
+ onWrite = undefined;
1304
+ }
1305
+
1306
+ // Vectorize lives outside this shard's SQLite, so a query whose result
1307
+ // depends on a similarity search cannot be proven current on reconnect —
1308
+ // an unrelated upsert (or a re-index) moves the matches without touching
1309
+ // \`__cdc_log\`. Wrapped AFTER \`onWrite\` is built so the write-through
1310
+ // vector-sync hook keeps calling the bare facade.
1311
+ vectors = markUnvouchableReads(vectors, options.onRead, ["getByIds", "query"]);
1312
+ `:"",sn=`{
1313
+ ...this.ctxDbTuning(),
1314
+ auth: { identity: identity ?? null, userId: userId ?? null },
1315
+ broadcast: (delta) => {
1316
+ this.recordChangedTable(delta.table, delta.indexKeys);
1317
+ },
1318
+ // Read at call time, not captured: the baseline belongs to the
1319
+ // dispatch in flight, and a queued mutation admitted after a
1320
+ // sibling's prologue must be judged against ITS caller's cursor.
1321
+ baselineSeq: () => this.getCurrentBaselineSeq(),
1322
+ cdc: config.cdc ?? false,
1323
+ // A dispatch with NO caller identity runs system-trusted: RLS scopes
1324
+ // rows to a user, and these have no user to scope to. This is the tier
1325
+ // migrations, imports and the external-source poll loop already run in
1326
+ // (see \`adminWriterPrelude\`). Only \`onShardInit\` and \`onQueryChange\`
1327
+ // reach it; \`onConnect\`/\`onDisconnect\` carry a verified identity and
1328
+ // stay guarded like any request.
1329
+ enforceRls: options.trusted !== true,
1330
+ headroom: options.headroom ?? this.transactionHeadroom(),
1331
+ // A live predicate, not a flag: the transaction opens AFTER this ctx
1332
+ // is built (a mutation dispatch wraps the handler), so only a call-time
1333
+ // read reports the truth. \`_commitSeq\` reuses one sequence across
1334
+ // writes only while they commit together — an action is not wrapped, so
1335
+ // each of its writes allocates its own.
1336
+ inTransaction: () => this.isInTransaction(),
1337
+ onIndexUse: this.getCtxDbIndexUseHook(),
1338
+ onStalePatchDropped: (event) => {
1339
+ this.recordStalePatchDropped(event);
1340
+ },
1341
+ // Bound to THIS dispatch's reactive-cache read scope (\`handleRpc\`
1342
+ // threads it in), so two concurrent queries never stamp each
1343
+ // other's dep sets. \`executeSubscription\` overrides both with its
1344
+ // own \`ReadFootprint\` pair instead, and a dispatch with neither
1345
+ // gets an unbound hook that stamps no deps.
1346
+ onRead: options.onRead ?? this.getCtxDbReadHook(options.scope),
1347
+ // Left \`undefined\` when there is no scope so \`createShardCtxDb\`
1348
+ // keeps its own "degrade a provable slice to a whole-table dep"
1349
+ // fallback rather than reporting into a no-op.
1350
+ onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${K?`
1351
+ // Vectorize is outside this shard's SQLite and cannot roll back, so
1352
+ // the sync is held until the mutation's transaction has COMMITTED
1353
+ // (\`deferAfterCommit\`) instead of running inline. Inline, a write
1354
+ // that later aborted left a vector pointing at a row that does not
1355
+ // exist — which a search then surfaces — and a rolled-back delete
1356
+ // left the row with its vector already purged. Outside a
1357
+ // transaction (an action) nothing is open and it runs at once.
1358
+ onWrite: onWrite === undefined ? undefined : (event) => this.deferAfterCommit(() => onWrite(event)),`:""}
1359
+ scheduler,
1360
+ schema: schema as unknown as SchemaLike,
1361
+ sql: this.sql as SqlExec,
1362
+ storage,${we?`
1363
+ globalDb,`:""}
1364
+ }`,ln=` /**
1365
+ * The bare writer every admin/maintenance entry point writes through.
1366
+ *
1367
+ * Admin and maintenance writes go through the SAME reactive-cache hooks as a
1368
+ * user mutation. Without this, a studio row edit, a TTL sweep, an admin
1369
+ * import, a CDC apply or a data-migration backfill writes without
1370
+ * invalidating, and the next query answers from the pre-write snapshot.
1371
+ *
1372
+ * \`headroom\` meters the transaction. An admin \`/rpc\` caller passes nothing
1373
+ * and falls back to \`this.transactionHeadroom()\`, which for an admin RPC is
1374
+ * \`undefined\` — \`handleAdminRpc\` answers before \`beginDispatch\`, so no
1375
+ * per-dispatch meter is in flight and a bulk loop is bounded by its per-call
1376
+ * row cap alone. The TTL sweep (an alarm work item, no dispatch) passes its
1377
+ * own by-value tracker explicitly instead.
1378
+ */
1379
+ private adminWriter(headroom?: TransactionHeadroomTracker): DatabaseWriterLike {
1380
+ const env = (this.env ?? {}) as Record<string, unknown>;
1381
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1382
+
1383
+ return createShardCtxDb({
1384
+ ...this.ctxDbTuning(),
1385
+ broadcast: (delta) => {
1386
+ this.recordChangedTable(delta.table, delta.indexKeys);
1387
+ },
1388
+ cdc: config.cdc ?? false,
1389
+ headroom,
1390
+ // Live predicate, same as the user-facing ctx — see \`databaseOptions\`.
1391
+ inTransaction: () => this.isInTransaction(),
1392
+ scheduler,
1393
+ schema: schema as unknown as SchemaLike,
1394
+ sql: this.sql as SqlExec,
1395
+ });
1396
+ }`,Q=(m="")=>` const writer = this.adminWriter(${m});`,cn=K?`
1397
+ vectors,`:"",dn=Qe?`
1398
+ 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 };
1399
+ const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
1400
+ `:"",hn=k&&we?`
1401
+ protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1402
+ const env = this.env as Record<string, unknown>;
1403
+ // A shape read performs no writes, so the widened request only needs
1404
+ // the inbound bookmark (pin the membership drain to the caller's own
1405
+ // prior writes) — no \`onBookmark\` here.
1406
+ //
1407
+ // The two identity members are named rather than spread, matching the
1408
+ // dispatch-path request built in \`buildCtx\`. A spread would also hand
1409
+ // the global writer \`ip\`, and \`globalShapeReadKey\` — the per-flush
1410
+ // cache in front of this read — keys on identity + userId only. Equal
1411
+ // keys must mean equal rows, so a field the writer can scope by has to
1412
+ // be either in the key or out of the request; it is out.
1413
+ const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity: identity?.identity, userId: identity?.userId };
1414
+ const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
1415
+ const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
1416
+
1417
+ let cursor: null | string = null;
1418
+
1419
+ // Drain every page of the global membership so the seed/diff sees the
1420
+ // full rowset (D1 \`findMany\` is paginated). Stop one row past the cap:
1421
+ // a broad \`.global()\` shape would otherwise materialize an unbounded
1422
+ // array before the caller's \`withinGlobalShapeBound\` check rejects it,
1423
+ // so bail early and let the caller fail it closed.
1424
+ do {
1425
+ // eslint-disable-next-line no-await-in-loop -- sequential page drain to assemble the full membership
1426
+ const page = await globalDb.findMany(resolved.table, { cursor, where: resolved.effectiveWhere });
1427
+
1428
+ for (const doc of page.page) {
1429
+ rows.push({ doc, id: String((doc as { _id?: unknown })._id) });
1430
+
1431
+ if (rows.length > ShardDOBase.GLOBAL_SHAPE_MAX_ROWS) {
1432
+ return rows;
1433
+ }
1434
+ }
1435
+
1436
+ cursor = page.isDone ? null : page.continueCursor;
1437
+ } while (cursor !== null);
1438
+
1439
+ return rows;
1440
+ }
1441
+
1442
+ protected override async readGlobalChangedTables(sinceSeq: number, cursorOnly?: boolean): Promise<{ cursor: number; floor?: number; tables: string[] } | undefined> {
1443
+ const env = this.env as Record<string, unknown>;
1444
+ // Metadata-only: this asks the global changelog which TABLES moved,
1445
+ // never what changed in them, so it costs one small read per poll tick
1446
+ // for the whole shard — and a tick whose answer omits a shape's table
1447
+ // skips that shape's membership drain entirely.
1448
+ const globalDb: DatabaseWriterLike = ${He}?.(env, { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() }) ?? globalDbStub;
1449
+
1450
+ return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
1451
+ }
1452
+ `:"",pn=ae?`
1453
+ const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1454
+ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1455
+ `:"",mn=`
1456
+ protected override async runShardInit(): Promise<void> {
1457
+ this.ensureMigrated();
1458
+ ${rt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1459
+ `:""}
1460
+ await this.dispatchShardInit();
1461
+ }
1462
+ `,gn=ae?`
1463
+ protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1464
+ const env = (this.env ?? {}) as Record<string, unknown>;
1465
+ const sourced = Object.entries((schema as unknown as SchemaLike).tables)
1466
+ .map(([table, definition]) => [table, (definition as { externalSource?: ExternalSourceLike }).externalSource] as const)
1467
+ .filter((entry): entry is [string, ExternalSourceLike] => entry[1] !== undefined);
1468
+
1469
+ if (sourced.length === 0) {
1470
+ return undefined;
1471
+ }
1472
+
1473
+ const shardKey = this.currentShardKey();
1474
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1475
+
1476
+ let clients = sourceClientCache.get(this);
1477
+
1478
+ if (clients === undefined) {
1479
+ clients = new Map();
1480
+ sourceClientCache.set(this, clients);
1481
+ }
1482
+
1483
+ let polledAt = sourcePollAtCache.get(this);
1484
+
1485
+ if (polledAt === undefined) {
1486
+ polledAt = new Map();
1487
+ sourcePollAtCache.set(this, polledAt);
1488
+ }
1489
+
1490
+ const now = Date.now();
1491
+ // \`nextDueAt\` tracks the EARLIEST next-due timestamp across every
1492
+ // non-manual source; the shared alarm re-arms there instead of the
1493
+ // fixed 2 s global-shape floor, so a large \`refresh.everyMs\` actually
1494
+ // sleeps until it's due. Stays \`undefined\` when every source is
1495
+ // \`refresh: "manual"\`, so the shared alarm goes idle for this tier.
1496
+ let nextDueAt: number | undefined;
1497
+
1498
+ for (const [table, source] of sourced) {
1499
+ if (source.refresh === "manual") {
1500
+ continue;
1501
+ }
1502
+
1503
+ if (isSourceDue(source.refresh, polledAt.get(table), now)) {
1504
+ try {
1505
+ let client = clients.get(source.binding);
1506
+
1507
+ if (client === undefined) {
1508
+ client = config.sourceClient?.(env, source.binding);
1509
+
1510
+ if (client !== undefined) {
1511
+ clients.set(source.binding, client);
1512
+ }
1513
+ }
1514
+
1515
+ if (client === undefined) {
1516
+ // No SqlClient resolved for this binding (host never wired
1517
+ // \`config.sourceClient\`, or wired it wrong). Surface it in the
1518
+ // Logs panel and stamp \`polledAt\` so a persistent misconfig backs
1519
+ // off to \`refresh.everyMs\` instead of retrying every alarm tick.
1520
+ this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`), trace);
1521
+ } else {
1522
+ // A FRESH tracker per TABLE, not one shared across the whole
1523
+ // loop: one table's runaway pull must not spend a budget a
1524
+ // sibling table needs, and a limit hit here must not block
1525
+ // that sibling from getting its own full budget this tick.
1526
+ const writer = createShardCtxDb({
1527
+ // Admin and maintenance writes go through the SAME reactive-cache hooks as
1528
+ // a user mutation. Without this, a studio row edit, a TTL sweep, an admin
1529
+ // import, a CDC apply or a data-migration backfill writes without
1530
+ // invalidating, and the next query answers from the pre-write snapshot.
1531
+ ...this.ctxDbTuning(),
1532
+ broadcast: (delta) => {
1533
+ this.recordChangedTable(delta.table, delta.indexKeys);
1534
+ },
1535
+ cdc: config.cdc ?? false,
1536
+ headroom: this.alarmHeadroom(),
1537
+ scheduler,
1538
+ schema: schema as unknown as SchemaLike,
1539
+ sql: this.sql as SqlExec,
1540
+ });
1541
+
1542
+ if (source.mode === "incremental") {
1543
+ // Incremental (plan 136): pull only rows past the durable
1544
+ // watermark (or a full-pull seed/reconcile), upsert-only.
1545
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
1546
+ await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
1547
+ } else {
1548
+ // 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
1549
+ await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
1550
+ }
1551
+ }
1552
+
1553
+ // Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
1554
+ // poll that outruns \`everyMs\` must not make \`nextDueAt\` (below)
1555
+ // stale-immediate and re-arm the alarm in a hammering loop.
1556
+ polledAt.set(table, Date.now());
1557
+ } catch (error) {
1558
+ if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
1559
+ // Batch full, not a genuine failure. Incremental mode only
1560
+ // persists its watermark AFTER a full apply (see
1561
+ // \`pullExternalSourceIncrementalTick\`), so this throw left it
1562
+ // untouched — the next tick safely re-pulls/re-applies the
1563
+ // SAME slice (idempotent upsert). Full-pull mode (and an
1564
+ // incremental source's own occasional full-pull/reconcile
1565
+ // sweep) has no resumable cursor at all — deliberately not
1566
+ // inventing one here; a retry just redoes the whole pull,
1567
+ // safe if wasteful. Either way: warn instead of
1568
+ // \`recordExternalSourceError\`, and leave \`polledAt\`
1569
+ // UNCHANGED (skip the stamp below via \`continue\`) so this
1570
+ // table stays "due" and \`nextPollAlarmTarget\`'s existing
1571
+ // due-now floor re-arms the shared alarm promptly — not a
1572
+ // fresh \`setAlarm(now)\`.
1573
+ this.recordExternalSourceWarning(
1574
+ table,
1575
+ \`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
1576
+ trace,
1577
+ );
1578
+
1579
+ nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
1580
+
1581
+ continue;
1582
+ }
1583
+
1584
+ this.recordExternalSourceError(table, error, trace);
1585
+ // Stamp on failure too, so a persistently failing source throttles
1586
+ // to \`refresh.everyMs\` rather than being hammered every tick.
1587
+ polledAt.set(table, Date.now());
1588
+ }
1589
+ }
1590
+
1591
+ // This source's own next-due time, read AFTER the poll-or-skip above
1592
+ // so a just-polled source reports \`now + everyMs\` (its FRESH due
1593
+ // time), not the stale pre-poll one. An omitted \`refresh\` (poll
1594
+ // every tick) is due again immediately.
1595
+ const sourceNextDueAt = source.refresh === undefined ? now : (polledAt.get(table) ?? now) + source.refresh.everyMs;
1596
+
1597
+ nextDueAt = nextDueAt === undefined ? sourceNextDueAt : Math.min(nextDueAt, sourceNextDueAt);
1598
+ }
1599
+
1600
+ return nextDueAt;
1601
+ }
1602
+ `:"",fn=at.length>0,bn=`
1603
+ public constructor(state: ShardDOState, env: unknown) {
1604
+ super(state, env, {
1605
+ // Every writer this file builds spreads the ctxDbTuning() slice —
1606
+ // the user-facing ctx and all three admin/maintenance writers — so
1607
+ // the base class can drop its coarse invalidation backstop. Only the
1608
+ // emitter can know that; a hand-written subclass leaves this unset
1609
+ // and keeps the backstop.
1610
+ ctxDbCacheWired: true,
1611
+ ...(config.maxRelationKeys === undefined ? {} : { maxRelationKeys: config.maxRelationKeys }),
1612
+ ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1613
+ ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1614
+ });
1615
+ ${ae?`
1616
+ const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1617
+ const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1618
+
1619
+ return source !== undefined && source.refresh !== "manual";
1620
+ });
1621
+
1622
+ if (autoSourced) {
1623
+ void this.scheduleSourcePoll();
1624
+ }
1625
+ `:""}${fn?`
1626
+ if (LUNORA_TTL_SWEEPS.length > 0) {
1627
+ void this.scheduleTtlSweep();
1628
+ }
1629
+ `:""} }
1630
+
1631
+ protected override isCacheableQuery(functionPath: string): boolean {
1632
+ // NOT \`kind === "query"\` alone. A cache hit answers without running
1633
+ // \`handleRpc\`, so the \`internal\` refusal at the top of it is skipped —
1634
+ // and an \`internalQuery\` primed by a trusted system dispatch was then
1635
+ // served to an anonymous client that the refusal would have 404'd.
1636
+ //
1637
+ // \`perDispatch\` is the same argument one layer out: the procedure's
1638
+ // own \`.use()\` chain runs INSIDE \`handleRpc\`, so a hit skips it too.
1639
+ // A \`.use(rateLimit(...))\` query was therefore charged once and then
1640
+ // served from the memo to every later request — each of which still
1641
+ // reached this Durable Object and still cost it a dispatch, so only
1642
+ // the accounting was skipped. Metering and memoizing are mutually
1643
+ // exclusive; the author asking for the first is choosing against the
1644
+ // second.
1645
+ const registered = LUNORA_FUNCTIONS[functionPath];
1646
+
1647
+ return registered?.kind === "query" && registered.visibility !== "internal" && registered.perDispatch !== true;
1648
+ }
1649
+
1650
+ protected override isPaidFunction(functionPath: string): boolean {
1651
+ return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1652
+ }
1653
+ `,yn=Qe?`
1654
+ const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1655
+ ${w.tables.map(m=>` facade[${JSON.stringify(m.name)}] = bindTableFacade(db, ${JSON.stringify(m.name)});`).join(`
1656
+ `)}
1657
+ `:"",wn=`${ue.build}${G.build}${_.build}${z.build}${he.build}
1658
+ const secrets = createSecrets(env);
1659
+ `,kn=`${ue.contextField}${G.contextField}${_.contextField}${te.contextField}${z.contextField}${he.contextField}
1660
+ secrets,`,xn=te.build,ct=y||g||d||x||R||$,vn=ct?`
1661
+ // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1662
+ // and attached only for an \`action\` so query/mutation ctx never carry them.
1663
+ if (isAction) {
1664
+ ${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(`
1665
+ `)}
1666
+ }
1667
+ `:"",Sn=ct?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1668
+ `:"";return`${S}${ke.join(`
1669
+ `)}
1670
+
1671
+ type FunctionKind = "action" | "mutation" | "query";
1672
+
1673
+ interface FunctionReference {
1674
+ __lunoraRef: string;
1675
+ }
1676
+
1677
+ /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1678
+ const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(Ft,void 0,4)};
1679
+
1680
+ /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1681
+ 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)};
1682
+
1683
+ /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1684
+ const LUNORA_TABLE_COLUMNS: Record<
1685
+ string,
1686
+ Array<{
1687
+ bucket?: string;
1688
+ enumValues?: string[];
1689
+ isStorage?: boolean;
1690
+ name: string;
1691
+ nullable?: boolean;
1692
+ onDelete?: "cascade" | "restrict" | "set null";
1693
+ optional: boolean;
1694
+ pk?: boolean;
1695
+ ref?: string;
1696
+ type: string;
1697
+ }>
1698
+ > = ${JSON.stringify(qt,void 0,4)};
1699
+
1700
+ /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1701
+ const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(jt,void 0,4)};
1702
+
1703
+ /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1704
+ const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(at,void 0,4)};
1705
+
1706
+ /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1707
+ const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(Ot,void 0,4)};
1708
+
1709
+ /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1710
+ const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(It,void 0,4)};
1711
+
1712
+ /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1713
+ const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(et,void 0,4)};
1714
+ ${lt}
1715
+ /** 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. */
1716
+ const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(Ct,void 0,4)};
1717
+
1718
+ /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1719
+ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Dt,void 0,4)};
1720
+
1721
+ /** 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. */
1722
+ const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(Lt,void 0,4)};
1723
+ ${F}${J.constant}${Et}${Pt}${me}${Me}${pe}${Be}
1724
+ export interface ShardDOConfig {
1725
+ /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1726
+ cdc?: boolean;
1727
+ /** Ceiling on the join keys one relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
1728
+ maxRelationKeys?: number;
1729
+ /** 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. */
1730
+ reactiveCache?: boolean | { maxBytes?: number; maxEntries?: number };
1731
+ /** 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. */
1732
+ relationExistsPushDown?: "always" | "auto" | "never";
1733
+ /** 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. */
1734
+ observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1735
+ /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1736
+ scheduler?: (env: Record<string, unknown>) => unknown;
1737
+ 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}
1738
+ }
1739
+ ${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}
1740
+ // Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
1741
+ // referencing call fails loudly with a clear error instead of overflowing the
1742
+ // stack. Tracked across the awaited handler chain (one DO invocation is
1743
+ // single-threaded), so the counter reflects true nesting depth.
1744
+ const MAX_RUN_DEPTH = 32;
1745
+ let runDepth = 0;
1746
+
1747
+ const dispatchRun = async (
1748
+ expected: FunctionKind,
1749
+ functionPath: string,
1750
+ args: Record<string, unknown>,
1751
+ ctx: unknown,
1752
+ // The kind of the context making the call, and — for a mutation target — the
1753
+ // transaction wrapper to run it under. Both are supplied by \`buildCtx\`, which
1754
+ // is the only place that knows which dispatch this \`ctx\` belongs to. Widened
1755
+ // past \`FunctionKind\` because the registry also carries \`"stream"\`, and
1756
+ // \`undefined\` for a ctx built outside a registered function (admin, migration).
1757
+ callerKind?: "stream" | FunctionKind,
1758
+ runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
1759
+ ): Promise<unknown> => {
1760
+ // A query is read-only. The ctx object installs \`run*\` on every kind (one
1761
+ // shape, built once), so the TYPE is all that stops a query from writing —
1762
+ // and a cast walks straight past it, inside a subscription re-run that can
1763
+ // execute many times per write. Checked on the CALLER, before the registry
1764
+ // lookup, so \`ctx.runMutation\` from a query fails identically whatever it
1765
+ // aimed at.
1766
+ if (callerKind === "query" && expected !== "query") {
1767
+ throw new LunoraError(
1768
+ "RUN_KIND_FORBIDDEN",
1769
+ \`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: a query may only compose other queries (tried to run "\${functionPath}")\`,
1770
+ );
1771
+ }
1772
+
1773
+ const registered = LUNORA_FUNCTIONS[functionPath];
1774
+
1775
+ if (!registered) {
1776
+ throw new Error(\`unknown function: \${functionPath}\`);
1777
+ }
1778
+
1779
+ if (registered.kind !== expected) {
1780
+ throw new Error(\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: "\${functionPath}" is registered as a \${registered.kind}, not a \${expected}\`);
1781
+ }
1782
+
1783
+ if (runDepth >= MAX_RUN_DEPTH) {
1784
+ throw new LunoraError("RUN_DEPTH_EXCEEDED", \`ctx.run*: composition depth limit (\${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation\`);
1785
+ }
1786
+
1787
+ runDepth += 1;
1788
+
1789
+ try {
1790
+ // A mutation composed from an action (or an http action) is the shape the
1791
+ // docs prescribe for atomicity — "do the transactional reads and writes in
1792
+ // a mutation and call it from the action". It only holds if the composed
1793
+ // dispatch gets the same BEGIN/COMMIT span and single-writer gate the
1794
+ // top-level mutation path gets; without it every write autocommits and a
1795
+ // mid-handler throw leaves the earlier ones durable. A \`runMutation\` from
1796
+ // inside a mutation rides the enclosing span instead of opening a second
1797
+ // one (see \`runMutationTransaction\`).
1798
+ if (runTransactional) {
1799
+ return await runTransactional(async () => registered.handler(ctx, args));
1800
+ }
1801
+
1802
+ return await registered.handler(ctx, args);
1803
+ } finally {
1804
+ runDepth -= 1;
1805
+ }
1806
+ };
1807
+
1808
+ /**
1809
+ * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1810
+ * from the worker entry so wrangler binds it by name.
1811
+ */
1812
+ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1813
+ class extends ShardDOBase {${bn}
1814
+ private migrated = false;
1815
+
1816
+ public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
1817
+ const registered = LUNORA_FUNCTIONS[functionPath];
1818
+
1819
+ // Internal functions are reachable server-side only: via \`ctx.run*\`
1820
+ // composition, or a trusted system dispatch (scheduler/cron, marked by
1821
+ // \`isSystemDispatch()\`). A client RPC never carries that flag, so its
1822
+ // internals stay not-found and never leak across the external boundary.
1823
+ if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) {
1824
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
1825
+ }
1826
+
1827
+ this.ensureMigrated();
1828
+
1829
+ // \`headroom\`, when the caller supplied one, is threaded straight
1830
+ // through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
1831
+ // fallback (the racy shared-field read) entirely for THIS dispatch.
1832
+ // The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
1833
+ // \`handleRunAs\` don't mint their own and omit it, so they keep the
1834
+ // prior fallback behavior unchanged.
1835
+ //
1836
+ // \`scope\` is the reactive cache's per-dispatch read capture, threaded
1837
+ // the same way and for the same reason: the ctx-db read hooks resolve
1838
+ // their tracker at READ time, so binding them to the scope THIS
1839
+ // dispatch was handed is what keeps a concurrent query's reads out of
1840
+ // our dep set — and ours out of theirs. A dispatch with no scope (a
1841
+ // mutation, an action, a cache-less shard) builds unbound hooks that
1842
+ // stamp no deps.
1843
+ const ctx = this.buildCtx({ bookmarks, functionPath, headroom, scope, trusted: registered.lifecycle === "init" });
1844
+
1845
+ // A mutation's writes must commit all-or-nothing, so its dispatch runs
1846
+ // under \`runMutationTransaction\` — the ONE place that opens the span,
1847
+ // settles the deferred schedules and flushes the deferred deletes. The
1848
+ // same helper backs \`ctx.runMutation\` and \`runReactor\`, because a
1849
+ // mutation reached by composition is promised exactly these guarantees
1850
+ // and used to get none of them.
1851
+ //
1852
+ // The replay bookkeeping (idempotency dedup row + custom-mutator
1853
+ // watermark advance) commits INSIDE the span via
1854
+ // \`commitMutationBookkeeping\`, so the writes, the dedup row, and the
1855
+ // watermark are atomic — a crash can't leave the writes durable without
1856
+ // the replay guard. It is deliberately NOT in the shared helper: it is
1857
+ // per-REQUEST bookkeeping, and a composed sub-mutation has no request of
1858
+ // its own to record.
1859
+ if (registered.kind === "mutation") {
1860
+ return await this.runMutationTransaction(ctx, async () => {
1861
+ const value = await registered.handler(ctx, args);
1862
+
1863
+ this.commitMutationBookkeeping(value);
1864
+
1865
+ return value;
1866
+ });
1867
+ }
1868
+
1869
+ const result = await registered.handler(ctx, args);
1870
+
1871
+ // An action is not itself transactional, but \`ctx.runMutation\` runs its
1872
+ // submutations on THIS ctx, so anything they queued after their own
1873
+ // transaction settled lands here. A dispatch with nothing queued no-ops.
1874
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
1875
+
1876
+ return result;
1877
+ }
1878
+
1879
+ /**
1880
+ * Run one mutation handler with the atomicity every caller of a mutation is
1881
+ * promised: a BEGIN/COMMIT span (with the single-writer gate
1882
+ * \`ShardRunner.runInTransaction\` composes in front of it), scheduled jobs
1883
+ * held until that span commits, and the deferred object deletes flushed
1884
+ * only once it has.
1885
+ *
1886
+ * Shared by the three entry points that dispatch a mutation handler — the
1887
+ * top-level RPC, \`ctx.runMutation\` from an action or http action, and a
1888
+ * reactor — because the guarantee is a property of the mutation, not of how
1889
+ * it was reached. The docs tell users to put the transactional part in a
1890
+ * mutation and call it from the action precisely so that composition is
1891
+ * atomic.
1892
+ *
1893
+ * A \`ctx.runMutation\` issued from inside a mutation is NESTED: SQLite-in-DO
1894
+ * has no savepoints and \`runInTransaction\` rejects a second open, so it
1895
+ * rides the enclosing span, which also owns its commit and therefore its
1896
+ * scheduler flush.
1897
+ *
1898
+ * Both deferral windows are opened here and settled against the SAME
1899
+ * outcome. The delete window is what keeps a composed mutation's queued
1900
+ * object deletes off the caller's flush when it rolls back: \`ctx\` is
1901
+ * shared, so without a window the keys are indistinguishable from the
1902
+ * action's own and the action's flush destroys objects whose rows the
1903
+ * rollback put back.
1904
+ */
1905
+ private async runMutationTransaction<T>(ctx: unknown, work: () => Promise<T>): Promise<T> {
1906
+ const settleSchedules = beginDeferredSchedules(ctx as { scheduler?: unknown });
1907
+ // Synchronous and non-throwing (it only moves queue entries), so it can
1908
+ // settle first on every path and cannot mask the outcome.
1909
+ const settleDeletes = beginDeferredDeletes(ctx);
1910
+
1911
+ if (this.isInTransaction()) {
1912
+ try {
1913
+ const nested = await work();
1914
+
1915
+ settleDeletes(true);
1916
+ await settleSchedules(true);
1917
+
1918
+ return nested;
1919
+ } catch (error) {
1920
+ settleDeletes(false);
1921
+ await settleSchedules(false);
1922
+
1923
+ throw error;
1924
+ }
1925
+ }
1926
+
1927
+ let result: T;
1928
+
1929
+ try {
1930
+ result = await this.runInTransaction(work);
1931
+ } catch (error) {
1932
+ // The span rolled back, so the rows are gone and the jobs that were
1933
+ // to run "after I commit" must go with them. Dropping them is the
1934
+ // whole point of buffering: a persisted job for a write that never
1935
+ // landed fires against state that does not exist.
1936
+ //
1937
+ // The queued object deletes go the same way, and for a sharper
1938
+ // reason: the rows they were to clean up after are still there, and
1939
+ // an R2 delete cannot be undone.
1940
+ settleDeletes(false);
1941
+ await settleSchedules(false);
1942
+
1943
+ throw error;
1944
+ }
1945
+
1946
+ // Committed, so this span's queued keys join whatever the flush below
1947
+ // (or an enclosing span's) will drain.
1948
+ settleDeletes(true);
1949
+
1950
+ // Committed. Schedules first and AWAITED: \`runAfter(0, ...)\` is
1951
+ // documented as the deterministic equivalent of an \`afterCommit\` hook,
1952
+ // so the job must be enqueued after the commit, and a failure to enqueue
1953
+ // it must be visible rather than swallowed.
1954
+ //
1955
+ // In a \`finally\`, because both halves of this are post-commit cleanup
1956
+ // and neither is allowed to cancel the other. \`settleSchedules\` drains
1957
+ // its whole queue and then rethrows what failed, so a SchedulerDO that
1958
+ // refused one job used to take the object cleanup down with it — the
1959
+ // rows were durably gone and their objects leaked with nothing logged.
1960
+ try {
1961
+ await settleSchedules(true);
1962
+ } finally {
1963
+ // Then the objects whose rows are now durably gone. Deliberately AFTER
1964
+ // the span, never inside it: an R2 delete cannot roll back, so a delete
1965
+ // issued from within a transaction that later aborts destroys data the
1966
+ // surviving row still points at.
1967
+ //
1968
+ // \`flushDeferredDeletes\` never rejects — the mutation has already
1969
+ // succeeded, so a failed cleanup must not turn into a failed response.
1970
+ // A leaked object is reported through \`ctx.log\` instead, with its key.
1971
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
1972
+ }
1973
+
1974
+ return result;
1975
+ }
1976
+
1977
+ // Only a \`mutation\` may enter the base class's single-writer gate for
1978
+ // mutation-replay dedup — it is \`blockConcurrencyWhile\`, so gating an
1979
+ // action would stall every other dispatch on the shard for the length of
1980
+ // its outbound I/O, on nothing but a caller-supplied header. Unregistered
1981
+ // paths answer \`false\`; \`handleRpc\` above rejects them anyway.
1982
+ protected override isMutationFunction(functionPath: string): boolean {
1983
+ return LUNORA_FUNCTIONS[functionPath]?.kind === "mutation";
1984
+ }
1985
+
1986
+ // The scheduler the deferred-schedule outbox retries through. Only the
1987
+ // CONFIGURED one: falling back to \`schedulerStub\` would have an app with no
1988
+ // scheduler retry every entry against a thrower until the attempt ceiling
1989
+ // parked it, and there is nothing to park — an app with no scheduler has no
1990
+ // \`ctx.scheduler\` call that reached the buffer in the first place.
1991
+ protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
1992
+ return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
1993
+ }
1994
+ ${st.override}
1995
+ protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
1996
+ const registered = LUNORA_FUNCTIONS[functionPath];
1997
+
1998
+ if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
1999
+ return null;
2000
+ }
2001
+
2002
+ this.ensureMigrated();
2003
+
2004
+ const footprint = createReadFootprint();
2005
+ // Identity is threaded EXPLICITLY from the (deferred/interleaved)
2006
+ // subscription caller — never read from the shared per-request field
2007
+ // here — so a concurrent RPC can't leak its identity into this re-run.
2008
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange });
2009
+ const result = await registered.handler(ctx, args);
2010
+
2011
+ // Ranges come from THIS run's reads, never a shared field on the DO:
2012
+ // a deferred re-run interleaves with unrelated dispatches.
2013
+ return { ranges: footprint.ranges(), result, tables: footprint.tables };
2014
+ }
2015
+
2016
+ protected override executeStream(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
2017
+ const registered = LUNORA_FUNCTIONS[functionPath];
2018
+
2019
+ if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
2020
+ return null;
2021
+ }
2022
+
2023
+ this.ensureMigrated();
2024
+
2025
+ return {
2026
+ ...(registered.durable ? { durable: registered.durable as { ttlMs?: number } } : {}),
2027
+ // Identity threaded EXPLICITLY from the socket, exactly as
2028
+ // \`executeSubscription\` above: the iterator is pulled after this
2029
+ // frame returned, interleaved with unrelated dispatches, so
2030
+ // \`buildCtx\`'s per-request fallback would run an \`rls()\` /
2031
+ // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
2032
+ iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
2033
+ };
2034
+ }
2035
+ ${Ut}${Wt}${hn}${gn}
2036
+ protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor"): readonly string[] {
2037
+ return LUNORA_LIFECYCLE_HOOKS[event];
2038
+ }
2039
+ ${mn}
2040
+ // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
2041
+ // socket-terminated half of the same reactivity — and differs only in who
2042
+ // consumes the result: the base's \`dispatchReactors\` stores the digest as
2043
+ // the new baseline and the footprint as the "should I even re-run this"
2044
+ // gate, instead of pushing a frame down a socket.
2045
+ //
2046
+ // Dispatched through \`runMutationTransaction\` because a reactor handler is
2047
+ // a mutation: its writes must commit all-or-nothing, the jobs it schedules
2048
+ // must wait for that commit, and the objects its row deletes orphaned must
2049
+ // be flushed once it lands. Safe to open a span here: the refresh drain
2050
+ // runs OUTSIDE any dispatch transaction (it is post-flush background work),
2051
+ // so this never nests.
2052
+ //
2053
+ // NO identity is threaded, and the ctx is built \`trusted\`. A reactor fires
2054
+ // because data moved, not because anyone asked, so there is no user for RLS
2055
+ // to scope to — it runs in the same system tier as migrations and the
2056
+ // external-source poll loop. Inheriting the shared per-request identity
2057
+ // would instead run an app's reactor as whichever user happened to write
2058
+ // last, which is worse than running it as nobody.
2059
+ protected override async runReactor(functionPath: string, previousDigest?: string): Promise<{ digest: string; ran: boolean; tables: readonly string[] } | undefined> {
2060
+ const registered = LUNORA_FUNCTIONS[functionPath];
2061
+
2062
+ if (!registered || registered.kind !== "mutation") {
2063
+ return undefined;
2064
+ }
2065
+
2066
+ this.ensureMigrated();
2067
+
2068
+ const footprint = createReadFootprint();
2069
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), onRead: footprint.onRead, onReadRange: footprint.onReadRange, trusted: true });
2070
+ const outcome = (await this.runMutationTransaction(ctx, async () =>
2071
+ registered.handler(ctx, { previousDigest } as unknown as Record<string, unknown>),
2072
+ )) as {
2073
+ digest: string;
2074
+ ran: boolean;
2075
+ };
2076
+
2077
+ return { digest: outcome.digest, ran: outcome.ran, tables: [...footprint.tables] };
2078
+ }
2079
+
2080
+
2081
+ protected override tableRefs(table: string): Record<string, string> | undefined {
2082
+ return LUNORA_TABLE_REFS[table];
2083
+ }
2084
+
2085
+ protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> {
2086
+ return LUNORA_TABLE_INDEXES[table] ?? [];
2087
+ }
2088
+
2089
+ protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> {
2090
+ return LUNORA_TTL_SWEEPS;
2091
+ }
2092
+
2093
+ protected override tableColumns(table: string): Array<{
2094
+ bucket?: string;
2095
+ enumValues?: string[];
2096
+ isStorage?: boolean;
2097
+ name: string;
2098
+ nullable?: boolean;
2099
+ onDelete?: "cascade" | "restrict" | "set null";
2100
+ optional: boolean;
2101
+ pk?: boolean;
2102
+ ref?: string;
2103
+ type: string;
2104
+ }> {
2105
+ return LUNORA_TABLE_COLUMNS[table] ?? [];
2106
+ }
2107
+
2108
+ protected override storageColumns(): Record<string, string[]> {
2109
+ return LUNORA_STORAGE_COLUMNS;
2110
+ }
2111
+
2112
+ protected override rlsMetadata(): RlsPoliciesResult {
2113
+ return LUNORA_RLS_METADATA;
2114
+ }
2115
+
2116
+ protected override maskMetadata(): MaskPoliciesResult {
2117
+ return LUNORA_MASK_METADATA;
2118
+ }
2119
+
2120
+ protected override storageRulesMetadata(): StorageRulesResult {
2121
+ return LUNORA_STORAGE_RULES;
2122
+ }
2123
+
2124
+ protected override studioFeatures(): StudioFeaturesResult {
2125
+ return LUNORA_STUDIO_FEATURES;
2126
+ }
2127
+ ${J.evaluateOverride}${J.subscriptionOverride}${_t}${Mt}
2128
+ protected override advisories(): AdvisoryFinding[] {
2129
+ return LUNORA_ADVISORIES;
2130
+ }
2131
+
2132
+ protected override advisorProcedures(): AdvisorProcedure[] {
2133
+ return LUNORA_ADVISOR_PROCEDURES;
2134
+ }
2135
+
2136
+ ${ln}
2137
+
2138
+ protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
2139
+ this.ensureMigrated();
2140
+
2141
+ // Falls back to the framework's reserved re-projection backfill
2142
+ // (\`__lunora_reproject__<table>\`), which rewrites rows whose
2143
+ // v.bigint()/v.bytes() columns are still stored in the pre-projection
2144
+ // tagged form. Built here rather than at module scope because it
2145
+ // needs this shard's \`sql\` handle to tell a legacy row from a
2146
+ // current one.
2147
+ const migration = LUNORA_MIGRATIONS[args.id] ?? buildReprojectionMigration(args.id, schema as unknown as SchemaLike, this.sql as SqlExec);
2148
+
2149
+ if (!migration) {
2150
+ throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
2151
+ }
2152
+
2153
+ ${Q()}
2154
+
2155
+ return runDataMigration({
2156
+ batchSize: args.batchSize,
2157
+ direction: args.direction,
2158
+ dryRun: args.dryRun,
2159
+ maxBatches: args.maxBatches,
2160
+ migration: migration as unknown as DataMigrationLike,
2161
+ // Flush after each batch so live migrationStatus subscribers see
2162
+ // progress mid-run (the base method records the reserved state
2163
+ // table the raw-SQL progress write is invisible to the tracker).
2164
+ onBatch: () => this.flushMigrationProgress(),
2165
+ sql: this.sql as SqlExec,
2166
+ writer,
2167
+ });
2168
+ }
2169
+
2170
+ protected override async runShardWrite(args: RunShardWriteArgs, headroom?: TransactionHeadroomTracker): Promise<RunShardWriteResult> {
2171
+ const definition = (schema as unknown as SchemaLike).tables[args.table];
2172
+
2173
+ if (!definition) {
2174
+ throw new LunoraError("UNKNOWN_TABLE", \`unknown table: \${args.table}\`, { status: 404 });
2175
+ }
2176
+
2177
+ // \`.global()\` tables live in D1, not this DO's SQLite — editing them
2178
+ // here would corrupt nothing but would fail confusingly, so reject up
2179
+ // front with a clear code the studio can surface.
2180
+ if (definition.shardMode?.kind === "global") {
2181
+ throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", \`table "\${args.table}" is global; edit it through D1, not the shard\`, { status: 400 });
2182
+ }
2183
+
2184
+ this.ensureMigrated();
2185
+
2186
+ ${Q("headroom ?? this.transactionHeadroom()")}
2187
+
2188
+ if (args.op === "insert") {
2189
+ const id = await writer.insert(args.table, args.doc ?? {});
2190
+
2191
+ return { id, op: "insert" };
2192
+ }
2193
+
2194
+ // Every by-id op PINS \`args.table\`. Unpinned, \`locateRowById\` probes
2195
+ // every non-global table for the id, so a request naming table A with an
2196
+ // id belonging to table B locates and mutates B's row — the by-id IDOR
2197
+ // the per-table \`ctx.db.<table>\` facade pins against. Pinning also stops
2198
+ // an absent row falling through to the \`.global()\` D1 twin, though that
2199
+ // branch is already unreachable here: \`adminWriter\` is built without a
2200
+ // \`globalDb\`, so a miss throws \`NOT_FOUND\` either way.
2201
+ if (args.op === "delete") {
2202
+ await writer.delete(args.id ?? "", args.table);
2203
+
2204
+ return { id: args.id ?? null, op: "delete" };
2205
+ }
2206
+
2207
+ if (args.op === "replace") {
2208
+ await writer.replace(args.id ?? "", args.doc ?? {}, args.table);
2209
+
2210
+ return { id: args.id ?? null, op: "replace" };
2211
+ }
2212
+
2213
+ await writer.patch(args.id ?? "", args.doc ?? {}, args.table);
2214
+
2215
+ return { id: args.id ?? null, op: "patch" };
2216
+ }
2217
+
2218
+ // The base \`ShardDO\` cannot build a schema-aware writer, so its
2219
+ // \`runShardExport\`/\`runShardImport\` return \`[]\` and \`{inserted:{}}\`.
2220
+ // Those are success-shaped: an empty export is what a correct export of
2221
+ // an empty shard looks like, so a backup of a populated sharded schema
2222
+ // reported success and wrote nothing, and an import reported success and
2223
+ // dropped every row. Overriding both here is what makes the two admin
2224
+ // RPCs real for a \`.shardBy()\` table.
2225
+ //
2226
+ // NOTE: the admin export RPC is not paginated — \`parseExportShardArgs\`
2227
+ // takes \`tables\`/\`batchSize\` but no cursor, and the coordinator issues
2228
+ // one call per shard — so the rows are collected into a single response.
2229
+ // \`batchSize\` bounds the SQLite scan page, not the reply. A shard holding
2230
+ // more rows than fit in the DO's memory budget will therefore fail the
2231
+ // export rather than stream it. That is a loud failure where the bug this
2232
+ // replaces was a silent empty one, but a cursor on the RPC is what makes
2233
+ // this a complete backup path for large shards.
2234
+ protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
2235
+ this.ensureMigrated();
2236
+
2237
+ ${Q()}
2238
+
2239
+ const rows: ExportRow[] = [];
2240
+
2241
+ // \`exportShardRows\` walks in keyset batches so a large table does not
2242
+ // materialize at once inside the generator; the admin RPC's response
2243
+ // is a single array, so it is collected here rather than streamed.
2244
+ for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, { batchSize: args.batchSize, tables: args.tables })) {
2245
+ rows.push(row);
2246
+ }
2247
+
2248
+ return rows;
2249
+ }
2250
+
2251
+ protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
2252
+ this.ensureMigrated();
2253
+
2254
+ ${Q()}
2255
+
2256
+ // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
2257
+ // database's \`_id\`s carry across verbatim and every foreign key
2258
+ // referencing them stays valid without a second remapping pass.
2259
+ return importShardRows(writer, schema as unknown as SchemaLike, { rows: args.rows, startLine: args.startLine });
2260
+ }
2261
+
2262
+ protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
2263
+ this.ensureMigrated();
2264
+
2265
+ ${Q()}
2266
+
2267
+ // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2268
+ // but the shard writer from \`createShardCtxDb\` always defines it.
2269
+ if (!writer.rankBefore) {
2270
+ throw new LunoraError("NOT_IMPLEMENTED", "rankBefore is unavailable on the shard writer", { status: 500 });
2271
+ }
2272
+
2273
+ return writer.rankBefore(args.table, args.index, {
2274
+ partitionKey: args.partitionKey,
2275
+ rowId: args.rowId,
2276
+ sortValues: args.sortValues,
2277
+ });
2278
+ }
2279
+
2280
+ protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
2281
+ this.ensureMigrated();
2282
+
2283
+ ${Q()}
2284
+
2285
+ // \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2286
+ // but the shard writer from \`createShardCtxDb\` always defines it — it
2287
+ // derives the edge set from this app's schema.
2288
+ if (!writer.related) {
2289
+ throw new LunoraError("NOT_IMPLEMENTED", "findRelated is unavailable on the shard writer", { status: 500 });
2290
+ }
2291
+
2292
+ return writer.related(
2293
+ { id: args.id, table: args.table },
2294
+ { cursor: args.cursor, depth: args.depth, direction: args.direction, edges: args.edges, limit: args.limit },
2295
+ );
2296
+ }
2297
+
2298
+ protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
2299
+ this.ensureMigrated();
2300
+
2301
+ ${Q()}
2302
+
2303
+ // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2304
+ // but the shard writer from \`createShardCtxDb\` always defines it. The sort
2305
+ // directions live in the schema's rankIndex, so the shard reads them itself;
2306
+ // \`args.directions\` is only the coordinator's comparator hint and isn't forwarded.
2307
+ if (!writer.rankPageRows) {
2308
+ throw new LunoraError("NOT_IMPLEMENTED", "rankPage is unavailable on the shard writer", { status: 500 });
2309
+ }
2310
+
2311
+ return writer.rankPageRows(args.table, args.index, {
2312
+ after: args.after,
2313
+ cursor: args.cursor,
2314
+ partitionKey: args.partitionKey,
2315
+ take: args.take,
2316
+ });
2317
+ }
2318
+
2319
+ protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
2320
+ this.ensureMigrated();
2321
+
2322
+ ${Q()}
2323
+
2324
+ await applyCdcChanges(writer, args.changes);
2325
+
2326
+ return { applied: args.changes.length };
2327
+ }
2328
+
2329
+ protected override ensureMigrated(): void {
2330
+ if (this.migrated) {
2331
+ return;
2332
+ }
2333
+
2334
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ce} });
2335
+ this.migrated = true;
2336
+ }
2337
+ ${Ke?`
2338
+ protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
2339
+ // Migrations create the fts5 companions; without them every backfill
2340
+ // statement would raise "no such table" on a shard that has never
2341
+ // served a request.
2342
+ this.ensureMigrated();
2343
+
2344
+ return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
2345
+ }
2346
+ `:""}
2347
+ 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 {
2348
+ const env = (this.env ?? {}) as Record<string, unknown>;
2349
+ // The caller context this ctx runs under, resolved ONCE on one
2350
+ // discriminant. When the caller threads an explicit identity
2351
+ // (subscription seed / refresh / stream pull / shape resolve — all
2352
+ // deferred or interleaved), it is used by value and the shared
2353
+ // per-request fields are never read, because a concurrent RPC owns
2354
+ // them: a refresh in particular runs inside the writing dispatch's
2355
+ // \`flushChangedTables\`, BEFORE its \`endDispatch\`, so \`getCurrentIp()\`
2356
+ // there is the MUTATING caller's address. Otherwise (the synchronous
2357
+ // RPC dispatch path) it falls back to those fields as before.
2358
+ //
2359
+ // One expression, not one per field: three parallel ternaries on the
2360
+ // same discriminant is how \`ip\` came to be the only one still reading
2361
+ // the shared field.
2362
+ const caller: SubscriptionIdentity = options.identity ?? {
2363
+ identity: this.getCurrentIdentity(),
2364
+ ip: this.getCurrentIp(),
2365
+ userId: this.getCurrentUserId(),
2366
+ };
2367
+ const { identity, ip, userId } = caller;
2368
+ ${on}${de}${wn}${Le}${_e}${De}${Fe}
2369
+ // Which dispatch this ctx belongs to. Drives the two deferral facades
2370
+ // below and the \`ctx.run*\` caller guard; a ctx built for an
2371
+ // admin/lifecycle path has no registered function, and so no kind.
2372
+ const contextKind = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind;
2373
+ // \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
2374
+ // reaches through, and pending jobs live in the SchedulerDO — nothing the
2375
+ // CDC changelog records — so reading them must forfeit a delta resume.
2376
+ // The scheduler's own \`runAfter\`/\`runAt\`/\`cancel\` are writes and stay unstamped.
2377
+ const schedulerBase = markUnvouchableReads((config.scheduler?.(env) ?? schedulerStub) as SchedulerLike, options.onRead, ["get", "list"]);
2378
+ // \`ctx.scheduler.runAfter(0, ...)\` is documented as the deterministic
2379
+ // equivalent of an \`afterCommit\` hook, and the SchedulerDO persists the
2380
+ // job the moment it is called — so inside a mutation the call is BUFFERED
2381
+ // and replayed after the transaction commits (a rollback drops it).
2382
+ // Wrapped on the same dispatches as the deferred-delete queue and for the
2383
+ // same reason: \`ctx.runMutation\` hands the CALLER's ctx to the callee, so
2384
+ // a mutation reached from an action schedules through the action's ctx.
2385
+ // An action's own schedules stay immediate — the window is only open
2386
+ // while a transaction is (see \`runMutationTransaction\`).
2387
+ //
2388
+ // Every kind but \`query\` is wrapped, because \`runMutationTransaction\`
2389
+ // is installed on \`ctx.runMutation\` for every kind but \`query\`: a
2390
+ // STREAM ctx, and an admin/lifecycle ctx with no registered kind at all,
2391
+ // both get the BEGIN/COMMIT span for a mutation they compose, and used
2392
+ // to get it with the deferral missing — so that mutation's job reached
2393
+ // the SchedulerDO while its transaction was still open, and survived the
2394
+ // rollback. A query cannot host a mutation handler (\`dispatchRun\`
2395
+ // refuses it) and its ctx is built on the hot subscription path, so it
2396
+ // stays unwrapped.
2397
+ //
2398
+ // Wrapped OUTSIDE the read-stamping facade so \`get\`/\`list\` stay stamped.
2399
+ //
2400
+ // \`this.scheduleOutbox()\` is what keeps the buffer honest. Everything
2401
+ // between the COMMIT and the scheduler's acknowledgement is outside the
2402
+ // transaction, so a failure there leaves writes that are durable and a
2403
+ // job that exists nowhere — and the mutation's replay-dedup row committed
2404
+ // inside the span, so the client's retry is answered from cache and told
2405
+ // it succeeded. The outbox takes custody of each buffered call inside the
2406
+ // transaction and releases it once the scheduler has the job; what
2407
+ // survives is retried by \`pollScheduleOutbox\` on the shared poll alarm.
2408
+ const scheduler = contextKind === "query" ? schedulerBase : withDeferredSchedules(schedulerBase, this.scheduleOutbox());
2409
+ // Build the storage adapter once and share it between \`ctx.storage\`
2410
+ // and \`ctx.db.system._storage\` so both read the same R2 binding. The
2411
+ // \`storageStub\` fallback satisfies SystemReaderStorageLike structurally
2412
+ // (its \`list\`/\`getMetadata\` throw the "no storage configured" error).
2413
+ //
2414
+ // Wrapped BEFORE the split so both consumers share one stamping facade.
2415
+ // Only the methods that actually reach R2 are stamped: \`getUrl\` and
2416
+ // \`getSignedUrl\` build a URL from the configured base (and an HMAC) and
2417
+ // read nothing, and they are what handlers overwhelmingly call — stamping
2418
+ // them would forfeit resumes for a dependency that cannot move the result.
2419
+ // \`bucket\` IS stamped: it hands back a sub-facade this wrapper does not
2420
+ // reach, so the selection is the last point at which the read can be seen.
2421
+ const storage = markUnvouchableReads(asBucketStorage(config.storage?.(env) ?? storageStub) as SystemReaderStorageLike, options.onRead, [
2422
+ "bucket",
2423
+ "download",
2424
+ "getMetadata",
2425
+ "list",
2426
+ ]);
2427
+ // \`ctx.storage.deleteAfterCommit(key)\`, on every dispatch that can host
2428
+ // a MUTATION handler — which is not only a mutation dispatch:
2429
+ // \`ctx.runMutation\` hands the CALLER's ctx to the callee, so a mutation
2430
+ // reached from an action runs on the action's ctx. Wrapping mutations
2431
+ // alone made that composition throw a bare TypeError on a method the
2432
+ // handler's own type promises. Queries stay unwrapped: they cannot host
2433
+ // one, and their ctx is built on the hot subscription path.
2434
+ //
2435
+ // Every dispatch wrapped here also flushes (see \`handleRpc\` and
2436
+ // \`runReactor\`) — a queue nothing drains leaks silently, which is worse
2437
+ // than not having the method at all.
2438
+ //
2439
+ // Wrapped OUTSIDE the read-stamping facade so \`bucket(name)\` still
2440
+ // resolves through it and stays stamped, and applied only to
2441
+ // \`ctx.storage\` so \`ctx.db.system._storage\` (which shares the adapter
2442
+ // above) is untouched.
2443
+ const contextStorage = contextKind === "mutation" || contextKind === "action" ? withDeferredDeletes(storage) : storage;
2444
+ // \`ctx.log\`: the DO base builds the attributed logger (structured
2445
+ // fields + \`.with(...)\` child + trace correlation) and routes each call
2446
+ // to the optional \`observability\` sink. It also buffers the line (studio
2447
+ // Logs panel) and emits a structured console event the dev-server formats.
2448
+ //
2449
+ // Resolved BEFORE \`ctx.db\` below, because the database is wrapped in
2450
+ // auto-instrumentation that needs the sink, the trace anchor, and the
2451
+ // dispatch's wide-event handle.
2452
+ const observability = config.observability?.(env);
2453
+ const logFunctionPath = options.functionPath ?? "";
2454
+ const log = this.makeLogger(logFunctionPath, observability);
2455
+ const traceAnchor = this.resolveDispatchAnchor(Boolean(options.identity));
2456
+
2457
+ // \`ctx.span\`: the handle onto the DISPATCH's own span — the wide-event
2458
+ // surface. Attributes attached here accumulate for the whole request
2459
+ // and are folded into the one span it already emits, instead of
2460
+ // becoming N separate log lines. Shares \`traceAnchor\` with \`ctx.trace\`
2461
+ // so both write to the same trace.
2462
+ const span = this.makeDispatchSpan(traceAnchor, observability);
2463
+
2464
+ ${un} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
2465
+ // adds aggregate counters (call count, total time, per-operation
2466
+ // breakdown) to the wide event rather than a span per call, so a
2467
+ // handler making hundreds of queries stays readable. See
2468
+ // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
2469
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${sn}), logFunctionPath, traceAnchor, observability);
2470
+ ${yn}${qe}
2471
+
2472
+ // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
2473
+ // The trace anchor is threaded explicitly for the same reason \`identity\`
2474
+ // is — a deferred caller (a subscription re-run) must not inherit the
2475
+ // writing mutation's trace from the shared per-request field.
2476
+ const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
2477
+ const metrics = this.makeMetrics(logFunctionPath, observability);
2478
+ ${xn}
2479
+ // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
2480
+ // captured ONCE so the whole handler body sees a single stable value.
2481
+ // A \`query\` handler is re-run by every live subscription that reads it,
2482
+ // so \`Date.now()\` there flickers between re-evaluations. A \`mutation\`
2483
+ // handler does not replay under ordinary dispatch (an OCC conflict throws
2484
+ // to the caller rather than retrying internally), but one called from a
2485
+ // workflow step or queue consumer runs again when that step replays. Both
2486
+ // read time through \`ctx.now\` — the \`nondeterministic_query_mutation\`
2487
+ // advisor flags \`Date.now()\`. Actions may still use ambient \`Date.now()\`.
2488
+ const now = Date.now();
2489
+
2490
+ const ctx: Record<string, unknown> = {
2491
+ auth: {
2492
+ getIdentity: async () => identity ?? null,
2493
+ userId: userId ?? null,
2494
+ },
2495
+ db,
2496
+ // Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
2497
+ // \`traceparent\` propagation, so time spent in a downstream service
2498
+ // is visible and its spans join this trace. Degrades to the bare
2499
+ // global when no sink is configured.
2500
+ fetch: this.makeFetch(logFunctionPath, traceAnchor, observability),
2501
+ // A GETTER, not a plain field, so the reactive cache can tell a
2502
+ // handler that reads the caller's address from the majority that
2503
+ // never do. \`ctx.ip\` is per-request state the memo must be keyed
2504
+ // by — otherwise two anonymous callers share one entry and the
2505
+ // second is served the first's address — but keying every entry
2506
+ // by address would shard the cache per client for every query.
2507
+ // Reading it here marks the dispatch's scope; \`runCachedQuery\`
2508
+ // folds the address into the key for this function from then on.
2509
+ get ip() {
2510
+ options.scope?.markIpRead();
2511
+
2512
+ return ip;
2513
+ },
2514
+ log,
2515
+ metrics,
2516
+ now,${dn}
2517
+ scheduler,
2518
+ span,
2519
+ storage: contextStorage,
2520
+ trace,${cn}${Ie}${kn}${be}${Ee}${Pe}${ve}${ge}
2521
+ };
2522
+ ${Sn}${vn}
2523
+ ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx, contextKind);
2524
+ // The composed mutation runs under the SAME wrapper the top-level RPC
2525
+ // uses, so "do the transactional work in a mutation and call it from the
2526
+ // action" — the recipe the docs give for atomicity — actually is atomic.
2527
+ ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) =>
2528
+ dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx, contextKind, async (work) => this.runMutationTransaction(ctx, work));
2529
+ // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
2530
+ // its OWN context, built without the subscription's read-footprint
2531
+ // hooks — so its reads never enter this subscription's footprint and a
2532
+ // write to the tables it touched does not re-run us. Everything else is
2533
+ // inherited: \`functionPath\` (log/metric attribution), \`headroom\` (the
2534
+ // sub-query must not escape this dispatch's resource ceiling),
2535
+ // \`scope\` (the reactive-cache capture — an untracked sub-query's reads
2536
+ // must still be deps of the entry the OUTER query is memoized as, or
2537
+ // the memo goes stale), and — load-bearing — the resolved \`caller\` BY VALUE
2538
+ // (identity, userId AND ip). Omitting it would let \`buildCtx\` fall back
2539
+ // to the shared per-request fields, which a concurrent RPC may have
2540
+ // re-set, and an RLS-scoped sub-query would then read as the wrong user
2541
+ // from the wrong address. A tracked call keeps sharing \`ctx\` exactly as
2542
+ // before.
2543
+ ctx.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>, runOptions?: { untracked?: boolean }) =>
2544
+ dispatchRun(
2545
+ "query",
2546
+ reference.__lunoraRef,
2547
+ fnArgs,
2548
+ runOptions?.untracked === true
2549
+ ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, scope: options.scope })
2550
+ : ctx,
2551
+ contextKind,
2552
+ );
2553
+
2554
+ return ctx;
2555
+ }
2556
+ };
2557
+ `},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:T(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:T(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(`
2558
+ `),r=e.indexes.length>0?`, (t) => ({
2559
+ ${e.indexes.map(a=>Gr(a)).join(`
2560
+ `)}
2561
+ })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
2562
+ ${n}
2563
+ }${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 {};
2564
+ `;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(`
2565
+
2566
+ `),h=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
2567
+ `:"",s?`import type { Id } from "./dataModel.js";
2568
+ `:""].join("");return`${S}import { ${c.join(", ")} } from "${n.serverDrizzle}";
2569
+ ${h}
2570
+ ${d}
2571
+ `},xa=(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)}},va=e=>e?`${S}/**
2572
+ * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
2573
+ * forward it — wrangler binds only what the entry exports:
2574
+ *
2575
+ * \`export * from "./lunora/_generated/scheduler.js";\`
2576
+ *
2577
+ * A Vite-first (class-A) app needs no such line: the generated worker entry
2578
+ * forwards this module for you whenever it exists.
2579
+ */
2580
+ export { SchedulerDO } from "@lunora/scheduler";
2581
+ `:"",Sa=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(`
2582
+ `),r=n.length>0?`
2583
+ ${n}
2584
+ `:"",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(`
2585
+ `);return` ${JSON.stringify(i)}: [
2586
+ ${c}
2587
+ ],`}).join(`
2588
+ `),o=a.length>0?`
2589
+ ${a}
2590
+ `:"";return`${S}/**
2591
+ * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
2592
+ * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
2593
+ * shard; \`workflow\` is a \`WORKFLOW_*\` binding name whose durable workflow is
2594
+ * started fresh per fire. \`args\` are forwarded verbatim (a workflow's become
2595
+ * its \`params\`).
2596
+ */
2597
+ export interface LunoraCronJob {
2598
+ args: Record<string, unknown>;
2599
+ functionPath?: string;
2600
+ name: string;
2601
+ workflow?: string;
2602
+ }
2603
+
2604
+ /**
2605
+ * Deduplicated cron schedules — mirror of wrangler's \`triggers.crons\`. The
2606
+ * Lunora vite plugin keeps \`wrangler.jsonc\` in sync with this array.
2607
+ */
2608
+ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
2609
+
2610
+ /**
2611
+ * Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
2612
+ * looks up \`event.cron\` here and dispatches every job in the list.
2613
+ */
2614
+ export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${o}};
2615
+ `},Ra=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(`
2616
+ `),n=t.length>0?`
2617
+ ${t}
2618
+ `:"";return`${S}/**
2619
+ * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
2620
+ * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
2621
+ * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
2622
+ * mirrored into Vectorize for filtering.
2623
+ */
2624
+ export interface LunoraVectorIndex {
2625
+ dimensions?: number;
2626
+ field?: string;
2627
+ metadata?: ReadonlyArray<string>;
2628
+ metric?: "cosine" | "dot-product" | "euclidean";
2629
+ name: string;
2630
+ table: string;
2631
+ }
2632
+
2633
+ /**
2634
+ * Static registry of every vector index in the schema, sorted by name.
2635
+ * Vectorize cannot enumerate indexes at runtime, so the worker passes this to
2636
+ * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2637
+ */
2638
+ export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
2639
+ `},$a=e=>[...new Set(e.map(t=>t.cron))];export{ca as A,In as C,S as G,er as U,ua as a,pa as b,fa as c,Sa as d,ya as e,da as f,xa as g,ga as h,va as i,ma as j,ka as k,Ra as l,ba as m,$a as n,yr as o,wa as p,ha as q};