@lunora/codegen 1.0.0-alpha.13 → 1.0.0-alpha.131

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