@lunora/codegen 1.0.0-alpha.130 → 1.0.0-alpha.132
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/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-NWWDWOX4.mjs → GENERATED_HEADER-etEAWhHs.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-DJerSBO-.mjs → MUTATORS_FILENAME-cczs0N_f.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-CPg7zlsb.mjs → NOTIFY_FILENAME-3hraPVOT.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-6XrIwoNr.mjs → OPENRPC_VERSION-l-E_pTg8.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME--CCXsODJ.mjs → SCHEMA_SNAPSHOT_FILENAME-DNjZUvv7.mjs} +1 -1
- package/dist/packem_shared/{SHAPES_FILENAME-DTp6VI6K.mjs → SHAPES_FILENAME-BTdasTq2.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-DDvSUMD9.mjs → buildOpenApiDocument-DBUr_qe5.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-5SwUVBO6.mjs +1 -0
- package/dist/packem_shared/{discoverHttpRoutes-BkwEwmK0.mjs → discoverHttpRoutes-oVY4IQQz.mjs} +1 -1
- package/dist/packem_shared/{discoverMaskProcedures-DExWLcsu.mjs → discoverMaskProcedures-BbiYrDLQ.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-xRw6-4OU.mjs → discoverNondeterministicCalls-BcWKCkrg.mjs} +1 -1
- package/dist/packem_shared/{discoverR2sqlCalls-Ciq0-bVB.mjs → discoverR2sqlCalls-Dy7i757M.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsMetadata-Bnn3zDlc.mjs → discoverRlsMetadata-BqCbCx8m.mjs} +1 -1
- package/dist/packem_shared/{discoverSchema-gJ93Xjpx.mjs → discoverSchema-Hsu_1xIc.mjs} +1 -1
- package/dist/packem_shared/{discoverStorageRulesMetadata-DYAgRSL6.mjs → discoverStorageRulesMetadata-Demj7Q4c.mjs} +1 -1
- package/dist/packem_shared/{emit-GW3Jf9w0.mjs → emit-DBZKVUBi.mjs} +130 -130
- package/dist/packem_shared/{emitApp-D-mz_p6P.mjs → emitApp-wqZEBJxy.mjs} +1 -1
- package/dist/packem_shared/parse-validator-BFTp87yz.mjs +1 -0
- package/package.json +4 -4
- package/dist/packem_shared/discoverFunctions-CYHtspcp.mjs +0 -1
- package/dist/packem_shared/parse-validator-C5ycrhR3.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as
|
|
1
|
+
import{agentComponent as it}from"@lunora/agent/component";import{LunoraError as te}from"@lunora/errors";import{serializeSchemaSnapshot as wn,hashSchemaSnapshot as kn}from"./SCHEMA_SNAPSHOT_VERSION-CftvRWB8.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";const lt=[{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,40 +15,40 @@ import{agentComponent as st}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"}],xn=lt,vn=new Map(xn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Yr=lt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),ct=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,Rn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),dt=e=>e.column!==void 0,Sn=(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
|
-
`}}
|
|
24
|
-
`}},Ke=(e,t,n)=>{if(!
|
|
23
|
+
`}},$n=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!ct.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
|
|
24
|
+
`}},Ke=(e,t,n)=>{if(!dt(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(Rn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Sn(e.kind,t)};switch(e.kind){case"array":return Nn(e,t,n);case"literal":return $n(e,t);case"object":return On(e,t,n);default:return}}},Nn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),s=`__arr${String(o)}`,i=`__i${String(o)}`,a=`__e${String(o)}`,c=Ke(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
|
|
25
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}},Tn=(e,t,n,r)=>{const o=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||dt(t))return;const{inner:i}=t;if(!i)return;const a=Ke(i,n,r);if(!a)return;const c=r.next(),d=`__has${String(c)}`,p=`__val${String(c)}`,m=`let ${d} = false;
|
|
31
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=Ke(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},
|
|
37
|
-
`,c=p}const d=
|
|
38
|
-
`},
|
|
39
|
-
${
|
|
40
|
-
`;return{out:i,pre:a}},
|
|
36
|
+
`;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:m}}const s=Ke(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},An=new Set(Object.getOwnPropertyNames(Object.prototype)),ut=(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(An.has(s)){const p=`__f${String(n.next())}`;r+=`const ${p} = Object.hasOwn(${t}, ${a}) ? ${t}[${a}] : undefined;
|
|
37
|
+
`,c=p}const d=Tn(s,i,c,n);if(!d)return;r+=d.pre,o.push(d.entry)}return{entries:o.join(", "),pre:r}},pt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
|
|
38
|
+
`},On=(e,t,n)=>{const r=e.shape??{},o=ut(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
|
+
${pt(t)}${o.pre}const ${i} = { ${o.entries} };
|
|
40
|
+
`;return{out:i,pre:a}},In=e=>{let t=0;const r=ut(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
|
+
${pt("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
|
-
`,ne=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},
|
|
46
|
+
`,ne=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},ht=/^[A-Za-z_$][\w$]*$/u,Cn=/^[\w./-]+$/u,g=(e,t)=>{if(!ht.test(e))throw new te("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ue=e=>e.charAt(0).toUpperCase()+e.slice(1),E=e=>ht.test(e)?e:JSON.stringify(e),Ln={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"},_n=e=>{if(e===void 0)return"unknown";if(!ct.test(e))throw new te("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},A=e=>{const t=Ln[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?A(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return g(n,"v.id() table name"),`Id<"${n}">`}case"literal":return _n(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>mt(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"}},mt=(e,t)=>{const n=E(e);if(t.kind==="optional"){const r=t.inner?A(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${A(t)}`},we=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>mt(n,r)).join("; ")} }`},gt=e=>e.kind==="optional"||!!e.column?.hasDefault,re=e=>e.kind==="optional"&&e.inner?e.inner:e,En=e=>{g(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=re(o),i=A(s),a=E(r);return gt(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}}`},Qe="schema",
|
|
51
|
+
_creationTime?: number;${n}}`},Qe="schema",Xr=e=>{for(const u of e.tables)g(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([R,x])=>{const I=E(R);if(x.kind==="optional"){const T=x.inner?A(x.inner):"unknown";return` ${I}?: ${T};`}return` ${I}: ${A(x)};`}).join(`
|
|
52
52
|
`),f=l?`
|
|
53
53
|
${l}
|
|
54
54
|
`:"",k=u.commitOrdered===!0?`
|
|
@@ -61,14 +61,14 @@ ${l}
|
|
|
61
61
|
`),i=e.tables.map(u=>{const l=u.searchIndexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
62
62
|
`),a=e.tables.map(u=>{const l=u.rankIndexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
63
63
|
`),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
64
|
-
`),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>
|
|
64
|
+
`),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>En(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(f=>(g(f.table,"relation target table"),` ${
|
|
67
|
+
`),y=e.tables.map(u=>{const l=u.relations.map(f=>(g(f.table,"relation target table"),` ${E(f.name)}: ${f.kind==="one"?"OneRelation":"ManyRelation"}<"${f.table}">;`)).join(`
|
|
68
68
|
`);return l?` ${u.name}: {
|
|
69
69
|
${l}
|
|
70
70
|
};`:` ${u.name}: {};`}).join(`
|
|
71
|
-
`);return
|
|
71
|
+
`);return D(`${$}export type TableName = ${t};
|
|
72
72
|
|
|
73
73
|
/**
|
|
74
74
|
* The tables **this app declared** — every {@link TableName} except those an add-on
|
|
@@ -160,11 +160,11 @@ export interface Relations {
|
|
|
160
160
|
${y}
|
|
161
161
|
}
|
|
162
162
|
|
|
163
|
-
`,Qe)},Dn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,
|
|
164
|
-
`);return` ${
|
|
163
|
+
`,Qe)},Dn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,ft=/^(?:\.\.?\/)*_generated\//u,bt=/\.[A-Za-z]\w*$/u,Pn=e=>e.replaceAll(Dn,(t,n)=>{const r=n.replace(ft,"./");return`import("${bt.test(r)?r:`${r}.js`}")`}),Fn=/import\("(?<spec>[^"]+)"\)/gu,ot="node_modules/",Mn=/^@types\//u,Bn=e=>e.replaceAll(Fn,(t,n)=>{const r=n.lastIndexOf(ot);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+ot.length);return o===""||Mn.test(o)?t:`import("${o}")`}),jn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,qn=/^(?:\.\.?\/)+/u,Wn=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("/")},Un=(e,t)=>e.replaceAll(jn,(n,r)=>{if(ft.test(r.replace(qn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Wn(`${o}/${r}`)}`;return`import("${bt.test(i)?i:`${i}.js`}")`}),D=(e,t)=>Pn(Un(Bn(e),t)),Kn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Qn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Kn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Vn={flags:new Set(["/web"]),platform:new Set},yt=(e,t)=>t?e.replaceAll(Qn,(n,r,o)=>{const s=Vn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,Ve=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),wt=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:A(e.output),He=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},at=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=D(we(s.args),s.filePath),a=D(wt(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
|
|
164
|
+
`);return` ${E(N(n))}: {
|
|
165
165
|
${o}
|
|
166
166
|
};`};return He(e).map(n=>t(n)).join(`
|
|
167
|
-
`)},
|
|
167
|
+
`)},Hn=(e,t)=>{if(e.length===0&&t.length===0)return{block:"",importLine:""};const n=[];let r="";if(e.length>0&&(r+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),r+=`
|
|
168
168
|
/** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
|
|
169
169
|
export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
170
170
|
readonly isLunoraWorkflow: true;
|
|
@@ -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("")}},Gn=()=>Object.keys(it().functions).toSorted((e,t)=>e.localeCompare(t)),kt=e=>new Set(e.filter(t=>N(t.filePath)==="agents").map(t=>t.exportName)),Jn=()=>new Set(Object.entries(it().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),zn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=kt(t),o=Jn(),s=t.find(a=>N(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new te("INTERNAL",`@lunora/codegen: "agents:${s.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${s.exportName}" export in ${s.filePath}`);const i=Gn().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
|
+
`}},Yn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>N(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new te("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
|
|
209
|
+
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},Xn=(e,t)=>{if(e.length===0)return[];const n=kt(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))},Zn=(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}))},er=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=He(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=D(d.chunkType??"unknown",d.filePath),m=D(we(d.searchParams),d.filePath),y=D(we(d.params),d.filePath);return` ${E(d.exportName)}: HttpStreamRef<${p}, ${m}, ${y}>;`}).join(`
|
|
210
|
+
`);return` ${E(N(i))}: {
|
|
211
211
|
${c}
|
|
212
212
|
};`}).join(`
|
|
213
|
-
`),o=n.map(([i,a])=>{const c=a.map(d=>` ${
|
|
214
|
-
`);return` ${
|
|
213
|
+
`),o=n.map(([i,a])=>{const c=a.map(d=>` ${E(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
|
|
214
|
+
`);return` ${E(N(i))}: {
|
|
215
215
|
${c}
|
|
216
216
|
},`}).join(`
|
|
217
217
|
`);return{block:`
|
|
@@ -223,7 +223,7 @@ ${r}
|
|
|
223
223
|
export const httpStreams: HttpStreamsRef = {
|
|
224
224
|
${o}
|
|
225
225
|
};
|
|
226
|
-
`,body:r}},
|
|
226
|
+
`,body:r}},Zr=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:s=!1,workflows:i=[]}=e,a=ne(s),c=[...n.filter(v=>v.visibility!=="internal"),...Xn(t,n),...Zn(o,n)],d=n.filter(v=>v.visibility==="internal"),p=at(c),m=at(d),y=er(r),u=`${p}
|
|
227
227
|
${m}
|
|
228
228
|
${y.body}`,l=Ve(u),f=l.length>0?`
|
|
229
229
|
import type { ${l.join(", ")} } from "./dataModel.js";
|
|
@@ -231,7 +231,7 @@ import type { ${l.join(", ")} } from "./dataModel.js";
|
|
|
231
231
|
${p}
|
|
232
232
|
`:"",R=m?`
|
|
233
233
|
${m}
|
|
234
|
-
`:"",x=
|
|
234
|
+
`:"",x=Hn(i,t),I=`export interface ApiTypes {${k}}
|
|
235
235
|
|
|
236
236
|
export const api = anyApi as unknown as ApiTypes;
|
|
237
237
|
|
|
@@ -240,9 +240,9 @@ export interface InternalApiTypes {${R}}
|
|
|
240
240
|
|
|
241
241
|
export const internal = anyApi as unknown as InternalApiTypes;
|
|
242
242
|
${x.block}${y.block}`,T=[...I.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],_=T.length>0?`import type { ${T.join(", ")} } from "${a.client}";
|
|
243
|
-
`:"";return
|
|
243
|
+
`:"";return yt(`${$}import { anyApi } from "${a.client}";
|
|
244
244
|
${_}${x.importLine}${f}
|
|
245
|
-
${I}`,s)},
|
|
245
|
+
${I}`,s)},eo=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
|
+
`:"",to=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=ne(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,s=e.map(c=>{g(c.exportName,"shape export name");const d=o(c),p=D(we(c.args),c.filePath),m=Object.keys(c.args).length>0,y=m?` args: ${p};`:` args?: ${p};`,u=m?`(args: ${p}) => void`:`(args?: ${p}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
|
|
263
263
|
export interface ${Ue(l)} {
|
|
264
264
|
${y}
|
|
265
265
|
/**
|
|
@@ -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
|
+
`},tr=(e,t)=>`lunora_${N(e)}_${String(t)}`,nr=`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
|
-
};`,
|
|
324
|
+
};`,rr=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,tr(l,o.size))};for(const l of e)s(l.filePath);for(const l of t)s(l.filePath);for(const l of n)s(l.filePath);for(const l of r)s(l.filePath);const i=[...o.entries()].map(([l,f])=>{if(!Cn.test(l))throw new te("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${f} from "../${l}.js";`}).join(`
|
|
325
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
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
329
|
`),m=n.map(l=>`${N(l.filePath)}:${l.exportName}`),y=[a,d].filter(l=>l.length>0).join(`
|
|
330
|
-
`),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const f=
|
|
330
|
+
`),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const f=In(l.args);return f===void 0?void 0:`installCompiledValidatorMap(${o.get(l.filePath)??""}.${l.exportName}.args, ${f});`}).filter(l=>l!==void 0).join(`
|
|
331
331
|
`);return{dispatchBody:y.length>0?`
|
|
332
332
|
${y}
|
|
333
333
|
`:"",importBlock:i.length>0?`${i}
|
|
@@ -336,15 +336,15 @@ ${y}
|
|
|
336
336
|
${c}
|
|
337
337
|
`:"",mutatorPaths:m,shapeBody:p.length>0?`
|
|
338
338
|
${p}
|
|
339
|
-
`:""}},
|
|
340
|
-
`);return` ${
|
|
339
|
+
`:""}},or=e=>{const t=He(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=D(we(a.args),a.filePath),d=c==="{}"?"?":"",p=D(wt(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` ${E(N(o))}: {
|
|
341
341
|
${i}
|
|
342
342
|
};`}).join(`
|
|
343
343
|
`);return{implementation:t.map(([o,s])=>{const i=N(o),a=s.map(c=>` ${c.exportName}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
|
|
344
|
-
`);return` ${
|
|
344
|
+
`);return` ${E(i)}: {
|
|
345
345
|
${a}
|
|
346
346
|
},`}).join(`
|
|
347
|
-
`),types:n}},
|
|
347
|
+
`),types:n}},ar=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=re(o);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&n.add(s.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},no=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:o=!1,hasAnalytics:s=!1,hasBrowser:i=!1,hasFlags:a=!1,hasHyperdrive:c=!1,hasImages:d=!1,hasKv:p=!1,hasNotify:m=!1,hasPayments:y=!1,hasPipelines:u=!1,hasR2sql:l=!1,hasX402:f=!1,identity:k,queues:R=[],schema:x,storageRuleBuckets:I=[],useUmbrella:T=!1,workflows:_=[]}={})=>{const v=ne(T),w=ar(x??{tables:[]},I).map(h=>JSON.stringify(h)).join(" | "),M=o?`import type { LunoraAi } from "@lunora/ai";
|
|
348
348
|
`:"",oe=o?`
|
|
349
349
|
readonly ai: LunoraAi;`:"",B=y?`import type { LunoraPayment } from "@lunora/payment";
|
|
350
350
|
`:"",ae=y?`
|
|
@@ -377,7 +377,7 @@ ${L}`:""}
|
|
|
377
377
|
}
|
|
378
378
|
|
|
379
379
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
380
|
-
export type Env = CloudflareBindings;`,j=(h,Me)=>Me?
|
|
380
|
+
export type Env = CloudflareBindings;`,j=(h,Me)=>Me?vn.get(h)?.field??"":"",ie=j("kv",p),le=j("analytics",s),$e=j("hyperdrive",c),Ne=j("browser",i),Te=j("images",d),ce=j("pipelines",u),V=j("r2sql",l),F=(x?.vectorIndexes.length??0)>0,H=F?' | "vectors"':"",Z=F?`
|
|
381
381
|
readonly vectors: VectorSearch<VectorIndexName>;`:"",de=F?`
|
|
382
382
|
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",G=F?`import type { VectorSearch, VectorSearchReader } from "${v.server}";
|
|
383
383
|
import type { VectorIndexName } from "./dataModel.js";
|
|
@@ -427,14 +427,14 @@ ${e.map(h=>(g(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.e
|
|
|
427
427
|
}`:"",Re=pe?`
|
|
428
428
|
readonly agents: LunoraAgents;`:"",_e=k?`import type { InferIdentity } from "${v.server}";
|
|
429
429
|
import type * as lunoraIdentityContract from "../identity.js";
|
|
430
|
-
`:"",
|
|
430
|
+
`:"",Ee=k?`
|
|
431
431
|
|
|
432
432
|
/** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
|
|
433
433
|
export type Identity = InferIdentity<typeof lunoraIdentityContract.${k.exportName}>;
|
|
434
434
|
|
|
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> };`:"",he=k?' | "auth"':"",me=k?`
|
|
437
|
-
readonly auth: NarrowedAuth;`:"",
|
|
437
|
+
readonly auth: NarrowedAuth;`:"",De=k?", Identity":"",Pe=n?`import type * as lunoraEnvContract from "../env.js";
|
|
438
438
|
`:"",Fe=n?`
|
|
439
439
|
|
|
440
440
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
@@ -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}${Ae}${Ie}${Le}${
|
|
558
|
+
export type StorageBucketName = ${w};${S}${Ae}${Ie}${Le}${Ee}${Fe}
|
|
559
559
|
|
|
560
560
|
/**
|
|
561
561
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -691,7 +691,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
|
|
|
691
691
|
* Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
|
|
692
692
|
* so the \`rls()\` chain discovers a policy authored either way the same.
|
|
693
693
|
*/
|
|
694
|
-
export const definePolicy = createPolicyDsl<DataModel, Relations${
|
|
694
|
+
export const definePolicy = createPolicyDsl<DataModel, Relations${De}>();
|
|
695
695
|
|
|
696
696
|
/**
|
|
697
697
|
* The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
|
|
@@ -708,12 +708,12 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Ee}>();
|
|
|
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
|
+
`},sr=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},ro=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=ne(i),{dispatchBody:p,importBlock:m,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:f}=rr(n,r,o,s),k=zn(t,n),R=Yn(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 T=
|
|
716
|
+
`);const T=sr(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\`.
|
|
@@ -737,14 +737,14 @@ 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
|
-
`:"",B=
|
|
740
|
+
`:"",B=or(n),ae=B.types?`
|
|
741
741
|
${B.types}
|
|
742
742
|
`:"",se=B.implementation?`
|
|
743
743
|
${B.implementation}
|
|
744
744
|
`:"",W=Ve(B.types),C=W.length>0?`import type { ${W.join(", ")} } from "./dataModel.js";
|
|
745
|
-
`:"",X=c?"context":"_context",L=c?`${
|
|
745
|
+
`:"",X=c?"context":"_context",L=c?`${nr}
|
|
746
746
|
|
|
747
|
-
`:"";return
|
|
747
|
+
`:"";return yt(`${$}${m}${k.importLine}${R.importLine}${M}${_}import { LunoraError } from "${d.server}";
|
|
748
748
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
749
749
|
${C}
|
|
750
750
|
/**
|
|
@@ -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)},ir=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=re(s);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},lr=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,s]of Object.entries(n.shape))re(s).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},cr=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},dr=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},ur=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},pr=(e,t)=>{const n=re(t),r={name:e,optional:gt(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=ur(n);return o!==void 0&&(r.enumValues=o),n.column?.notNull===!1&&(r.nullable=!0),r},hr=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(pr(o,s));t[n.name]=r}return t},mr=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:""},gr=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
|
-
`},P={build:"",configField:"",contextField:"",importLines:[],stub:""},
|
|
901
|
+
`},P={build:"",configField:"",contextField:"",importLines:[],stub:""},fr=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"])}:P,
|
|
915
|
+
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:O("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:P,br=(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:""}:P,
|
|
922
|
+
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:P,yr=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:""}:P,
|
|
926
|
+
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:P,wr=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:""}:P,
|
|
929
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:P,kr=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:""}:P,
|
|
932
|
+
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:P,xr=(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,25 +991,25 @@ 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}},vr=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"]})}:P,
|
|
999
|
+
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:O("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:P,Rr=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"])}:P,
|
|
1004
|
+
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:O("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:P,Sr=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:`
|
|
1008
|
-
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:O("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:P
|
|
1008
|
+
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:O("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:P,$r=e=>e?{build:`
|
|
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"])}:P,
|
|
1012
|
+
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:O("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:P,Nr=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"]})}:P,
|
|
1023
|
+
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:O("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:P,Tr=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"])}:P,
|
|
1027
|
+
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:O("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:P,oo=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(g(s.exportName,`container export "${s.exportName}"`),g(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
|
|
1028
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}`},Ar=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)g(r.exportName,`container export "${r.exportName}"`),g(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
|
|
1053
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}`},Sr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1058
1058
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1059
1059
|
${n}
|
|
1060
1060
|
];
|
|
1061
|
-
`}},
|
|
1061
|
+
`}},ao=e=>{if(e.length===0)return"";const t=e.map(r=>(g(r.exportName,`workflow export "${r.exportName}"`),g(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
|
|
1062
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,7 +1086,7 @@ 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}`},so=e=>{if(e.length===0)return"";const n=e.filter(a=>a.voice).length>0,r=e.map(a=>{g(a.exportName,`agent export "${a.exportName}"`),g(a.className,`agent class "${a.className}"`);const c=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
|
|
1090
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}");
|
|
@@ -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}`},io=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)g(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
|
|
1118
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
|
+
`},Or=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`workflow export "${n.exportName}"`),g(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
|
|
1133
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
|
+
`}},Ir=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`queue export "${n.exportName}"`),g(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
|
|
1142
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
|
+
`}},Cr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`agent export "${n.exportName}"`),g(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
|
|
1151
1151
|
`);return{build:`
|
|
1152
1152
|
const agents = createAgentContext(env, LUNORA_AGENTS);
|
|
1153
1153
|
`,contextField:`
|
|
@@ -1156,28 +1156,28 @@ ${t}
|
|
|
1156
1156
|
const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
|
|
1157
1157
|
${t}
|
|
1158
1158
|
];
|
|
1159
|
-
`}},
|
|
1159
|
+
`}},xt=(e,t,n,r,o)=>({constant:`
|
|
1160
1160
|
${o}
|
|
1161
1161
|
const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
|
|
1162
1162
|
`,override:`
|
|
1163
1163
|
protected override ${n}(): ${t} {
|
|
1164
1164
|
return ${e};
|
|
1165
1165
|
}
|
|
1166
|
-
`}),
|
|
1166
|
+
`}),Lr=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 xt("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. */")},_r=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 xt("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. */")},Er=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:""},Dr=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:""},Pr=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],lo=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:m=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:k=!1,hasR2sql:R=!1,hasX402:x=!1,maskMetadata:I,mutators:T=[],queues:_=[],rlsMetadata:v,schema:w,schemaSnapshot:M,shapes:oe=[],storageRules:B,studioFeatures:ae,useUmbrella:se=!1,workflows:W=[]})=>{const C=ne(se),X=T.length>0,L=oe.length>0,S=M===void 0?"":wn(M),j=M===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
|
-
`,ie=M===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:$e,contextField:Ne,stub:Te}=
|
|
1179
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(kn(M))}, json: ${JSON.stringify(S)} };
|
|
1180
|
+
`,ie=M===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:$e,contextField:Ne,stub:Te}=gr(a),ce=kr(i),V=fr(u),F=br(p,C.flags),H=xr(s,p,C.flags),Z=yr(l),de=wr(o),G=vr(c),U=Rr(y),K=Sr(m),Q=$r(d),q=Nr(R),ee=Tr(k),{build:Ae,contextField:ke,importLines:xe,specs:ue}=Ir(_),{build:Oe,contextField:Ie,importLines:ve,specs:pe}=Ar(r,w.jurisdiction),{build:Ce,contextField:Le,importLines:Re,specs:_e}=Or(W),{build:Ee,contextField:he,importLines:me,specs:De}=Cr(n),{build:Pe,configField:Fe,contextField:ge,imports:fe,stub:Je}=Er(f),{build:h,configField:Me,imports:Rt,stub:St}=Dr(x),$t=e,Nt=t,Tt=v??{policies:[],roles:[]},At=I??{columns:[]},Ot=B??{rules:[]},It=ae??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ct,override:Lt}=Lr(W),{constant:_t,override:Et}=_r(_),J=w.vectorIndexes.length>0,ze=new Set(w.tables.filter(b=>typeof b.shardMode=="object"&&b.shardMode.kind==="shardBy").map(b=>b.name)),Se=w.vectorIndexes.some(b=>ze.has(b.table)),be=w.tables.some(b=>b.shardMode==="global"),Be=w.tables.some(b=>b.shardMode==="global"&&b.globalBackend==="hyperdrive"),Ye=w.tables.some(b=>b.shardMode==="global"&&b.globalBackend!=="hyperdrive"),z=w.tables.some(b=>b.externalSource!==void 0),Xe=w.tables.some(b=>b.memory===!0),je=w.tables.some(b=>b.shardMode!=="global"&&b.searchIndexes.length>0);if(Ye&&Be)throw new te("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const qe=w.tables.length>0,Dt=ir(w),Pt=cr(w),Ft=hr(w),Mt=lr(w),Ze=dr(w),et=Pr(J,W.length>0,_.length>0,p,je);L&&et.push("WhereInput");const tt=mr(be),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,25 +1230,25 @@ 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=X?`
|
|
1234
1234
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1235
1235
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1236
1236
|
}
|
|
1237
|
-
`:"",
|
|
1238
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
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;`:"",
|
|
1240
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1241
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
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, ":"",ye=[`import type { ${et.join(", ")} } from "${C.do}";`,`import { applyCdcChanges, ${je?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${Xe?"clearMemoryTables, ":""}${Wt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${z?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Se?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${tt.importFragment}ShardDO as ShardDOBase } from "${C.do}";`,...z?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${C.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes } from "${C.server}";`:`import { asBucketStorage, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes } from "${C.server}";`];qe&&ye.push(`import { bindOrm, bindTableFacade } from "${C.server}";`),J&&ye.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&ye.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ye.push(...ce.importLines,...V.importLines,...F.importLines,...Z.importLines,...de.importLines,...G.importLines,...U.importLines,...K.importLines,...Q.importLines,...q.importLines,...ee.importLines,...ve,...Re,...xe,...me,...fe,...Rt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...X?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ut=J?`
|
|
1238
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Kt=Ye?`
|
|
1239
|
+
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Qt=Be?`
|
|
1240
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Vt=z?`
|
|
1241
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Ht='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Gt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Jt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',zt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Yt=be?O("globalDbStub: DatabaseWriterLike",Ht,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Xt=J?O("vectorsStub: VectorSearchLike",Gt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Zt=Se?`
|
|
1242
1242
|
const vectorShardKey = this.currentShardKey();
|
|
1243
|
-
`:"",
|
|
1243
|
+
`:"",en=Se?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",tn=Se?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${w.vectorIndexes.filter(b=>ze.has(b.table)).map(b=>JSON.stringify(b.name)).join(", ")}] }`:"",nn=J?`
|
|
1244
1244
|
let vectors: VectorSearchLike;
|
|
1245
1245
|
let onWrite: WriteHook | undefined;
|
|
1246
1246
|
|
|
1247
1247
|
if (config.vectors) {
|
|
1248
1248
|
const lunora = createVectors({ indexes: config.vectors(env) });
|
|
1249
|
-
${
|
|
1250
|
-
vectors = createContextVectors(lunora${
|
|
1251
|
-
onWrite = createVectorSyncHook({ ${
|
|
1249
|
+
${Zt}
|
|
1250
|
+
vectors = createContextVectors(lunora${tn});
|
|
1251
|
+
onWrite = createVectorSyncHook({ ${en}schema: schema as unknown as VectorSchemaLike, vectors });
|
|
1252
1252
|
} else {
|
|
1253
1253
|
vectors = vectorsStub;
|
|
1254
1254
|
onWrite = undefined;
|
|
@@ -1260,7 +1260,7 @@ ${Xt}
|
|
|
1260
1260
|
// \`__cdc_log\`. Wrapped AFTER \`onWrite\` is built so the write-through
|
|
1261
1261
|
// vector-sync hook keeps calling the bare facade.
|
|
1262
1262
|
vectors = markUnvouchableReads(vectors, options.onRead, ["getByIds", "query"]);
|
|
1263
|
-
`:"",
|
|
1263
|
+
`:"",rn=`{
|
|
1264
1264
|
auth: { identity: identity ?? null, userId: userId ?? null },
|
|
1265
1265
|
broadcast: (delta) => {
|
|
1266
1266
|
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
@@ -1301,11 +1301,11 @@ ${Xt}
|
|
|
1301
1301
|
scheduler,
|
|
1302
1302
|
schema: schema as unknown as SchemaLike,
|
|
1303
1303
|
sql: this.sql as SqlExec,
|
|
1304
|
-
});`,
|
|
1305
|
-
vectors,`:"",
|
|
1306
|
-
orm: bindOrm(facade),`:"",We=Be?"config.hyperdriveGlobal":"config.d1",
|
|
1304
|
+
});`,on=J?`
|
|
1305
|
+
vectors,`:"",an=qe?`
|
|
1306
|
+
orm: bindOrm(facade),`:"",We=Be?"config.hyperdriveGlobal":"config.d1",sn=be?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
|
|
1307
1307
|
const globalDb: DatabaseWriterLike = ${We}?.(env, globalRequest) ?? globalDbStub;
|
|
1308
|
-
`:"",
|
|
1308
|
+
`:"",ln=L&&be?`
|
|
1309
1309
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1310
1310
|
const env = this.env as Record<string, unknown>;
|
|
1311
1311
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1350,17 +1350,17 @@ ${Xt}
|
|
|
1350
1350
|
|
|
1351
1351
|
return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
|
|
1352
1352
|
}
|
|
1353
|
-
`:"",
|
|
1353
|
+
`:"",cn=z?`
|
|
1354
1354
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1355
1355
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1356
|
-
`:"",
|
|
1356
|
+
`:"",dn=`
|
|
1357
1357
|
protected override async runShardInit(): Promise<void> {
|
|
1358
1358
|
this.ensureMigrated();
|
|
1359
1359
|
${Xe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
|
|
1360
1360
|
`:""}
|
|
1361
1361
|
await this.dispatchShardInit();
|
|
1362
1362
|
}
|
|
1363
|
-
`,
|
|
1363
|
+
`,un=z?`
|
|
1364
1364
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1365
1365
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1366
1366
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1495,7 +1495,7 @@ ${Xe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1495
1495
|
|
|
1496
1496
|
return nextDueAt;
|
|
1497
1497
|
}
|
|
1498
|
-
`:"",nt=Ze.length>0,
|
|
1498
|
+
`:"",nt=Ze.length>0,pn=z||nt?`
|
|
1499
1499
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1500
1500
|
super(state, env);
|
|
1501
1501
|
${z?`
|
|
@@ -1513,21 +1513,21 @@ ${z?`
|
|
|
1513
1513
|
void this.scheduleTtlSweep();
|
|
1514
1514
|
}
|
|
1515
1515
|
`:""} }
|
|
1516
|
-
`:"",
|
|
1516
|
+
`:"",hn=qe?`
|
|
1517
1517
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1518
1518
|
${w.tables.map(b=>` facade[${JSON.stringify(b.name)}] = bindTableFacade(db, ${JSON.stringify(b.name)});`).join(`
|
|
1519
1519
|
`)}
|
|
1520
|
-
`:"",
|
|
1520
|
+
`:"",mn=`${ce.build}${V.build}${F.build}${G.build}${de.build}
|
|
1521
1521
|
const secrets = createSecrets(env);
|
|
1522
|
-
`,
|
|
1523
|
-
secrets,`,
|
|
1522
|
+
`,gn=`${ce.contextField}${V.contextField}${F.contextField}${Z.contextField}${G.contextField}${de.contextField}
|
|
1523
|
+
secrets,`,fn=Z.build,rt=y||m||d||R||k||x,bn=rt?`
|
|
1524
1524
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1525
1525
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
1526
1526
|
if (isAction) {
|
|
1527
1527
|
${U.build}${K.build}${Q.build}${q.build}${ee.build}${h}${[...y?[" ctx.images = images;"]:[],...m?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...R?[" ctx.r2sql = r2sql;"]:[],...k?[" ctx.pipelines = pipelines;"]:[],...x?[" ctx.x402 = x402;"]:[]].join(`
|
|
1528
1528
|
`)}
|
|
1529
1529
|
}
|
|
1530
|
-
`:"",
|
|
1530
|
+
`:"",yn=rt?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
|
|
1531
1531
|
`:"";return`${$}${ye.join(`
|
|
1532
1532
|
`)}
|
|
1533
1533
|
|
|
@@ -1541,47 +1541,47 @@ interface FunctionReference {
|
|
|
1541
1541
|
const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(Dt,void 0,4)};
|
|
1542
1542
|
|
|
1543
1543
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1544
|
-
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(
|
|
1544
|
+
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(Pt,void 0,4)};
|
|
1545
1545
|
|
|
1546
1546
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1547
1547
|
const LUNORA_TABLE_COLUMNS: Record<
|
|
1548
1548
|
string,
|
|
1549
1549
|
Array<{ bucket?: string; enumValues?: string[]; isStorage?: boolean; name: string; nullable?: boolean; optional: boolean; pk?: boolean; ref?: string; type: string }>
|
|
1550
|
-
> = ${JSON.stringify(
|
|
1550
|
+
> = ${JSON.stringify(Ft,void 0,4)};
|
|
1551
1551
|
|
|
1552
1552
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1553
|
-
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(
|
|
1553
|
+
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(Mt,void 0,4)};
|
|
1554
1554
|
|
|
1555
1555
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1556
1556
|
const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(Ze,void 0,4)};
|
|
1557
1557
|
|
|
1558
1558
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1559
|
-
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(
|
|
1559
|
+
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify($t,void 0,4)};
|
|
1560
1560
|
|
|
1561
1561
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1562
|
-
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(
|
|
1562
|
+
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(Nt,void 0,4)};
|
|
1563
1563
|
|
|
1564
1564
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1565
|
-
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(
|
|
1565
|
+
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(Tt,void 0,4)};
|
|
1566
1566
|
|
|
1567
1567
|
/** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
|
|
1568
|
-
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(
|
|
1568
|
+
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(At,void 0,4)};
|
|
1569
1569
|
|
|
1570
1570
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1571
|
-
const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(
|
|
1571
|
+
const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Ot,void 0,4)};
|
|
1572
1572
|
|
|
1573
1573
|
/** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
|
|
1574
|
-
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(
|
|
1575
|
-
${j}${H.constant}${
|
|
1574
|
+
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(It,void 0,4)};
|
|
1575
|
+
${j}${H.constant}${qt}${Ct}${_t}${pe}${_e}${ue}${De}
|
|
1576
1576
|
export interface ShardDOConfig {
|
|
1577
1577
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1578
1578
|
cdc?: boolean;
|
|
1579
1579
|
/** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
|
|
1580
1580
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1581
1581
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1582
|
-
storage?: (env: Record<string, unknown>) => unknown;${
|
|
1582
|
+
storage?: (env: Record<string, unknown>) => unknown;${Ut}${$e}${V.configField}${F.configField}${G.configField}${U.configField}${K.configField}${Q.configField}${q.configField}${ee.configField}${Fe}${Me}${Kt}${Qt}${Vt}
|
|
1583
1583
|
}
|
|
1584
|
-
${O("schedulerStub",
|
|
1584
|
+
${O("schedulerStub",Jt,["cancel","runAfter","runAt"])}${O("storageStub",zt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${Yt}${cn}${Xt}${Te}${V.stub}${F.stub}${G.stub}${U.stub}${K.stub}${Q.stub}${q.stub}${ee.stub}${Je}${St}
|
|
1585
1585
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1586
1586
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1587
1587
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -1618,7 +1618,7 @@ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: R
|
|
|
1618
1618
|
* from the worker entry so wrangler binds it by name.
|
|
1619
1619
|
*/
|
|
1620
1620
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1621
|
-
class extends ShardDOBase {${
|
|
1621
|
+
class extends ShardDOBase {${pn}
|
|
1622
1622
|
private migrated = false;
|
|
1623
1623
|
|
|
1624
1624
|
public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker): Promise<unknown> {
|
|
@@ -1734,11 +1734,11 @@ ${tt.override}
|
|
|
1734
1734
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
|
|
1735
1735
|
};
|
|
1736
1736
|
}
|
|
1737
|
-
${
|
|
1737
|
+
${jt}${Bt}${ln}${un}
|
|
1738
1738
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor"): readonly string[] {
|
|
1739
1739
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1740
1740
|
}
|
|
1741
|
-
${
|
|
1741
|
+
${dn}
|
|
1742
1742
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1743
1743
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
1744
1744
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -1820,7 +1820,7 @@ ${cn}
|
|
|
1820
1820
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1821
1821
|
return LUNORA_STUDIO_FEATURES;
|
|
1822
1822
|
}
|
|
1823
|
-
${H.evaluateOverride}${H.subscriptionOverride}${
|
|
1823
|
+
${H.evaluateOverride}${H.subscriptionOverride}${Lt}${Et}
|
|
1824
1824
|
protected override advisories(): AdvisoryFinding[] {
|
|
1825
1825
|
return LUNORA_ADVISORIES;
|
|
1826
1826
|
}
|
|
@@ -2062,7 +2062,7 @@ ${je?`
|
|
|
2062
2062
|
// dispatch path) fall back to the per-request fields as before.
|
|
2063
2063
|
const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
|
|
2064
2064
|
const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
|
|
2065
|
-
${
|
|
2065
|
+
${nn}${le}${mn}${Oe}${Ce}${Ae}${Ee}
|
|
2066
2066
|
// \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
|
|
2067
2067
|
// reaches through, and pending jobs live in the SchedulerDO — nothing the
|
|
2068
2068
|
// CDC changelog records — so reading them must forfeit a delta resume.
|
|
@@ -2124,13 +2124,13 @@ ${tn}${le}${hn}${Oe}${Ce}${Ae}${De}
|
|
|
2124
2124
|
// so both write to the same trace.
|
|
2125
2125
|
const span = this.makeDispatchSpan(traceAnchor, observability);
|
|
2126
2126
|
|
|
2127
|
-
${
|
|
2127
|
+
${sn} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
|
|
2128
2128
|
// adds aggregate counters (call count, total time, per-operation
|
|
2129
2129
|
// breakdown) to the wide event rather than a span per call, so a
|
|
2130
2130
|
// handler making hundreds of queries stays readable. See
|
|
2131
2131
|
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
2132
|
-
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${
|
|
2133
|
-
${
|
|
2132
|
+
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${rn}), logFunctionPath, traceAnchor, observability);
|
|
2133
|
+
${hn}${Pe}
|
|
2134
2134
|
|
|
2135
2135
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
2136
2136
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -2138,7 +2138,7 @@ ${pn}${Pe}
|
|
|
2138
2138
|
// writing mutation's trace from the shared per-request field.
|
|
2139
2139
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
|
|
2140
2140
|
const metrics = this.makeMetrics(logFunctionPath, observability);
|
|
2141
|
-
${
|
|
2141
|
+
${fn}
|
|
2142
2142
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
2143
2143
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
2144
2144
|
// Query/mutation handlers must be deterministic (they may be re-run on
|
|
@@ -2161,13 +2161,13 @@ ${gn}
|
|
|
2161
2161
|
ip: this.getCurrentIp(),
|
|
2162
2162
|
log,
|
|
2163
2163
|
metrics,
|
|
2164
|
-
now,${
|
|
2164
|
+
now,${an}
|
|
2165
2165
|
scheduler,
|
|
2166
2166
|
span,
|
|
2167
2167
|
storage: contextStorage,
|
|
2168
|
-
trace,${
|
|
2168
|
+
trace,${on}${Ne}${gn}${ge}${Ie}${Le}${ke}${he}
|
|
2169
2169
|
};
|
|
2170
|
-
${
|
|
2170
|
+
${yn}${bn}
|
|
2171
2171
|
ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
|
|
2172
2172
|
ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
|
|
2173
2173
|
// \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
|
|
@@ -2193,21 +2193,21 @@ ${bn}${fn}
|
|
|
2193
2193
|
return ctx;
|
|
2194
2194
|
}
|
|
2195
2195
|
};
|
|
2196
|
-
`},Ge=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:A(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:A(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Ge(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},
|
|
2196
|
+
`},Ge=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:A(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:A(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Ge(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},vt=(e,t)=>{const n=re(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Fr=(e,t,n)=>{g(e,"drizzle column name");const r=Ge(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=vt(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},Mr=e=>{g(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(g(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},Br=(e,t)=>{g(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,s])=>` ${o}: ${Fr(o,s,t)},`)].join(`
|
|
2197
2197
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2198
|
-
${e.indexes.map(o=>
|
|
2198
|
+
${e.indexes.map(o=>Mr(o)).join(`
|
|
2199
2199
|
`)}
|
|
2200
2200
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2201
2201
|
${n}
|
|
2202
|
-
}${r});`},
|
|
2203
|
-
`;const n=ne(t),r=new Set(e.map(m=>m.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=
|
|
2202
|
+
}${r});`},jr=e=>e.typeAnnotation?.includes('Id<"')??!1,qr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Ge(a);n.add(c.builder),s=s||jr(c),o=o||vt(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}},st=(e,t=!1)=>{if(e.length===0)return`${$}export {};
|
|
2203
|
+
`;const n=ne(t),r=new Set(e.map(m=>m.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=qr(e,r),c=[...s,...o].toSorted((m,y)=>m.localeCompare(y)),d=e.map(m=>Br(m,r)).join(`
|
|
2204
2204
|
|
|
2205
2205
|
`),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2206
2206
|
`:"",a?`import type { Id } from "./dataModel.js";
|
|
2207
2207
|
`:""].join("");return`${$}import { ${c.join(", ")} } from "${n.serverDrizzle}";
|
|
2208
2208
|
${p}
|
|
2209
2209
|
${d}
|
|
2210
|
-
`},
|
|
2210
|
+
`},co=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:D(st(n,t),Qe),shard:D(st(r,t),Qe)}},uo=e=>{const t=new Map;for(const i of e){const a=t.get(i.cron);a?a.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
|
|
2211
2211
|
`),r=n.length>0?`
|
|
2212
2212
|
${n}
|
|
2213
2213
|
`:"",o=[...t.entries()].map(([i,a])=>{const c=a.map(d=>{const p=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${p}, args: ${JSON.stringify(d.args)} },`}).join(`
|
|
@@ -2241,7 +2241,7 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
|
|
|
2241
2241
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2242
2242
|
*/
|
|
2243
2243
|
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
|
|
2244
|
-
`},
|
|
2244
|
+
`},po=e=>{const t=[...e].toSorted((r,o)=>r.name.localeCompare(o.name)).map(r=>{const o=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&o.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&o.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&o.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&o.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${o.join(", ")} },`}).join(`
|
|
2245
2245
|
`),n=t.length>0?`
|
|
2246
2246
|
${t}
|
|
2247
2247
|
`:"";return`${$}/**
|
|
@@ -2265,4 +2265,4 @@ export interface LunoraVectorIndex {
|
|
|
2265
2265
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2266
2266
|
*/
|
|
2267
2267
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2268
|
-
`},
|
|
2268
|
+
`},ho=e=>[...new Set(e.map(t=>t.cron))];export{Yr as A,xn as C,$ as G,Kn as U,Zr as a,to as b,oo as c,uo as d,so as e,Xr as f,co as g,ro as h,no as i,lo as j,po as k,ao as l,ho as m,lr as n,io as o,eo as p};
|