@lunora/codegen 1.0.0-alpha.207 → 1.0.0-alpha.209
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-uwXtvaIR.mjs +1 -0
- package/dist/packem_shared/{MUTATORS_FILENAME-Dv8PMtzE.mjs → MUTATORS_FILENAME-CE7K7DfT.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION--vy88dC-.mjs → OPENRPC_VERSION-BDtZHc87.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-D6t1w2ef.mjs +9 -0
- package/dist/packem_shared/{buildOpenApiDocument-Ckg1Yc6n.mjs → buildOpenApiDocument-Bj_gSM-g.mjs} +1 -1
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-7IsdPbJJ.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-HeBP7vhK.mjs +1 -0
- package/dist/packem_shared/{emit-Ba1jzhVh.mjs → emit-CE9-QEca.mjs} +66 -66
- package/dist/packem_shared/{emitApp-DSSyAMLC.mjs → emitApp-bdvaYlkn.mjs} +1 -1
- package/dist/packem_shared/unwrap-handler-return-BEdusskg.mjs +1 -0
- package/package.json +7 -7
- package/dist/packem_shared/GENERATED_HEADER-D78azhBx.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bg_8gyHl.mjs +0 -9
- package/dist/packem_shared/discoverFunctions-azmV60kc.mjs +0 -1
- package/dist/packem_shared/discoverHttpRoutes-BrDDCDdD.mjs +0 -1
- package/dist/packem_shared/unwrap-handler-return-FZxbgxxx.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as
|
|
1
|
+
import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{d as Nn}from"./declared-output-Iaar469J.mjs";import{isHyperdriveGlobalTable as An,isD1GlobalTable as On}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as A}from"./paths-C-9fwEgQ.mjs";import{acceptsAbsentIr as In}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const mt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access",requiredPackage:"@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",requiredPackage:"@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",requiredPackage:"@lunora/bindings",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:"Build the `ctx.browser` helper, e.g. `(env) => createBrowser({ binding: env.BROWSER, launch })`. REQUIRED: unlike the binding-backed capabilities, `ctx.browser` is not auto-constructed — without this thunk every method throws, because the generated worker deliberately stays free of the optional `@cloudflare/playwright` peer.",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",requiredPackage:"@lunora/browser",serverCtxField:{field:`
|
|
4
4
|
/** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
|
|
@@ -15,41 +15,41 @@ import{agentComponent as pt}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"}],Cn=mt,Dn=new Map(Cn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),ha=mt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),gt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,Ln=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),ft=e=>e.column!==void 0,En=(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
|
-
`,
|
|
25
|
-
`}},Ge=(e,t,n)=>{if(!ft(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if(
|
|
23
|
+
`}},_n=(e,t)=>e.stringMaxLength===void 0?"":`if (${t}.length > ${String(e.stringMaxLength)}) return DEFER;
|
|
24
|
+
`,Pn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!gt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
|
|
25
|
+
`}},Ge=(e,t,n)=>{if(!ft(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if(Ln.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:En(e.kind,t)+_n(e,t)};switch(e.kind){case"array":return Mn(e,t,n);case"literal":return Pn(e,t);case"object":return qn(e,t,n);default:return}}},Mn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const a=n.next(),o=`__arr${String(a)}`,i=`__i${String(a)}`,s=`__e${String(a)}`,c=Ge(r,s,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
|
|
26
26
|
const ${o} = new Array(${t}.length);
|
|
27
27
|
for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
|
|
28
28
|
const ${s} = ${t}[${i}];
|
|
29
29
|
${c.pre}${o}[${i}] = ${c.out};
|
|
30
30
|
}
|
|
31
|
-
`;return{out:o,pre:d}},
|
|
31
|
+
`;return{out:o,pre:d}},Fn=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||ft(t))return;const{inner:i}=t;if(!i)return;const s=Ge(i,n,r);if(!s)return;const c=r.next(),d=`__has${String(c)}`,h=`__val${String(c)}`,g=`let ${d} = false;
|
|
32
32
|
let ${h};
|
|
33
33
|
if (${n} !== undefined) {
|
|
34
34
|
${s.pre}${h} = ${s.out};
|
|
35
35
|
${d} = true;
|
|
36
36
|
}
|
|
37
|
-
`;return{entry:`...(${d} ? { ${a}: ${h} } : {})`,pre:g}}const o=Ge(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},
|
|
38
|
-
`,c=h}const d=
|
|
39
|
-
`},
|
|
37
|
+
`;return{entry:`...(${d} ? { ${a}: ${h} } : {})`,pre:g}}const o=Ge(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},Bn=new Set(Object.getOwnPropertyNames(Object.prototype)),bt=(e,t,n)=>{let r="";const a=[];for(const o of Object.keys(e)){const i=e[o];if(!i)return;const s=JSON.stringify(o);let c=`${t}[${s}]`;if(Bn.has(o)){const h=`__f${String(n.next())}`;r+=`const ${h} = Object.hasOwn(${t}, ${s}) ? ${t}[${s}] : undefined;
|
|
38
|
+
`,c=h}const d=Fn(o,i,c,n);if(!d)return;r+=d.pre,a.push(d.entry)}return{entries:a.join(", "),pre:r}},yt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
|
|
39
|
+
`},qn=(e,t,n)=>{const r=e.shape??{},a=bt(r,t,n);if(!a)return;const o=n.next(),i=`__obj${String(o)}`,s=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
|
|
40
40
|
${yt(t)}${a.pre}const ${i} = { ${a.entries} };
|
|
41
|
-
`;return{out:i,pre:s}},
|
|
41
|
+
`;return{out:i,pre:s}},jn=e=>{let t=0;const r=bt(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
|
|
42
42
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
43
43
|
${yt("source")}${r.pre}return { ${r.entries} };
|
|
44
44
|
}`},S=`// GENERATED by @lunora/codegen — do not edit.
|
|
45
45
|
// Run \`lunora codegen\` to regenerate.
|
|
46
46
|
|
|
47
|
-
`,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"},wt=/^[A-Za-z_$][\w$]*$/u,
|
|
47
|
+
`,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"},wt=/^[A-Za-z_$][\w$]*$/u,Wn=/^[\w./-]+$/u,f=(e,t)=>{if(!wt.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=>wt.test(e)?e:JSON.stringify(e),Y=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),Un={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"},Kn=e=>{if(e===void 0)return"unknown";if(!gt.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},N=e=>{const t=Un[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?N(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 Kn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,a])=>kt(r,a)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?N(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?N(e.keyType):"string",r=e.valueType?N(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>N(n)).join(" | "):"never";default:return"unknown"}},kt=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?N(t.inner):"unknown";return`${n}?: ${r}`}return In(t)?`${n}?: ${N(t)}`:`${n}: ${N(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>kt(n,r)).join("; ")} }`},xt=e=>e.kind==="optional"||!!e.column?.hasDefault,se=e=>e.kind==="optional"&&e.inner?e.inner:e,Qn=e=>{f(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=se(a),i=N(o),s=q(r);return xt(a)?` ${s}?: ${i};`:` ${s}: ${i};`}).join(`
|
|
48
48
|
`),n=t?`
|
|
49
49
|
${t}
|
|
50
50
|
`:"";return`export interface Insert_${e.name} {
|
|
51
51
|
_id?: Id<"${e.name}">;
|
|
52
|
-
_creationTime?: number;${n}}`},Je="schema",
|
|
52
|
+
_creationTime?: number;${n}}`},Je="schema",pa=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const $=q(x);if(v.kind==="optional"){const T=v.inner?N(v.inner):"unknown";return` ${$}?: ${T};`}return` ${$}: ${N(v)};`}).join(`
|
|
53
53
|
`),b=l?`
|
|
54
54
|
${l}
|
|
55
55
|
`:"",R=u.commitOrdered===!0?`
|
|
@@ -62,7 +62,7 @@ ${l}
|
|
|
62
62
|
`),i=e.tables.map(u=>{const l=u.searchIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
63
63
|
`),s=e.tables.map(u=>{const l=u.rankIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
64
64
|
`),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
65
|
-
`),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",h=e.tables.map(u=>
|
|
65
|
+
`),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",h=e.tables.map(u=>Qn(u)).join(`
|
|
66
66
|
|
|
67
67
|
`),g=e.tables.map(u=>` ${u.name}: Insert_${u.name};`).join(`
|
|
68
68
|
`),y=e.tables.map(u=>{const l=u.relations.map(b=>(f(b.table,"relation target table"),` ${q(b.name)}: ${b.kind==="one"?"OneRelation":"ManyRelation"}<"${b.table}">;`)).join(`
|
|
@@ -161,11 +161,11 @@ export interface Relations {
|
|
|
161
161
|
${y}
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
`,Je)},
|
|
164
|
+
`,Je)},Hn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,vt=/^(?:\.\.?\/)*_generated\//u,St=/\.[A-Za-z]\w*$/u,Vn=e=>e.replaceAll(Hn,(t,n)=>{const r=n.replace(vt,"./");return`import("${St.test(r)?r:`${r}.js`}")`}),Gn=/import\("(?<spec>[^"]+)"\)/gu,dt="node_modules/",Jn=/^@types\//u,zn=e=>e.replaceAll(Gn,(t,n)=>{const r=n.lastIndexOf(dt);if(r===-1||r>0&&n[r-1]!=="/")return t;const a=n.slice(r+dt.length);return a===""||Jn.test(a)?t:`import("${a}")`}),Yn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Xn=/^(?:\.\.?\/)+/u,Zn=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("/")},er=(e,t)=>e.replaceAll(Yn,(n,r)=>{if(vt.test(r.replace(Xn,"")))return n;const a=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Zn(`${a}/${r}`)}`;return`import("${St.test(i)?i:`${i}.js`}")`}),L=(e,t)=>Vn(er(zn(e),t)),tr=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],nr=new RegExp(String.raw`import\("@lunora/(?<pkg>${tr.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),rr={flags:new Set(["/web"]),platform:new Set},Rt=(e,t)=>t?e.replaceAll(nr,(n,r,a)=>{const o=rr[r];return a&&o&&!o.has(a)?n:`import("lunorash/${r}${a??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),$t=e=>Nn(e)?N(e.output):e.returnType,Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},ut=e=>{const t=([n,r])=>{const a=r.toSorted((o,i)=>o.exportName.localeCompare(i.exportName)).map(o=>{const i=L(xe(o.args),o.filePath),s=L($t(o),o.filePath);return` ${o.exportName}: FunctionReference<"${o.kind}", ${i}, ${s}>;`}).join(`
|
|
165
165
|
`);return` ${q(A(n))}: {
|
|
166
166
|
${a}
|
|
167
167
|
};`};return Ye(e).map(n=>t(n)).join(`
|
|
168
|
-
`)},
|
|
168
|
+
`)},ar=(e,t)=>{if(e.length===0&&t.length===0)return{block:"",importLine:""};const n=[];let r="";if(e.length>0&&(r+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),r+=`
|
|
169
169
|
/** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
|
|
170
170
|
export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
171
171
|
readonly isLunoraWorkflow: true;
|
|
@@ -197,7 +197,7 @@ export const agents: AgentsRef = {
|
|
|
197
197
|
${i}
|
|
198
198
|
};
|
|
199
199
|
`,n.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
200
|
-
`)}return{block:r,importLine:n.join("")}},
|
|
200
|
+
`)}return{block:r,importLine:n.join("")}},or=()=>Object.keys(pt().functions).toSorted((e,t)=>e.localeCompare(t)),Tt=e=>new Set(e.filter(t=>A(t.filePath)==="agents").map(t=>t.exportName)),sr=()=>new Set(Object.entries(pt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),ir=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Tt(t),a=sr(),o=t.find(s=>A(s.filePath)==="agents"&&a.has(s.exportName));if(o)throw new X("INTERNAL",`@lunora/codegen: "agents:${o.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${o.exportName}" export in ${o.filePath}`);const i=or().filter(s=>!r.has(s));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
201
201
|
`,lines:i.map(s=>` "agents:${s}": lunoraAgentRuntimeFunctions.${s} as unknown as RegisteredLunoraFunction,`).join(`
|
|
202
202
|
`),prelude:`
|
|
203
203
|
/**
|
|
@@ -206,8 +206,8 @@ ${i}
|
|
|
206
206
|
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
207
207
|
*/
|
|
208
208
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
209
|
-
`}},
|
|
210
|
-
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},
|
|
209
|
+
`}},lr=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>A(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new X("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
|
|
210
|
+
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},cr=(e,t)=>{if(e.length===0)return[];const n=Tt(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 a of e)a.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${a.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(a=>!n.has(a.exportName))},dr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>A(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}))},ur=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,s])=>{const c=s.map(d=>{const h=L(d.chunkType??"unknown",d.filePath),g=L(xe(d.searchParams),d.filePath),y=L(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${h}, ${g}, ${y}>;`}).join(`
|
|
211
211
|
`);return` ${q(A(i))}: {
|
|
212
212
|
${c}
|
|
213
213
|
};`}).join(`
|
|
@@ -224,7 +224,7 @@ ${r}
|
|
|
224
224
|
export const httpStreams: HttpStreamsRef = {
|
|
225
225
|
${a}
|
|
226
226
|
};
|
|
227
|
-
`,body:r}},
|
|
227
|
+
`,body:r}},ma=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=oe(o),c=[...n.filter(O=>O.visibility!=="internal"),...cr(t,n),...dr(a,n)],d=n.filter(O=>O.visibility==="internal"),h=ut(c),g=ut(d),y=ur(r),u=`${h}
|
|
228
228
|
${g}
|
|
229
229
|
${y.body}`,l=ze(u),b=l.length>0?`
|
|
230
230
|
import type { ${l.join(", ")} } from "./dataModel.js";
|
|
@@ -232,7 +232,7 @@ import type { ${l.join(", ")} } from "./dataModel.js";
|
|
|
232
232
|
${h}
|
|
233
233
|
`:"",x=g?`
|
|
234
234
|
${g}
|
|
235
|
-
`:"",v=
|
|
235
|
+
`:"",v=ar(i,t),$=`export interface ApiTypes {${R}}
|
|
236
236
|
|
|
237
237
|
export const api = anyApi as unknown as ApiTypes;
|
|
238
238
|
|
|
@@ -243,7 +243,7 @@ export const internal = anyApi as unknown as InternalApiTypes;
|
|
|
243
243
|
${v.block}${y.block}`,T=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],H=T.length>0?`import type { ${T.join(", ")} } from "${s.client}";
|
|
244
244
|
`:"";return Rt(`${S}import { anyApi } from "${s.client}";
|
|
245
245
|
${H}${v.importLine}${b}
|
|
246
|
-
${$}`,o)},
|
|
246
|
+
${$}`,o)},ga=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
247
247
|
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
248
248
|
|
|
249
249
|
import schema from "../schema.js";
|
|
@@ -260,7 +260,7 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
260
260
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
261
261
|
*/
|
|
262
262
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
263
|
-
`:"",
|
|
263
|
+
`:"",fa=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=oe(n),a=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,o=e.map(c=>{f(c.exportName,"shape export name");const d=a(c),h=L(xe(c.args),c.filePath),g=Object.keys(c.args).length>0,y=g?` args: ${h};`:` args?: ${h};`,u=g?`(args: ${h}) => void`:`(args?: ${h}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
|
|
264
264
|
export interface ${Ve(l)} {
|
|
265
265
|
${y}
|
|
266
266
|
/**
|
|
@@ -314,7 +314,7 @@ import type { Collection } from "@tanstack/db";
|
|
|
314
314
|
import { createCollection } from "@tanstack/db";
|
|
315
315
|
${s}
|
|
316
316
|
${o}
|
|
317
|
-
`},
|
|
317
|
+
`},hr=(e,t)=>`lunora_${A(e)}_${String(t)}`,pr=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
318
318
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
319
319
|
|
|
320
320
|
if (!registered) {
|
|
@@ -343,13 +343,13 @@ ${o}
|
|
|
343
343
|
}
|
|
344
344
|
|
|
345
345
|
return (await registered.handler(context, args ?? {})) as R;
|
|
346
|
-
};`,
|
|
346
|
+
};`,mr=(e,t,n=[],r=[])=>{const a=new Map,o=l=>{a.has(l)||a.set(l,hr(l,a.size))};for(const l of e)o(l.filePath);for(const l of t)o(l.filePath);for(const l of n)o(l.filePath);for(const l of r)o(l.filePath);const i=[...a.entries()].map(([l,b])=>{if(!Wn.test(l))throw new X("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${b} from "../${l}.js";`}).join(`
|
|
347
347
|
`),s=e.map(l=>` "${A(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
348
348
|
`),c=t.map(l=>` ${JSON.stringify(l.id)}: ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
349
349
|
`),d=n.map(l=>` "${A(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
350
350
|
`),h=r.map(l=>` "${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
|
|
351
351
|
`),g=n.map(l=>`${A(l.filePath)}:${l.exportName}`),y=[s,d].filter(l=>l.length>0).join(`
|
|
352
|
-
`),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const b=
|
|
352
|
+
`),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const b=jn(l.args);return b===void 0?void 0:`installCompiledValidatorMap(${a.get(l.filePath)??""}.${l.exportName}.args, ${b});`}).filter(l=>l!==void 0).join(`
|
|
353
353
|
`);return{dispatchBody:y.length>0?`
|
|
354
354
|
${y}
|
|
355
355
|
`:"",importBlock:i.length>0?`${i}
|
|
@@ -358,7 +358,7 @@ ${y}
|
|
|
358
358
|
${c}
|
|
359
359
|
`:"",mutatorPaths:g,shapeBody:h.length>0?`
|
|
360
360
|
${h}
|
|
361
|
-
`:""}},
|
|
361
|
+
`:""}},gr=e=>{const t=Ye(e),n=t.map(([a,o])=>{const i=o.map(s=>{const c=L(xe(s.args),s.filePath),d=c==="{}"?"?":"",h=L($t(s),s.filePath);return s.kind==="stream"?` ${s.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${h}>>;`:` ${s.exportName}: (args${d}: ${c}) => Promise<${h}>;`}).join(`
|
|
362
362
|
`);return` ${q(A(a))}: {
|
|
363
363
|
${i}
|
|
364
364
|
};`}).join(`
|
|
@@ -366,7 +366,7 @@ ${i}
|
|
|
366
366
|
`);return` ${Y(i)}: {
|
|
367
367
|
${s}
|
|
368
368
|
},`}).join(`
|
|
369
|
-
`),types:n}},
|
|
369
|
+
`),types:n}},fr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=se(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},ba=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasVectors:s=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:h=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:R=!1,identity:x,queues:v=[],schema:$,storageRuleBuckets:T=[],useUmbrella:H=!1,workflows:O=[]}={})=>{const C=oe(H),k=fr($??{tables:[]},T).map(p=>JSON.stringify(p)).join(" | "),P=a?`import type { LunoraAi } from "@lunora/ai";
|
|
370
370
|
`:"",M=a?`
|
|
371
371
|
readonly ai: LunoraAi;`:"",ie=u?`import type { LunoraPayment } from "@lunora/payment";
|
|
372
372
|
`:"",le=u?`
|
|
@@ -399,7 +399,7 @@ ${w}`:""}
|
|
|
399
399
|
}
|
|
400
400
|
|
|
401
401
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
402
|
-
export type Env = CloudflareBindings;`,F=(p,We,Te)=>{const re=
|
|
402
|
+
export type Env = CloudflareBindings;`,F=(p,We,Te)=>{const re=Dn.get(p);if(re!==void 0&&re.tier!==Te)throw new X("INTERNAL",`@lunora/codegen: capability "${p}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Te}" context — update whichever is wrong.`);return We?re?.field??"":""},ce=F("kv",g,"every"),de=F("analytics",o,"every"),Oe=F("hyperdrive",d,"action"),Ie=F("browser",i,"action"),Ce=F("images",h,"action"),ue=F("pipelines",l,"action"),G=F("r2sql",b,"action"),_=s&&($?.vectorIndexes.length??0)>0,J=_?' | "vectors"':"",te=_?`
|
|
403
403
|
readonly vectors: VectorSearch<VectorIndexName>;`:"",he=_?`
|
|
404
404
|
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",z=_?`import type { VectorSearch, VectorSearchReader } from "${C.server}";
|
|
405
405
|
import type { VectorIndexName } from "./dataModel.js";
|
|
@@ -730,12 +730,12 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Be}>();
|
|
|
730
730
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
731
731
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
732
732
|
};
|
|
733
|
-
`},
|
|
733
|
+
`},br=e=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${A(n.filePath)}:${n.exportName}`);return t},ya=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,c=n.length>0,d=oe(i),{dispatchBody:h,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=mr(n,r,a,o),R=ir(t,n),x=lr(s,n),v=[R.lines,x.lines].filter(w=>w.length>0).join(`
|
|
734
734
|
`);let $=h;v.length>0&&($=h.length>0?`${h.trimEnd()}
|
|
735
735
|
${v}
|
|
736
736
|
`:`
|
|
737
737
|
${v}
|
|
738
|
-
`);const T=
|
|
738
|
+
`);const T=br(n),H=o.length>0?`import type { RegisteredShape } from "${d.server}";
|
|
739
739
|
`:"",O=o.length>0?`
|
|
740
740
|
/**
|
|
741
741
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
@@ -759,12 +759,12 @@ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(w=>JSO
|
|
|
759
759
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
760
760
|
*/
|
|
761
761
|
${y}
|
|
762
|
-
`:"",M=
|
|
762
|
+
`:"",M=gr(n),ie=M.types?`
|
|
763
763
|
${M.types}
|
|
764
764
|
`:"",le=M.implementation?`
|
|
765
765
|
${M.implementation}
|
|
766
766
|
`:"",Z=ze(M.types),V=Z.length>0?`import type { ${Z.join(", ")} } from "./dataModel.js";
|
|
767
|
-
`:"",D=c?"context":"_context",ee=c?`${
|
|
767
|
+
`:"",D=c?"context":"_context",ee=c?`${pr}
|
|
768
768
|
|
|
769
769
|
`:"";return Rt(`${S}${g}${R.importLine}${x.importLine}${k}${H}import { LunoraError } from "${d.server}";
|
|
770
770
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
@@ -896,7 +896,7 @@ export interface RegisteredDataMigration {
|
|
|
896
896
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
897
897
|
*/
|
|
898
898
|
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
|
|
899
|
-
`,i)},
|
|
899
|
+
`,i)},yr=e=>{const t={};for(const n of e.tables){const r={};for(const[a,o]of Object.entries(n.shape)){const i=se(o);i.kind==="id"&&i.tableName!==void 0&&(r[a]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},wr=e=>{const t={};for(const n of e.tables){const r=[];for(const[a,o]of Object.entries(n.shape))se(o).kind==="storage"&&r.push(a);r.length>0&&(t[n.name]=r)}return t},kr=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(a=>({fields:[...a.fields],name:a.name,type:"index",...a.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(a=>({fields:[a.field,...a.filterFields??[]],name:a.name,type:"search"})),...(n.geoIndexes??[]).map(a=>({fields:[a.field],name:a.name,type:"geo"})),...n.rankIndexes.map(a=>({fields:a.sortBy.map(o=>o.field),name:a.name,type:"rank"})),...n.vectorIndexes.map(a=>({fields:a.field===void 0?[]:[a.field],name:a.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},xr=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},vr=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},Sr=(e,t,n)=>{const r=se(t),a={name:e,optional:xt(t),type:r.kind};if(r.kind==="id"&&r.tableName!==void 0){a.ref=r.tableName;const i=n.get(e);i!==void 0&&(a.onDelete=i)}r.kind==="storage"&&(a.isStorage=!0,r.bucket!==void 0&&(a.bucket=r.bucket));const o=vr(r);return o!==void 0&&(a.enumValues=o),r.column?.notNull===!1&&(a.nullable=!0),a},Rr=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"}]:[]],a=new Map(n.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,i]of Object.entries(n.shape))r.push(Sr(o,i,a));t[n.name]=r}return t},$r=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
900
900
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
901
901
|
this.ensureMigrated();
|
|
902
902
|
|
|
@@ -904,7 +904,7 @@ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}}
|
|
|
904
904
|
|
|
905
905
|
return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
|
|
906
906
|
}
|
|
907
|
-
`}:{importFragment:"",override:""}
|
|
907
|
+
`}:{importFragment:"",override:""},Tr=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:`
|
|
908
908
|
const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
|
|
909
909
|
// Correlate AI-Gateway-routed calls with the Lunora trace: thread the
|
|
910
910
|
// function path + trace id into createAi, which folds them into the
|
|
@@ -942,7 +942,7 @@ const aiStub: LunoraAi = {
|
|
|
942
942
|
const ${e} = {
|
|
943
943
|
${o}
|
|
944
944
|
}${r};
|
|
945
|
-
`},E={build:"",configField:"",contextField:"",importLines:[],stub:""},
|
|
945
|
+
`},E={build:"",configField:"",contextField:"",importLines:[],stub:""},Nr=e=>e?{build:`
|
|
946
946
|
const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
|
|
947
947
|
// KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
|
|
948
948
|
// when a value changes — a subscription that read one can never be proven
|
|
@@ -956,24 +956,24 @@ ${o}
|
|
|
956
956
|
]);
|
|
957
957
|
`,configField:`
|
|
958
958
|
kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
|
|
959
|
-
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:I("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:E,
|
|
959
|
+
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:I("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:E,Ar=(e,t)=>e?{build:`
|
|
960
960
|
const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
|
|
961
961
|
provider: () => config.flags?.(env),
|
|
962
962
|
targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
|
|
963
963
|
});
|
|
964
964
|
`,configField:`
|
|
965
965
|
flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
|
|
966
|
-
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:E,
|
|
966
|
+
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:E,Or=e=>e?{build:`
|
|
967
967
|
const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
|
|
968
968
|
`,configField:"",contextField:`
|
|
969
969
|
notify,
|
|
970
|
-
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:E,
|
|
970
|
+
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:E,Ir=e=>e?{build:`
|
|
971
971
|
const envConfig = lunoraEnvContract.${e.exportName}(env);
|
|
972
972
|
`,configField:"",contextField:`
|
|
973
|
-
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:E,
|
|
973
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:E,Cr=e=>e?{build:`
|
|
974
974
|
const access = accessFacade(identity, userId);
|
|
975
975
|
`,configField:"",contextField:`
|
|
976
|
-
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:E,
|
|
976
|
+
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:E,Dr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
|
|
977
977
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
978
978
|
const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
|
|
979
979
|
provider: () => config.flags?.(env),
|
|
@@ -1035,25 +1035,25 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
1035
1035
|
|
|
1036
1036
|
return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
|
|
1037
1037
|
}
|
|
1038
|
-
`;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},
|
|
1038
|
+
`;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},Lr=e=>e?{build:`
|
|
1039
1039
|
const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
|
|
1040
1040
|
const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
|
|
1041
1041
|
`,configField:`
|
|
1042
1042
|
analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
|
|
1043
|
-
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:I("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:E,
|
|
1043
|
+
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:I("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:E,Er=e=>e?{build:`
|
|
1044
1044
|
const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
|
|
1045
1045
|
const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
|
|
1046
1046
|
`,configField:`
|
|
1047
1047
|
images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
|
|
1048
|
-
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:I("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:E,
|
|
1048
|
+
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:I("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:E,_r=e=>e?{build:`
|
|
1049
1049
|
const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
|
|
1050
1050
|
`,configField:`
|
|
1051
1051
|
sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
|
|
1052
|
-
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:I("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:E,
|
|
1052
|
+
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:I("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:E,Pr=e=>e?{build:`
|
|
1053
1053
|
const browser: Browser = config.browser ? config.browser(env) : browserStub;
|
|
1054
1054
|
`,configField:`
|
|
1055
1055
|
browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
|
|
1056
|
-
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:I("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:E,
|
|
1056
|
+
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:I("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:E,Mr=e=>e?{build:`
|
|
1057
1057
|
const r2sqlEnv = env as Record<string, unknown>;
|
|
1058
1058
|
const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
|
|
1059
1059
|
const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
|
|
@@ -1064,11 +1064,11 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
1064
1064
|
? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
|
|
1065
1065
|
: r2sqlStub;
|
|
1066
1066
|
`,configField:`
|
|
1067
|
-
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:I("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:E,
|
|
1067
|
+
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:I("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:E,Fr=e=>e?{build:`
|
|
1068
1068
|
const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
|
|
1069
1069
|
const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
|
|
1070
1070
|
`,configField:`
|
|
1071
|
-
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,
|
|
1071
|
+
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,wa=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(o=>(f(o.exportName,`container export "${o.exportName}"`),f(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
|
|
1072
1072
|
export class ${o.className} extends LunoraContainer {
|
|
1073
1073
|
public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
|
|
1074
1074
|
super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
|
|
@@ -1093,7 +1093,7 @@ import { ${a} } from "../containers.js";
|
|
|
1093
1093
|
|
|
1094
1094
|
export { ContainerProxy } from "@lunora/container/do";
|
|
1095
1095
|
|
|
1096
|
-
${r}`},
|
|
1096
|
+
${r}`},Br=(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 a=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${a} },`}).join(`
|
|
1097
1097
|
`);return{build:`
|
|
1098
1098
|
const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
|
|
1099
1099
|
`,contextField:`
|
|
@@ -1102,7 +1102,7 @@ ${r}`},Fr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1102
1102
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1103
1103
|
${n}
|
|
1104
1104
|
];
|
|
1105
|
-
`}},
|
|
1105
|
+
`}},ka=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}\`). */
|
|
1106
1106
|
export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
|
|
1107
1107
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1108
1108
|
super(ctx, env, ${r.exportName}, "${r.exportName}");
|
|
@@ -1130,7 +1130,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
1130
1130
|
/** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
|
|
1131
1131
|
type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
|
|
1132
1132
|
|
|
1133
|
-
${t}`},
|
|
1133
|
+
${t}`},xa=e=>{if(e.length===0)return"";const n=e.filter(s=>s.voice).length>0,r=e.map(s=>{f(s.exportName,`agent export "${s.exportName}"`),f(s.className,`agent class "${s.className}"`);const c=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent (binding \`${s.bindingName}\`). */
|
|
1134
1134
|
export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
1135
1135
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1136
1136
|
super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
|
|
@@ -1158,7 +1158,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
|
|
|
1158
1158
|
|
|
1159
1159
|
import { ${a} } from "../agents.js";
|
|
1160
1160
|
|
|
1161
|
-
${r}`},
|
|
1161
|
+
${r}`},va=e=>{const t=e.filter(a=>a.mode==="push");if(t.length===0)return"";for(const a of t)f(a.exportName,`queue export "${a.exportName}"`);const n=t.map(a=>a.exportName).join(", "),r=t.map(a=>` ${JSON.stringify(a.name)}: { definition: ${a.exportName}, exportName: ${JSON.stringify(a.exportName)} },`).join(`
|
|
1162
1162
|
`);return`${S}/**
|
|
1163
1163
|
* Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
|
|
1164
1164
|
* composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
|
|
@@ -1173,7 +1173,7 @@ import { ${n} } from "../queues.js";
|
|
|
1173
1173
|
export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
|
|
1174
1174
|
${r}
|
|
1175
1175
|
};
|
|
1176
|
-
`},
|
|
1176
|
+
`},qr=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(`
|
|
1177
1177
|
`);return{build:`
|
|
1178
1178
|
const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
|
|
1179
1179
|
`,contextField:`
|
|
@@ -1182,7 +1182,7 @@ ${r}
|
|
|
1182
1182
|
const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
|
|
1183
1183
|
${t}
|
|
1184
1184
|
];
|
|
1185
|
-
`}},
|
|
1185
|
+
`}},jr=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(`
|
|
1186
1186
|
`);return{build:`
|
|
1187
1187
|
const queues = createQueueContext(env, LUNORA_QUEUES);
|
|
1188
1188
|
`,contextField:`
|
|
@@ -1191,7 +1191,7 @@ ${t}
|
|
|
1191
1191
|
const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
|
|
1192
1192
|
${t}
|
|
1193
1193
|
];
|
|
1194
|
-
`}},
|
|
1194
|
+
`}},Wr=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(`
|
|
1195
1195
|
`);return{build:`
|
|
1196
1196
|
const agents = createAgentContext(env, LUNORA_AGENTS);
|
|
1197
1197
|
`,contextField:`
|
|
@@ -1207,21 +1207,21 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
|
|
|
1207
1207
|
protected override ${n}(): ${t} {
|
|
1208
1208
|
return ${e};
|
|
1209
1209
|
}
|
|
1210
|
-
`}),
|
|
1210
|
+
`}),Ur=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 Nt("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. */")},Kr=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 Nt("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. */")},Qr=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
|
|
1211
1211
|
const payments: LunoraPayment = config.payment
|
|
1212
1212
|
? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
|
|
1213
1213
|
: paymentStub;
|
|
1214
1214
|
`,configField:`
|
|
1215
1215
|
payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
|
|
1216
|
-
payments,`,stub:I("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},
|
|
1216
|
+
payments,`,stub:I("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},Hr=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
|
|
1217
1217
|
const x402: X402Pay = config.x402
|
|
1218
1218
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1219
1219
|
: x402Stub;
|
|
1220
1220
|
`,configField:`
|
|
1221
|
-
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},
|
|
1221
|
+
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Vr=(e,t,n,r,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],Sa=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:$=!1,maskMetadata:T,mutators:H=[],queues:O=[],rlsMetadata:C,schema:k,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const D=oe(Z),ee=H.length>0,w=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
|
|
1222
1222
|
/** 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. */
|
|
1223
1223
|
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Tn(P))}, json: ${JSON.stringify(Ae)} };
|
|
1224
|
-
`,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}
|
|
1224
|
+
`,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=Tr(s),ue=Cr(i),G=Nr(u),_=Ar(h,D.flags),J=Dr(o,h,D.flags),te=Or(l),he=Ir(a),z=Lr(c),j=Er(y),W=_r(g),U=Pr(d),B=Mr(x),ne=Fr(R),{build:De,contextField:ve,importLines:Se,specs:pe}=jr(O),{build:Le,contextField:Ee,importLines:Re,specs:me}=Br(r,k.jurisdiction),{build:_e,contextField:Pe,importLines:$e,specs:Me}=qr(V),{build:Fe,contextField:ge,importLines:fe,specs:Be}=Wr(n),{build:qe,configField:je,contextField:be,imports:ye,stub:Ze}=Qr(b),{build:p,configField:We,imports:Te,stub:re}=Hr($),Ot=e,It=t,et=C??{policies:[],roles:[]},Ct=T??{columns:[]},Dt=ie??{rules:[]},Lt=le??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Et,override:_t}=Ur(V),{constant:Pt,override:Mt}=Kr(O),K=v&&k.vectorIndexes.length>0,tt=new Set(k.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&k.vectorIndexes.some(m=>tt.has(m.table)),we=k.tables.some(m=>m.shardMode==="global"),Ue=k.tables.some(m=>An(m)),nt=k.tables.some(m=>On(m)),ae=k.tables.some(m=>m.externalSource!==void 0),rt=k.tables.some(m=>m.memory===!0),Ke=k.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(nt&&Ue)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=k.tables.length>0,Ft=yr(k),Bt=kr(k),qt=Rr(k),jt=wr(k),at=xr(k),ot=Vr(K,V.length>0,O.length>0,h,Ke);w&&ot.push("WhereInput");const st=$r(we),Wt=w?`
|
|
1225
1225
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
1226
1226
|
const shape = LUNORA_SHAPES[name];
|
|
1227
1227
|
|
|
@@ -2574,21 +2574,21 @@ ${Sn}${vn}
|
|
|
2574
2574
|
return ctx;
|
|
2575
2575
|
}
|
|
2576
2576
|
};
|
|
2577
|
-
`},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:N(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:N(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Xe(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},At=(e,t)=>{const n=se(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},
|
|
2577
|
+
`},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:N(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:N(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Xe(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},At=(e,t)=>{const n=se(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Gr=(e,t,n)=>{f(e,"drizzle column name");const r=Xe(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const i=At(t,n);return i!==void 0&&(o+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(o+=".notNull()"),o},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}),`},zr=(e,t)=>{f(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([a,o])=>` ${a}: ${Gr(a,o,t)},`)].join(`
|
|
2578
2578
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2579
|
-
${e.indexes.map(a=>
|
|
2579
|
+
${e.indexes.map(a=>Jr(a)).join(`
|
|
2580
2580
|
`)}
|
|
2581
2581
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2582
2582
|
${n}
|
|
2583
|
-
}${r});`},
|
|
2584
|
-
`;const n=oe(t),r=new Set(e.map(g=>g.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=
|
|
2583
|
+
}${r});`},Yr=e=>e.typeAnnotation?.includes('Id<"')??!1,Xr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let a=!1,o=!1;for(const i of e){for(const s of Object.values(i.shape)){const c=Xe(s);n.add(c.builder),o=o||Yr(c),a=a||At(s,t)!==void 0}for(const s of i.indexes)r.add(s.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,s)=>i.localeCompare(s)),indexes:[...r].toSorted((i,s)=>i.localeCompare(s)),needsAnyColumn:a,needsId:o}},ht=(e,t=!1)=>{if(e.length===0)return`${S}export {};
|
|
2584
|
+
`;const n=oe(t),r=new Set(e.map(g=>g.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=Xr(e,r),c=[...o,...a].toSorted((g,y)=>g.localeCompare(y)),d=e.map(g=>zr(g,r)).join(`
|
|
2585
2585
|
|
|
2586
2586
|
`),h=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2587
2587
|
`:"",s?`import type { Id } from "./dataModel.js";
|
|
2588
2588
|
`:""].join("");return`${S}import { ${c.join(", ")} } from "${n.serverDrizzle}";
|
|
2589
2589
|
${h}
|
|
2590
2590
|
${d}
|
|
2591
|
-
`},
|
|
2591
|
+
`},Ra=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:L(ht(n,t),Je),shard:L(ht(r,t),Je)}},$a=e=>e?`${S}/**
|
|
2592
2592
|
* The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
|
|
2593
2593
|
* forward it — wrangler binds only what the entry exports:
|
|
2594
2594
|
*
|
|
@@ -2598,7 +2598,7 @@ ${d}
|
|
|
2598
2598
|
* forwards this module for you whenever it exists.
|
|
2599
2599
|
*/
|
|
2600
2600
|
export { SchedulerDO } from "@lunora/scheduler";
|
|
2601
|
-
`:"",
|
|
2601
|
+
`:"",Ta=e=>{const t=new Map;for(const i of e){const s=t.get(i.cron);s?s.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
|
|
2602
2602
|
`),r=n.length>0?`
|
|
2603
2603
|
${n}
|
|
2604
2604
|
`:"",a=[...t.entries()].map(([i,s])=>{const c=s.map(d=>{const h=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${h}, args: ${JSON.stringify(d.args)} },`}).join(`
|
|
@@ -2632,7 +2632,7 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
|
|
|
2632
2632
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2633
2633
|
*/
|
|
2634
2634
|
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${o}};
|
|
2635
|
-
`}
|
|
2635
|
+
`},Na=e=>{const t=[...e].toSorted((r,a)=>r.name.localeCompare(a.name)).map(r=>{const a=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&a.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&a.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&a.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&a.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${a.join(", ")} },`}).join(`
|
|
2636
2636
|
`),n=t.length>0?`
|
|
2637
2637
|
${t}
|
|
2638
2638
|
`:"";return`${S}/**
|
|
@@ -2656,4 +2656,4 @@ export interface LunoraVectorIndex {
|
|
|
2656
2656
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2657
2657
|
*/
|
|
2658
2658
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2659
|
-
`},
|
|
2659
|
+
`},Aa=e=>[...new Set(e.map(t=>t.cron))];export{ha as A,Cn as C,S as G,tr as U,ma as a,fa as b,wa as c,Ta as d,xa as e,pa as f,Ra as g,ya as h,$a as i,ba as j,Sa as k,Na as l,ka as m,Aa as n,wr as o,va as p,ga as q};
|