@lunora/codegen 1.0.0-alpha.16 → 1.0.0-alpha.161

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