@lunora/codegen 1.0.0-alpha.148 → 1.0.0-alpha.149

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 (22) hide show
  1. package/dist/index.d.mts +22 -7
  2. package/dist/index.d.ts +22 -7
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/DEFAULT_TARGET-lPq34YeN.mjs +1 -0
  5. package/dist/packem_shared/{GENERATED_HEADER-D-zn2qzV.mjs → GENERATED_HEADER--PCtJMQc.mjs} +1 -1
  6. package/dist/packem_shared/{MUTATORS_FILENAME-BKSzaCkq.mjs → MUTATORS_FILENAME-DHX1qUP5.mjs} +1 -1
  7. package/dist/packem_shared/{OPENRPC_VERSION-C6usyZYe.mjs → OPENRPC_VERSION-C4UXIUyy.mjs} +1 -1
  8. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DazENDSB.mjs +9 -0
  9. package/dist/packem_shared/{SHAPES_FILENAME-D3N7xcEk.mjs → SHAPES_FILENAME-DhZ3JkkH.mjs} +1 -1
  10. package/dist/packem_shared/SchemaSnapshotParseError-yZc-1mxR.mjs +18 -0
  11. package/dist/packem_shared/{buildOpenApiDocument-CyoTgJNE.mjs → buildOpenApiDocument-D5xOB07T.mjs} +1 -1
  12. package/dist/packem_shared/{discoverFunctions-C29Tvxas.mjs → discoverFunctions-CXURzTDU.mjs} +1 -1
  13. package/dist/packem_shared/{discoverHttpRoutes-CFIXlUy4.mjs → discoverHttpRoutes-2XhMbeh5.mjs} +1 -1
  14. package/dist/packem_shared/{discoverSchema-CubSTjtY.mjs → discoverSchema-D5XGH2wu.mjs} +1 -1
  15. package/dist/packem_shared/{emit-DHDqyZ_P.mjs → emit-CXfWb_pY.mjs} +235 -234
  16. package/dist/packem_shared/{emitApp-B1pTKVES.mjs → emitApp-DcrQNgaz.mjs} +34 -8
  17. package/dist/packem_shared/parse-validator-CMV0eq2a.mjs +1 -0
  18. package/package.json +10 -10
  19. package/dist/packem_shared/DEFAULT_TARGET-BvzxeWRZ.mjs +0 -1
  20. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BOb60wCS.mjs +0 -9
  21. package/dist/packem_shared/SchemaSnapshotParseError-BA80Pxar.mjs +0 -18
  22. package/dist/packem_shared/parse-validator-Q58kladC.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{agentComponent as ct}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as xn,hashSchemaSnapshot as vn}from"./SCHEMA_SNAPSHOT_VERSION-B1BUjuG5.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";const dt=[{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:`
1
+ import{agentComponent as dt}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as xn,hashSchemaSnapshot as vn}from"./SCHEMA_SNAPSHOT_VERSION-B1BUjuG5.mjs";import{s as $}from"./paths-C-9fwEgQ.mjs";const ut=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",serverCtxField:{field:`
2
2
  /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
3
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
4
  /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
@@ -15,60 +15,61 @@ import{agentComponent as ct}from"@lunora/agent/component";import{LunoraError as
15
15
  /**
16
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
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"}],Rn=dt,Sn=new Map(Rn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Zr=dt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),ut=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,$n=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),pt=e=>e.column!==void 0,Nn=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
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"}],Rn=ut,Sn=new Map(Rn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),eo=ut.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),pt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,$n=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),ht=e=>e.column!==void 0,Nn=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
19
19
  `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
20
20
  `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
21
21
  `;case"null":return`if (${t} !== null) return DEFER;
22
22
  `;default:return`if (typeof ${t} !== "string") return DEFER;
23
- `}},Tn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!ut.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
24
- `}},He=(e,t,n)=>{if(!pt(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if($n.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Nn(e.kind,t)};switch(e.kind){case"array":return An(e,t,n);case"literal":return Tn(e,t);case"object":return Cn(e,t,n);default:return}}},An=(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=He(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
23
+ `}},Tn=(e,t)=>e.stringMaxLength===void 0?"":`if (${t}.length > ${String(e.stringMaxLength)}) return DEFER;
24
+ `,An=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!pt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
25
+ `}},Ge=(e,t,n)=>{if(!ht(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if($n.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Nn(e.kind,t)+Tn(e,t)};switch(e.kind){case"array":return On(e,t,n);case"literal":return An(e,t);case"object":return Ln(e,t,n);default:return}}},On=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),s=`__arr${String(o)}`,i=`__i${String(o)}`,a=`__e${String(o)}`,c=Ge(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
25
26
  const ${s} = new Array(${t}.length);
26
27
  for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
27
28
  const ${a} = ${t}[${i}];
28
29
  ${c.pre}${s}[${i}] = ${c.out};
29
30
  }
30
- `;return{out:s,pre:d}},On=(e,t,n,r)=>{const o=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||pt(t))return;const{inner:i}=t;if(!i)return;const a=He(i,n,r);if(!a)return;const c=r.next(),d=`__has${String(c)}`,p=`__val${String(c)}`,m=`let ${d} = false;
31
+ `;return{out:s,pre:d}},In=(e,t,n,r)=>{const o=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||ht(t))return;const{inner:i}=t;if(!i)return;const a=Ge(i,n,r);if(!a)return;const c=r.next(),d=`__has${String(c)}`,p=`__val${String(c)}`,m=`let ${d} = false;
31
32
  let ${p};
32
33
  if (${n} !== undefined) {
33
34
  ${a.pre}${p} = ${a.out};
34
35
  ${d} = true;
35
36
  }
36
- `;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:m}}const s=He(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},In=new Set(Object.getOwnPropertyNames(Object.prototype)),ht=(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(In.has(s)){const p=`__f${String(n.next())}`;r+=`const ${p} = Object.hasOwn(${t}, ${a}) ? ${t}[${a}] : undefined;
37
- `,c=p}const d=On(s,i,c,n);if(!d)return;r+=d.pre,o.push(d.entry)}return{entries:o.join(", "),pre:r}},mt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
38
- `},Cn=(e,t,n)=>{const r=e.shape??{},o=ht(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
- ${mt(t)}${o.pre}const ${i} = { ${o.entries} };
40
- `;return{out:i,pre:a}},Ln=e=>{let t=0;const r=ht(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
37
+ `;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:m}}const s=Ge(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},Cn=new Set(Object.getOwnPropertyNames(Object.prototype)),mt=(e,t,n)=>{let r="";const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)return;const a=JSON.stringify(s);let c=`${t}[${a}]`;if(Cn.has(s)){const p=`__f${String(n.next())}`;r+=`const ${p} = Object.hasOwn(${t}, ${a}) ? ${t}[${a}] : undefined;
38
+ `,c=p}const d=In(s,i,c,n);if(!d)return;r+=d.pre,o.push(d.entry)}return{entries:o.join(", "),pre:r}},gt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
39
+ `},Ln=(e,t,n)=>{const r=e.shape??{},o=mt(r,t,n);if(!o)return;const s=n.next(),i=`__obj${String(s)}`,a=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
40
+ ${gt(t)}${o.pre}const ${i} = { ${o.entries} };
41
+ `;return{out:i,pre:a}},_n=e=>{let t=0;const r=mt(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
41
42
  if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
42
- ${mt("source")}${r.pre}return { ${r.entries} };
43
- }`},$=`// GENERATED by @lunora/codegen — do not edit.
43
+ ${gt("source")}${r.pre}return { ${r.entries} };
44
+ }`},S=`// GENERATED by @lunora/codegen — do not edit.
44
45
  // Run \`lunora codegen\` to regenerate.
45
46
 
46
- `,oe=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},gt=/^[A-Za-z_$][\w$]*$/u,_n=/^[\w./-]+$/u,f=(e,t)=>{if(!gt.test(e))throw new X("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ve=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>gt.test(e)?e:JSON.stringify(e),Y=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),En={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"},Dn=e=>{if(e===void 0)return"unknown";if(!ut.test(e))throw new X("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},A=e=>{const t=En[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 f(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Dn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>ft(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"}},ft=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?A(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${A(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>ft(n,r)).join("; ")} }`},bt=e=>e.kind==="optional"||!!e.column?.hasDefault,ae=e=>e.kind==="optional"&&e.inner?e.inner:e,Pn=e=>{f(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=ae(o),i=A(s),a=q(r);return bt(o)?` ${a}?: ${i};`:` ${a}: ${i};`}).join(`
47
+ `,ae=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},ft=/^[A-Za-z_$][\w$]*$/u,En=/^[\w./-]+$/u,b=(e,t)=>{if(!ft.test(e))throw new Z("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},He=e=>e.charAt(0).toUpperCase()+e.slice(1),j=e=>ft.test(e)?e:JSON.stringify(e),X=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:j(e),Dn={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"},Pn=e=>{if(e===void 0)return"unknown";if(!pt.test(e))throw new Z("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},A=e=>{const t=Dn[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 b(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Pn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>bt(r,o)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?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"}},bt=(e,t)=>{const n=j(e);if(t.kind==="optional"){const r=t.inner?A(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${A(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>bt(n,r)).join("; ")} }`},yt=e=>e.kind==="optional"||!!e.column?.hasDefault,se=e=>e.kind==="optional"&&e.inner?e.inner:e,Fn=e=>{b(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=se(o),i=A(s),a=j(r);return yt(o)?` ${a}?: ${i};`:` ${a}: ${i};`}).join(`
47
48
  `),n=t?`
48
49
  ${t}
49
50
  `:"";return`export interface Insert_${e.name} {
50
51
  _id?: Id<"${e.name}">;
51
- _creationTime?: number;${n}}`},Je="schema",eo=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([R,x])=>{const I=q(R);if(x.kind==="optional"){const T=x.inner?A(x.inner):"unknown";return` ${I}?: ${T};`}return` ${I}: ${A(x)};`}).join(`
52
- `),b=l?`
52
+ _creationTime?: number;${n}}`},Je="schema",to=e=>{for(const u of e.tables)b(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,k])=>{const N=j(x);if(k.kind==="optional"){const T=k.inner?A(k.inner):"unknown";return` ${N}?: ${T};`}return` ${N}: ${A(k)};`}).join(`
53
+ `),y=l?`
53
54
  ${l}
54
- `:"",k=u.commitOrdered===!0?`
55
+ `:"",R=u.commitOrdered===!0?`
55
56
  _commitSeq: number;`:"";return`export interface Doc_${u.name} {
56
57
  _id: Id<"${u.name}">;
57
- _creationTime: number;${k}${b}}`}).join(`
58
+ _creationTime: number;${R}${y}}`}).join(`
58
59
 
59
60
  `),o=e.tables.map(u=>` ${u.name}: Doc_${u.name};`).join(`
60
- `),s=e.tables.map(u=>{const l=u.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
61
- `),i=e.tables.map(u=>{const l=u.searchIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
62
- `),a=e.tables.map(u=>{const l=u.rankIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
63
- `),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
64
- `),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>Pn(u)).join(`
61
+ `),s=e.tables.map(u=>{const l=u.indexes.map(y=>JSON.stringify(y.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
62
+ `),i=e.tables.map(u=>{const l=u.searchIndexes.map(y=>JSON.stringify(y.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
63
+ `),a=e.tables.map(u=>{const l=u.rankIndexes.map(y=>JSON.stringify(y.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
64
+ `),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(y=>JSON.stringify(y.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
65
+ `),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>Fn(u)).join(`
65
66
 
66
67
  `),m=e.tables.map(u=>` ${u.name}: Insert_${u.name};`).join(`
67
- `),y=e.tables.map(u=>{const l=u.relations.map(b=>(f(b.table,"relation target table"),` ${q(b.name)}: ${b.kind==="one"?"OneRelation":"ManyRelation"}<"${b.table}">;`)).join(`
68
+ `),w=e.tables.map(u=>{const l=u.relations.map(y=>(b(y.table,"relation target table"),` ${j(y.name)}: ${y.kind==="one"?"OneRelation":"ManyRelation"}<"${y.table}">;`)).join(`
68
69
  `);return l?` ${u.name}: {
69
70
  ${l}
70
71
  };`:` ${u.name}: {};`}).join(`
71
- `);return E(`${$}export type TableName = ${t};
72
+ `);return _(`${S}export type TableName = ${t};
72
73
 
73
74
  /**
74
75
  * The tables **this app declared** — every {@link TableName} except those an add-on
@@ -157,14 +158,14 @@ export interface ManyRelation<Target extends keyof DataModel> {
157
158
 
158
159
  /** Per-table relation map keyed by accessor name. \`{}\` for tables with none. */
159
160
  export interface Relations {
160
- ${y}
161
+ ${w}
161
162
  }
162
163
 
163
- `,Je)},Fn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,yt=/^(?:\.\.?\/)*_generated\//u,wt=/\.[A-Za-z]\w*$/u,Mn=e=>e.replaceAll(Fn,(t,n)=>{const r=n.replace(yt,"./");return`import("${wt.test(r)?r:`${r}.js`}")`}),Bn=/import\("(?<spec>[^"]+)"\)/gu,st="node_modules/",jn=/^@types\//u,qn=e=>e.replaceAll(Bn,(t,n)=>{const r=n.lastIndexOf(st);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+st.length);return o===""||jn.test(o)?t:`import("${o}")`}),Wn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Un=/^(?:\.\.?\/)+/u,Kn=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("/")},Qn=(e,t)=>e.replaceAll(Wn,(n,r)=>{if(yt.test(r.replace(Un,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Kn(`${o}/${r}`)}`;return`import("${wt.test(i)?i:`${i}.js`}")`}),E=(e,t)=>Mn(Qn(qn(e),t)),Vn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Hn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Vn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Jn={flags:new Set(["/web"]),platform:new Set},kt=(e,t)=>t?e.replaceAll(Hn,(n,r,o)=>{const s=Jn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,Ge=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),xt=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:A(e.output),ze=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))},it=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=E(xe(s.args),s.filePath),a=E(xt(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
164
- `);return` ${q(N(n))}: {
164
+ `,Je)},Mn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,wt=/^(?:\.\.?\/)*_generated\//u,kt=/\.[A-Za-z]\w*$/u,Bn=e=>e.replaceAll(Mn,(t,n)=>{const r=n.replace(wt,"./");return`import("${kt.test(r)?r:`${r}.js`}")`}),jn=/import\("(?<spec>[^"]+)"\)/gu,it="node_modules/",qn=/^@types\//u,Wn=e=>e.replaceAll(jn,(t,n)=>{const r=n.lastIndexOf(it);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+it.length);return o===""||qn.test(o)?t:`import("${o}")`}),Un=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Kn=/^(?:\.\.?\/)+/u,Qn=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("/")},Vn=(e,t)=>e.replaceAll(Un,(n,r)=>{if(wt.test(r.replace(Kn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Qn(`${o}/${r}`)}`;return`import("${kt.test(i)?i:`${i}.js`}")`}),_=(e,t)=>Bn(Vn(Wn(e),t)),Hn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Gn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Hn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Jn={flags:new Set(["/web"]),platform:new Set},xt=(e,t)=>t?e.replaceAll(Gn,(n,r,o)=>{const s=Jn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),vt=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:A(e.output),Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},lt=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=_(xe(s.args),s.filePath),a=_(vt(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
165
+ `);return` ${j($(n))}: {
165
166
  ${o}
166
- };`};return ze(e).map(n=>t(n)).join(`
167
- `)},Gn=(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+=`
167
+ };`};return Ye(e).map(n=>t(n)).join(`
168
+ `)},zn=(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
169
  /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
169
170
  export interface WorkflowReference<Params = Record<string, unknown>> {
170
171
  readonly isLunoraWorkflow: true;
@@ -173,7 +174,7 @@ export interface WorkflowReference<Params = Record<string, unknown>> {
173
174
  readonly name: string;
174
175
  }
175
176
  `,e.length>0){const o=[...e].toSorted((a,c)=>a.exportName.localeCompare(c.exportName)),s=o.map(a=>` ${a.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${a.exportName}>>;`).join(`
176
- `),i=o.map(a=>` ${Y(a.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.exportName)} },`).join(`
177
+ `),i=o.map(a=>` ${X(a.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.exportName)} },`).join(`
177
178
  `);r+=`
178
179
  /** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
179
180
  export interface WorkflowsRef {
@@ -185,7 +186,7 @@ ${i}
185
186
  };
186
187
  `,n.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
187
188
  `)}if(t.length>0){const o=[...t].toSorted((a,c)=>a.exportName.localeCompare(c.exportName)),s=o.map(a=>` ${a.exportName}: WorkflowReference<AgentRunInput>;`).join(`
188
- `),i=o.map(a=>` ${Y(a.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.name)} },`).join(`
189
+ `),i=o.map(a=>` ${X(a.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.name)} },`).join(`
189
190
  `);r+=`
190
191
  /** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
191
192
  export interface AgentsRef {
@@ -196,7 +197,7 @@ export const agents: AgentsRef = {
196
197
  ${i}
197
198
  };
198
199
  `,n.push(`import type { AgentRunInput } from "@lunora/agent";
199
- `)}return{block:r,importLine:n.join("")}},zn=()=>Object.keys(ct().functions).toSorted((e,t)=>e.localeCompare(t)),vt=e=>new Set(e.filter(t=>N(t.filePath)==="agents").map(t=>t.exportName)),Yn=()=>new Set(Object.entries(ct().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Xn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=vt(t),o=Yn(),s=t.find(a=>N(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new X("INTERNAL",`@lunora/codegen: "agents:${s.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${s.exportName}" export in ${s.filePath}`);const i=zn().filter(a=>!r.has(a));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
200
+ `)}return{block:r,importLine:n.join("")}},Yn=()=>Object.keys(dt().functions).toSorted((e,t)=>e.localeCompare(t)),Rt=e=>new Set(e.filter(t=>$(t.filePath)==="agents").map(t=>t.exportName)),Xn=()=>new Set(Object.entries(dt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Zn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Rt(t),o=Xn(),s=t.find(a=>$(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new Z("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=Yn().filter(a=>!r.has(a));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
200
201
  `,lines:i.map(a=>` "agents:${a}": lunoraAgentRuntimeFunctions.${a} as unknown as RegisteredLunoraFunction,`).join(`
201
202
  `),prelude:`
202
203
  /**
@@ -205,13 +206,13 @@ ${i}
205
206
  * subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
206
207
  */
207
208
  const lunoraAgentRuntimeFunctions = agentComponent().functions;
208
- `}},Zn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>N(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new X("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
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"}},er=(e,t)=>{if(e.length===0)return[];const n=vt(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))},tr=(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}))},nr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=ze(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=E(d.chunkType??"unknown",d.filePath),m=E(xe(d.searchParams),d.filePath),y=E(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${p}, ${m}, ${y}>;`}).join(`
210
- `);return` ${q(N(i))}: {
209
+ `}},er=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>$(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new Z("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
210
+ `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},tr=(e,t)=>{if(e.length===0)return[];const n=Rt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},nr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>$(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}))},rr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=_(d.chunkType??"unknown",d.filePath),m=_(xe(d.searchParams),d.filePath),w=_(xe(d.params),d.filePath);return` ${j(d.exportName)}: HttpStreamRef<${p}, ${m}, ${w}>;`}).join(`
211
+ `);return` ${j($(i))}: {
211
212
  ${c}
212
213
  };`}).join(`
213
- `),o=n.map(([i,a])=>{const c=a.map(d=>` ${Y(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
214
- `);return` ${Y(N(i))}: {
214
+ `),o=n.map(([i,a])=>{const c=a.map(d=>` ${X(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
215
+ `);return` ${X($(i))}: {
215
216
  ${c}
216
217
  },`}).join(`
217
218
  `);return{block:`
@@ -223,26 +224,26 @@ ${r}
223
224
  export const httpStreams: HttpStreamsRef = {
224
225
  ${o}
225
226
  };
226
- `,body:r}},to=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:s=!1,workflows:i=[]}=e,a=oe(s),c=[...n.filter(v=>v.visibility!=="internal"),...er(t,n),...tr(o,n)],d=n.filter(v=>v.visibility==="internal"),p=it(c),m=it(d),y=nr(r),u=`${p}
227
+ `,body:r}},no=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:s=!1,workflows:i=[]}=e,a=ae(s),c=[...n.filter(C=>C.visibility!=="internal"),...tr(t,n),...nr(o,n)],d=n.filter(C=>C.visibility==="internal"),p=lt(c),m=lt(d),w=rr(r),u=`${p}
227
228
  ${m}
228
- ${y.body}`,l=Ge(u),b=l.length>0?`
229
+ ${w.body}`,l=ze(u),y=l.length>0?`
229
230
  import type { ${l.join(", ")} } from "./dataModel.js";
230
- `:"",k=p?`
231
+ `:"",R=p?`
231
232
  ${p}
232
- `:"",R=m?`
233
+ `:"",x=m?`
233
234
  ${m}
234
- `:"",x=Gn(i,t),I=`export interface ApiTypes {${k}}
235
+ `:"",k=zn(i,t),N=`export interface ApiTypes {${R}}
235
236
 
236
237
  export const api = anyApi as unknown as ApiTypes;
237
238
 
238
239
  /** Internal functions — callable only server-side via \`ctx.run*\`, never from a client. */
239
- export interface InternalApiTypes {${R}}
240
+ export interface InternalApiTypes {${x}}
240
241
 
241
242
  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 kt(`${$}import { anyApi } from "${a.client}";
244
- ${_}${x.importLine}${b}
245
- ${I}`,s)},no=e=>e?`${$}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
243
+ ${k.block}${w.block}`,T=[...N.includes("FunctionReference<")?["FunctionReference"]:[],...w.block===""?[]:["HttpStreamRef"]],D=T.length>0?`import type { ${T.join(", ")} } from "${a.client}";
244
+ `:"";return xt(`${S}import { anyApi } from "${a.client}";
245
+ ${D}${k.importLine}${y}
246
+ ${N}`,s)},ro=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
246
247
  import type { SeedClient, SeedClientOptions } from "@lunora/seed";
247
248
 
248
249
  import schema from "../schema.js";
@@ -259,9 +260,9 @@ import type { InsertModel } from "./dataModel.js";
259
260
  * const { posts } = await seed.posts((x) => x([10, 20]));
260
261
  */
261
262
  export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
262
- `:"",ro=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=oe(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,s=e.map(c=>{f(c.exportName,"shape export name");const d=o(c),p=E(xe(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 ${Ve(l)} {
264
- ${y}
263
+ `:"",oo=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=ae(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,s=e.map(c=>{b(c.exportName,"shape export name");const d=o(c),p=_(xe(c.args),c.filePath),m=Object.keys(c.args).length>0,w=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. */
264
+ export interface ${He(l)} {
265
+ ${w}
265
266
  /**
266
267
  * Share the optimistic-overlay gate with other collections + mutators on this
267
268
  * shard. Defaults to the shared per-shard registry, which is almost always what
@@ -285,7 +286,7 @@ ${y}
285
286
  * \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
286
287
  * \`scope\` to re-point the subscription.
287
288
  */
288
- export const ${c.exportName}CollectionOptions = (options: ${Ve(l)}): LunoraCollectionOptions<${d}> =>
289
+ export const ${c.exportName}CollectionOptions = (options: ${He(l)}): LunoraCollectionOptions<${d}> =>
289
290
  lunoraCollectionOptions<${d}>({
290
291
  client: options.client,
291
292
  ...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
@@ -298,22 +299,22 @@ export const ${c.exportName}CollectionOptions = (options: ${Ve(l)}): LunoraColle
298
299
 
299
300
  /** Live collection for the \`${c.exportName}\` shape, with its sync controls. */
300
301
  export const ${c.exportName}Collection = (
301
- options: ${Ve(l)},
302
+ options: ${He(l)},
302
303
  ): { checkpoints: CheckpointRegistry; collection: Collection<${d}, string>; scope: ${u} } => {
303
304
  const { checkpoints, config, scope } = ${c.exportName}CollectionOptions(options);
304
305
 
305
306
  return { checkpoints, collection: createCollection(config), scope };
306
307
  };`}).join(`
307
308
 
308
- `),i=Ge(s),a=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
309
- `:"";return`${$}import type { LunoraClient, SubscriptionError } from "${r.client}";
309
+ `),i=ze(s),a=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
310
+ `:"";return`${S}import type { LunoraClient, SubscriptionError } from "${r.client}";
310
311
  import { lunoraCollectionOptions } from "@lunora/db/collections";
311
312
  import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
312
313
  import type { Collection } from "@tanstack/db";
313
314
  import { createCollection } from "@tanstack/db";
314
315
  ${a}
315
316
  ${s}
316
- `},rr=(e,t)=>`lunora_${N(e)}_${String(t)}`,or=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
317
+ `},or=(e,t)=>`lunora_${$(e)}_${String(t)}`,ar=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
317
318
  const registered = LUNORA_FUNCTIONS[functionPath];
318
319
 
319
320
  if (!registered) {
@@ -321,45 +322,45 @@ ${s}
321
322
  }
322
323
 
323
324
  return (await registered.handler(context, args ?? {})) as R;
324
- };`,ar=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,rr(l,o.size))};for(const l of e)s(l.filePath);for(const l of t)s(l.filePath);for(const l of n)s(l.filePath);for(const l of r)s(l.filePath);const i=[...o.entries()].map(([l,b])=>{if(!_n.test(l))throw new X("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${b} from "../${l}.js";`}).join(`
325
- `),a=e.map(l=>` "${N(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
325
+ };`,sr=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,or(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,y])=>{if(!En.test(l))throw new Z("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${y} from "../${l}.js";`}).join(`
326
+ `),a=e.map(l=>` "${$(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
326
327
  `),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
+ `),d=n.map(l=>` "${$(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
328
329
  `),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 b=Ln(l.args);return b===void 0?void 0:`installCompiledValidatorMap(${o.get(l.filePath)??""}.${l.exportName}.args, ${b});`}).filter(l=>l!==void 0).join(`
331
- `);return{dispatchBody:y.length>0?`
332
- ${y}
330
+ `),m=n.map(l=>`${$(l.filePath)}:${l.exportName}`),w=[a,d].filter(l=>l.length>0).join(`
331
+ `),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const y=_n(l.args);return y===void 0?void 0:`installCompiledValidatorMap(${o.get(l.filePath)??""}.${l.exportName}.args, ${y});`}).filter(l=>l!==void 0).join(`
332
+ `);return{dispatchBody:w.length>0?`
333
+ ${w}
333
334
  `:"",importBlock:i.length>0?`${i}
334
335
 
335
336
  `:"",installBlock:u,migrationBody:c.length>0?`
336
337
  ${c}
337
338
  `:"",mutatorPaths:m,shapeBody:p.length>0?`
338
339
  ${p}
339
- `:""}},sr=e=>{const t=ze(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=E(xe(a.args),a.filePath),d=c==="{}"?"?":"",p=E(xt(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` ${q(N(o))}: {
340
+ `:""}},ir=e=>{const t=Ye(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=_(xe(a.args),a.filePath),d=c==="{}"?"?":"",p=_(vt(a),a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
341
+ `);return` ${j($(o))}: {
341
342
  ${i}
342
343
  };`}).join(`
343
- `);return{implementation:t.map(([o,s])=>{const i=N(o),a=s.map(c=>` ${Y(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
344
- `);return` ${Y(i)}: {
344
+ `);return{implementation:t.map(([o,s])=>{const i=$(o),a=s.map(c=>` ${X(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
345
+ `);return` ${X(i)}: {
345
346
  ${a}
346
347
  },`}).join(`
347
- `),types:n}},ir=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=ae(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))]},oo=({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:b=!1,identity:k,queues:R=[],schema:x,storageRuleBuckets:I=[],useUmbrella:T=!1,workflows:_=[]}={})=>{const v=oe(T),w=ir(x??{tables:[]},I).map(h=>JSON.stringify(h)).join(" | "),F=o?`import type { LunoraAi } from "@lunora/ai";
348
- `:"",se=o?`
349
- readonly ai: LunoraAi;`:"",M=y?`import type { LunoraPayment } from "@lunora/payment";
350
- `:"",ie=y?`
351
- readonly payments: LunoraPayment;`:"",le=b?`import type { X402Pay } from "@lunora/x402/pay";
352
- `:"",W=b?`
353
- readonly x402: X402Pay;`:"",C=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
354
- `:"",Z=t.length>0?`
348
+ `),types:n}},lr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=se(o);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&n.add(s.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},ao=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:o=!1,hasAnalytics:s=!1,hasBrowser:i=!1,hasVectors:a=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:p=!1,hasKv:m=!1,hasNotify:w=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:y=!1,hasX402:R=!1,identity:x,queues:k=[],schema:N,storageRuleBuckets:T=[],useUmbrella:D=!1,workflows:C=[]}={})=>{const f=ae(D),P=lr(N??{tables:[]},T).map(h=>JSON.stringify(h)).join(" | "),ie=o?`import type { LunoraAi } from "@lunora/ai";
349
+ `:"",F=o?`
350
+ readonly ai: LunoraAi;`:"",le=u?`import type { LunoraPayment } from "@lunora/payment";
351
+ `:"",ce=u?`
352
+ readonly payments: LunoraPayment;`:"",q=R?`import type { X402Pay } from "@lunora/x402/pay";
353
+ `:"",I=R?`
354
+ readonly x402: X402Pay;`:"",ee=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
355
+ `:"",L=t.length>0?`
355
356
  readonly containers: {${t.map(h=>`
356
357
  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=>(f(h.bindingName,`container binding "${h.bindingName}"`),` /** Durable Object namespace for the \`${h.exportName}\` container. */
358
- readonly ${h.bindingName}?: unknown;`)),..._.map(h=>(f(h.bindingName,`workflow binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` workflow. */
359
- readonly ${h.bindingName}?: unknown;`)),...R.map(h=>(f(h.bindingName,`queue binding "${h.bindingName}"`),` /** Queue producer binding for the \`${h.exportName}\` queue. */
360
- readonly ${h.bindingName}?: unknown;`)),...e.map(h=>(f(h.bindingName,`agent binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` agent. */
358
+ };`:"",v=[...o?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(h=>(b(h.bindingName,`container binding "${h.bindingName}"`),` /** Durable Object namespace for the \`${h.exportName}\` container. */
359
+ readonly ${h.bindingName}?: unknown;`)),...C.map(h=>(b(h.bindingName,`workflow binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` workflow. */
360
+ readonly ${h.bindingName}?: unknown;`)),...k.map(h=>(b(h.bindingName,`queue binding "${h.bindingName}"`),` /** Queue producer binding for the \`${h.exportName}\` queue. */
361
+ readonly ${h.bindingName}?: unknown;`)),...e.map(h=>(b(h.bindingName,`agent binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` agent. */
361
362
  readonly ${h.bindingName}?: unknown;`))].join(`
362
- `),S=`
363
+ `),Ae=`
363
364
 
364
365
  /**
365
366
  * This project's Cloudflare bindings, as far as codegen can discover them from
@@ -372,26 +373,26 @@ ${a}
372
373
  * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
373
374
  */
374
375
  export interface CloudflareBindings {
375
- readonly [binding: string]: unknown;${L?`
376
- ${L}`:""}
376
+ readonly [binding: string]: unknown;${v?`
377
+ ${v}`:""}
377
378
  }
378
379
 
379
380
  /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
380
- export type Env = CloudflareBindings;`,B=(h,qe,Ne)=>{const ne=Sn.get(h);if(ne!==void 0&&ne.tier!==Ne)throw new X("INTERNAL",`@lunora/codegen: capability "${h}" declares tier "${ne.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Ne}" context — update whichever is wrong.`);return qe?ne?.field??"":""},ce=B("kv",p,"every"),de=B("analytics",s,"every"),Ae=B("hyperdrive",c,"action"),Oe=B("browser",i,"action"),Ie=B("images",d,"action"),ue=B("pipelines",u,"action"),V=B("r2sql",l,"action"),P=(x?.vectorIndexes.length??0)>0,H=P?' | "vectors"':"",ee=P?`
381
- readonly vectors: VectorSearch<VectorIndexName>;`:"",pe=P?`
382
- readonly vectors: VectorSearchReader<VectorIndexName>;`:"",J=P?`import type { VectorSearch, VectorSearchReader } from "${v.server}";
381
+ export type Env = CloudflareBindings;`,M=(h,We,Ne)=>{const re=Sn.get(h);if(re!==void 0&&re.tier!==Ne)throw new Z("INTERNAL",`@lunora/codegen: capability "${h}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Ne}" context — update whichever is wrong.`);return We?re?.field??"":""},de=M("kv",m,"every"),ue=M("analytics",s,"every"),Oe=M("hyperdrive",d,"action"),Ie=M("browser",i,"action"),pe=M("images",p,"action"),V=M("pipelines",l,"action"),H=M("r2sql",y,"action"),W=a&&(N?.vectorIndexes.length??0)>0,G=W?' | "vectors"':"",te=W?`
382
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",J=W?`
383
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",ne=W?`import type { VectorSearch, VectorSearchReader } from "${f.server}";
383
384
  import type { VectorIndexName } from "./dataModel.js";
384
385
  `:"",U=r?`
385
386
  /** 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
+ readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",K=c?`
387
388
  /** 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
+ readonly flags: import("${f.flags}").LunoraFlags;`:"",Q=w?`
389
390
  /** 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
391
  readonly notify: import("@lunora/notify").LunoraNotify;
391
392
  /** 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;`:"",j=_.length>0,te=j?`import type { WorkflowHandle } from "@lunora/workflow";
393
+ readonly push: import("@lunora/notify").LunoraPush;`:"",B=C.length>0,Ce=B?`import type { WorkflowHandle } from "@lunora/workflow";
393
394
  import type * as lunoraWorkflowDefinitions from "../workflows.js";
394
- `:"",Ce=j?`
395
+ `:"",Le=B?`
395
396
 
396
397
  /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
397
398
  type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
@@ -402,43 +403,43 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
402
403
 
403
404
  /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
404
405
  export interface LunoraWorkflows {
405
- ${_.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
406
+ ${C.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
406
407
  `)}
407
- }`:"",ve=j?' | "workflows"':"",Re=j?`
408
- readonly workflows: LunoraWorkflows;`:"",he=R.length>0,Le=he?`import type { QueueProducer } from "@lunora/queue";
408
+ }`:"",ve=B?' | "workflows"':"",Re=B?`
409
+ readonly workflows: LunoraWorkflows;`:"",he=k.length>0,_e=he?`import type { QueueProducer } from "@lunora/queue";
409
410
  import type * as lunoraQueueDefinitions from "../queues.js";
410
- `:"",_e=he?`
411
+ `:"",Ee=he?`
411
412
 
412
413
  /** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
413
414
  type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
414
415
 
415
416
  /** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
416
417
  export interface LunoraQueues {
417
- ${R.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${h.exportName}>>;`).join(`
418
+ ${k.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${h.exportName}>>;`).join(`
418
419
  `)}
419
420
  }`:"",Se=he?`
420
- readonly queues: LunoraQueues;`:"",me=e.length>0,Ee=me?`import type { AgentHandle } from "@lunora/agent";
421
- `:"",De=me?`
421
+ readonly queues: LunoraQueues;`:"",me=e.length>0,De=me?`import type { AgentHandle } from "@lunora/agent";
422
+ `:"",Pe=me?`
422
423
 
423
424
  /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
424
425
  export interface LunoraAgents {
425
- ${e.map(h=>(f(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
426
+ ${e.map(h=>(b(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
426
427
  `)}
427
428
  }`:"",$e=me?`
428
- readonly agents: LunoraAgents;`:"",Pe=k?`import type { InferIdentity } from "${v.server}";
429
+ readonly agents: LunoraAgents;`:"",Fe=x?`import type { InferIdentity } from "${f.server}";
429
430
  import type * as lunoraIdentityContract from "../identity.js";
430
- `:"",Fe=k?`
431
+ `:"",Me=x?`
431
432
 
432
433
  /** 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
+ export type Identity = InferIdentity<typeof lunoraIdentityContract.${x.exportName}>;
434
435
 
435
436
  /** \`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> };`:"",ge=k?' | "auth"':"",fe=k?`
437
- readonly auth: NarrowedAuth;`:"",Me=k?", Identity":"",Be=n?`import type * as lunoraEnvContract from "../env.js";
438
- `:"",je=n?`
437
+ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",ge=x?' | "auth"':"",fe=x?`
438
+ readonly auth: NarrowedAuth;`:"",Be=x?", Identity":"",je=n?`import type * as lunoraEnvContract from "../env.js";
439
+ `:"",qe=n?`
439
440
 
440
441
  /** 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}>;`:"",be=n?' | "env"':"",ye=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${$}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${v.server}";
442
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",be=n?' | "env"':"",ye=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${S}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${f.server}";
442
443
  import type {
443
444
  ActionBuilder,
444
445
  ActionCtx as ActionCtxBase,
@@ -460,7 +461,7 @@ import type {
460
461
  Storage as StorageBase,
461
462
  TableReader,
462
463
  Validator,
463
- } from "${v.server}";
464
+ } from "${f.server}";
464
465
 
465
466
  import type {
466
467
  DatabaseReaderFacade as DatabaseReaderFacadeOf,
@@ -469,7 +470,7 @@ import type {
469
470
  TableReaderFacade as TableReaderFacadeOf,
470
471
  TableWriterFacade as TableWriterFacadeOf,
471
472
  WithArg as WithArgOf,
472
- } from "${v.serverDataModel}";
473
+ } from "${f.serverDataModel}";
473
474
 
474
475
  export type {
475
476
  AggregateOp,
@@ -492,10 +493,10 @@ export type {
492
493
  Where,
493
494
  WhereOf,
494
495
  WhereOperators,
495
- } from "${v.serverDataModel}";
496
+ } from "${f.serverDataModel}";
496
497
 
497
498
  import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
498
- ${J}${F}${M}${le}${C}${te}${Le}${Ee}${Pe}${Be}
499
+ ${ne}${ie}${le}${q}${ee}${Ce}${_e}${De}${Fe}${je}
499
500
  export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
500
501
 
501
502
  /**
@@ -555,7 +556,7 @@ export interface OrmWriter extends OrmReader {
555
556
  }
556
557
 
557
558
  /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
558
- export type StorageBucketName = ${w};${S}${Ce}${_e}${De}${Fe}${je}
559
+ export type StorageBucketName = ${P};${Ae}${Le}${Ee}${Pe}${Me}${qe}
559
560
 
560
561
  /**
561
562
  * Project-typed contexts. The base contexts from \`@lunora/server\` are
@@ -618,22 +619,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
618
619
  */
619
620
  type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
620
621
 
621
- export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${H}${ge}${be}> {
622
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${G}${ge}${be}> {
622
623
  readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
623
624
  readonly orm: OrmReader;
624
- readonly storage: ReadOnlyStorage<StorageBucketName>;${pe}${U}${ce}${K}${Q}${de}${ye}${fe}
625
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${J}${U}${de}${K}${Q}${ue}${ye}${fe}
625
626
  }
626
627
 
627
- export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${H}${ve}${ge}${be}> {
628
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${G}${ve}${ge}${be}> {
628
629
  readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
629
630
  readonly orm: OrmWriter;
630
- readonly storage: MutationStorage<StorageBucketName>;${ee}${U}${ce}${K}${Q}${de}${ye}${Re}${Se}${$e}${fe}
631
+ readonly storage: MutationStorage<StorageBucketName>;${te}${U}${de}${K}${Q}${ue}${ye}${Re}${Se}${$e}${fe}
631
632
  }
632
633
 
633
- export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${H}${ve}${ge}${be}> {
634
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${G}${ve}${ge}${be}> {
634
635
  readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
635
636
  readonly orm: OrmWriter;
636
- readonly storage: StorageBase<StorageBucketName>;${ee}${U}${se}${ie}${W}${Z}${ce}${K}${Q}${Ae}${Oe}${Ie}${de}${ue}${V}${ye}${Re}${Se}${$e}${fe}
637
+ readonly storage: StorageBase<StorageBucketName>;${te}${U}${F}${ce}${I}${L}${de}${K}${Q}${Oe}${Ie}${pe}${ue}${V}${H}${ye}${Re}${Se}${$e}${fe}
637
638
  }
638
639
 
639
640
  /**
@@ -666,7 +667,7 @@ export const internalAction = lunoraBuilders.internalAction as unknown as Intern
666
667
  /**
667
668
  * \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
668
669
  * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
669
- * \`${v.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
670
+ * \`${f.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
670
671
  * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
671
672
  * \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
672
673
  * no \`as unknown as\` cast. Runtime-identical to the package export; only the
@@ -691,7 +692,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
691
692
  * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
692
693
  * so the \`rls()\` chain discovers a policy authored either way the same.
693
694
  */
694
- export const definePolicy = createPolicyDsl<DataModel, Relations${Me}>();
695
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Be}>();
695
696
 
696
697
  /**
697
698
  * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
@@ -708,45 +709,45 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Me}>();
708
709
  export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
709
710
  id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
710
711
  };
711
- `},lr=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},ao=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=oe(i),{dispatchBody:p,importBlock:m,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=ar(n,r,o,s),k=Xn(t,n),R=Zn(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}
712
+ `},cr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${$(n.filePath)}:${n.exportName}`);return t},so=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=ae(i),{dispatchBody:p,importBlock:m,installBlock:w,migrationBody:u,mutatorPaths:l,shapeBody:y}=sr(n,r,o,s),R=Zn(t,n),x=er(a,n),k=[R.lines,x.lines].filter(v=>v.length>0).join(`
713
+ `);let N=p;k.length>0&&(N=p.length>0?`${p.trimEnd()}
714
+ ${k}
714
715
  `:`
715
- ${x}
716
- `);const T=lr(n),_=s.length>0?`import type { RegisteredShape } from "${d.server}";
717
- `:"",v=s.length>0?`
716
+ ${k}
717
+ `);const T=cr(n),D=s.length>0?`import type { RegisteredShape } from "${d.server}";
718
+ `:"",C=s.length>0?`
718
719
  /**
719
720
  * Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
720
721
  * The generated ShardDO's \`resolveShape\` override looks a shape up by name and
721
722
  * evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
722
723
  * \`shape_subscribe\` (reads-as-permissions).
723
724
  */
724
- export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${b}};
725
- `:"",w=l.length>0?`
725
+ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${y}};
726
+ `:"",f=l.length>0?`
726
727
  /**
727
728
  * Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
728
729
  * ShardDO's \`isCustomMutator\` override routes through the client-watermark push
729
730
  * protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
730
731
  */
731
- export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(S=>JSON.stringify(S)).join(", ")}]);
732
- `:"",F=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
733
- `:"",se=y.length>0?`
732
+ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(v=>JSON.stringify(v)).join(", ")}]);
733
+ `:"",P=w.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
734
+ `:"",ie=w.length>0?`
734
735
  /**
735
736
  * AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
736
737
  * onto its function's live \`.args\` object and consulted by the interpreted
737
738
  * parser as a zero-allocation fast path; anything it can't model is deferred.
738
739
  */
739
- ${y}
740
- `:"",M=sr(n),ie=M.types?`
741
- ${M.types}
742
- `:"",le=M.implementation?`
743
- ${M.implementation}
744
- `:"",W=Ge(M.types),C=W.length>0?`import type { ${W.join(", ")} } from "./dataModel.js";
745
- `:"",Z=c?"context":"_context",L=c?`${or}
746
-
747
- `:"";return kt(`${$}${m}${k.importLine}${R.importLine}${F}${_}import { LunoraError } from "${d.server}";
740
+ ${w}
741
+ `:"",F=ir(n),le=F.types?`
742
+ ${F.types}
743
+ `:"",ce=F.implementation?`
744
+ ${F.implementation}
745
+ `:"",q=ze(F.types),I=q.length>0?`import type { ${q.join(", ")} } from "./dataModel.js";
746
+ `:"",ee=c?"context":"_context",L=c?`${ar}
747
+
748
+ `:"";return xt(`${S}${m}${R.importLine}${x.importLine}${P}${D}import { LunoraError } from "${d.server}";
748
749
  import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
749
- ${C}
750
+ ${I}
750
751
  /**
751
752
  * Single registered function, narrowed to the shape \`handleRpc\` needs.
752
753
  * The real argument validators / return types are checked elsewhere — at
@@ -778,13 +779,13 @@ export interface RegisteredLunoraFunction {
778
779
  /** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
779
780
  visibility?: "internal" | "public";
780
781
  }
781
- ${k.prelude}${R.prelude}
782
+ ${R.prelude}${x.prelude}
782
783
  /**
783
784
  * Static dispatch table. The key matches the \`__lunoraRef\` the client
784
785
  * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
785
786
  */
786
- export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${I}};
787
- ${se}${v}${w}
787
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${N}};
788
+ ${ie}${C}${f}
788
789
  /**
789
790
  * Lifecycle manifest: the function paths the generated ShardDO dispatches when a
790
791
  * client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
@@ -795,10 +796,10 @@ ${se}${v}${w}
795
796
  * anonymous — all via system dispatch.
796
797
  */
797
798
  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(", ")}],
799
+ connect: [${T.connect.map(v=>JSON.stringify(v)).join(", ")}],
800
+ disconnect: [${T.disconnect.map(v=>JSON.stringify(v)).join(", ")}],
801
+ init: [${T.init.map(v=>JSON.stringify(v)).join(", ")}],
802
+ reactor: [${T.reactor.map(v=>JSON.stringify(v)).join(", ")}],
802
803
  };
803
804
 
804
805
  /**
@@ -829,10 +830,10 @@ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
829
830
  * with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
830
831
  * \`runAction\` but without re-stating the function path.
831
832
  */
832
- export interface Caller {${ie}}
833
+ export interface Caller {${le}}
833
834
 
834
835
  ${L}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
835
- export const createCaller = (${Z}: CallerCtx): Caller => ({${le}});
836
+ export const createCaller = (${ee}: CallerCtx): Caller => ({${ce}});
836
837
 
837
838
  /**
838
839
  * Single registered data migration, narrowed to the shape the per-shard runner
@@ -852,7 +853,7 @@ export interface RegisteredDataMigration {
852
853
  * shard DO's admin RPC and the CLI resolve migrations to run through this map.
853
854
  */
854
855
  export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
855
- `,i)},cr=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=ae(s);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},dr=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,s]of Object.entries(n.shape))ae(s).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},ur=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},pr=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},hr=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},mr=(e,t)=>{const n=ae(t),r={name:e,optional:bt(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=hr(n);return o!==void 0&&(r.enumValues=o),n.column?.notNull===!1&&(r.nullable=!0),r},gr=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(mr(o,s));t[n.name]=r}return t},fr=e=>e?{importFragment:"serveRelationFanout, ",override:`
856
+ `,i)},dr=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=se(s);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},ur=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,s]of Object.entries(n.shape))se(s).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},pr=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(o=>({fields:[...o.fields],name:o.name,type:"index",...o.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(o=>({fields:[o.field,...o.filterFields??[]],name:o.name,type:"search"})),...(n.geoIndexes??[]).map(o=>({fields:[o.field],name:o.name,type:"geo"})),...n.rankIndexes.map(o=>({fields:o.sortBy.map(s=>s.field),name:o.name,type:"rank"})),...n.vectorIndexes.map(o=>({fields:o.field===void 0?[]:[o.field],name:o.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},hr=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},mr=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},gr=(e,t)=>{const n=se(t),r={name:e,optional:yt(t),type:n.kind};n.kind==="id"&&n.tableName!==void 0&&(r.ref=n.tableName),n.kind==="storage"&&(r.isStorage=!0,n.bucket!==void 0&&(r.bucket=n.bucket));const o=mr(n);return o!==void 0&&(r.enumValues=o),n.column?.notNull===!1&&(r.nullable=!0),r},fr=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(gr(o,s));t[n.name]=r}return t},br=e=>e?{importFragment:"serveRelationFanout, ",override:`
856
857
  protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
857
858
  this.ensureMigrated();
858
859
 
@@ -860,7 +861,7 @@ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}}
860
861
 
861
862
  return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
862
863
  }
863
- `}:{importFragment:"",override:""},br=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
+ `}:{importFragment:"",override:""},yr=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
865
  const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
865
866
  // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
866
867
  // function path + trace id into createAi, which folds them into the
@@ -898,7 +899,7 @@ const aiStub: LunoraAi = {
898
899
  const ${e} = {
899
900
  ${s}
900
901
  }${r};
901
- `},D={build:"",configField:"",contextField:"",importLines:[],stub:""},yr=e=>e?{build:`
902
+ `},E={build:"",configField:"",contextField:"",importLines:[],stub:""},wr=e=>e?{build:`
902
903
  const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
903
904
  // KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
904
905
  // when a value changes — a subscription that read one can never be proven
@@ -912,24 +913,24 @@ ${s}
912
913
  ]);
913
914
  `,configField:`
914
915
  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"])}:D,wr=(e,t)=>e?{build:`
916
+ 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"])}:E,kr=(e,t)=>e?{build:`
916
917
  const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
917
918
  provider: () => config.flags?.(env),
918
919
  targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
919
920
  });
920
921
  `,configField:`
921
922
  flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
922
- flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:D,kr=e=>e?{build:`
923
+ flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:E,xr=e=>e?{build:`
923
924
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
924
925
  `,configField:"",contextField:`
925
926
  notify,
926
- push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,xr=e=>e?{build:`
927
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:E,vr=e=>e?{build:`
927
928
  const envConfig = lunoraEnvContract.${e.exportName}(env);
928
929
  `,configField:"",contextField:`
929
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,vr=e=>e?{build:`
930
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:E,Rr=e=>e?{build:`
930
931
  const access = accessFacade(identity, userId);
931
932
  `,configField:"",contextField:`
932
- access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,Rr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=a=>`
933
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:E,Sr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=a=>`
933
934
  const env = (this.env ?? {}) as Record<string, unknown>;
934
935
  const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
935
936
  provider: () => config.flags?.(env),
@@ -991,25 +992,25 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
991
992
 
992
993
  return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
993
994
  }
994
- `;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},Sr=e=>e?{build:`
995
+ `;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},$r=e=>e?{build:`
995
996
  const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
996
997
  const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
997
998
  `,configField:`
998
999
  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"]})}:D,$r=e=>e?{build:`
1000
+ 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"]})}:E,Nr=e=>e?{build:`
1000
1001
  const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
1001
1002
  const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
1002
1003
  `,configField:`
1003
1004
  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"])}:D,Nr=e=>e?{build:`
1005
+ 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"])}:E,Tr=e=>e?{build:`
1005
1006
  const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
1006
1007
  `,configField:`
1007
1008
  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"])}:D,Tr=e=>e?{build:`
1009
+ 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"])}:E,Ar=e=>e?{build:`
1009
1010
  const browser: Browser = config.browser ? config.browser(env) : browserStub;
1010
1011
  `,configField:`
1011
1012
  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"])}:D,Ar=e=>e?{build:`
1013
+ 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"])}:E,Or=e=>e?{build:`
1013
1014
  const r2sqlEnv = env as Record<string, unknown>;
1014
1015
  const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
1015
1016
  const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
@@ -1020,18 +1021,18 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
1020
1021
  ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
1021
1022
  : r2sqlStub;
1022
1023
  `,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"]})}:D,Or=e=>e?{build:`
1024
+ 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"]})}:E,Ir=e=>e?{build:`
1024
1025
  const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
1025
1026
  const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
1026
1027
  `,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"])}:D,so=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(f(s.exportName,`container export "${s.exportName}"`),f(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
1028
+ 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"])}:E,io=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(b(s.exportName,`container export "${s.exportName}"`),b(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
1028
1029
  export class ${s.className} extends LunoraContainer {
1029
1030
  public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1030
1031
  super(ctx, env, ${s.exportName}, "${s.exportName}"${n});
1031
1032
  }
1032
1033
  }
1033
1034
  `)).join(`
1034
- `),o=e.map(s=>s.exportName).join(", ");return`${$}/**
1035
+ `),o=e.map(s=>s.exportName).join(", ");return`${S}/**
1035
1036
  * Container-enabled Durable Object classes for the containers declared in
1036
1037
  * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
1037
1038
  * requires each \`containers[].class_name\` to be exported by the worker:
@@ -1049,7 +1050,7 @@ import { ${o} } from "../containers.js";
1049
1050
 
1050
1051
  export { ContainerProxy } from "@lunora/container/do";
1051
1052
 
1052
- ${r}`},Ir=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)f(r.exportName,`container export "${r.exportName}"`),f(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
1053
+ ${r}`},Cr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)b(r.exportName,`container export "${r.exportName}"`),b(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
1054
  `);return{build:`
1054
1055
  const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
1055
1056
  `,contextField:`
@@ -1058,14 +1059,14 @@ ${r}`},Ir=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
1058
1059
  const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
1059
1060
  ${n}
1060
1061
  ];
1061
- `}},io=e=>{if(e.length===0)return"";const t=e.map(r=>(f(r.exportName,`workflow export "${r.exportName}"`),f(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
1062
+ `}},lo=e=>{if(e.length===0)return"";const t=e.map(r=>(b(r.exportName,`workflow export "${r.exportName}"`),b(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
1062
1063
  export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
1063
1064
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1064
1065
  super(ctx, env, ${r.exportName}, "${r.exportName}");
1065
1066
  }
1066
1067
  }
1067
1068
  `)).join(`
1068
- `),n=e.map(r=>r.exportName).join(", ");return`${$}/**
1069
+ `),n=e.map(r=>r.exportName).join(", ");return`${S}/**
1069
1070
  * WorkflowEntrypoint classes for the workflows declared in
1070
1071
  * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
1071
1072
  * requires each \`workflows[].class_name\` to be exported by the worker:
@@ -1086,13 +1087,13 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
1086
1087
  /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
1087
1088
  type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
1088
1089
 
1089
- ${t}`},lo=e=>{if(e.length===0)return"";const n=e.filter(a=>a.voice).length>0,r=e.map(a=>{f(a.exportName,`agent export "${a.exportName}"`),f(a.className,`agent class "${a.className}"`);const c=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
1090
+ ${t}`},co=e=>{if(e.length===0)return"";const n=e.filter(a=>a.voice).length>0,r=e.map(a=>{b(a.exportName,`agent export "${a.exportName}"`),b(a.className,`agent class "${a.className}"`);const c=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
1090
1091
  export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1091
1092
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1092
1093
  super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
1093
1094
  }
1094
1095
  }
1095
- `;if(!a.voice)return c;const d=a.voiceClassName??"",p=a.voiceBindingName??"";f(d,`agent voice class "${d}"`);const m=`
1096
+ `;if(!a.voice)return c;const d=a.voiceClassName??"",p=a.voiceBindingName??"";b(d,`agent voice class "${d}"`);const m=`
1096
1097
  /** Voice-session Durable Object for the \`${a.exportName}\` agent (binding \`${p}\`). */
1097
1098
  export class ${d} extends VoiceSessionDO {
1098
1099
  public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
@@ -1100,7 +1101,7 @@ export class ${d} extends VoiceSessionDO {
1100
1101
  }
1101
1102
  }
1102
1103
  `;return`${c}${m}`}).join(`
1103
- `),o=e.map(a=>a.exportName).join(", ");return`${$}/**
1104
+ `),o=e.map(a=>a.exportName).join(", ");return`${S}/**
1104
1105
  * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
1105
1106
  * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
1106
1107
  * Workflow. Re-export them from your worker entry — wrangler requires each
@@ -1114,8 +1115,8 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
1114
1115
 
1115
1116
  import { ${o} } from "../agents.js";
1116
1117
 
1117
- ${r}`},co=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)f(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
1118
- `);return`${$}/**
1118
+ ${r}`},uo=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)b(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(`
1119
+ `);return`${S}/**
1119
1120
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
1120
1121
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
1121
1122
  * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
@@ -1129,7 +1130,7 @@ import { ${n} } from "../queues.js";
1129
1130
  export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
1130
1131
  ${r}
1131
1132
  };
1132
- `},Cr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)f(n.exportName,`workflow export "${n.exportName}"`),f(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
1133
+ `},Lr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)b(n.exportName,`workflow export "${n.exportName}"`),b(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
1133
1134
  `);return{build:`
1134
1135
  const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
1135
1136
  `,contextField:`
@@ -1138,7 +1139,7 @@ ${r}
1138
1139
  const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
1139
1140
  ${t}
1140
1141
  ];
1141
- `}},Lr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)f(n.exportName,`queue export "${n.exportName}"`),f(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
1142
+ `}},_r=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)b(n.exportName,`queue export "${n.exportName}"`),b(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
1142
1143
  `);return{build:`
1143
1144
  const queues = createQueueContext(env, LUNORA_QUEUES);
1144
1145
  `,contextField:`
@@ -1147,7 +1148,7 @@ ${t}
1147
1148
  const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
1148
1149
  ${t}
1149
1150
  ];
1150
- `}},_r=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)f(n.exportName,`agent export "${n.exportName}"`),f(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
1151
+ `}},Er=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)b(n.exportName,`agent export "${n.exportName}"`),b(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
1151
1152
  `);return{build:`
1152
1153
  const agents = createAgentContext(env, LUNORA_AGENTS);
1153
1154
  `,contextField:`
@@ -1156,28 +1157,28 @@ ${t}
1156
1157
  const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
1157
1158
  ${t}
1158
1159
  ];
1159
- `}},Rt=(e,t,n,r,o)=>({constant:`
1160
+ `}},St=(e,t,n,r,o)=>({constant:`
1160
1161
  ${o}
1161
1162
  const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1162
1163
  `,override:`
1163
1164
  protected override ${n}(): ${t} {
1164
1165
  return ${e};
1165
1166
  }
1166
- `}),Er=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 Rt("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. */")},Dr=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 Rt("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. */")},Pr=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
1167
+ `}),Dr=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return St("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Pr=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return St("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Fr=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
1167
1168
  const payments: LunoraPayment = config.payment
1168
1169
  ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
1169
1170
  : paymentStub;
1170
1171
  `,configField:`
1171
1172
  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:""},Fr=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
1173
+ 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:""},Mr=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
1173
1174
  const x402: X402Pay = config.x402
1174
1175
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1175
1176
  : x402Stub;
1176
1177
  `,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:""},Mr=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],uo=({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:b=!1,hasPipelines:k=!1,hasR2sql:R=!1,hasX402:x=!1,maskMetadata:I,mutators:T=[],queues:_=[],rlsMetadata:v,schema:w,schemaSnapshot:F,shapes:se=[],storageRules:M,studioFeatures:ie,useUmbrella:le=!1,workflows:W=[]})=>{const C=oe(le),Z=T.length>0,L=se.length>0,S=F===void 0?"":xn(F),B=F===void 0?"":`
1178
+ 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:""},Br=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],po=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:m=!1,hasImages:w=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:y=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasX402:k=!1,maskMetadata:N,mutators:T=[],queues:D=[],rlsMetadata:C,schema:f,schemaSnapshot:P,shapes:ie=[],storageRules:F,studioFeatures:le,useUmbrella:ce=!1,workflows:q=[]})=>{const I=ae(ce),ee=T.length>0,L=ie.length>0,v=P===void 0?"":xn(P),Ae=P===void 0?"":`
1178
1179
  /** 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(vn(F))}, json: ${JSON.stringify(S)} };
1180
- `,ce=F===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Ae,contextField:Oe,stub:Ie}=br(a),ue=vr(i),V=yr(u),P=wr(p,C.flags),H=Rr(s,p,C.flags),ee=kr(l),pe=xr(o),J=Sr(c),U=$r(y),K=Nr(m),Q=Tr(d),j=Ar(R),te=Or(k),{build:Ce,contextField:ve,importLines:Re,specs:he}=Lr(_),{build:Le,contextField:_e,importLines:Se,specs:me}=Ir(r,w.jurisdiction),{build:Ee,contextField:De,importLines:$e,specs:Pe}=Cr(W),{build:Fe,contextField:ge,importLines:fe,specs:Me}=_r(n),{build:Be,configField:je,contextField:be,imports:ye,stub:Xe}=Pr(b),{build:h,configField:qe,imports:Ne,stub:ne}=Fr(x),$t=e,Nt=t,Tt=v??{policies:[],roles:[]},At=I??{columns:[]},Ot=M??{rules:[]},It=ie??{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:Ct,override:Lt}=Er(W),{constant:_t,override:Et}=Dr(_),G=w.vectorIndexes.length>0,Ze=new Set(w.tables.filter(g=>typeof g.shardMode=="object"&&g.shardMode.kind==="shardBy").map(g=>g.name)),Te=w.vectorIndexes.some(g=>Ze.has(g.table)),we=w.tables.some(g=>g.shardMode==="global"),We=w.tables.some(g=>g.shardMode==="global"&&g.globalBackend==="hyperdrive"),et=w.tables.some(g=>g.shardMode==="global"&&g.globalBackend!=="hyperdrive"),re=w.tables.some(g=>g.externalSource!==void 0),tt=w.tables.some(g=>g.memory===!0),Ue=w.tables.some(g=>g.shardMode!=="global"&&g.searchIndexes.length>0);if(et&&We)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Ke=w.tables.length>0,Dt=cr(w),Pt=ur(w),Ft=gr(w),Mt=dr(w),nt=pr(w),rt=Mr(G,W.length>0,_.length>0,p,Ue);L&&rt.push("WhereInput");const ot=fr(we),Bt=L?`
1180
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(vn(P))}, json: ${JSON.stringify(v)} };
1181
+ `,M=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:ue,contextField:Oe,stub:Ie}=yr(a),pe=Rr(i),V=wr(u),H=kr(p,I.flags),W=Sr(s,p,I.flags),G=xr(l),te=vr(o),J=$r(c),ne=Nr(w),U=Tr(m),K=Ar(d),Q=Or(x),B=Ir(R),{build:Ce,contextField:Le,importLines:ve,specs:Re}=_r(D),{build:he,contextField:_e,importLines:Ee,specs:Se}=Cr(r,f.jurisdiction),{build:me,contextField:De,importLines:Pe,specs:$e}=Lr(q),{build:Fe,contextField:Me,importLines:ge,specs:fe}=Er(n),{build:Be,configField:je,contextField:qe,imports:be,stub:ye}=Fr(y),{build:Ze,configField:h,imports:We,stub:Ne}=Mr(k),re=e,Nt=t,Tt=C??{policies:[],roles:[]},At=N??{columns:[]},Ot=F??{rules:[]},It=le??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ct,override:Lt}=Dr(q),{constant:_t,override:Et}=Pr(D),z=f.vectorIndexes.length>0,et=new Set(f.tables.filter(g=>typeof g.shardMode=="object"&&g.shardMode.kind==="shardBy").map(g=>g.name)),Te=f.vectorIndexes.some(g=>et.has(g.table)),we=f.tables.some(g=>g.shardMode==="global"),Ue=f.tables.some(g=>g.shardMode==="global"&&g.globalBackend==="hyperdrive"),tt=f.tables.some(g=>g.shardMode==="global"&&g.globalBackend!=="hyperdrive"),oe=f.tables.some(g=>g.externalSource!==void 0),nt=f.tables.some(g=>g.memory===!0),Ke=f.tables.some(g=>g.shardMode!=="global"&&g.searchIndexes.length>0);if(tt&&Ue)throw new Z("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=f.tables.length>0,Dt=dr(f),Pt=pr(f),Ft=fr(f),Mt=ur(f),rt=hr(f),ot=Br(z,q.length>0,D.length>0,p,Ke);L&&ot.push("WhereInput");const at=br(we),Bt=L?`
1181
1182
  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
1183
  const shape = LUNORA_SHAPES[name];
1183
1184
 
@@ -1229,17 +1230,17 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1229
1230
 
1230
1231
  return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
1231
1232
  }
1232
- `:"",jt=Z?`
1233
+ `:"",jt=ee?`
1233
1234
  protected override isCustomMutator(functionPath: string): boolean {
1234
1235
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1235
1236
  }
1236
- `:"",qt=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":"",Wt=L?"assertShapeShardable, ":"",ke=[`import type { ${rt.join(", ")} } from "${C.do}";`,`import { applyCdcChanges, ${Ue?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${tt?"clearMemoryTables, ":""}${Wt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${re?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Te?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ot.importFragment}ShardDO as ShardDOBase } from "${C.do}";`,...re?[`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}";`];Ke&&ke.push(`import { bindOrm, bindTableFacade } from "${C.server}";`),G&&ke.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&ke.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ke.push(...ue.importLines,...V.importLines,...P.importLines,...ee.importLines,...pe.importLines,...J.importLines,...U.importLines,...K.importLines,...Q.importLines,...j.importLines,...te.importLines,...Se,...$e,...Re,...fe,...ye,...Ne,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...Z?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ut=G?`
1237
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Kt=et?`
1238
- 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;`:"",Qt=We?`
1239
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Vt=re?`
1240
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Ht='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Jt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Gt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',zt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Yt=we?O("globalDbStub: DatabaseWriterLike",Ht,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Xt=G?O("vectorsStub: VectorSearchLike",Jt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Zt=Te?`
1237
+ `:"",qt=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":"",Wt=L?"assertShapeShardable, ":"",ke=[`import type { ${ot.join(", ")} } from "${I.do}";`,`import { applyCdcChanges, ${Ke?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${nt?"clearMemoryTables, ":""}${Wt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${oe?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Te?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${at.importFragment}ShardDO as ShardDOBase } from "${I.do}";`,...oe?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${I.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes } from "${I.server}";`:`import { asBucketStorage, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes } from "${I.server}";`];Qe&&ke.push(`import { bindOrm, bindTableFacade } from "${I.server}";`),z&&ke.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&ke.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ke.push(...pe.importLines,...V.importLines,...H.importLines,...G.importLines,...te.importLines,...J.importLines,...ne.importLines,...U.importLines,...K.importLines,...Q.importLines,...B.importLines,...Ee,...Pe,...ve,...ge,...be,...We,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ee?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ut=z?`
1238
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Kt=tt?`
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;`:"",Qt=Ue?`
1240
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Vt=oe?`
1241
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Ht='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Gt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Jt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',zt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Yt=we?O("globalDbStub: DatabaseWriterLike",Ht,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Xt=z?O("vectorsStub: VectorSearchLike",Gt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Zt=Te?`
1241
1242
  const vectorShardKey = this.currentShardKey();
1242
- `:"",en=Te?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",tn=Te?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${w.vectorIndexes.filter(g=>Ze.has(g.table)).map(g=>JSON.stringify(g.name)).join(", ")}] }`:"",nn=G?`
1243
+ `:"",en=Te?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",tn=Te?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${f.vectorIndexes.filter(g=>et.has(g.table)).map(g=>JSON.stringify(g.name)).join(", ")}] }`:"",nn=z?`
1243
1244
  let vectors: VectorSearchLike;
1244
1245
  let onWrite: WriteHook | undefined;
1245
1246
 
@@ -1290,7 +1291,7 @@ ${Zt}
1290
1291
  // Left \`undefined\` when there is no scope so \`createShardCtxDb\`
1291
1292
  // keeps its own "degrade a provable slice to a whole-table dep"
1292
1293
  // fallback rather than reporting into a no-op.
1293
- onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${G?`
1294
+ onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${z?`
1294
1295
  onWrite,`:""}
1295
1296
  scheduler,
1296
1297
  schema: schema as unknown as SchemaLike,
@@ -1329,10 +1330,10 @@ ${Zt}
1329
1330
  schema: schema as unknown as SchemaLike,
1330
1331
  sql: this.sql as SqlExec,
1331
1332
  });
1332
- }`,z=(g="")=>` const writer = this.adminWriter(${g});`,an=G?`
1333
- vectors,`:"",sn=Ke?`
1334
- orm: bindOrm(facade),`:"",Qe=We?"config.hyperdriveGlobal":"config.d1",ln=we?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
1335
- const globalDb: DatabaseWriterLike = ${Qe}?.(env, globalRequest) ?? globalDbStub;
1333
+ }`,Y=(g="")=>` const writer = this.adminWriter(${g});`,an=z?`
1334
+ vectors,`:"",sn=Qe?`
1335
+ orm: bindOrm(facade),`:"",Ve=Ue?"config.hyperdriveGlobal":"config.d1",ln=we?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
1336
+ const globalDb: DatabaseWriterLike = ${Ve}?.(env, globalRequest) ?? globalDbStub;
1336
1337
  `:"",cn=L&&we?`
1337
1338
  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 }>> {
1338
1339
  const env = this.env as Record<string, unknown>;
@@ -1340,7 +1341,7 @@ ${Zt}
1340
1341
  // the inbound bookmark (pin the membership drain to the caller's own
1341
1342
  // prior writes) — no \`onBookmark\` here.
1342
1343
  const globalRequest = { ...identity, ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
1343
- const globalDb: DatabaseWriterLike = ${Qe}?.(env, globalRequest) ?? globalDbStub;
1344
+ const globalDb: DatabaseWriterLike = ${Ve}?.(env, globalRequest) ?? globalDbStub;
1344
1345
  const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
1345
1346
 
1346
1347
  let cursor: null | string = null;
@@ -1374,21 +1375,21 @@ ${Zt}
1374
1375
  // never what changed in them, so it costs one small read per poll tick
1375
1376
  // for the whole shard — and a tick whose answer omits a shape's table
1376
1377
  // skips that shape's membership drain entirely.
1377
- const globalDb: DatabaseWriterLike = ${Qe}?.(env, { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() }) ?? globalDbStub;
1378
+ const globalDb: DatabaseWriterLike = ${Ve}?.(env, { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() }) ?? globalDbStub;
1378
1379
 
1379
1380
  return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
1380
1381
  }
1381
- `:"",dn=re?`
1382
+ `:"",dn=oe?`
1382
1383
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1383
1384
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1384
1385
  `:"",un=`
1385
1386
  protected override async runShardInit(): Promise<void> {
1386
1387
  this.ensureMigrated();
1387
- ${tt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1388
+ ${nt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1388
1389
  `:""}
1389
1390
  await this.dispatchShardInit();
1390
1391
  }
1391
- `,pn=re?`
1392
+ `,pn=oe?`
1392
1393
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1393
1394
  const env = (this.env ?? {}) as Record<string, unknown>;
1394
1395
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1528,7 +1529,7 @@ ${tt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1528
1529
 
1529
1530
  return nextDueAt;
1530
1531
  }
1531
- `:"",hn=nt.length>0,mn=`
1532
+ `:"",hn=rt.length>0,mn=`
1532
1533
  public constructor(state: ShardDOState, env: unknown) {
1533
1534
  super(state, env, {
1534
1535
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1541,7 +1542,7 @@ ${tt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1541
1542
  ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1542
1543
  ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1543
1544
  });
1544
- ${re?`
1545
+ ${oe?`
1545
1546
  const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1546
1547
  const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1547
1548
 
@@ -1560,22 +1561,22 @@ ${re?`
1560
1561
  protected override isQueryFunction(functionPath: string): boolean {
1561
1562
  return LUNORA_FUNCTIONS[functionPath]?.kind === "query";
1562
1563
  }
1563
- `,gn=Ke?`
1564
+ `,gn=Qe?`
1564
1565
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1565
- ${w.tables.map(g=>` facade[${JSON.stringify(g.name)}] = bindTableFacade(db, ${JSON.stringify(g.name)});`).join(`
1566
+ ${f.tables.map(g=>` facade[${JSON.stringify(g.name)}] = bindTableFacade(db, ${JSON.stringify(g.name)});`).join(`
1566
1567
  `)}
1567
- `:"",fn=`${ue.build}${V.build}${P.build}${J.build}${pe.build}
1568
+ `:"",fn=`${pe.build}${V.build}${H.build}${J.build}${te.build}
1568
1569
  const secrets = createSecrets(env);
1569
- `,bn=`${ue.contextField}${V.contextField}${P.contextField}${ee.contextField}${J.contextField}${pe.contextField}
1570
- secrets,`,yn=ee.build,at=y||m||d||R||k||x,wn=at?`
1570
+ `,bn=`${pe.contextField}${V.contextField}${H.contextField}${G.contextField}${J.contextField}${te.contextField}
1571
+ secrets,`,yn=G.build,st=w||m||d||x||R||k,wn=st?`
1571
1572
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1572
1573
  // and attached only for an \`action\` so query/mutation ctx never carry them.
1573
1574
  if (isAction) {
1574
- ${U.build}${K.build}${Q.build}${j.build}${te.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(`
1575
+ ${ne.build}${U.build}${K.build}${Q.build}${B.build}${Ze}${[...w?[" ctx.images = images;"]:[],...m?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...x?[" ctx.r2sql = r2sql;"]:[],...R?[" ctx.pipelines = pipelines;"]:[],...k?[" ctx.x402 = x402;"]:[]].join(`
1575
1576
  `)}
1576
1577
  }
1577
- `:"",kn=at?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1578
- `:"";return`${$}${ke.join(`
1578
+ `:"",kn=st?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1579
+ `:"";return`${S}${ke.join(`
1579
1580
  `)}
1580
1581
 
1581
1582
  type FunctionKind = "action" | "mutation" | "query";
@@ -1600,10 +1601,10 @@ const LUNORA_TABLE_COLUMNS: Record<
1600
1601
  const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(Mt,void 0,4)};
1601
1602
 
1602
1603
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1603
- const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(nt,void 0,4)};
1604
+ const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(rt,void 0,4)};
1604
1605
 
1605
1606
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1606
- const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify($t,void 0,4)};
1607
+ const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(re,void 0,4)};
1607
1608
 
1608
1609
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1609
1610
  const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(Nt,void 0,4)};
@@ -1619,7 +1620,7 @@ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Ot,void 0,4)};
1619
1620
 
1620
1621
  /** 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. */
1621
1622
  const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(It,void 0,4)};
1622
- ${B}${H.constant}${qt}${Ct}${_t}${me}${Pe}${he}${Me}
1623
+ ${Ae}${W.constant}${qt}${Ct}${_t}${Se}${$e}${Re}${fe}
1623
1624
  export interface ShardDOConfig {
1624
1625
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1625
1626
  cdc?: boolean;
@@ -1633,9 +1634,9 @@ export interface ShardDOConfig {
1633
1634
  observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1634
1635
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1635
1636
  scheduler?: (env: Record<string, unknown>) => unknown;
1636
- storage?: (env: Record<string, unknown>) => unknown;${Ut}${Ae}${V.configField}${P.configField}${J.configField}${U.configField}${K.configField}${Q.configField}${j.configField}${te.configField}${je}${qe}${Kt}${Qt}${Vt}
1637
+ storage?: (env: Record<string, unknown>) => unknown;${Ut}${ue}${V.configField}${H.configField}${J.configField}${ne.configField}${U.configField}${K.configField}${Q.configField}${B.configField}${je}${h}${Kt}${Qt}${Vt}
1637
1638
  }
1638
- ${O("schedulerStub",Gt,["cancel","runAfter","runAt"])}${O("storageStub",zt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${Yt}${dn}${Xt}${Ie}${V.stub}${P.stub}${J.stub}${U.stub}${K.stub}${Q.stub}${j.stub}${te.stub}${Xe}${ne}
1639
+ ${O("schedulerStub",Jt,["cancel","runAfter","runAt"])}${O("storageStub",zt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${Yt}${dn}${Xt}${Ie}${V.stub}${H.stub}${J.stub}${ne.stub}${U.stub}${K.stub}${Q.stub}${B.stub}${ye}${Ne}
1639
1640
  // Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
1640
1641
  // referencing call fails loudly with a clear error instead of overflowing the
1641
1642
  // stack. Tracked across the awaited handler chain (one DO invocation is
@@ -1760,7 +1761,7 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
1760
1761
  protected override isMutationFunction(functionPath: string): boolean {
1761
1762
  return LUNORA_FUNCTIONS[functionPath]?.kind === "mutation";
1762
1763
  }
1763
- ${ot.override}
1764
+ ${at.override}
1764
1765
  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> {
1765
1766
  const registered = LUNORA_FUNCTIONS[functionPath];
1766
1767
 
@@ -1882,7 +1883,7 @@ ${un}
1882
1883
  protected override studioFeatures(): StudioFeaturesResult {
1883
1884
  return LUNORA_STUDIO_FEATURES;
1884
1885
  }
1885
- ${H.evaluateOverride}${H.subscriptionOverride}${Lt}${Et}
1886
+ ${W.evaluateOverride}${W.subscriptionOverride}${Lt}${Et}
1886
1887
  protected override advisories(): AdvisoryFinding[] {
1887
1888
  return LUNORA_ADVISORIES;
1888
1889
  }
@@ -1908,7 +1909,7 @@ ${on}
1908
1909
  throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
1909
1910
  }
1910
1911
 
1911
- ${z()}
1912
+ ${Y()}
1912
1913
 
1913
1914
  return runDataMigration({
1914
1915
  batchSize: args.batchSize,
@@ -1941,7 +1942,7 @@ ${z()}
1941
1942
 
1942
1943
  this.ensureMigrated();
1943
1944
 
1944
- ${z("headroom ?? this.transactionHeadroom()")}
1945
+ ${Y("headroom ?? this.transactionHeadroom()")}
1945
1946
 
1946
1947
  if (args.op === "insert") {
1947
1948
  const id = await writer.insert(args.table, args.doc ?? {});
@@ -1992,7 +1993,7 @@ ${z("headroom ?? this.transactionHeadroom()")}
1992
1993
  protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
1993
1994
  this.ensureMigrated();
1994
1995
 
1995
- ${z()}
1996
+ ${Y()}
1996
1997
 
1997
1998
  const rows: ExportRow[] = [];
1998
1999
 
@@ -2009,7 +2010,7 @@ ${z()}
2009
2010
  protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
2010
2011
  this.ensureMigrated();
2011
2012
 
2012
- ${z()}
2013
+ ${Y()}
2013
2014
 
2014
2015
  // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
2015
2016
  // database's \`_id\`s carry across verbatim and every foreign key
@@ -2020,7 +2021,7 @@ ${z()}
2020
2021
  protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
2021
2022
  this.ensureMigrated();
2022
2023
 
2023
- ${z()}
2024
+ ${Y()}
2024
2025
 
2025
2026
  // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2026
2027
  // but the shard writer from \`createShardCtxDb\` always defines it.
@@ -2038,7 +2039,7 @@ ${z()}
2038
2039
  protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
2039
2040
  this.ensureMigrated();
2040
2041
 
2041
- ${z()}
2042
+ ${Y()}
2042
2043
 
2043
2044
  // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2044
2045
  // but the shard writer from \`createShardCtxDb\` always defines it. The sort
@@ -2059,7 +2060,7 @@ ${z()}
2059
2060
  protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
2060
2061
  this.ensureMigrated();
2061
2062
 
2062
- ${z()}
2063
+ ${Y()}
2063
2064
 
2064
2065
  await applyCdcChanges(writer, args.changes);
2065
2066
 
@@ -2071,10 +2072,10 @@ ${z()}
2071
2072
  return;
2072
2073
  }
2073
2074
 
2074
- runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ce} });
2075
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${M} });
2075
2076
  this.migrated = true;
2076
2077
  }
2077
- ${Ue?`
2078
+ ${Ke?`
2078
2079
  protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
2079
2080
  // Migrations create the fts5 companions; without them every backfill
2080
2081
  // statement would raise "no such table" on a shard that has never
@@ -2093,7 +2094,7 @@ ${Ue?`
2093
2094
  // dispatch path) fall back to the per-request fields as before.
2094
2095
  const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
2095
2096
  const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
2096
- ${nn}${de}${fn}${Le}${Ee}${Ce}${Fe}
2097
+ ${nn}${de}${fn}${he}${me}${Ce}${Fe}
2097
2098
  // \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
2098
2099
  // reaches through, and pending jobs live in the SchedulerDO — nothing the
2099
2100
  // CDC changelog records — so reading them must forfeit a delta resume.
@@ -2196,7 +2197,7 @@ ${yn}
2196
2197
  scheduler,
2197
2198
  span,
2198
2199
  storage: contextStorage,
2199
- trace,${an}${Oe}${bn}${be}${_e}${De}${ve}${ge}
2200
+ trace,${an}${Oe}${bn}${qe}${_e}${De}${Le}${Me}
2200
2201
  };
2201
2202
  ${kn}${wn}
2202
2203
  ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
@@ -2226,21 +2227,21 @@ ${kn}${wn}
2226
2227
  return ctx;
2227
2228
  }
2228
2229
  };
2229
- `},Ye=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?Ye(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},St=(e,t)=>{const n=ae(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Br=(e,t,n)=>{f(e,"drizzle column name");const r=Ye(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=St(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},jr=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(f(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${Y(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},qr=(e,t)=>{f(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,s])=>` ${o}: ${Br(o,s,t)},`)].join(`
2230
+ `},Xe=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?Xe(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},$t=(e,t)=>{const n=se(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},jr=(e,t,n)=>{b(e,"drizzle column name");const r=Xe(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=$t(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},qr=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(b(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${X(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},Wr=(e,t)=>{b(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,s])=>` ${o}: ${jr(o,s,t)},`)].join(`
2230
2231
  `),r=e.indexes.length>0?`, (t) => ({
2231
- ${e.indexes.map(o=>jr(o)).join(`
2232
+ ${e.indexes.map(o=>qr(o)).join(`
2232
2233
  `)}
2233
2234
  })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
2234
2235
  ${n}
2235
- }${r});`},Wr=e=>e.typeAnnotation?.includes('Id<"')??!1,Ur=(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=Ye(a);n.add(c.builder),s=s||Wr(c),o=o||St(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}},lt=(e,t=!1)=>{if(e.length===0)return`${$}export {};
2236
- `;const n=oe(t),r=new Set(e.map(m=>m.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=Ur(e,r),c=[...s,...o].toSorted((m,y)=>m.localeCompare(y)),d=e.map(m=>qr(m,r)).join(`
2236
+ }${r});`},Ur=e=>e.typeAnnotation?.includes('Id<"')??!1,Kr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Xe(a);n.add(c.builder),s=s||Ur(c),o=o||$t(a,t)!==void 0}for(const a of i.indexes)r.add(a.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,a)=>i.localeCompare(a)),indexes:[...r].toSorted((i,a)=>i.localeCompare(a)),needsAnyColumn:o,needsId:s}},ct=(e,t=!1)=>{if(e.length===0)return`${S}export {};
2237
+ `;const n=ae(t),r=new Set(e.map(m=>m.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=Kr(e,r),c=[...s,...o].toSorted((m,w)=>m.localeCompare(w)),d=e.map(m=>Wr(m,r)).join(`
2237
2238
 
2238
2239
  `),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
2239
2240
  `:"",a?`import type { Id } from "./dataModel.js";
2240
- `:""].join("");return`${$}import { ${c.join(", ")} } from "${n.serverDrizzle}";
2241
+ `:""].join("");return`${S}import { ${c.join(", ")} } from "${n.serverDrizzle}";
2241
2242
  ${p}
2242
2243
  ${d}
2243
- `},po=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:E(lt(n,t),Je),shard:E(lt(r,t),Je)}},ho=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(`
2244
+ `},ho=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:_(ct(n,t),Je),shard:_(ct(r,t),Je)}},mo=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(`
2244
2245
  `),r=n.length>0?`
2245
2246
  ${n}
2246
2247
  `:"",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(`
@@ -2249,7 +2250,7 @@ ${c}
2249
2250
  ],`}).join(`
2250
2251
  `),s=o.length>0?`
2251
2252
  ${o}
2252
- `:"";return`${$}/**
2253
+ `:"";return`${S}/**
2253
2254
  * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
2254
2255
  * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
2255
2256
  * shard; \`workflow\` is a \`WORKFLOW_*\` binding name whose durable workflow is
@@ -2274,10 +2275,10 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
2274
2275
  * looks up \`event.cron\` here and dispatches every job in the list.
2275
2276
  */
2276
2277
  export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
2277
- `},mo=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(`
2278
+ `},go=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(`
2278
2279
  `),n=t.length>0?`
2279
2280
  ${t}
2280
- `:"";return`${$}/**
2281
+ `:"";return`${S}/**
2281
2282
  * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
2282
2283
  * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
2283
2284
  * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
@@ -2298,4 +2299,4 @@ export interface LunoraVectorIndex {
2298
2299
  * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2299
2300
  */
2300
2301
  export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
2301
- `},go=e=>[...new Set(e.map(t=>t.cron))];export{Zr as A,Rn as C,$ as G,Vn as U,to as a,ro as b,so as c,ho as d,lo as e,eo as f,po as g,ao as h,oo as i,uo as j,mo as k,io as l,go as m,dr as n,co as o,no as p};
2302
+ `},fo=e=>[...new Set(e.map(t=>t.cron))];export{eo as A,Rn as C,S as G,Hn as U,no as a,oo as b,io as c,mo as d,co as e,to as f,ho as g,so as h,ao as i,po as j,go as k,lo as l,fo as m,ur as n,uo as o,ro as p};