@lunora/codegen 1.0.0-alpha.144 → 1.0.0-alpha.146
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.
- package/README.md +1 -1
- package/dist/index.d.mts +75 -12
- package/dist/index.d.ts +75 -12
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AGENTS_FILENAME-D1qA0h5m.mjs → AGENTS_FILENAME-B1Abt3Gl.mjs} +1 -1
- package/dist/packem_shared/{CONTAINERS_FILENAME-oKaARMoA.mjs → CONTAINERS_FILENAME-CtcysaKS.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-BvzxeWRZ.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-B3VZ6vTw.mjs +1 -0
- package/dist/packem_shared/{GENERATED_HEADER-F2VhjmJG.mjs → GENERATED_HEADER-Dfc3qlLQ.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-B-eIjru_.mjs → NOTIFY_FILENAME-CKO5gtGe.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-C30LtXay.mjs → OPENRPC_VERSION-CdKqq_QT.mjs} +1 -1
- package/dist/packem_shared/{QUEUES_FILENAME-D229WtRm.mjs → QUEUES_FILENAME-C-pzLGy4.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CeOctEWC.mjs +9 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CTWRkAF5.mjs +2 -0
- package/dist/packem_shared/SchemaSnapshotParseError-qXCOA7dD.mjs +18 -0
- package/dist/packem_shared/{WORKFLOWS_FILENAME-DRaiCNa6.mjs → WORKFLOWS_FILENAME-BfvqsG9Z.mjs} +1 -1
- package/dist/packem_shared/ast-BYoSZlae.mjs +1 -0
- package/dist/packem_shared/{buildOpenApiDocument-CmLfuJpW.mjs → buildOpenApiDocument-D40ZeYsu.mjs} +1 -1
- package/dist/packem_shared/chain-Dygm2apY.mjs +1 -0
- package/dist/packem_shared/{classify-procedure-call-AKeIK05y.mjs → classify-procedure-call-Ib2EMtFH.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-DXH-4MTZ.mjs → context-property-calls-Br0sVv8E.mjs} +1 -1
- package/dist/packem_shared/{discoverAuthApiCalls-C35kkayg.mjs → discoverAuthApiCalls-DoNQSgso.mjs} +1 -1
- package/dist/packem_shared/{discoverCrons-wXBfQcfn.mjs → discoverCrons-DCxl4hty.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-DglkHRlt.mjs → discoverFunctions-C29Tvxas.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-B60GWv_I.mjs → discoverHttpRoutes-CFIXlUy4.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DTq4PKT5.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-C5l2INmE.mjs → discoverInserts-qU5F4W4g.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-BZsC5dHd.mjs +1 -0
- package/dist/packem_shared/{discoverMigrations-CWH7T6qz.mjs → discoverMigrations-BFkJQ8Sy.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-JsO91i57.mjs → discoverNondeterministicCalls-B-NNzzPW.mjs} +1 -1
- package/dist/packem_shared/discoverQueries-B4emAFn5.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-C2GtrFnl.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-DGUGYgWs.mjs → discoverRlsMetadata-BKcUnSNr.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-CRshfYZE.mjs → discoverRlsProcedures-fAhxiIyD.mjs} +1 -1
- package/dist/packem_shared/discoverSandboxUsage-CJhnKA0_.mjs +1 -0
- package/dist/packem_shared/{discoverStorageRulesMetadata-gyO60A5S.mjs → discoverStorageRulesMetadata-C7XmORWp.mjs} +1 -1
- package/dist/packem_shared/{emit-EJw8shd_.mjs → emit-BcAkLUfn.mjs} +179 -199
- package/dist/packem_shared/{emitApp-DftAzAA2.mjs → emitApp-DoR55vKV.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-MlZRKqSD.mjs → exported-procedure-chains-M40rbSYM.mjs} +1 -1
- package/dist/packem_shared/{index-CCDlo9L7.mjs → index-xGhyK9J_.mjs} +1 -1
- package/dist/packem_shared/{queries-B_xEHIeL.mjs → queries-Ddvo5dCs.mjs} +1 -1
- package/package.json +10 -10
- package/dist/packem_shared/DEFAULT_TARGET-CwB3hjFH.mjs +0 -1
- package/dist/packem_shared/FLAGS_FILENAME-BasxlnVS.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-D7qF6qrd.mjs +0 -9
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DLXXalg2.mjs +0 -2
- package/dist/packem_shared/SchemaSnapshotParseError-CvPTjDrT.mjs +0 -16
- package/dist/packem_shared/ast-CjWtsS6S.mjs +0 -1
- package/dist/packem_shared/chain-CtC3-wwZ.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-De_QiFIl.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-Df4JQp_2.mjs +0 -1
- package/dist/packem_shared/discoverQueries-iypfwfdZ.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-BdkZw-D2.mjs +0 -1
- package/dist/packem_shared/discoverSandboxUsage-DdewAOuj.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
|
|
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-CTWRkAF5.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:`
|
|
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,56 +15,56 @@ 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"}],
|
|
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;
|
|
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
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(
|
|
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;
|
|
25
25
|
const ${s} = new Array(${t}.length);
|
|
26
26
|
for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
|
|
27
27
|
const ${a} = ${t}[${i}];
|
|
28
28
|
${c.pre}${s}[${i}] = ${c.out};
|
|
29
29
|
}
|
|
30
|
-
`;return{out:s,pre:d}},
|
|
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
31
|
let ${p};
|
|
32
32
|
if (${n} !== undefined) {
|
|
33
33
|
${a.pre}${p} = ${a.out};
|
|
34
34
|
${d} = true;
|
|
35
35
|
}
|
|
36
|
-
`;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:m}}const s=He(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},
|
|
37
|
-
`,c=p}const d=
|
|
38
|
-
`},
|
|
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
39
|
${mt(t)}${o.pre}const ${i} = { ${o.entries} };
|
|
40
|
-
`;return{out:i,pre:a}},
|
|
40
|
+
`;return{out:i,pre:a}},Ln=e=>{let t=0;const r=ht(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
|
|
41
41
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
42
42
|
${mt("source")}${r.pre}return { ${r.entries} };
|
|
43
43
|
}`},$=`// GENERATED by @lunora/codegen — do not edit.
|
|
44
44
|
// Run \`lunora codegen\` to regenerate.
|
|
45
45
|
|
|
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,
|
|
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
47
|
`),n=t?`
|
|
48
48
|
${t}
|
|
49
49
|
`:"";return`export interface Insert_${e.name} {
|
|
50
50
|
_id?: Id<"${e.name}">;
|
|
51
|
-
_creationTime?: number;${n}}`},
|
|
52
|
-
`),
|
|
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?`
|
|
53
53
|
${l}
|
|
54
54
|
`:"",k=u.commitOrdered===!0?`
|
|
55
55
|
_commitSeq: number;`:"";return`export interface Doc_${u.name} {
|
|
56
56
|
_id: Id<"${u.name}">;
|
|
57
|
-
_creationTime: number;${k}${
|
|
57
|
+
_creationTime: number;${k}${b}}`}).join(`
|
|
58
58
|
|
|
59
59
|
`),o=e.tables.map(u=>` ${u.name}: Doc_${u.name};`).join(`
|
|
60
|
-
`),s=e.tables.map(u=>{const l=u.indexes.map(
|
|
61
|
-
`),i=e.tables.map(u=>{const l=u.searchIndexes.map(
|
|
62
|
-
`),a=e.tables.map(u=>{const l=u.rankIndexes.map(
|
|
63
|
-
`),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(
|
|
64
|
-
`),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>
|
|
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(`
|
|
65
65
|
|
|
66
66
|
`),m=e.tables.map(u=>` ${u.name}: Insert_${u.name};`).join(`
|
|
67
|
-
`),y=e.tables.map(u=>{const l=u.relations.map(
|
|
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
68
|
`);return l?` ${u.name}: {
|
|
69
69
|
${l}
|
|
70
70
|
};`:` ${u.name}: {};`}).join(`
|
|
@@ -160,8 +160,8 @@ export interface Relations {
|
|
|
160
160
|
${y}
|
|
161
161
|
}
|
|
162
162
|
|
|
163
|
-
`,
|
|
164
|
-
`);return` ${
|
|
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))}: {
|
|
165
165
|
${o}
|
|
166
166
|
};`};return ze(e).map(n=>t(n)).join(`
|
|
167
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+=`
|
|
@@ -196,7 +196,7 @@ export const agents: AgentsRef = {
|
|
|
196
196
|
${i}
|
|
197
197
|
};
|
|
198
198
|
`,n.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
199
|
-
`)}return{block:r,importLine:n.join("")}},
|
|
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
200
|
`,lines:i.map(a=>` "agents:${a}": lunoraAgentRuntimeFunctions.${a} as unknown as RegisteredLunoraFunction,`).join(`
|
|
201
201
|
`),prelude:`
|
|
202
202
|
/**
|
|
@@ -205,13 +205,13 @@ ${i}
|
|
|
205
205
|
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
206
206
|
*/
|
|
207
207
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
208
|
-
`}},
|
|
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"}},
|
|
210
|
-
`);return` ${
|
|
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))}: {
|
|
211
211
|
${c}
|
|
212
212
|
};`}).join(`
|
|
213
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(
|
|
214
|
+
`);return` ${Y(N(i))}: {
|
|
215
215
|
${c}
|
|
216
216
|
},`}).join(`
|
|
217
217
|
`);return{block:`
|
|
@@ -223,9 +223,9 @@ ${r}
|
|
|
223
223
|
export const httpStreams: HttpStreamsRef = {
|
|
224
224
|
${o}
|
|
225
225
|
};
|
|
226
|
-
`,body:r}},
|
|
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
227
|
${m}
|
|
228
|
-
${y.body}`,l=
|
|
228
|
+
${y.body}`,l=Ge(u),b=l.length>0?`
|
|
229
229
|
import type { ${l.join(", ")} } from "./dataModel.js";
|
|
230
230
|
`:"",k=p?`
|
|
231
231
|
${p}
|
|
@@ -239,10 +239,10 @@ export const api = anyApi as unknown as ApiTypes;
|
|
|
239
239
|
export interface InternalApiTypes {${R}}
|
|
240
240
|
|
|
241
241
|
export const internal = anyApi as unknown as InternalApiTypes;
|
|
242
|
-
${x.block}${y.block}`,
|
|
242
|
+
${x.block}${y.block}`,T=[...I.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],_=T.length>0?`import type { ${T.join(", ")} } from "${a.client}";
|
|
243
243
|
`:"";return kt(`${$}import { anyApi } from "${a.client}";
|
|
244
|
-
${_}${x.importLine}${
|
|
245
|
-
${I}`,s)},
|
|
244
|
+
${_}${x.importLine}${b}
|
|
245
|
+
${I}`,s)},no=e=>e?`${$}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
246
246
|
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
247
247
|
|
|
248
248
|
import schema from "../schema.js";
|
|
@@ -259,7 +259,7 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
259
259
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
260
260
|
*/
|
|
261
261
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
262
|
-
`:"",
|
|
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
263
|
export interface ${Ve(l)} {
|
|
264
264
|
${y}
|
|
265
265
|
/**
|
|
@@ -305,7 +305,7 @@ export const ${c.exportName}Collection = (
|
|
|
305
305
|
return { checkpoints, collection: createCollection(config), scope };
|
|
306
306
|
};`}).join(`
|
|
307
307
|
|
|
308
|
-
`),i=
|
|
308
|
+
`),i=Ge(s),a=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
|
|
309
309
|
`:"";return`${$}import type { LunoraClient, SubscriptionError } from "${r.client}";
|
|
310
310
|
import { lunoraCollectionOptions } from "@lunora/db/collections";
|
|
311
311
|
import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
|
|
@@ -313,7 +313,7 @@ import type { Collection } from "@tanstack/db";
|
|
|
313
313
|
import { createCollection } from "@tanstack/db";
|
|
314
314
|
${a}
|
|
315
315
|
${s}
|
|
316
|
-
`},
|
|
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
317
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
318
318
|
|
|
319
319
|
if (!registered) {
|
|
@@ -321,13 +321,13 @@ ${s}
|
|
|
321
321
|
}
|
|
322
322
|
|
|
323
323
|
return (await registered.handler(context, args ?? {})) as R;
|
|
324
|
-
};`,
|
|
325
|
-
`),a=e.map(l=>` "${
|
|
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(`
|
|
326
326
|
`),c=t.map(l=>` ${JSON.stringify(l.id)}: ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
327
|
-
`),d=n.map(l=>` "${
|
|
327
|
+
`),d=n.map(l=>` "${N(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
328
328
|
`),p=r.map(l=>` "${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
|
|
329
|
-
`),m=n.map(l=>`${
|
|
330
|
-
`),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const
|
|
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
331
|
`);return{dispatchBody:y.length>0?`
|
|
332
332
|
${y}
|
|
333
333
|
`:"",importBlock:i.length>0?`${i}
|
|
@@ -336,28 +336,28 @@ ${y}
|
|
|
336
336
|
${c}
|
|
337
337
|
`:"",mutatorPaths:m,shapeBody:p.length>0?`
|
|
338
338
|
${p}
|
|
339
|
-
`:""}},
|
|
340
|
-
`);return` ${
|
|
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))}: {
|
|
341
341
|
${i}
|
|
342
342
|
};`}).join(`
|
|
343
|
-
`);return{implementation:t.map(([o,s])=>{const i=
|
|
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
344
|
`);return` ${Y(i)}: {
|
|
345
345
|
${a}
|
|
346
346
|
},`}).join(`
|
|
347
|
-
`),types:n}},
|
|
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
348
|
`:"",se=o?`
|
|
349
349
|
readonly ai: LunoraAi;`:"",M=y?`import type { LunoraPayment } from "@lunora/payment";
|
|
350
350
|
`:"",ie=y?`
|
|
351
|
-
readonly payments: LunoraPayment;`:"",le=
|
|
352
|
-
`:"",W=
|
|
351
|
+
readonly payments: LunoraPayment;`:"",le=b?`import type { X402Pay } from "@lunora/x402/pay";
|
|
352
|
+
`:"",W=b?`
|
|
353
353
|
readonly x402: X402Pay;`:"",C=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
|
|
354
354
|
`:"",Z=t.length>0?`
|
|
355
355
|
readonly containers: {${t.map(h=>`
|
|
356
356
|
readonly ${h.exportName}: ContainerAccessor;`).join("")}
|
|
357
|
-
};`:"",L=[...o?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(h=>(
|
|
358
|
-
readonly ${h.bindingName}?: unknown;`)),..._.map(h=>(
|
|
359
|
-
readonly ${h.bindingName}?: unknown;`)),...R.map(h=>(
|
|
360
|
-
readonly ${h.bindingName}?: unknown;`)),...e.map(h=>(
|
|
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. */
|
|
361
361
|
readonly ${h.bindingName}?: unknown;`))].join(`
|
|
362
362
|
`),S=`
|
|
363
363
|
|
|
@@ -377,9 +377,9 @@ ${L}`:""}
|
|
|
377
377
|
}
|
|
378
378
|
|
|
379
379
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
380
|
-
export type Env = CloudflareBindings;`,B=(h,
|
|
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
381
|
readonly vectors: VectorSearch<VectorIndexName>;`:"",pe=P?`
|
|
382
|
-
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",
|
|
382
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",J=P?`import type { VectorSearch, VectorSearchReader } from "${v.server}";
|
|
383
383
|
import type { VectorIndexName } from "./dataModel.js";
|
|
384
384
|
`:"",U=r?`
|
|
385
385
|
/** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
|
|
@@ -389,9 +389,9 @@ import type { VectorIndexName } from "./dataModel.js";
|
|
|
389
389
|
/** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
|
|
390
390
|
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
391
391
|
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
392
|
-
readonly push: import("@lunora/notify").LunoraPush;`:"",
|
|
392
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",j=_.length>0,te=j?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
393
393
|
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
394
|
-
`:"",Ce=
|
|
394
|
+
`:"",Ce=j?`
|
|
395
395
|
|
|
396
396
|
/** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
|
|
397
397
|
type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
|
|
@@ -404,7 +404,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
404
404
|
export interface LunoraWorkflows {
|
|
405
405
|
${_.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
|
|
406
406
|
`)}
|
|
407
|
-
}`:"",ve=
|
|
407
|
+
}`:"",ve=j?' | "workflows"':"",Re=j?`
|
|
408
408
|
readonly workflows: LunoraWorkflows;`:"",he=R.length>0,Le=he?`import type { QueueProducer } from "@lunora/queue";
|
|
409
409
|
import type * as lunoraQueueDefinitions from "../queues.js";
|
|
410
410
|
`:"",_e=he?`
|
|
@@ -422,7 +422,7 @@ ${R.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunor
|
|
|
422
422
|
|
|
423
423
|
/** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
|
|
424
424
|
export interface LunoraAgents {
|
|
425
|
-
${e.map(h=>(
|
|
425
|
+
${e.map(h=>(f(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
|
|
426
426
|
`)}
|
|
427
427
|
}`:"",$e=me?`
|
|
428
428
|
readonly agents: LunoraAgents;`:"",Pe=k?`import type { InferIdentity } from "${v.server}";
|
|
@@ -435,7 +435,7 @@ export type Identity = InferIdentity<typeof lunoraIdentityContract.${k.exportNam
|
|
|
435
435
|
/** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
|
|
436
436
|
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",ge=k?' | "auth"':"",fe=k?`
|
|
437
437
|
readonly auth: NarrowedAuth;`:"",Me=k?", Identity":"",Be=n?`import type * as lunoraEnvContract from "../env.js";
|
|
438
|
-
`:"",
|
|
438
|
+
`:"",je=n?`
|
|
439
439
|
|
|
440
440
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
441
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}";
|
|
@@ -495,7 +495,7 @@ export type {
|
|
|
495
495
|
} from "${v.serverDataModel}";
|
|
496
496
|
|
|
497
497
|
import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
|
|
498
|
-
${
|
|
498
|
+
${J}${F}${M}${le}${C}${te}${Le}${Ee}${Pe}${Be}
|
|
499
499
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
500
500
|
|
|
501
501
|
/**
|
|
@@ -555,7 +555,7 @@ export interface OrmWriter extends OrmReader {
|
|
|
555
555
|
}
|
|
556
556
|
|
|
557
557
|
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
558
|
-
export type StorageBucketName = ${w};${S}${Ce}${_e}${De}${Fe}${
|
|
558
|
+
export type StorageBucketName = ${w};${S}${Ce}${_e}${De}${Fe}${je}
|
|
559
559
|
|
|
560
560
|
/**
|
|
561
561
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -708,12 +708,12 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Me}>();
|
|
|
708
708
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
709
709
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
710
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
712
|
`);let I=p;x.length>0&&(I=p.length>0?`${p.trimEnd()}
|
|
713
713
|
${x}
|
|
714
714
|
`:`
|
|
715
715
|
${x}
|
|
716
|
-
`);const
|
|
716
|
+
`);const T=lr(n),_=s.length>0?`import type { RegisteredShape } from "${d.server}";
|
|
717
717
|
`:"",v=s.length>0?`
|
|
718
718
|
/**
|
|
719
719
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
@@ -721,7 +721,7 @@ ${x}
|
|
|
721
721
|
* evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
|
|
722
722
|
* \`shape_subscribe\` (reads-as-permissions).
|
|
723
723
|
*/
|
|
724
|
-
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${
|
|
724
|
+
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${b}};
|
|
725
725
|
`:"",w=l.length>0?`
|
|
726
726
|
/**
|
|
727
727
|
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
@@ -737,12 +737,12 @@ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(S=>JSO
|
|
|
737
737
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
738
738
|
*/
|
|
739
739
|
${y}
|
|
740
|
-
`:"",M=
|
|
740
|
+
`:"",M=sr(n),ie=M.types?`
|
|
741
741
|
${M.types}
|
|
742
742
|
`:"",le=M.implementation?`
|
|
743
743
|
${M.implementation}
|
|
744
|
-
`:"",W=
|
|
745
|
-
`:"",Z=c?"context":"_context",L=c?`${
|
|
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
746
|
|
|
747
747
|
`:"";return kt(`${$}${m}${k.importLine}${R.importLine}${F}${_}import { LunoraError } from "${d.server}";
|
|
748
748
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
@@ -795,10 +795,10 @@ ${se}${v}${w}
|
|
|
795
795
|
* anonymous — all via system dispatch.
|
|
796
796
|
*/
|
|
797
797
|
export const LUNORA_LIFECYCLE_HOOKS: { connect: readonly string[]; disconnect: readonly string[]; init: readonly string[]; reactor: readonly string[] } = {
|
|
798
|
-
connect: [${
|
|
799
|
-
disconnect: [${
|
|
800
|
-
init: [${
|
|
801
|
-
reactor: [${
|
|
798
|
+
connect: [${T.connect.map(S=>JSON.stringify(S)).join(", ")}],
|
|
799
|
+
disconnect: [${T.disconnect.map(S=>JSON.stringify(S)).join(", ")}],
|
|
800
|
+
init: [${T.init.map(S=>JSON.stringify(S)).join(", ")}],
|
|
801
|
+
reactor: [${T.reactor.map(S=>JSON.stringify(S)).join(", ")}],
|
|
802
802
|
};
|
|
803
803
|
|
|
804
804
|
/**
|
|
@@ -852,7 +852,7 @@ export interface RegisteredDataMigration {
|
|
|
852
852
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
853
853
|
*/
|
|
854
854
|
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
|
|
855
|
-
`,i)},
|
|
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
856
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
857
857
|
this.ensureMigrated();
|
|
858
858
|
|
|
@@ -860,7 +860,7 @@ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}}
|
|
|
860
860
|
|
|
861
861
|
return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
|
|
862
862
|
}
|
|
863
|
-
`}:{importFragment:"",override:""},
|
|
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
864
|
const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
|
|
865
865
|
// Correlate AI-Gateway-routed calls with the Lunora trace: thread the
|
|
866
866
|
// function path + trace id into createAi, which folds them into the
|
|
@@ -898,7 +898,7 @@ const aiStub: LunoraAi = {
|
|
|
898
898
|
const ${e} = {
|
|
899
899
|
${s}
|
|
900
900
|
}${r};
|
|
901
|
-
`},D={build:"",configField:"",contextField:"",importLines:[],stub:""},
|
|
901
|
+
`},D={build:"",configField:"",contextField:"",importLines:[],stub:""},yr=e=>e?{build:`
|
|
902
902
|
const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
|
|
903
903
|
// KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
|
|
904
904
|
// when a value changes — a subscription that read one can never be proven
|
|
@@ -912,24 +912,24 @@ ${s}
|
|
|
912
912
|
]);
|
|
913
913
|
`,configField:`
|
|
914
914
|
kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
|
|
915
|
-
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:O("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:D,
|
|
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
916
|
const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
|
|
917
917
|
provider: () => config.flags?.(env),
|
|
918
918
|
targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
|
|
919
919
|
});
|
|
920
920
|
`,configField:`
|
|
921
921
|
flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
|
|
922
|
-
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:D,
|
|
922
|
+
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:D,kr=e=>e?{build:`
|
|
923
923
|
const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
|
|
924
924
|
`,configField:"",contextField:`
|
|
925
925
|
notify,
|
|
926
|
-
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,
|
|
926
|
+
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,xr=e=>e?{build:`
|
|
927
927
|
const envConfig = lunoraEnvContract.${e.exportName}(env);
|
|
928
928
|
`,configField:"",contextField:`
|
|
929
|
-
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,
|
|
929
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,vr=e=>e?{build:`
|
|
930
930
|
const access = accessFacade(identity, userId);
|
|
931
931
|
`,configField:"",contextField:`
|
|
932
|
-
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,
|
|
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
933
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
934
934
|
const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
|
|
935
935
|
provider: () => config.flags?.(env),
|
|
@@ -991,17 +991,17 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
991
991
|
|
|
992
992
|
return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
|
|
993
993
|
}
|
|
994
|
-
`;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},
|
|
994
|
+
`;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},Sr=e=>e?{build:`
|
|
995
995
|
const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
|
|
996
996
|
const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
|
|
997
997
|
`,configField:`
|
|
998
998
|
analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
|
|
999
|
-
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:O("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:D
|
|
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
1000
|
const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
|
|
1001
1001
|
const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
|
|
1002
1002
|
`,configField:`
|
|
1003
1003
|
images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
|
|
1004
|
-
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:O("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:D
|
|
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
1005
|
const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
|
|
1006
1006
|
`,configField:`
|
|
1007
1007
|
sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
|
|
@@ -1009,7 +1009,7 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
1009
1009
|
const browser: Browser = config.browser ? config.browser(env) : browserStub;
|
|
1010
1010
|
`,configField:`
|
|
1011
1011
|
browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
|
|
1012
|
-
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:O("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:D,
|
|
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
1013
|
const r2sqlEnv = env as Record<string, unknown>;
|
|
1014
1014
|
const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
|
|
1015
1015
|
const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
|
|
@@ -1020,11 +1020,11 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
1020
1020
|
? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
|
|
1021
1021
|
: r2sqlStub;
|
|
1022
1022
|
`,configField:`
|
|
1023
|
-
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:O("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:D,
|
|
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
1024
|
const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
|
|
1025
1025
|
const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
|
|
1026
1026
|
`,configField:`
|
|
1027
|
-
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:O("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:D,
|
|
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
1028
|
export class ${s.className} extends LunoraContainer {
|
|
1029
1029
|
public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
|
|
1030
1030
|
super(ctx, env, ${s.exportName}, "${s.exportName}"${n});
|
|
@@ -1049,7 +1049,7 @@ import { ${o} } from "../containers.js";
|
|
|
1049
1049
|
|
|
1050
1050
|
export { ContainerProxy } from "@lunora/container/do";
|
|
1051
1051
|
|
|
1052
|
-
${r}`},
|
|
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
1053
|
`);return{build:`
|
|
1054
1054
|
const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
|
|
1055
1055
|
`,contextField:`
|
|
@@ -1058,7 +1058,7 @@ ${r}`},Or=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1058
1058
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1059
1059
|
${n}
|
|
1060
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
1062
|
export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
|
|
1063
1063
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1064
1064
|
super(ctx, env, ${r.exportName}, "${r.exportName}");
|
|
@@ -1086,13 +1086,13 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
1086
1086
|
/** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
|
|
1087
1087
|
type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
|
|
1088
1088
|
|
|
1089
|
-
${t}`},
|
|
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
1090
|
export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
1091
1091
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1092
1092
|
super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
|
|
1093
1093
|
}
|
|
1094
1094
|
}
|
|
1095
|
-
`;if(!a.voice)return c;const d=a.voiceClassName??"",p=a.voiceBindingName??"";
|
|
1095
|
+
`;if(!a.voice)return c;const d=a.voiceClassName??"",p=a.voiceBindingName??"";f(d,`agent voice class "${d}"`);const m=`
|
|
1096
1096
|
/** Voice-session Durable Object for the \`${a.exportName}\` agent (binding \`${p}\`). */
|
|
1097
1097
|
export class ${d} extends VoiceSessionDO {
|
|
1098
1098
|
public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
|
|
@@ -1114,7 +1114,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
|
|
|
1114
1114
|
|
|
1115
1115
|
import { ${o} } from "../agents.js";
|
|
1116
1116
|
|
|
1117
|
-
${r}`},
|
|
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
1118
|
`);return`${$}/**
|
|
1119
1119
|
* Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
|
|
1120
1120
|
* composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
|
|
@@ -1129,7 +1129,7 @@ import { ${n} } from "../queues.js";
|
|
|
1129
1129
|
export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
|
|
1130
1130
|
${r}
|
|
1131
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
1133
|
`);return{build:`
|
|
1134
1134
|
const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
|
|
1135
1135
|
`,contextField:`
|
|
@@ -1138,7 +1138,7 @@ ${r}
|
|
|
1138
1138
|
const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
|
|
1139
1139
|
${t}
|
|
1140
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
1142
|
`);return{build:`
|
|
1143
1143
|
const queues = createQueueContext(env, LUNORA_QUEUES);
|
|
1144
1144
|
`,contextField:`
|
|
@@ -1147,7 +1147,7 @@ ${t}
|
|
|
1147
1147
|
const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
|
|
1148
1148
|
${t}
|
|
1149
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
1151
|
`);return{build:`
|
|
1152
1152
|
const agents = createAgentContext(env, LUNORA_AGENTS);
|
|
1153
1153
|
`,contextField:`
|
|
@@ -1163,21 +1163,21 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
|
|
|
1163
1163
|
protected override ${n}(): ${t} {
|
|
1164
1164
|
return ${e};
|
|
1165
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
1167
|
const payments: LunoraPayment = config.payment
|
|
1168
1168
|
? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
|
|
1169
1169
|
: paymentStub;
|
|
1170
1170
|
`,configField:`
|
|
1171
1171
|
payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
|
|
1172
|
-
payments,`,stub:O("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},
|
|
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
1173
|
const x402: X402Pay = config.x402
|
|
1174
1174
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1175
1175
|
: x402Stub;
|
|
1176
1176
|
`,configField:`
|
|
1177
|
-
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:O("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},
|
|
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
1178
|
/** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
|
|
1179
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1180
|
-
`,ce=F===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Ae,contextField:Oe,stub:Ie}=
|
|
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?`
|
|
1181
1181
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
1182
1182
|
const shape = LUNORA_SHAPES[name];
|
|
1183
1183
|
|
|
@@ -1230,17 +1230,17 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1230
1230
|
|
|
1231
1231
|
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
1232
1232
|
}
|
|
1233
|
-
`:"",
|
|
1233
|
+
`:"",jt=Z?`
|
|
1234
1234
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1235
1235
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1236
1236
|
}
|
|
1237
|
-
`:"",
|
|
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 { ${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?`
|
|
1238
1238
|
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Kt=et?`
|
|
1239
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=We?`
|
|
1240
1240
|
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Vt=re?`
|
|
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().");',
|
|
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().");',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?`
|
|
1242
1242
|
const vectorShardKey = this.currentShardKey();
|
|
1243
|
-
`:"",en=
|
|
1243
|
+
`:"",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?`
|
|
1244
1244
|
let vectors: VectorSearchLike;
|
|
1245
1245
|
let onWrite: WriteHook | undefined;
|
|
1246
1246
|
|
|
@@ -1291,35 +1291,50 @@ ${Zt}
|
|
|
1291
1291
|
// Left \`undefined\` when there is no scope so \`createShardCtxDb\`
|
|
1292
1292
|
// keeps its own "degrade a provable slice to a whole-table dep"
|
|
1293
1293
|
// fallback rather than reporting into a no-op.
|
|
1294
|
-
onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${
|
|
1294
|
+
onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${G?`
|
|
1295
1295
|
onWrite,`:""}
|
|
1296
1296
|
scheduler,
|
|
1297
1297
|
schema: schema as unknown as SchemaLike,
|
|
1298
1298
|
sql: this.sql as SqlExec,
|
|
1299
1299
|
storage,${we?`
|
|
1300
1300
|
globalDb,`:""}
|
|
1301
|
-
}`,
|
|
1301
|
+
}`,on=` /**
|
|
1302
|
+
* The bare writer every admin/maintenance entry point writes through.
|
|
1303
|
+
*
|
|
1304
|
+
* Admin and maintenance writes go through the SAME reactive-cache hooks as a
|
|
1305
|
+
* user mutation. Without this, a studio row edit, a TTL sweep, an admin
|
|
1306
|
+
* import, a CDC apply or a data-migration backfill writes without
|
|
1307
|
+
* invalidating, and the next query answers from the pre-write snapshot.
|
|
1308
|
+
*
|
|
1309
|
+
* \`headroom\` meters the transaction. An admin \`/rpc\` caller passes nothing
|
|
1310
|
+
* and falls back to \`this.transactionHeadroom()\`, which for an admin RPC is
|
|
1311
|
+
* \`undefined\` — \`handleAdminRpc\` answers before \`beginDispatch\`, so no
|
|
1312
|
+
* per-dispatch meter is in flight and a bulk loop is bounded by its per-call
|
|
1313
|
+
* row cap alone. The TTL sweep (an alarm work item, no dispatch) passes its
|
|
1314
|
+
* own by-value tracker explicitly instead.
|
|
1315
|
+
*/
|
|
1316
|
+
private adminWriter(headroom?: TransactionHeadroomTracker): DatabaseWriterLike {
|
|
1317
|
+
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1302
1318
|
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
// a user mutation. Without this, a studio row edit, a TTL sweep, an admin
|
|
1306
|
-
// import, a CDC apply or a data-migration backfill writes without
|
|
1307
|
-
// invalidating, and the next query answers from the pre-write snapshot.
|
|
1319
|
+
|
|
1320
|
+
return createShardCtxDb({
|
|
1308
1321
|
...this.ctxDbTuning(),
|
|
1309
1322
|
broadcast: (delta) => {
|
|
1310
1323
|
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
1311
1324
|
},
|
|
1312
1325
|
cdc: config.cdc ?? false,
|
|
1326
|
+
headroom,
|
|
1313
1327
|
// Live predicate, same as the user-facing ctx — see \`databaseOptions\`.
|
|
1314
1328
|
inTransaction: () => this.isInTransaction(),
|
|
1315
1329
|
scheduler,
|
|
1316
1330
|
schema: schema as unknown as SchemaLike,
|
|
1317
1331
|
sql: this.sql as SqlExec,
|
|
1318
|
-
})
|
|
1319
|
-
|
|
1320
|
-
|
|
1332
|
+
});
|
|
1333
|
+
}`,z=(g="")=>` const writer = this.adminWriter(${g});`,an=G?`
|
|
1334
|
+
vectors,`:"",sn=Ke?`
|
|
1335
|
+
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 };
|
|
1321
1336
|
const globalDb: DatabaseWriterLike = ${Qe}?.(env, globalRequest) ?? globalDbStub;
|
|
1322
|
-
`:"",
|
|
1337
|
+
`:"",cn=L&&we?`
|
|
1323
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 }>> {
|
|
1324
1339
|
const env = this.env as Record<string, unknown>;
|
|
1325
1340
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1364,17 +1379,17 @@ ${Zt}
|
|
|
1364
1379
|
|
|
1365
1380
|
return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
|
|
1366
1381
|
}
|
|
1367
|
-
`:"",
|
|
1382
|
+
`:"",dn=re?`
|
|
1368
1383
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1369
1384
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1370
|
-
`:"",
|
|
1385
|
+
`:"",un=`
|
|
1371
1386
|
protected override async runShardInit(): Promise<void> {
|
|
1372
1387
|
this.ensureMigrated();
|
|
1373
1388
|
${tt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
|
|
1374
1389
|
`:""}
|
|
1375
1390
|
await this.dispatchShardInit();
|
|
1376
1391
|
}
|
|
1377
|
-
`,
|
|
1392
|
+
`,pn=re?`
|
|
1378
1393
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1379
1394
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1380
1395
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1514,7 +1529,7 @@ ${tt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1514
1529
|
|
|
1515
1530
|
return nextDueAt;
|
|
1516
1531
|
}
|
|
1517
|
-
`:"",
|
|
1532
|
+
`:"",hn=nt.length>0,mn=`
|
|
1518
1533
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1519
1534
|
super(state, env, {
|
|
1520
1535
|
// Every writer this file builds spreads the ctxDbTuning() slice —
|
|
@@ -1537,7 +1552,7 @@ ${re?`
|
|
|
1537
1552
|
if (autoSourced) {
|
|
1538
1553
|
void this.scheduleSourcePoll();
|
|
1539
1554
|
}
|
|
1540
|
-
`:""}${
|
|
1555
|
+
`:""}${hn?`
|
|
1541
1556
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1542
1557
|
void this.scheduleTtlSweep();
|
|
1543
1558
|
}
|
|
@@ -1546,21 +1561,21 @@ ${re?`
|
|
|
1546
1561
|
protected override isQueryFunction(functionPath: string): boolean {
|
|
1547
1562
|
return LUNORA_FUNCTIONS[functionPath]?.kind === "query";
|
|
1548
1563
|
}
|
|
1549
|
-
`,
|
|
1564
|
+
`,gn=Ke?`
|
|
1550
1565
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1551
|
-
${w.tables.map(
|
|
1566
|
+
${w.tables.map(g=>` facade[${JSON.stringify(g.name)}] = bindTableFacade(db, ${JSON.stringify(g.name)});`).join(`
|
|
1552
1567
|
`)}
|
|
1553
|
-
`:"",
|
|
1568
|
+
`:"",fn=`${ue.build}${V.build}${P.build}${J.build}${pe.build}
|
|
1554
1569
|
const secrets = createSecrets(env);
|
|
1555
|
-
`,
|
|
1556
|
-
secrets,`,
|
|
1570
|
+
`,bn=`${ue.contextField}${V.contextField}${P.contextField}${ee.contextField}${J.contextField}${pe.contextField}
|
|
1571
|
+
secrets,`,yn=ee.build,at=y||m||d||R||k||x,wn=at?`
|
|
1557
1572
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1558
1573
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
1559
1574
|
if (isAction) {
|
|
1560
|
-
${U.build}${K.build}${Q.build}${
|
|
1575
|
+
${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(`
|
|
1561
1576
|
`)}
|
|
1562
1577
|
}
|
|
1563
|
-
`:"",
|
|
1578
|
+
`:"",kn=at?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
|
|
1564
1579
|
`:"";return`${$}${ke.join(`
|
|
1565
1580
|
`)}
|
|
1566
1581
|
|
|
@@ -1592,10 +1607,10 @@ const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?
|
|
|
1592
1607
|
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify($t,void 0,4)};
|
|
1593
1608
|
|
|
1594
1609
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1595
|
-
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(
|
|
1610
|
+
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(Nt,void 0,4)};
|
|
1596
1611
|
|
|
1597
1612
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1598
|
-
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(
|
|
1613
|
+
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(Tt,void 0,4)};
|
|
1599
1614
|
|
|
1600
1615
|
/** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
|
|
1601
1616
|
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(At,void 0,4)};
|
|
@@ -1605,7 +1620,7 @@ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Ot,void 0,4)};
|
|
|
1605
1620
|
|
|
1606
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. */
|
|
1607
1622
|
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(It,void 0,4)};
|
|
1608
|
-
${B}${H.constant}${
|
|
1623
|
+
${B}${H.constant}${qt}${Ct}${_t}${me}${Pe}${he}${Me}
|
|
1609
1624
|
export interface ShardDOConfig {
|
|
1610
1625
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1611
1626
|
cdc?: boolean;
|
|
@@ -1617,10 +1632,11 @@ export interface ShardDOConfig {
|
|
|
1617
1632
|
relationExistsPushDown?: "always" | "auto" | "never";
|
|
1618
1633
|
/** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
|
|
1619
1634
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1635
|
+
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1620
1636
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1621
|
-
storage?: (env: Record<string, unknown>) => unknown;${Ut}${Ae}${V.configField}${P.configField}${
|
|
1637
|
+
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}
|
|
1622
1638
|
}
|
|
1623
|
-
${O("schedulerStub",
|
|
1639
|
+
${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}
|
|
1624
1640
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1625
1641
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1626
1642
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -1657,7 +1673,7 @@ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: R
|
|
|
1657
1673
|
* from the worker entry so wrangler binds it by name.
|
|
1658
1674
|
*/
|
|
1659
1675
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1660
|
-
class extends ShardDOBase {${
|
|
1676
|
+
class extends ShardDOBase {${mn}
|
|
1661
1677
|
private migrated = false;
|
|
1662
1678
|
|
|
1663
1679
|
public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope): Promise<unknown> {
|
|
@@ -1781,11 +1797,11 @@ ${ot.override}
|
|
|
1781
1797
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
|
|
1782
1798
|
};
|
|
1783
1799
|
}
|
|
1784
|
-
${
|
|
1800
|
+
${jt}${Bt}${cn}${pn}
|
|
1785
1801
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor"): readonly string[] {
|
|
1786
1802
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1787
1803
|
}
|
|
1788
|
-
${
|
|
1804
|
+
${un}
|
|
1789
1805
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1790
1806
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
1791
1807
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -1876,6 +1892,8 @@ ${H.evaluateOverride}${H.subscriptionOverride}${Lt}${Et}
|
|
|
1876
1892
|
return LUNORA_ADVISOR_PROCEDURES;
|
|
1877
1893
|
}
|
|
1878
1894
|
|
|
1895
|
+
${on}
|
|
1896
|
+
|
|
1879
1897
|
protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
|
|
1880
1898
|
this.ensureMigrated();
|
|
1881
1899
|
|
|
@@ -1891,7 +1909,7 @@ ${H.evaluateOverride}${H.subscriptionOverride}${Lt}${Et}
|
|
|
1891
1909
|
throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
|
|
1892
1910
|
}
|
|
1893
1911
|
|
|
1894
|
-
${z}
|
|
1912
|
+
${z()}
|
|
1895
1913
|
|
|
1896
1914
|
return runDataMigration({
|
|
1897
1915
|
batchSize: args.batchSize,
|
|
@@ -1908,7 +1926,7 @@ ${z}
|
|
|
1908
1926
|
});
|
|
1909
1927
|
}
|
|
1910
1928
|
|
|
1911
|
-
protected override async runShardWrite(args: RunShardWriteArgs): Promise<RunShardWriteResult> {
|
|
1929
|
+
protected override async runShardWrite(args: RunShardWriteArgs, headroom?: TransactionHeadroomTracker): Promise<RunShardWriteResult> {
|
|
1912
1930
|
const definition = (schema as unknown as SchemaLike).tables[args.table];
|
|
1913
1931
|
|
|
1914
1932
|
if (!definition) {
|
|
@@ -1924,7 +1942,7 @@ ${z}
|
|
|
1924
1942
|
|
|
1925
1943
|
this.ensureMigrated();
|
|
1926
1944
|
|
|
1927
|
-
${z}
|
|
1945
|
+
${z("headroom ?? this.transactionHeadroom()")}
|
|
1928
1946
|
|
|
1929
1947
|
if (args.op === "insert") {
|
|
1930
1948
|
const id = await writer.insert(args.table, args.doc ?? {});
|
|
@@ -1932,19 +1950,26 @@ ${z}
|
|
|
1932
1950
|
return { id, op: "insert" };
|
|
1933
1951
|
}
|
|
1934
1952
|
|
|
1953
|
+
// Every by-id op PINS \`args.table\`. Unpinned, \`locateRowById\` probes
|
|
1954
|
+
// every non-global table for the id, so a request naming table A with an
|
|
1955
|
+
// id belonging to table B locates and mutates B's row — the by-id IDOR
|
|
1956
|
+
// the per-table \`ctx.db.<table>\` facade pins against. Pinning also stops
|
|
1957
|
+
// an absent row falling through to the \`.global()\` D1 twin, though that
|
|
1958
|
+
// branch is already unreachable here: \`adminWriter\` is built without a
|
|
1959
|
+
// \`globalDb\`, so a miss throws \`NOT_FOUND\` either way.
|
|
1935
1960
|
if (args.op === "delete") {
|
|
1936
|
-
await writer.delete(args.id ?? "");
|
|
1961
|
+
await writer.delete(args.id ?? "", args.table);
|
|
1937
1962
|
|
|
1938
1963
|
return { id: args.id ?? null, op: "delete" };
|
|
1939
1964
|
}
|
|
1940
1965
|
|
|
1941
1966
|
if (args.op === "replace") {
|
|
1942
|
-
await writer.replace(args.id ?? "", args.doc ?? {});
|
|
1967
|
+
await writer.replace(args.id ?? "", args.doc ?? {}, args.table);
|
|
1943
1968
|
|
|
1944
1969
|
return { id: args.id ?? null, op: "replace" };
|
|
1945
1970
|
}
|
|
1946
1971
|
|
|
1947
|
-
await writer.patch(args.id ?? "", args.doc ?? {});
|
|
1972
|
+
await writer.patch(args.id ?? "", args.doc ?? {}, args.table);
|
|
1948
1973
|
|
|
1949
1974
|
return { id: args.id ?? null, op: "patch" };
|
|
1950
1975
|
}
|
|
@@ -1968,7 +1993,7 @@ ${z}
|
|
|
1968
1993
|
protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
|
|
1969
1994
|
this.ensureMigrated();
|
|
1970
1995
|
|
|
1971
|
-
${z}
|
|
1996
|
+
${z()}
|
|
1972
1997
|
|
|
1973
1998
|
const rows: ExportRow[] = [];
|
|
1974
1999
|
|
|
@@ -1985,7 +2010,7 @@ ${z}
|
|
|
1985
2010
|
protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
|
|
1986
2011
|
this.ensureMigrated();
|
|
1987
2012
|
|
|
1988
|
-
${z}
|
|
2013
|
+
${z()}
|
|
1989
2014
|
|
|
1990
2015
|
// \`importShardRows\` inserts with \`allowExplicitId\`, so a source
|
|
1991
2016
|
// database's \`_id\`s carry across verbatim and every foreign key
|
|
@@ -1993,55 +2018,10 @@ ${z}
|
|
|
1993
2018
|
return importShardRows(writer, schema as unknown as SchemaLike, { rows: args.rows, startLine: args.startLine });
|
|
1994
2019
|
}
|
|
1995
2020
|
|
|
1996
|
-
protected override async deleteRowThroughWriter(table: string, id: string, headroom?: TransactionHeadroomTracker): Promise<void> {
|
|
1997
|
-
const definition = (schema as unknown as SchemaLike).tables[table];
|
|
1998
|
-
|
|
1999
|
-
if (!definition) {
|
|
2000
|
-
throw new LunoraError("UNKNOWN_TABLE", \`unknown table: \${table}\`, { status: 404 });
|
|
2001
|
-
}
|
|
2002
|
-
|
|
2003
|
-
// \`.global()\` tables live in D1, not this DO's SQLite — the same
|
|
2004
|
-
// guard \`runShardWrite\` applies to single-row edits.
|
|
2005
|
-
if (definition.shardMode?.kind === "global") {
|
|
2006
|
-
throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", \`table "\${table}" is global; edit it through D1, not the shard\`, { status: 400 });
|
|
2007
|
-
}
|
|
2008
|
-
|
|
2009
|
-
this.ensureMigrated();
|
|
2010
|
-
|
|
2011
|
-
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
2012
|
-
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
2013
|
-
const writer = createShardCtxDb({
|
|
2014
|
-
// Admin and maintenance writes go through the SAME reactive-cache hooks as
|
|
2015
|
-
// a user mutation. Without this, a studio row edit, a TTL sweep, an admin
|
|
2016
|
-
// import, a CDC apply or a data-migration backfill writes without
|
|
2017
|
-
// invalidating, and the next query answers from the pre-write snapshot.
|
|
2018
|
-
...this.ctxDbTuning(),
|
|
2019
|
-
broadcast: (delta) => {
|
|
2020
|
-
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
2021
|
-
},
|
|
2022
|
-
cdc: config.cdc ?? false,
|
|
2023
|
-
// \`runShardBulkDelete\` (a normal \`/rpc\` dispatch) calls this with no
|
|
2024
|
-
// explicit \`headroom\`, so it falls back to \`this.transactionHeadroom()\`
|
|
2025
|
-
// — the SAME per-dispatch meter every other write goes through, mirroring
|
|
2026
|
-
// \`buildCtx\`'s \`options.headroom ?? this.transactionHeadroom()\`. The TTL
|
|
2027
|
-
// sweep (an alarm work item, no dispatch in flight) passes its own
|
|
2028
|
-
// by-value tracker explicitly instead.
|
|
2029
|
-
headroom: headroom ?? this.transactionHeadroom(),
|
|
2030
|
-
scheduler,
|
|
2031
|
-
schema: schema as unknown as SchemaLike,
|
|
2032
|
-
sql: this.sql as SqlExec,
|
|
2033
|
-
});
|
|
2034
|
-
|
|
2035
|
-
// Routes through the writer (not raw SQL) so FTS / aggregate / rank
|
|
2036
|
-
// shadow tables stay in sync and \`onDelete\` cascades fire — the
|
|
2037
|
-
// bounded loop lives in the base \`runShardBulkDelete\`.
|
|
2038
|
-
await writer.delete(id);
|
|
2039
|
-
}
|
|
2040
|
-
|
|
2041
2021
|
protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
|
|
2042
2022
|
this.ensureMigrated();
|
|
2043
2023
|
|
|
2044
|
-
${z}
|
|
2024
|
+
${z()}
|
|
2045
2025
|
|
|
2046
2026
|
// \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
2047
2027
|
// but the shard writer from \`createShardCtxDb\` always defines it.
|
|
@@ -2059,7 +2039,7 @@ ${z}
|
|
|
2059
2039
|
protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
|
|
2060
2040
|
this.ensureMigrated();
|
|
2061
2041
|
|
|
2062
|
-
${z}
|
|
2042
|
+
${z()}
|
|
2063
2043
|
|
|
2064
2044
|
// \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
2065
2045
|
// but the shard writer from \`createShardCtxDb\` always defines it. The sort
|
|
@@ -2080,7 +2060,7 @@ ${z}
|
|
|
2080
2060
|
protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
|
|
2081
2061
|
this.ensureMigrated();
|
|
2082
2062
|
|
|
2083
|
-
${z}
|
|
2063
|
+
${z()}
|
|
2084
2064
|
|
|
2085
2065
|
await applyCdcChanges(writer, args.changes);
|
|
2086
2066
|
|
|
@@ -2114,7 +2094,7 @@ ${Ue?`
|
|
|
2114
2094
|
// dispatch path) fall back to the per-request fields as before.
|
|
2115
2095
|
const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
|
|
2116
2096
|
const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
|
|
2117
|
-
${nn}${de}${
|
|
2097
|
+
${nn}${de}${fn}${Le}${Ee}${Ce}${Fe}
|
|
2118
2098
|
// \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
|
|
2119
2099
|
// reaches through, and pending jobs live in the SchedulerDO — nothing the
|
|
2120
2100
|
// CDC changelog records — so reading them must forfeit a delta resume.
|
|
@@ -2176,13 +2156,13 @@ ${nn}${de}${gn}${Le}${Ee}${Ce}${Fe}
|
|
|
2176
2156
|
// so both write to the same trace.
|
|
2177
2157
|
const span = this.makeDispatchSpan(traceAnchor, observability);
|
|
2178
2158
|
|
|
2179
|
-
${
|
|
2159
|
+
${ln} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
|
|
2180
2160
|
// adds aggregate counters (call count, total time, per-operation
|
|
2181
2161
|
// breakdown) to the wide event rather than a span per call, so a
|
|
2182
2162
|
// handler making hundreds of queries stays readable. See
|
|
2183
2163
|
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
2184
2164
|
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${rn}), logFunctionPath, traceAnchor, observability);
|
|
2185
|
-
${
|
|
2165
|
+
${gn}${Be}
|
|
2186
2166
|
|
|
2187
2167
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
2188
2168
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -2190,7 +2170,7 @@ ${mn}${Be}
|
|
|
2190
2170
|
// writing mutation's trace from the shared per-request field.
|
|
2191
2171
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
|
|
2192
2172
|
const metrics = this.makeMetrics(logFunctionPath, observability);
|
|
2193
|
-
${
|
|
2173
|
+
${yn}
|
|
2194
2174
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
2195
2175
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
2196
2176
|
// Query/mutation handlers must be deterministic (they may be re-run on
|
|
@@ -2213,13 +2193,13 @@ ${bn}
|
|
|
2213
2193
|
ip: this.getCurrentIp(),
|
|
2214
2194
|
log,
|
|
2215
2195
|
metrics,
|
|
2216
|
-
now,${
|
|
2196
|
+
now,${sn}
|
|
2217
2197
|
scheduler,
|
|
2218
2198
|
span,
|
|
2219
2199
|
storage: contextStorage,
|
|
2220
|
-
trace,${
|
|
2200
|
+
trace,${an}${Oe}${bn}${be}${_e}${De}${ve}${ge}
|
|
2221
2201
|
};
|
|
2222
|
-
${
|
|
2202
|
+
${kn}${wn}
|
|
2223
2203
|
ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
|
|
2224
2204
|
ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
|
|
2225
2205
|
// \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
|
|
@@ -2247,21 +2227,21 @@ ${wn}${yn}
|
|
|
2247
2227
|
return ctx;
|
|
2248
2228
|
}
|
|
2249
2229
|
};
|
|
2250
|
-
`},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},
|
|
2230
|
+
`},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(`
|
|
2251
2231
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2252
|
-
${e.indexes.map(o=>
|
|
2232
|
+
${e.indexes.map(o=>jr(o)).join(`
|
|
2253
2233
|
`)}
|
|
2254
2234
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2255
2235
|
${n}
|
|
2256
|
-
}${r});`},
|
|
2257
|
-
`;const n=oe(t),r=new Set(e.map(m=>m.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=
|
|
2236
|
+
}${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 {};
|
|
2237
|
+
`;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(`
|
|
2258
2238
|
|
|
2259
2239
|
`),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2260
2240
|
`:"",a?`import type { Id } from "./dataModel.js";
|
|
2261
2241
|
`:""].join("");return`${$}import { ${c.join(", ")} } from "${n.serverDrizzle}";
|
|
2262
2242
|
${p}
|
|
2263
2243
|
${d}
|
|
2264
|
-
`},
|
|
2244
|
+
`},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(`
|
|
2265
2245
|
`),r=n.length>0?`
|
|
2266
2246
|
${n}
|
|
2267
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(`
|
|
@@ -2295,7 +2275,7 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
|
|
|
2295
2275
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2296
2276
|
*/
|
|
2297
2277
|
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
|
|
2298
|
-
`},
|
|
2278
|
+
`},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(`
|
|
2299
2279
|
`),n=t.length>0?`
|
|
2300
2280
|
${t}
|
|
2301
2281
|
`:"";return`${$}/**
|
|
@@ -2319,4 +2299,4 @@ export interface LunoraVectorIndex {
|
|
|
2319
2299
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2320
2300
|
*/
|
|
2321
2301
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2322
|
-
`},
|
|
2302
|
+
`},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};
|