@lunora/codegen 1.0.0-alpha.211 → 1.0.0-alpha.212
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.d.mts +9 -8
- package/dist/index.d.ts +9 -8
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-Clwlg6jB.mjs → GENERATED_HEADER-BlvEedrV.mjs} +1 -1
- package/dist/packem_shared/OPENRPC_VERSION-ClwB3jCx.mjs +3 -0
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-D2xc36Bb.mjs → SCHEMA_SNAPSHOT_FILENAME-BtDKUUYV.mjs} +1 -1
- package/dist/packem_shared/buildOpenApiDocument-sc25Dacj.mjs +3 -0
- package/dist/packem_shared/{emit-_LUzQG_K.mjs → emit-akFzQrlf.mjs} +259 -259
- package/dist/packem_shared/{emitApp-CgW3zBjL.mjs → emitApp-DHEB4XFE.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/OPENRPC_VERSION-BRCNaNPW.mjs +0 -3
- package/dist/packem_shared/buildOpenApiDocument-Ck7uULMF.mjs +0 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as
|
|
1
|
+
import{agentComponent as gt}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as Nn,hashSchemaSnapshot as An}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{d as On}from"./declared-output-Iaar469J.mjs";import{isHyperdriveGlobalTable as In,isD1GlobalTable as Cn}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as A}from"./paths-C-9fwEgQ.mjs";import{acceptsAbsentIr as Dn}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const ft=[{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 mt}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"}],Ln=ft,En=new Map(Ln.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),ma=ft.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),bt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,_n=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),yt=e=>e.column!==void 0,Pn=(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
|
-
`}},
|
|
26
|
-
const ${
|
|
23
|
+
`}},Mn=(e,t)=>e.stringMaxLength===void 0?"":`if (${t}.length > ${String(e.stringMaxLength)}) return DEFER;
|
|
24
|
+
`,Fn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!bt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
|
|
25
|
+
`}},ze=(e,t,n)=>{if(!yt(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if(_n.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Pn(e.kind,t)+Mn(e,t)};switch(e.kind){case"array":return Bn(e,t,n);case"literal":return Fn(e,t);case"object":return Wn(e,t,n);default:return}}},Bn=(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=ze(r,s,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
|
|
26
|
+
const ${o} = new Array(${t}.length);
|
|
27
27
|
for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
|
|
28
28
|
const ${s} = ${t}[${i}];
|
|
29
|
-
${c.pre}${
|
|
29
|
+
${c.pre}${o}[${i}] = ${c.out};
|
|
30
30
|
}
|
|
31
|
-
`;return{out:
|
|
31
|
+
`;return{out:o,pre:d}},qn=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||yt(t))return;const{inner:i}=t;if(!i)return;const s=ze(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} ? { ${
|
|
38
|
-
`,c=h}const d=
|
|
39
|
-
`},
|
|
40
|
-
${
|
|
41
|
-
`;return{out:i,pre:s}},
|
|
37
|
+
`;return{entry:`...(${d} ? { ${a}: ${h} } : {})`,pre:g}}const o=ze(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},jn=new Set(Object.getOwnPropertyNames(Object.prototype)),wt=(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(jn.has(o)){const h=`__f${String(n.next())}`;r+=`const ${h} = Object.hasOwn(${t}, ${s}) ? ${t}[${s}] : undefined;
|
|
38
|
+
`,c=h}const d=qn(o,i,c,n);if(!d)return;r+=d.pre,a.push(d.entry)}return{entries:a.join(", "),pre:r}},kt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
|
|
39
|
+
`},Wn=(e,t,n)=>{const r=e.shape??{},a=wt(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
|
+
${kt(t)}${a.pre}const ${i} = { ${a.entries} };
|
|
41
|
+
`;return{out:i,pre:s}},Un=e=>{let t=0;const r=wt(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
|
|
42
42
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
43
|
-
${
|
|
44
|
-
}`},S=`// GENERATED by @lunora/codegen — do not edit.
|
|
43
|
+
${kt("source")}${r.pre}return { ${r.entries} };
|
|
44
|
+
}`},I=(e,t)=>`JSON.parse(${JSON.stringify(JSON.stringify(e))}) as ${t}`,S=`// GENERATED by @lunora/codegen — do not edit.
|
|
45
45
|
// Run \`lunora codegen\` to regenerate.
|
|
46
46
|
|
|
47
|
-
`,
|
|
47
|
+
`,se=(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"},xt=/^[A-Za-z_$][\w$]*$/u,Kn=/^[\w./-]+$/u,f=(e,t)=>{if(!xt.test(e))throw new Z("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ge=e=>e.charAt(0).toUpperCase()+e.slice(1),W=e=>xt.test(e)?e:JSON.stringify(e),X=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:W(e),Qn={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"},Vn=e=>{if(e===void 0)return"unknown";if(!bt.test(e))throw new Z("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},N=e=>{const t=Qn[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 Vn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,a])=>vt(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"}},vt=(e,t)=>{const n=W(e);if(t.kind==="optional"){const r=t.inner?N(t.inner):"unknown";return`${n}?: ${r}`}return Dn(t)?`${n}?: ${N(t)}`:`${n}: ${N(t)}`},ve=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>vt(n,r)).join("; ")} }`},St=e=>e.kind==="optional"||!!e.column?.hasDefault,ie=e=>e.kind==="optional"&&e.inner?e.inner:e,Hn=e=>{f(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=ie(a),i=N(o),s=W(r);return St(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",ga=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 $=W(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?`
|
|
@@ -57,19 +57,19 @@ ${l}
|
|
|
57
57
|
_id: Id<"${u.name}">;
|
|
58
58
|
_creationTime: number;${R}${b}}`}).join(`
|
|
59
59
|
|
|
60
|
-
`),
|
|
61
|
-
`),
|
|
60
|
+
`),a=e.tables.map(u=>` ${u.name}: Doc_${u.name};`).join(`
|
|
61
|
+
`),o=e.tables.map(u=>{const l=u.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
|
|
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=>Hn(u)).join(`
|
|
66
66
|
|
|
67
67
|
`),g=e.tables.map(u=>` ${u.name}: Insert_${u.name};`).join(`
|
|
68
|
-
`),y=e.tables.map(u=>{const l=u.relations.map(b=>(f(b.table,"relation target table"),` ${
|
|
68
|
+
`),y=e.tables.map(u=>{const l=u.relations.map(b=>(f(b.table,"relation target table"),` ${W(b.name)}: ${b.kind==="one"?"OneRelation":"ManyRelation"}<"${b.table}">;`)).join(`
|
|
69
69
|
`);return l?` ${u.name}: {
|
|
70
70
|
${l}
|
|
71
71
|
};`:` ${u.name}: {};`}).join(`
|
|
72
|
-
`);return
|
|
72
|
+
`);return E(`${S}export type TableName = ${t};
|
|
73
73
|
|
|
74
74
|
/**
|
|
75
75
|
* The tables **this app declared** — every {@link TableName} except those an add-on
|
|
@@ -93,7 +93,7 @@ export type Id<TName extends string> = string & { readonly __table: TName };
|
|
|
93
93
|
${r}
|
|
94
94
|
|
|
95
95
|
export interface DataModel {
|
|
96
|
-
${
|
|
96
|
+
${a}
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
export type Doc<T extends keyof DataModel> = DataModel[T];
|
|
@@ -103,7 +103,7 @@ export type Doc<T extends keyof DataModel> = DataModel[T];
|
|
|
103
103
|
* Used by \`TableReader.withIndex()\` to constrain callers to declared names.
|
|
104
104
|
*/
|
|
105
105
|
export interface IndexNamesByTable {
|
|
106
|
-
${
|
|
106
|
+
${o}
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
|
|
@@ -161,11 +161,11 @@ export interface Relations {
|
|
|
161
161
|
${y}
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
`,Je)},
|
|
165
|
-
`);return` ${
|
|
166
|
-
${
|
|
167
|
-
};`};return
|
|
168
|
-
`)},
|
|
164
|
+
`,Je)},Gn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,Rt=/^(?:\.\.?\/)*_generated\//u,$t=/\.[A-Za-z]\w*$/u,zn=e=>e.replaceAll(Gn,(t,n)=>{const r=n.replace(Rt,"./");return`import("${$t.test(r)?r:`${r}.js`}")`}),Jn=/import\("(?<spec>[^"]+)"\)/gu,ht="node_modules/",Yn=/^@types\//u,Xn=e=>e.replaceAll(Jn,(t,n)=>{const r=n.lastIndexOf(ht);if(r===-1||r>0&&n[r-1]!=="/")return t;const a=n.slice(r+ht.length);return a===""||Yn.test(a)?t:`import("${a}")`}),Zn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,er=/^(?:\.\.?\/)+/u,tr=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("/")},nr=(e,t)=>e.replaceAll(Zn,(n,r)=>{if(Rt.test(r.replace(er,"")))return n;const a=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${tr(`${a}/${r}`)}`;return`import("${$t.test(i)?i:`${i}.js`}")`}),E=(e,t)=>zn(nr(Xn(e),t)),rr=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],ar=new RegExp(String.raw`import\("@lunora/(?<pkg>${rr.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),or={flags:new Set(["/web"]),platform:new Set},Tt=(e,t)=>t?e.replaceAll(ar,(n,r,a)=>{const o=or[r];return a&&o&&!o.has(a)?n:`import("lunorash/${r}${a??""}")`}):e,Ye=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),Nt=e=>On(e)?N(e.output):e.returnType,Xe=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))},pt=e=>{const t=([n,r])=>{const a=r.toSorted((o,i)=>o.exportName.localeCompare(i.exportName)).map(o=>{const i=E(ve(o.args),o.filePath),s=E(Nt(o),o.filePath);return` ${o.exportName}: FunctionReference<"${o.kind}", ${i}, ${s}>;`}).join(`
|
|
165
|
+
`);return` ${W(A(n))}: {
|
|
166
|
+
${a}
|
|
167
|
+
};`};return Xe(e).map(n=>t(n)).join(`
|
|
168
|
+
`)},sr=(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;
|
|
@@ -173,31 +173,31 @@ export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
|
173
173
|
readonly binding: string;
|
|
174
174
|
readonly name: string;
|
|
175
175
|
}
|
|
176
|
-
`,e.length>0){const
|
|
177
|
-
`),i=
|
|
176
|
+
`,e.length>0){const a=[...e].toSorted((s,c)=>s.exportName.localeCompare(c.exportName)),o=a.map(s=>` ${s.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${s.exportName}>>;`).join(`
|
|
177
|
+
`),i=a.map(s=>` ${X(s.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.exportName)} },`).join(`
|
|
178
178
|
`);r+=`
|
|
179
179
|
/** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
|
|
180
180
|
export interface WorkflowsRef {
|
|
181
|
-
${
|
|
181
|
+
${o}
|
|
182
182
|
}
|
|
183
183
|
|
|
184
184
|
export const workflows: WorkflowsRef = {
|
|
185
185
|
${i}
|
|
186
186
|
};
|
|
187
187
|
`,n.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
188
|
-
`)}if(t.length>0){const
|
|
189
|
-
`),i=
|
|
188
|
+
`)}if(t.length>0){const a=[...t].toSorted((s,c)=>s.exportName.localeCompare(c.exportName)),o=a.map(s=>` ${s.exportName}: WorkflowReference<AgentRunInput>;`).join(`
|
|
189
|
+
`),i=a.map(s=>` ${X(s.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.name)} },`).join(`
|
|
190
190
|
`);r+=`
|
|
191
191
|
/** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
|
|
192
192
|
export interface AgentsRef {
|
|
193
|
-
${
|
|
193
|
+
${o}
|
|
194
194
|
}
|
|
195
195
|
|
|
196
196
|
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("")}},ir=()=>Object.keys(gt().functions).toSorted((e,t)=>e.localeCompare(t)),At=e=>new Set(e.filter(t=>A(t.filePath)==="agents").map(t=>t.exportName)),lr=()=>new Set(Object.entries(gt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),cr=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=At(t),a=lr(),o=t.find(s=>A(s.filePath)==="agents"&&a.has(s.exportName));if(o)throw new Z("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=ir().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,13 +206,13 @@ ${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"}},
|
|
211
|
-
`);return` ${
|
|
209
|
+
`}},dr=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>A(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new Z("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
|
|
210
|
+
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},ur=(e,t)=>{if(e.length===0)return[];const n=At(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))},hr=(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}))},pr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Xe(t),r=n.map(([i,s])=>{const c=s.map(d=>{const h=E(d.chunkType??"unknown",d.filePath),g=E(ve(d.searchParams),d.filePath),y=E(ve(d.params),d.filePath);return` ${W(d.exportName)}: HttpStreamRef<${h}, ${g}, ${y}>;`}).join(`
|
|
211
|
+
`);return` ${W(A(i))}: {
|
|
212
212
|
${c}
|
|
213
213
|
};`}).join(`
|
|
214
|
-
`),
|
|
215
|
-
`);return` ${
|
|
214
|
+
`),a=n.map(([i,s])=>{const c=s.map(d=>` ${X(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
|
|
215
|
+
`);return` ${X(A(i))}: {
|
|
216
216
|
${c}
|
|
217
217
|
},`}).join(`
|
|
218
218
|
`);return{block:`
|
|
@@ -222,17 +222,17 @@ ${r}
|
|
|
222
222
|
}
|
|
223
223
|
|
|
224
224
|
export const httpStreams: HttpStreamsRef = {
|
|
225
|
-
${
|
|
225
|
+
${a}
|
|
226
226
|
};
|
|
227
|
-
`,body:r}},
|
|
227
|
+
`,body:r}},fa=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=se(o),c=[...n.filter(O=>O.visibility!=="internal"),...ur(t,n),...hr(a,n)],d=n.filter(O=>O.visibility==="internal"),h=pt(c),g=pt(d),y=pr(r),u=`${h}
|
|
228
228
|
${g}
|
|
229
|
-
${y.body}`,l=
|
|
229
|
+
${y.body}`,l=Ye(u),b=l.length>0?`
|
|
230
230
|
import type { ${l.join(", ")} } from "./dataModel.js";
|
|
231
231
|
`:"",R=h?`
|
|
232
232
|
${h}
|
|
233
233
|
`:"",x=g?`
|
|
234
234
|
${g}
|
|
235
|
-
`:"",v=
|
|
235
|
+
`:"",v=sr(i,t),$=`export interface ApiTypes {${R}}
|
|
236
236
|
|
|
237
237
|
export const api = anyApi as unknown as ApiTypes;
|
|
238
238
|
|
|
@@ -240,10 +240,10 @@ export const api = anyApi as unknown as ApiTypes;
|
|
|
240
240
|
export interface InternalApiTypes {${x}}
|
|
241
241
|
|
|
242
242
|
export const internal = anyApi as unknown as InternalApiTypes;
|
|
243
|
-
${v.block}${y.block}`,T=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],
|
|
244
|
-
`:"";return
|
|
245
|
-
${
|
|
246
|
-
${$}`,
|
|
243
|
+
${v.block}${y.block}`,T=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],H=T.length>0?`import type { ${T.join(", ")} } from "${s.client}";
|
|
244
|
+
`:"";return Tt(`${S}import { anyApi } from "${s.client}";
|
|
245
|
+
${H}${v.importLine}${b}
|
|
246
|
+
${$}`,o)},ba=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,8 +260,8 @@ 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
|
-
`:"",
|
|
264
|
-
export interface ${
|
|
263
|
+
`:"",ya=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=se(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=E(ve(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
|
+
export interface ${Ge(l)} {
|
|
265
265
|
${y}
|
|
266
266
|
/**
|
|
267
267
|
* Share the optimistic-overlay gate with other collections + mutators on this
|
|
@@ -286,7 +286,7 @@ ${y}
|
|
|
286
286
|
* \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
|
|
287
287
|
* \`scope\` to re-point the subscription.
|
|
288
288
|
*/
|
|
289
|
-
export const ${c.exportName}CollectionOptions = (options: ${
|
|
289
|
+
export const ${c.exportName}CollectionOptions = (options: ${Ge(l)}): LunoraCollectionOptions<${d}> =>
|
|
290
290
|
lunoraCollectionOptions<${d}>({
|
|
291
291
|
client: options.client,
|
|
292
292
|
...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
|
|
@@ -299,22 +299,22 @@ export const ${c.exportName}CollectionOptions = (options: ${He(l)}): LunoraColle
|
|
|
299
299
|
|
|
300
300
|
/** Live collection for the \`${c.exportName}\` shape, with its sync controls. */
|
|
301
301
|
export const ${c.exportName}Collection = (
|
|
302
|
-
options: ${
|
|
302
|
+
options: ${Ge(l)},
|
|
303
303
|
): { checkpoints: CheckpointRegistry; collection: Collection<${d}, string>; scope: ${u} } => {
|
|
304
304
|
const { checkpoints, config, scope } = ${c.exportName}CollectionOptions(options);
|
|
305
305
|
|
|
306
306
|
return { checkpoints, collection: createCollection(config), scope };
|
|
307
307
|
};`}).join(`
|
|
308
308
|
|
|
309
|
-
`),i=
|
|
309
|
+
`),i=Ye(o),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
|
|
310
310
|
`:"";return`${S}import type { LunoraClient, SubscriptionError } from "${r.client}";
|
|
311
311
|
import { lunoraCollectionOptions } from "@lunora/db/collections";
|
|
312
312
|
import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
|
|
313
313
|
import type { Collection } from "@tanstack/db";
|
|
314
314
|
import { createCollection } from "@tanstack/db";
|
|
315
315
|
${s}
|
|
316
|
-
${
|
|
317
|
-
`},
|
|
316
|
+
${o}
|
|
317
|
+
`},mr=(e,t)=>`lunora_${A(e)}_${String(t)}`,gr=`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 @@ ${a}
|
|
|
343
343
|
}
|
|
344
344
|
|
|
345
345
|
return (await registered.handler(context, args ?? {})) as R;
|
|
346
|
-
};`,
|
|
347
|
-
`),s=e.map(l=>` "${A(l.filePath)}:${l.exportName}": ${
|
|
348
|
-
`),c=t.map(l=>` ${JSON.stringify(l.id)}: ${
|
|
349
|
-
`),d=n.map(l=>` "${A(l.filePath)}:${l.exportName}": ${
|
|
350
|
-
`),h=r.map(l=>` "${l.exportName}": ${
|
|
346
|
+
};`,fr=(e,t,n=[],r=[])=>{const a=new Map,o=l=>{a.has(l)||a.set(l,mr(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(!Kn.test(l))throw new Z("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${b} from "../${l}.js";`}).join(`
|
|
347
|
+
`),s=e.map(l=>` "${A(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
348
|
+
`),c=t.map(l=>` ${JSON.stringify(l.id)}: ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
349
|
+
`),d=n.map(l=>` "${A(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
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=Un(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,30 +358,30 @@ ${y}
|
|
|
358
358
|
${c}
|
|
359
359
|
`:"",mutatorPaths:g,shapeBody:h.length>0?`
|
|
360
360
|
${h}
|
|
361
|
-
`:""}},
|
|
362
|
-
`);return` ${
|
|
361
|
+
`:""}},br=e=>{const t=Xe(e),n=t.map(([a,o])=>{const i=o.map(s=>{const c=E(ve(s.args),s.filePath),d=c==="{}"?"?":"",h=E(Nt(s),s.filePath);return s.kind==="stream"?` ${s.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${h}>>;`:` ${s.exportName}: (args${d}: ${c}) => Promise<${h}>;`}).join(`
|
|
362
|
+
`);return` ${W(A(a))}: {
|
|
363
363
|
${i}
|
|
364
364
|
};`}).join(`
|
|
365
|
-
`);return{implementation:t.map(([o
|
|
366
|
-
`);return` ${
|
|
365
|
+
`);return{implementation:t.map(([a,o])=>{const i=A(a),s=o.map(c=>` ${X(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
|
|
366
|
+
`);return` ${X(i)}: {
|
|
367
367
|
${s}
|
|
368
368
|
},`}).join(`
|
|
369
|
-
`),types:n}},
|
|
370
|
-
`:"",
|
|
371
|
-
readonly ai: LunoraAi;`:"",
|
|
372
|
-
`:"",
|
|
373
|
-
readonly payments: LunoraPayment;`:"",
|
|
374
|
-
`:"",
|
|
375
|
-
readonly x402: X402Pay;`:"",
|
|
376
|
-
`:"",
|
|
369
|
+
`),types:n}},yr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=ie(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))]},wa=({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 D=se(H),k=yr($??{tables:[]},T).map(p=>JSON.stringify(p)).join(" | "),F=a?`import type { LunoraAi } from "@lunora/ai";
|
|
370
|
+
`:"",B=a?`
|
|
371
|
+
readonly ai: LunoraAi;`:"",le=u?`import type { LunoraPayment } from "@lunora/payment";
|
|
372
|
+
`:"",ce=u?`
|
|
373
|
+
readonly payments: LunoraPayment;`:"",ee=R?`import type { X402Pay } from "@lunora/x402/pay";
|
|
374
|
+
`:"",G=R?`
|
|
375
|
+
readonly x402: X402Pay;`:"",L=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
|
|
376
|
+
`:"",te=t.length>0?`
|
|
377
377
|
readonly containers: {${t.map(p=>`
|
|
378
378
|
readonly ${p.exportName}: ContainerAccessor;`).join("")}
|
|
379
|
-
};`:"",w=[...
|
|
379
|
+
};`:"",w=[...a?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(p=>(f(p.bindingName,`container binding "${p.bindingName}"`),` /** Durable Object namespace for the \`${p.exportName}\` container. */
|
|
380
380
|
readonly ${p.bindingName}?: unknown;`)),...O.map(p=>(f(p.bindingName,`workflow binding "${p.bindingName}"`),` /** Workflow binding for the \`${p.exportName}\` workflow. */
|
|
381
381
|
readonly ${p.bindingName}?: unknown;`)),...v.map(p=>(f(p.bindingName,`queue binding "${p.bindingName}"`),` /** Queue producer binding for the \`${p.exportName}\` queue. */
|
|
382
382
|
readonly ${p.bindingName}?: unknown;`)),...e.map(p=>(f(p.bindingName,`agent binding "${p.bindingName}"`),` /** Workflow binding for the \`${p.exportName}\` agent. */
|
|
383
383
|
readonly ${p.bindingName}?: unknown;`))].join(`
|
|
384
|
-
`),
|
|
384
|
+
`),Oe=`
|
|
385
385
|
|
|
386
386
|
/**
|
|
387
387
|
* This project's Cloudflare bindings, as far as codegen can discover them from
|
|
@@ -399,21 +399,21 @@ ${w}`:""}
|
|
|
399
399
|
}
|
|
400
400
|
|
|
401
401
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
402
|
-
export type Env = CloudflareBindings;`,
|
|
403
|
-
readonly vectors: VectorSearch<VectorIndexName>;`:"",
|
|
404
|
-
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",
|
|
402
|
+
export type Env = CloudflareBindings;`,q=(p,Ue,Ne)=>{const ae=En.get(p);if(ae!==void 0&&ae.tier!==Ne)throw new Z("INTERNAL",`@lunora/codegen: capability "${p}" declares tier "${ae.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Ne}" context — update whichever is wrong.`);return Ue?ae?.field??"":""},de=q("kv",g,"every"),ue=q("analytics",o,"every"),Ie=q("hyperdrive",d,"action"),Ce=q("browser",i,"action"),De=q("images",h,"action"),he=q("pipelines",l,"action"),z=q("r2sql",b,"action"),P=s&&($?.vectorIndexes.length??0)>0,J=P?' | "vectors"':"",ne=P?`
|
|
403
|
+
readonly vectors: VectorSearch<VectorIndexName>;`:"",pe=P?`
|
|
404
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",Y=P?`import type { VectorSearch, VectorSearchReader } from "${D.server}";
|
|
405
405
|
import type { VectorIndexName } from "./dataModel.js";
|
|
406
|
-
`:"",
|
|
406
|
+
`:"",U=r?`
|
|
407
407
|
/** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
|
|
408
|
-
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",
|
|
408
|
+
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",K=c?`
|
|
409
409
|
/** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
|
|
410
|
-
readonly flags: import("${
|
|
410
|
+
readonly flags: import("${D.flags}").LunoraFlags;`:"",Q=y?`
|
|
411
411
|
/** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
|
|
412
412
|
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
413
413
|
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
414
|
-
readonly push: import("@lunora/notify").LunoraPush;`:"",
|
|
414
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",j=O.length>0,re=j?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
415
415
|
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
416
|
-
`:"",
|
|
416
|
+
`:"",Le=j?`
|
|
417
417
|
|
|
418
418
|
/** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
|
|
419
419
|
type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
|
|
@@ -426,10 +426,10 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
426
426
|
export interface LunoraWorkflows {
|
|
427
427
|
${O.map(p=>` get(name: ${JSON.stringify(p.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${p.exportName}>>;`).join(`
|
|
428
428
|
`)}
|
|
429
|
-
}`:"",
|
|
430
|
-
readonly workflows: LunoraWorkflows;`:"",
|
|
429
|
+
}`:"",Se=j?' | "workflows"':"",Re=j?`
|
|
430
|
+
readonly workflows: LunoraWorkflows;`:"",me=v.length>0,Ee=me?`import type { QueueProducer } from "@lunora/queue";
|
|
431
431
|
import type * as lunoraQueueDefinitions from "../queues.js";
|
|
432
|
-
`:"",
|
|
432
|
+
`:"",_e=me?`
|
|
433
433
|
|
|
434
434
|
/** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
|
|
435
435
|
type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
|
|
@@ -438,29 +438,29 @@ type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body }
|
|
|
438
438
|
export interface LunoraQueues {
|
|
439
439
|
${v.map(p=>` readonly ${p.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${p.exportName}>>;`).join(`
|
|
440
440
|
`)}
|
|
441
|
-
}`:""
|
|
442
|
-
readonly queues: LunoraQueues;`:"",
|
|
443
|
-
`:"",
|
|
441
|
+
}`:"",$e=me?`
|
|
442
|
+
readonly queues: LunoraQueues;`:"",ge=e.length>0,Pe=ge?`import type { AgentHandle } from "@lunora/agent";
|
|
443
|
+
`:"",Me=ge?`
|
|
444
444
|
|
|
445
445
|
/** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
|
|
446
446
|
export interface LunoraAgents {
|
|
447
447
|
${e.map(p=>(f(p.exportName,`agent export "${p.exportName}"`),` readonly ${p.exportName}: AgentHandle;`)).join(`
|
|
448
448
|
`)}
|
|
449
|
-
}`:""
|
|
450
|
-
readonly agents: LunoraAgents;`:"",
|
|
449
|
+
}`:"",Te=ge?`
|
|
450
|
+
readonly agents: LunoraAgents;`:"",Fe=x?`import type { InferIdentity } from "${D.server}";
|
|
451
451
|
import type * as lunoraIdentityContract from "../identity.js";
|
|
452
|
-
`:"",
|
|
452
|
+
`:"",Be=x?`
|
|
453
453
|
|
|
454
454
|
/** 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. */
|
|
455
455
|
export type Identity = InferIdentity<typeof lunoraIdentityContract.${x.exportName}>;
|
|
456
456
|
|
|
457
457
|
/** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
|
|
458
|
-
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",
|
|
459
|
-
readonly auth: NarrowedAuth;`:"",
|
|
460
|
-
`:"",
|
|
458
|
+
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",fe=x?' | "auth"':"",be=x?`
|
|
459
|
+
readonly auth: NarrowedAuth;`:"",qe=x?", Identity":"",je=n?`import type * as lunoraEnvContract from "../env.js";
|
|
460
|
+
`:"",We=n?`
|
|
461
461
|
|
|
462
462
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
463
|
-
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",
|
|
463
|
+
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",ye=n?' | "env"':"",we=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${S}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${D.server}";
|
|
464
464
|
import type {
|
|
465
465
|
ActionBuilder,
|
|
466
466
|
ActionCtx as ActionCtxBase,
|
|
@@ -482,7 +482,7 @@ import type {
|
|
|
482
482
|
Storage as StorageBase,
|
|
483
483
|
TableReader,
|
|
484
484
|
Validator,
|
|
485
|
-
} from "${
|
|
485
|
+
} from "${D.server}";
|
|
486
486
|
|
|
487
487
|
import type {
|
|
488
488
|
DatabaseReaderFacade as DatabaseReaderFacadeOf,
|
|
@@ -491,7 +491,7 @@ import type {
|
|
|
491
491
|
TableReaderFacade as TableReaderFacadeOf,
|
|
492
492
|
TableWriterFacade as TableWriterFacadeOf,
|
|
493
493
|
WithArg as WithArgOf,
|
|
494
|
-
} from "${
|
|
494
|
+
} from "${D.serverDataModel}";
|
|
495
495
|
|
|
496
496
|
export type {
|
|
497
497
|
AggregateOp,
|
|
@@ -514,10 +514,10 @@ export type {
|
|
|
514
514
|
Where,
|
|
515
515
|
WhereOf,
|
|
516
516
|
WhereOperators,
|
|
517
|
-
} from "${
|
|
517
|
+
} from "${D.serverDataModel}";
|
|
518
518
|
|
|
519
519
|
import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
|
|
520
|
-
${
|
|
520
|
+
${Y}${F}${le}${ee}${L}${re}${Ee}${Pe}${Fe}${je}
|
|
521
521
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
522
522
|
|
|
523
523
|
/**
|
|
@@ -577,7 +577,7 @@ export interface OrmWriter extends OrmReader {
|
|
|
577
577
|
}
|
|
578
578
|
|
|
579
579
|
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
580
|
-
export type StorageBucketName = ${k};${
|
|
580
|
+
export type StorageBucketName = ${k};${Oe}${Le}${_e}${Me}${Be}${We}
|
|
581
581
|
|
|
582
582
|
/**
|
|
583
583
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -640,22 +640,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
|
|
|
640
640
|
*/
|
|
641
641
|
type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
|
|
642
642
|
|
|
643
|
-
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${J}${
|
|
643
|
+
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${J}${fe}${ye}> {
|
|
644
644
|
readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
645
645
|
readonly orm: OrmReader;
|
|
646
|
-
readonly storage: ReadOnlyStorage<StorageBucketName>;${
|
|
646
|
+
readonly storage: ReadOnlyStorage<StorageBucketName>;${pe}${U}${de}${K}${Q}${ue}${we}${be}
|
|
647
647
|
}
|
|
648
648
|
|
|
649
|
-
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${J}${
|
|
649
|
+
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${J}${Se}${fe}${ye}> {
|
|
650
650
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
651
651
|
readonly orm: OrmWriter;
|
|
652
|
-
readonly storage: MutationStorage<StorageBucketName>;${
|
|
652
|
+
readonly storage: MutationStorage<StorageBucketName>;${ne}${U}${de}${K}${Q}${ue}${we}${Re}${$e}${Te}${be}
|
|
653
653
|
}
|
|
654
654
|
|
|
655
|
-
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${J}${
|
|
655
|
+
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${J}${Se}${fe}${ye}> {
|
|
656
656
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
657
657
|
readonly orm: OrmWriter;
|
|
658
|
-
readonly storage: StorageBase<StorageBucketName>;${
|
|
658
|
+
readonly storage: StorageBase<StorageBucketName>;${ne}${U}${B}${ce}${G}${te}${de}${K}${Q}${Ie}${Ce}${De}${ue}${he}${z}${we}${Re}${$e}${Te}${be}
|
|
659
659
|
}
|
|
660
660
|
|
|
661
661
|
/**
|
|
@@ -688,7 +688,7 @@ export const internalAction = lunoraBuilders.internalAction as unknown as Intern
|
|
|
688
688
|
/**
|
|
689
689
|
* \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
|
|
690
690
|
* custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
|
|
691
|
-
* \`${
|
|
691
|
+
* \`${D.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
|
|
692
692
|
* schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
|
|
693
693
|
* \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
|
|
694
694
|
* no \`as unknown as\` cast. Runtime-identical to the package export; only the
|
|
@@ -713,7 +713,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
|
|
|
713
713
|
* Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
|
|
714
714
|
* so the \`rls()\` chain discovers a policy authored either way the same.
|
|
715
715
|
*/
|
|
716
|
-
export const definePolicy = createPolicyDsl<DataModel, Relations${
|
|
716
|
+
export const definePolicy = createPolicyDsl<DataModel, Relations${qe}>();
|
|
717
717
|
|
|
718
718
|
/**
|
|
719
719
|
* The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
|
|
@@ -730,13 +730,13 @@ 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
|
+
`},wr=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},ka=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,c=n.length>0,d=se(i),{dispatchBody:h,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=fr(n,r,a,o),R=cr(t,n),x=dr(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=
|
|
739
|
-
`:"",O=
|
|
738
|
+
`);const T=wr(n),H=o.length>0?`import type { RegisteredShape } from "${d.server}";
|
|
739
|
+
`:"",O=o.length>0?`
|
|
740
740
|
/**
|
|
741
741
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
742
742
|
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
@@ -744,7 +744,7 @@ ${v}
|
|
|
744
744
|
* \`shape_subscribe\` (reads-as-permissions).
|
|
745
745
|
*/
|
|
746
746
|
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${b}};
|
|
747
|
-
`:"",
|
|
747
|
+
`:"",D=l.length>0?`
|
|
748
748
|
/**
|
|
749
749
|
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
750
750
|
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
@@ -752,23 +752,23 @@ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${b}};
|
|
|
752
752
|
*/
|
|
753
753
|
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(w=>JSON.stringify(w)).join(", ")}]);
|
|
754
754
|
`:"",k=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
|
|
755
|
-
`:"",
|
|
755
|
+
`:"",F=y.length>0?`
|
|
756
756
|
/**
|
|
757
757
|
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
758
758
|
* onto its function's live \`.args\` object and consulted by the interpreted
|
|
759
759
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
760
760
|
*/
|
|
761
761
|
${y}
|
|
762
|
-
`:"",
|
|
763
|
-
${
|
|
764
|
-
`:"",
|
|
765
|
-
${
|
|
766
|
-
`:"",
|
|
767
|
-
`:"",
|
|
768
|
-
|
|
769
|
-
`:"";return
|
|
762
|
+
`:"",B=br(n),le=B.types?`
|
|
763
|
+
${B.types}
|
|
764
|
+
`:"",ce=B.implementation?`
|
|
765
|
+
${B.implementation}
|
|
766
|
+
`:"",ee=Ye(B.types),G=ee.length>0?`import type { ${ee.join(", ")} } from "./dataModel.js";
|
|
767
|
+
`:"",L=c?"context":"_context",te=c?`${gr}
|
|
768
|
+
|
|
769
|
+
`:"";return Tt(`${S}${g}${R.importLine}${x.importLine}${k}${H}import { LunoraError } from "${d.server}";
|
|
770
770
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
771
|
-
${
|
|
771
|
+
${G}
|
|
772
772
|
/**
|
|
773
773
|
* Single registered function, narrowed to the shape \`handleRpc\` needs.
|
|
774
774
|
* The real argument validators / return types are checked elsewhere — at
|
|
@@ -820,7 +820,7 @@ ${R.prelude}${x.prelude}
|
|
|
820
820
|
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
821
821
|
*/
|
|
822
822
|
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${$}};
|
|
823
|
-
${
|
|
823
|
+
${F}${O}${D}
|
|
824
824
|
/**
|
|
825
825
|
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
826
826
|
* client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
|
|
@@ -873,10 +873,10 @@ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
|
873
873
|
* with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
|
|
874
874
|
* \`runAction\` but without re-stating the function path.
|
|
875
875
|
*/
|
|
876
|
-
export interface Caller {${
|
|
876
|
+
export interface Caller {${le}}
|
|
877
877
|
|
|
878
|
-
${
|
|
879
|
-
export const createCaller = (${
|
|
878
|
+
${te}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
879
|
+
export const createCaller = (${L}: CallerCtx): Caller => ({${ce}});
|
|
880
880
|
|
|
881
881
|
/**
|
|
882
882
|
* Single registered data migration, narrowed to the shape the per-shard runner
|
|
@@ -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)},kr=e=>{const t={};for(const n of e.tables){const r={};for(const[a,o]of Object.entries(n.shape)){const i=ie(o);i.kind==="id"&&i.tableName!==void 0&&(r[a]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},xr=e=>{const t={};for(const n of e.tables){const r=[];for(const[a,o]of Object.entries(n.shape))ie(o).kind==="storage"&&r.push(a);r.length>0&&(t[n.name]=r)}return t},vr=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},Sr=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},Rr=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},$r=(e,t,n)=>{const r=ie(t),a={name:e,optional:St(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=Rr(r);return o!==void 0&&(a.enumValues=o),r.column?.notNull===!1&&(a.nullable=!0),a},Tr=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($r(o,i,a));t[n.name]=r}return t},Nr=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:""},Ar=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
|
|
@@ -935,14 +935,14 @@ const aiStub: LunoraAi = {
|
|
|
935
935
|
${t}
|
|
936
936
|
}) as unknown as LunoraAi["workersai"],
|
|
937
937
|
};
|
|
938
|
-
`}},
|
|
938
|
+
`}},C=(e,t,n,{cast:r="",sync:a=[]}={})=>{const o=n.map(i=>` ${i}: ${a.includes(i)?"":"async "}() => {
|
|
939
939
|
${t}
|
|
940
940
|
},`).join(`
|
|
941
941
|
`);return`
|
|
942
942
|
const ${e} = {
|
|
943
|
-
${
|
|
943
|
+
${o}
|
|
944
944
|
}${r};
|
|
945
|
-
`},
|
|
945
|
+
`},_={build:"",configField:"",contextField:"",importLines:[],stub:""},Or=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,32 +956,32 @@ ${a}
|
|
|
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:
|
|
959
|
+
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:C("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"])}:_,Ir=(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:""}:
|
|
966
|
+
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:_,Cr=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:""}:
|
|
970
|
+
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:_,Dr=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:""}:
|
|
973
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:_,Lr=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:""}:
|
|
976
|
+
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:_,Er=(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),
|
|
980
980
|
targetingKey: ${s},
|
|
981
|
-
});`,
|
|
981
|
+
});`,a=`
|
|
982
982
|
/** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
|
|
983
|
-
const LUNORA_FLAG_KEYS
|
|
984
|
-
`,
|
|
983
|
+
const LUNORA_FLAG_KEYS = ${I(e,'ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }>')};
|
|
984
|
+
`,o=`
|
|
985
985
|
protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${r("undefined")}
|
|
986
986
|
const evalContext = context as import("${n}").EvaluationContext | undefined;
|
|
987
987
|
const evaluations: FlagsResult["flags"] = [];
|
|
@@ -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:
|
|
1038
|
+
`;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},_r=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:
|
|
1043
|
+
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:C("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"]})}:_,Pr=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:
|
|
1048
|
+
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:C("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"])}:_,Mr=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:
|
|
1052
|
+
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:C("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"])}:_,Fr=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:
|
|
1056
|
+
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:C("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"])}:_,Br=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,18 +1064,18 @@ 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:
|
|
1067
|
+
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:C("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"]})}:_,qr=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:
|
|
1072
|
-
export class ${
|
|
1071
|
+
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:C("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"])}:_,xa=(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
|
+
export class ${o.className} extends LunoraContainer {
|
|
1073
1073
|
public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
|
|
1074
|
-
super(ctx, env, ${
|
|
1074
|
+
super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
|
|
1075
1075
|
}
|
|
1076
1076
|
}
|
|
1077
1077
|
`)).join(`
|
|
1078
|
-
`),
|
|
1078
|
+
`),a=e.map(o=>o.exportName).join(", ");return`${S}/**
|
|
1079
1079
|
* Container-enabled Durable Object classes for the containers declared in
|
|
1080
1080
|
* \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
|
|
1081
1081
|
* requires each \`containers[].class_name\` to be exported by the worker:
|
|
@@ -1089,11 +1089,11 @@ export class ${a.className} extends LunoraContainer {
|
|
|
1089
1089
|
*/
|
|
1090
1090
|
import { LunoraContainer } from "@lunora/container/do";
|
|
1091
1091
|
|
|
1092
|
-
import { ${
|
|
1092
|
+
import { ${a} } from "../containers.js";
|
|
1093
1093
|
|
|
1094
1094
|
export { ContainerProxy } from "@lunora/container/do";
|
|
1095
1095
|
|
|
1096
|
-
${r}`},
|
|
1096
|
+
${r}`},jr=(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}`},qr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1102
1102
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1103
1103
|
${n}
|
|
1104
1104
|
];
|
|
1105
|
-
`}},
|
|
1105
|
+
`}},va=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}`},Sa=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}");
|
|
@@ -1144,7 +1144,7 @@ export class ${d} extends VoiceSessionDO {
|
|
|
1144
1144
|
}
|
|
1145
1145
|
}
|
|
1146
1146
|
`;return`${c}${g}`}).join(`
|
|
1147
|
-
`),
|
|
1147
|
+
`),a=e.map(s=>s.exportName).join(", ");return`${S}/**
|
|
1148
1148
|
* WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
|
|
1149
1149
|
* Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
|
|
1150
1150
|
* Workflow. Re-export them from your worker entry — wrangler requires each
|
|
@@ -1156,9 +1156,9 @@ import LunoraWorkflow from "@lunora/workflow/do";
|
|
|
1156
1156
|
${n?'import { compileAgentWorkflow, VoiceSessionDO } from "@lunora/agent";':'import { compileAgentWorkflow } from "@lunora/agent";'}
|
|
1157
1157
|
import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
|
|
1158
1158
|
|
|
1159
|
-
import { ${
|
|
1159
|
+
import { ${a} } from "../agents.js";
|
|
1160
1160
|
|
|
1161
|
-
${r}`},
|
|
1161
|
+
${r}`},Ra=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
|
+
`},Wr=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
|
+
`}},Ur=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
|
+
`}},Kr=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:`
|
|
@@ -1200,28 +1200,28 @@ ${t}
|
|
|
1200
1200
|
const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
|
|
1201
1201
|
${t}
|
|
1202
1202
|
];
|
|
1203
|
-
`}},
|
|
1204
|
-
${
|
|
1205
|
-
const ${e}
|
|
1203
|
+
`}},Ot=(e,t,n,r,a)=>({constant:`
|
|
1204
|
+
${a}
|
|
1205
|
+
const ${e} = ${I(r,t)};
|
|
1206
1206
|
`,override:`
|
|
1207
1207
|
protected override ${n}(): ${t} {
|
|
1208
1208
|
return ${e};
|
|
1209
1209
|
}
|
|
1210
|
-
`}),
|
|
1210
|
+
`}),Qr=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 Ot("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. */")},Vr=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 Ot("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. */")},Hr=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:
|
|
1216
|
+
payments,`,stub:C("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:""},Gr=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:
|
|
1221
|
+
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:C("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:""},zr=(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",...e?["VectorBackfillProgress"]:[],...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],$a=({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:D,schema:k,schemaSnapshot:F,shapes:B=[],storageRules:le,studioFeatures:ce,useUmbrella:ee=!1,workflows:G=[]})=>{const L=se(ee),te=H.length>0,w=B.length>0,Oe=F===void 0?"":Nn(F),q=F===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
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1224
|
-
`,
|
|
1223
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(An(F))}, json: ${JSON.stringify(Oe)} };
|
|
1224
|
+
`,de=F===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:ue,configField:Ie,contextField:Ce,stub:De}=Ar(s),he=Lr(i),z=Or(u),P=Ir(h,L.flags),J=Er(o,h,L.flags),ne=Cr(l),pe=Dr(a),Y=_r(c),U=Pr(y),K=Mr(g),Q=Fr(d),j=Br(x),re=qr(R),{build:Le,contextField:Se,importLines:Re,specs:me}=Ur(O),{build:Ee,contextField:_e,importLines:$e,specs:ge}=jr(r,k.jurisdiction),{build:Pe,contextField:Me,importLines:Te,specs:Fe}=Wr(G),{build:Be,contextField:fe,importLines:be,specs:qe}=Kr(n),{build:je,configField:We,contextField:ye,imports:we,stub:et}=Hr(b),{build:p,configField:Ue,imports:Ne,stub:ae}=Gr($),Ct=e,Dt=t,tt=D??{policies:[],roles:[]},Lt=T??{columns:[]},Et=le??{rules:[]},_t=ce??{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:Pt,override:Mt}=Qr(G),{constant:Ft,override:Bt}=Vr(O),M=v&&k.vectorIndexes.length>0,nt=new Set(k.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ae=M&&k.vectorIndexes.some(m=>nt.has(m.table)),ke=k.tables.some(m=>m.shardMode==="global"),Ke=k.tables.some(m=>In(m)),rt=k.tables.some(m=>Cn(m)),oe=k.tables.some(m=>m.externalSource!==void 0),at=k.tables.some(m=>m.memory===!0),Qe=k.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(rt&&Ke)throw new Z("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Ve=k.tables.length>0,qt=kr(k),jt=vr(k),Wt=Tr(k),Ut=xr(k),ot=Sr(k),st=zr(M,G.length>0,O.length>0,h,Qe);w&&st.push("WhereInput");const it=Nr(ke),Kt=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
|
|
|
@@ -1285,19 +1285,19 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1285
1285
|
|
|
1286
1286
|
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
1287
1287
|
}
|
|
1288
|
-
`:"",
|
|
1288
|
+
`:"",lt=w?[...new Set(tt.policies.filter(m=>m.on==="read"&&m.table!=="").map(m=>m.table))].toSorted((m,Tn)=>m.localeCompare(Tn)):[],ct=lt.length>0?`
|
|
1289
1289
|
/** Refuses to boot a shape that would replicate around the read policies its table is governed by (\`defineShape({ use })\` is how a shape opts in; \`use: []\` acknowledges an ungoverned one). */
|
|
1290
|
-
assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(
|
|
1291
|
-
`:"",
|
|
1290
|
+
assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(lt)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
|
|
1291
|
+
`:"",Qt=te?`
|
|
1292
1292
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1293
1293
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1294
1294
|
}
|
|
1295
|
-
`:"",
|
|
1296
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
1297
|
-
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;`:"",Jt=
|
|
1298
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1299
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
1300
|
-
`:"",
|
|
1295
|
+
`:"",Vt=w?"assertShapeShardable, ":"",Ht=ct===""?"":"assertShapesDeclareReadPolicies, ",xe=[`import type { ${st.join(", ")} } from "${L.do}";`,`import { applyCdcChanges, ${Qe?"backfillSearchIndexes, ":""}${M?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${at?"clearMemoryTables, ":""}${Vt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${oe?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${it.importFragment}ShardDO as ShardDOBase } from "${L.do}";`,...oe?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${L.do}";`]:[],w?`import { asBucketStorage, ${Ht}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${L.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${L.server}";`];Ve&&xe.push(`import { bindOrm, bindTableFacade } from "${L.server}";`),M&&xe.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),s&&xe.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),xe.push(...he.importLines,...z.importLines,...P.importLines,...ne.importLines,...pe.importLines,...Y.importLines,...U.importLines,...K.importLines,...Q.importLines,...j.importLines,...re.importLines,...$e,...Te,...Re,...be,...we,...Ne,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...te?["LUNORA_MUTATOR_PATHS"]:[],...w?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Gt=M?`
|
|
1296
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",zt=rt?`
|
|
1297
|
+
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;`:"",Jt=Ke?`
|
|
1298
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Yt=oe?`
|
|
1299
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Xt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Zt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',en='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',tn='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',nn=ke?C("globalDbStub: DatabaseWriterLike",Xt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",rn=M?C("vectorsStub: VectorSearchLike",Zt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",an=Ae?` const vectorShardKey = this.currentShardKey();
|
|
1300
|
+
`:"",dt=Ae?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",on=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...Ae?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${k.vectorIndexes.filter(m=>nt.has(m.table)).map(m=>JSON.stringify(m.name)).join(", ")}]`]:[]].join(", ")} }`,sn=M?`
|
|
1301
1301
|
const vectorSync = this.vectorSync(env);
|
|
1302
1302
|
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
1303
1303
|
// depends on a similarity search cannot be proven current on reconnect —
|
|
@@ -1307,18 +1307,18 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(it)}, (schema as
|
|
|
1307
1307
|
const bareVectors = vectorSync?.vectors ?? vectorsStub;
|
|
1308
1308
|
const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
|
|
1309
1309
|
const onWrite = vectorSync?.onWrite;
|
|
1310
|
-
`:"",
|
|
1310
|
+
`:"",ln=M?`
|
|
1311
1311
|
private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
|
|
1312
1312
|
if (!config.vectors) {
|
|
1313
1313
|
return undefined;
|
|
1314
1314
|
}
|
|
1315
1315
|
|
|
1316
1316
|
const lunora = createVectors({ indexes: config.vectors(env) });
|
|
1317
|
-
${
|
|
1317
|
+
${an} const vectors = createContextVectors(lunora${on});
|
|
1318
1318
|
|
|
1319
1319
|
return {
|
|
1320
|
-
backfill: createVectorBackfillSync({ ${
|
|
1321
|
-
onWrite: createVectorSyncHook({ ${
|
|
1320
|
+
backfill: createVectorBackfillSync({ ${dt}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
|
|
1321
|
+
onWrite: createVectorSyncHook({ ${dt}schema: schema as unknown as VectorSchemaLike, vectors }),
|
|
1322
1322
|
vectors,
|
|
1323
1323
|
};
|
|
1324
1324
|
}
|
|
@@ -1340,7 +1340,7 @@ ${rn} const vectors = createContextVectors(lunora${on});
|
|
|
1340
1340
|
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1341
1341
|
});
|
|
1342
1342
|
}
|
|
1343
|
-
`:"",
|
|
1343
|
+
`:"",cn=`{
|
|
1344
1344
|
...this.ctxDbTuning(),
|
|
1345
1345
|
auth: { identity: identity ?? null, userId: userId ?? null },
|
|
1346
1346
|
broadcast: (delta) => {
|
|
@@ -1378,7 +1378,7 @@ ${rn} const vectors = createContextVectors(lunora${on});
|
|
|
1378
1378
|
// Left \`undefined\` when there is no scope so \`createShardCtxDb\`
|
|
1379
1379
|
// keeps its own "degrade a provable slice to a whole-table dep"
|
|
1380
1380
|
// fallback rather than reporting into a no-op.
|
|
1381
|
-
onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${
|
|
1381
|
+
onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${M?`
|
|
1382
1382
|
// Vectorize is outside this shard's SQLite and cannot roll back, so
|
|
1383
1383
|
// the sync is held until the mutation's transaction has COMMITTED
|
|
1384
1384
|
// (\`deferAfterCommit\`) instead of running inline. Inline, a write
|
|
@@ -1390,9 +1390,9 @@ ${rn} const vectors = createContextVectors(lunora${on});
|
|
|
1390
1390
|
scheduler,
|
|
1391
1391
|
schema: schema as unknown as SchemaLike,
|
|
1392
1392
|
sql: this.sql as SqlExec,
|
|
1393
|
-
storage,${
|
|
1393
|
+
storage,${ke?`
|
|
1394
1394
|
globalDb,`:""}
|
|
1395
|
-
}`,
|
|
1395
|
+
}`,dn=` /**
|
|
1396
1396
|
* The bare writer every admin/maintenance entry point writes through.
|
|
1397
1397
|
*
|
|
1398
1398
|
* Admin and maintenance writes go through the SAME reactive-cache hooks as a
|
|
@@ -1424,11 +1424,11 @@ ${rn} const vectors = createContextVectors(lunora${on});
|
|
|
1424
1424
|
schema: schema as unknown as SchemaLike,
|
|
1425
1425
|
sql: this.sql as SqlExec,
|
|
1426
1426
|
});
|
|
1427
|
-
}`,
|
|
1428
|
-
vectors,`:"",
|
|
1429
|
-
orm: bindOrm(facade),`:"",
|
|
1430
|
-
const globalDb: DatabaseWriterLike = ${
|
|
1431
|
-
`:"",
|
|
1427
|
+
}`,V=(m="")=>` const writer = this.adminWriter(${m});`,un=M?`
|
|
1428
|
+
vectors,`:"",hn=Ve?`
|
|
1429
|
+
orm: bindOrm(facade),`:"",He=Ke?"config.hyperdriveGlobal":"config.d1",pn=ke?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
|
|
1430
|
+
const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
|
|
1431
|
+
`:"",mn=w&&ke?`
|
|
1432
1432
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1433
1433
|
const env = this.env as Record<string, unknown>;
|
|
1434
1434
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1442,7 +1442,7 @@ ${rn} const vectors = createContextVectors(lunora${on});
|
|
|
1442
1442
|
// keys must mean equal rows, so a field the writer can scope by has to
|
|
1443
1443
|
// be either in the key or out of the request; it is out.
|
|
1444
1444
|
const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity: identity?.identity, userId: identity?.userId };
|
|
1445
|
-
const globalDb: DatabaseWriterLike = ${
|
|
1445
|
+
const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
|
|
1446
1446
|
const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
|
|
1447
1447
|
|
|
1448
1448
|
let cursor: null | string = null;
|
|
@@ -1483,21 +1483,21 @@ ${rn} const vectors = createContextVectors(lunora${on});
|
|
|
1483
1483
|
// emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
|
|
1484
1484
|
// a \`defineShape\`. The Hyperdrive factory simply never reads it.
|
|
1485
1485
|
const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
|
|
1486
|
-
const globalDb: DatabaseWriterLike = ${
|
|
1486
|
+
const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
|
|
1487
1487
|
|
|
1488
1488
|
return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
|
|
1489
1489
|
}
|
|
1490
|
-
`:"",
|
|
1490
|
+
`:"",gn=oe?`
|
|
1491
1491
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1492
1492
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1493
|
-
`:"",
|
|
1493
|
+
`:"",fn=`
|
|
1494
1494
|
protected override async runShardInit(): Promise<void> {
|
|
1495
1495
|
this.ensureMigrated();
|
|
1496
|
-
${
|
|
1496
|
+
${at?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
|
|
1497
1497
|
`:""}
|
|
1498
1498
|
await this.dispatchShardInit();
|
|
1499
1499
|
}
|
|
1500
|
-
`,
|
|
1500
|
+
`,bn=oe?`
|
|
1501
1501
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1502
1502
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1503
1503
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1637,7 +1637,7 @@ ${rt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1637
1637
|
|
|
1638
1638
|
return nextDueAt;
|
|
1639
1639
|
}
|
|
1640
|
-
`:"",
|
|
1640
|
+
`:"",yn=ot.length>0,wn=`
|
|
1641
1641
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1642
1642
|
super(state, env, {
|
|
1643
1643
|
// Every writer this file builds spreads the ctxDbTuning() slice —
|
|
@@ -1660,7 +1660,7 @@ ${oe?`
|
|
|
1660
1660
|
if (autoSourced) {
|
|
1661
1661
|
void this.scheduleSourcePoll();
|
|
1662
1662
|
}
|
|
1663
|
-
`:""}${
|
|
1663
|
+
`:""}${yn?`
|
|
1664
1664
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1665
1665
|
void this.scheduleTtlSweep();
|
|
1666
1666
|
}
|
|
@@ -1688,22 +1688,22 @@ ${oe?`
|
|
|
1688
1688
|
protected override isPaidFunction(functionPath: string): boolean {
|
|
1689
1689
|
return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
|
|
1690
1690
|
}
|
|
1691
|
-
`,
|
|
1691
|
+
`,kn=Ve?`
|
|
1692
1692
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1693
1693
|
${k.tables.map(m=>` facade[${JSON.stringify(m.name)}] = bindTableFacade(db, ${JSON.stringify(m.name)});`).join(`
|
|
1694
1694
|
`)}
|
|
1695
|
-
`:"",
|
|
1695
|
+
`:"",xn=`${he.build}${z.build}${P.build}${Y.build}${pe.build}
|
|
1696
1696
|
const secrets = createSecrets(env);
|
|
1697
|
-
`,
|
|
1698
|
-
secrets,`,
|
|
1697
|
+
`,vn=`${he.contextField}${z.contextField}${P.contextField}${ne.contextField}${Y.contextField}${pe.contextField}
|
|
1698
|
+
secrets,`,Sn=ne.build,ut=y||g||d||x||R||$,Rn=ut?`
|
|
1699
1699
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1700
1700
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
1701
1701
|
if (isAction) {
|
|
1702
|
-
${
|
|
1702
|
+
${U.build}${K.build}${Q.build}${j.build}${re.build}${p}${[...y?[" ctx.images = images;"]:[],...g?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...x?[" ctx.r2sql = r2sql;"]:[],...R?[" ctx.pipelines = pipelines;"]:[],...$?[" ctx.x402 = x402;"]:[]].join(`
|
|
1703
1703
|
`)}
|
|
1704
1704
|
}
|
|
1705
|
-
`:""
|
|
1706
|
-
`:"";return`${S}${
|
|
1705
|
+
`:"",$n=ut?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
|
|
1706
|
+
`:"";return`${S}${xe.join(`
|
|
1707
1707
|
`)}
|
|
1708
1708
|
|
|
1709
1709
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1713,13 +1713,13 @@ interface FunctionReference {
|
|
|
1713
1713
|
}
|
|
1714
1714
|
|
|
1715
1715
|
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1716
|
-
const LUNORA_TABLE_REFS
|
|
1716
|
+
const LUNORA_TABLE_REFS = ${I(qt,"Record<string, Record<string, string>>")};
|
|
1717
1717
|
|
|
1718
1718
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1719
|
-
const LUNORA_TABLE_INDEXES
|
|
1719
|
+
const LUNORA_TABLE_INDEXES = ${I(jt,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
|
|
1720
1720
|
|
|
1721
1721
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1722
|
-
const LUNORA_TABLE_COLUMNS
|
|
1722
|
+
const LUNORA_TABLE_COLUMNS = ${I(Wt,`Record<
|
|
1723
1723
|
string,
|
|
1724
1724
|
Array<{
|
|
1725
1725
|
bucket?: string;
|
|
@@ -1733,32 +1733,32 @@ const LUNORA_TABLE_COLUMNS: Record<
|
|
|
1733
1733
|
ref?: string;
|
|
1734
1734
|
type: string;
|
|
1735
1735
|
}>
|
|
1736
|
-
|
|
1736
|
+
>`)};
|
|
1737
1737
|
|
|
1738
1738
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1739
|
-
const LUNORA_STORAGE_COLUMNS
|
|
1739
|
+
const LUNORA_STORAGE_COLUMNS = ${I(Ut,"Record<string, string[]>")};
|
|
1740
1740
|
|
|
1741
1741
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1742
|
-
const LUNORA_TTL_SWEEPS
|
|
1742
|
+
const LUNORA_TTL_SWEEPS = ${I(ot,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
|
|
1743
1743
|
|
|
1744
1744
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1745
|
-
const LUNORA_ADVISORIES
|
|
1745
|
+
const LUNORA_ADVISORIES = ${I(Ct,"AdvisoryFinding[]")};
|
|
1746
1746
|
|
|
1747
1747
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1748
|
-
const LUNORA_ADVISOR_PROCEDURES
|
|
1748
|
+
const LUNORA_ADVISOR_PROCEDURES = ${I(Dt,"AdvisorProcedure[]")};
|
|
1749
1749
|
|
|
1750
1750
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1751
|
-
const LUNORA_RLS_METADATA
|
|
1752
|
-
${
|
|
1751
|
+
const LUNORA_RLS_METADATA = ${I(tt,"RlsPoliciesResult")};
|
|
1752
|
+
${ct}
|
|
1753
1753
|
/** 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. */
|
|
1754
|
-
const LUNORA_MASK_METADATA
|
|
1754
|
+
const LUNORA_MASK_METADATA = ${I(Lt,"MaskPoliciesResult")};
|
|
1755
1755
|
|
|
1756
1756
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1757
|
-
const LUNORA_STORAGE_RULES
|
|
1757
|
+
const LUNORA_STORAGE_RULES = ${I(Et,"StorageRulesResult")};
|
|
1758
1758
|
|
|
1759
1759
|
/** 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. */
|
|
1760
|
-
const LUNORA_STUDIO_FEATURES
|
|
1761
|
-
${
|
|
1760
|
+
const LUNORA_STUDIO_FEATURES = ${I(_t,"StudioFeaturesResult")};
|
|
1761
|
+
${q}${J.constant}${Pt}${Ft}${ge}${Fe}${me}${qe}
|
|
1762
1762
|
export interface ShardDOConfig {
|
|
1763
1763
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1764
1764
|
cdc?: boolean;
|
|
@@ -1772,9 +1772,9 @@ export interface ShardDOConfig {
|
|
|
1772
1772
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1773
1773
|
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1774
1774
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1775
|
-
storage?: (env: Record<string, unknown>) => unknown;${
|
|
1775
|
+
storage?: (env: Record<string, unknown>) => unknown;${Gt}${Ie}${z.configField}${P.configField}${Y.configField}${U.configField}${K.configField}${Q.configField}${j.configField}${re.configField}${We}${Ue}${zt}${Jt}${Yt}
|
|
1776
1776
|
}
|
|
1777
|
-
${
|
|
1777
|
+
${C("schedulerStub",en,["cancel","runAfter","runAt"])}${C("storageStub",tn,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${nn}${gn}${rn}${De}${z.stub}${P.stub}${Y.stub}${U.stub}${K.stub}${Q.stub}${j.stub}${re.stub}${et}${ae}
|
|
1778
1778
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1779
1779
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1780
1780
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -1848,7 +1848,7 @@ const dispatchRun = async (
|
|
|
1848
1848
|
* from the worker entry so wrangler binds it by name.
|
|
1849
1849
|
*/
|
|
1850
1850
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1851
|
-
class extends ShardDOBase {${
|
|
1851
|
+
class extends ShardDOBase {${wn}
|
|
1852
1852
|
private migrated = false;
|
|
1853
1853
|
|
|
1854
1854
|
public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
|
|
@@ -2029,7 +2029,7 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
|
|
|
2029
2029
|
protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
|
|
2030
2030
|
return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
2031
2031
|
}
|
|
2032
|
-
${
|
|
2032
|
+
${it.override}
|
|
2033
2033
|
protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
2034
2034
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
2035
2035
|
|
|
@@ -2070,11 +2070,11 @@ ${st.override}
|
|
|
2070
2070
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
|
|
2071
2071
|
};
|
|
2072
2072
|
}
|
|
2073
|
-
${
|
|
2073
|
+
${Qt}${Kt}${mn}${bn}
|
|
2074
2074
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
2075
2075
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
2076
2076
|
}
|
|
2077
|
-
${
|
|
2077
|
+
${fn}
|
|
2078
2078
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
2079
2079
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
2080
2080
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -2162,7 +2162,7 @@ ${gn}
|
|
|
2162
2162
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
2163
2163
|
return LUNORA_STUDIO_FEATURES;
|
|
2164
2164
|
}
|
|
2165
|
-
${J.evaluateOverride}${J.subscriptionOverride}${
|
|
2165
|
+
${J.evaluateOverride}${J.subscriptionOverride}${Mt}${Bt}
|
|
2166
2166
|
protected override advisories(): AdvisoryFinding[] {
|
|
2167
2167
|
return LUNORA_ADVISORIES;
|
|
2168
2168
|
}
|
|
@@ -2171,7 +2171,7 @@ ${J.evaluateOverride}${J.subscriptionOverride}${Pt}${Ft}
|
|
|
2171
2171
|
return LUNORA_ADVISOR_PROCEDURES;
|
|
2172
2172
|
}
|
|
2173
2173
|
|
|
2174
|
-
${
|
|
2174
|
+
${dn}
|
|
2175
2175
|
|
|
2176
2176
|
protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
|
|
2177
2177
|
this.ensureMigrated();
|
|
@@ -2188,7 +2188,7 @@ ${cn}
|
|
|
2188
2188
|
throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
|
|
2189
2189
|
}
|
|
2190
2190
|
|
|
2191
|
-
${
|
|
2191
|
+
${V()}
|
|
2192
2192
|
|
|
2193
2193
|
return runDataMigration({
|
|
2194
2194
|
batchSize: args.batchSize,
|
|
@@ -2221,7 +2221,7 @@ ${Q()}
|
|
|
2221
2221
|
|
|
2222
2222
|
this.ensureMigrated();
|
|
2223
2223
|
|
|
2224
|
-
${
|
|
2224
|
+
${V("headroom ?? this.transactionHeadroom()")}
|
|
2225
2225
|
|
|
2226
2226
|
if (args.op === "insert") {
|
|
2227
2227
|
const id = await writer.insert(args.table, args.doc ?? {});
|
|
@@ -2276,7 +2276,7 @@ ${Q("headroom ?? this.transactionHeadroom()")}
|
|
|
2276
2276
|
protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
|
|
2277
2277
|
this.ensureMigrated();
|
|
2278
2278
|
|
|
2279
|
-
${
|
|
2279
|
+
${V()}
|
|
2280
2280
|
|
|
2281
2281
|
const rows: ExportRow[] = [];
|
|
2282
2282
|
|
|
@@ -2293,7 +2293,7 @@ ${Q()}
|
|
|
2293
2293
|
protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
|
|
2294
2294
|
this.ensureMigrated();
|
|
2295
2295
|
|
|
2296
|
-
${
|
|
2296
|
+
${V()}
|
|
2297
2297
|
|
|
2298
2298
|
// \`importShardRows\` inserts with \`allowExplicitId\`, so a source
|
|
2299
2299
|
// database's \`_id\`s carry across verbatim and every foreign key
|
|
@@ -2304,7 +2304,7 @@ ${Q()}
|
|
|
2304
2304
|
protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
|
|
2305
2305
|
this.ensureMigrated();
|
|
2306
2306
|
|
|
2307
|
-
${
|
|
2307
|
+
${V()}
|
|
2308
2308
|
|
|
2309
2309
|
// \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
2310
2310
|
// but the shard writer from \`createShardCtxDb\` always defines it.
|
|
@@ -2322,7 +2322,7 @@ ${Q()}
|
|
|
2322
2322
|
protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
|
|
2323
2323
|
this.ensureMigrated();
|
|
2324
2324
|
|
|
2325
|
-
${
|
|
2325
|
+
${V()}
|
|
2326
2326
|
|
|
2327
2327
|
// \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
2328
2328
|
// but the shard writer from \`createShardCtxDb\` always defines it — it
|
|
@@ -2340,7 +2340,7 @@ ${Q()}
|
|
|
2340
2340
|
protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
|
|
2341
2341
|
this.ensureMigrated();
|
|
2342
2342
|
|
|
2343
|
-
${
|
|
2343
|
+
${V()}
|
|
2344
2344
|
|
|
2345
2345
|
// \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
2346
2346
|
// but the shard writer from \`createShardCtxDb\` always defines it. The sort
|
|
@@ -2361,7 +2361,7 @@ ${Q()}
|
|
|
2361
2361
|
protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
|
|
2362
2362
|
this.ensureMigrated();
|
|
2363
2363
|
|
|
2364
|
-
${
|
|
2364
|
+
${V()}
|
|
2365
2365
|
|
|
2366
2366
|
await applyCdcChanges(writer, args.changes);
|
|
2367
2367
|
|
|
@@ -2373,10 +2373,10 @@ ${Q()}
|
|
|
2373
2373
|
return;
|
|
2374
2374
|
}
|
|
2375
2375
|
|
|
2376
|
-
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${
|
|
2376
|
+
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${de} });
|
|
2377
2377
|
this.migrated = true;
|
|
2378
2378
|
}
|
|
2379
|
-
${
|
|
2379
|
+
${Qe?`
|
|
2380
2380
|
protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
|
|
2381
2381
|
// Migrations create the fts5 companions; without them every backfill
|
|
2382
2382
|
// statement would raise "no such table" on a shard that has never
|
|
@@ -2385,7 +2385,7 @@ ${Ke?`
|
|
|
2385
2385
|
|
|
2386
2386
|
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
2387
2387
|
}
|
|
2388
|
-
`:""}${
|
|
2388
|
+
`:""}${ln}
|
|
2389
2389
|
private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
|
|
2390
2390
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
2391
2391
|
// The caller context this ctx runs under, resolved ONCE on one
|
|
@@ -2407,7 +2407,7 @@ ${Ke?`
|
|
|
2407
2407
|
userId: this.getCurrentUserId(),
|
|
2408
2408
|
};
|
|
2409
2409
|
const { identity, ip, userId } = caller;
|
|
2410
|
-
${
|
|
2410
|
+
${sn}${ue}${xn}${Ee}${Pe}${Le}${Be}
|
|
2411
2411
|
// Which dispatch this ctx belongs to. Drives the two deferral facades
|
|
2412
2412
|
// below and the \`ctx.run*\` caller guard; a ctx built for an
|
|
2413
2413
|
// admin/lifecycle path has no registered function, and so no kind.
|
|
@@ -2503,13 +2503,13 @@ ${an}${de}${kn}${Le}${_e}${De}${Fe}
|
|
|
2503
2503
|
// so both write to the same trace.
|
|
2504
2504
|
const span = this.makeDispatchSpan(traceAnchor, observability);
|
|
2505
2505
|
|
|
2506
|
-
${
|
|
2506
|
+
${pn} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
|
|
2507
2507
|
// adds aggregate counters (call count, total time, per-operation
|
|
2508
2508
|
// breakdown) to the wide event rather than a span per call, so a
|
|
2509
2509
|
// handler making hundreds of queries stays readable. See
|
|
2510
2510
|
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
2511
|
-
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${
|
|
2512
|
-
${
|
|
2511
|
+
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${cn}), logFunctionPath, traceAnchor, observability);
|
|
2512
|
+
${kn}${je}
|
|
2513
2513
|
|
|
2514
2514
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
2515
2515
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -2517,7 +2517,7 @@ ${wn}${qe}
|
|
|
2517
2517
|
// writing mutation's trace from the shared per-request field.
|
|
2518
2518
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
|
|
2519
2519
|
const metrics = this.makeMetrics(logFunctionPath, observability);
|
|
2520
|
-
${
|
|
2520
|
+
${Sn}
|
|
2521
2521
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
2522
2522
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
2523
2523
|
// A \`query\` handler is re-run by every live subscription that reads it,
|
|
@@ -2555,13 +2555,13 @@ ${vn}
|
|
|
2555
2555
|
},
|
|
2556
2556
|
log,
|
|
2557
2557
|
metrics,
|
|
2558
|
-
now,${
|
|
2558
|
+
now,${hn}
|
|
2559
2559
|
scheduler,
|
|
2560
2560
|
span,
|
|
2561
2561
|
storage: contextStorage,
|
|
2562
|
-
trace,${
|
|
2562
|
+
trace,${un}${Ce}${vn}${ye}${_e}${Me}${Se}${fe}
|
|
2563
2563
|
};
|
|
2564
|
-
${
|
|
2564
|
+
${$n}${Rn}
|
|
2565
2565
|
ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx, contextKind);
|
|
2566
2566
|
// The composed mutation runs under the SAME wrapper the top-level RPC
|
|
2567
2567
|
// uses, so "do the transactional work in a mutation and call it from the
|
|
@@ -2596,21 +2596,21 @@ ${Rn}${Sn}
|
|
|
2596
2596
|
return ctx;
|
|
2597
2597
|
}
|
|
2598
2598
|
};
|
|
2599
|
-
`},
|
|
2599
|
+
`},Ze=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?Ze(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},It=(e,t)=>{const n=ie(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Jr=(e,t,n)=>{f(e,"drizzle column name");const r=Ze(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const i=It(t,n);return i!==void 0&&(o+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(o+=".notNull()"),o},Yr=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(f(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${X(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},Xr=(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}: ${Jr(a,o,t)},`)].join(`
|
|
2600
2600
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2601
|
-
${e.indexes.map(
|
|
2601
|
+
${e.indexes.map(a=>Yr(a)).join(`
|
|
2602
2602
|
`)}
|
|
2603
2603
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2604
2604
|
${n}
|
|
2605
|
-
}${r});`},
|
|
2606
|
-
`;const n=
|
|
2605
|
+
}${r});`},Zr=e=>e.typeAnnotation?.includes('Id<"')??!1,ea=(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=Ze(s);n.add(c.builder),o=o||Zr(c),a=a||It(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}},mt=(e,t=!1)=>{if(e.length===0)return`${S}export {};
|
|
2606
|
+
`;const n=se(t),r=new Set(e.map(g=>g.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=ea(e,r),c=[...o,...a].toSorted((g,y)=>g.localeCompare(y)),d=e.map(g=>Xr(g,r)).join(`
|
|
2607
2607
|
|
|
2608
2608
|
`),h=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2609
2609
|
`:"",s?`import type { Id } from "./dataModel.js";
|
|
2610
2610
|
`:""].join("");return`${S}import { ${c.join(", ")} } from "${n.serverDrizzle}";
|
|
2611
2611
|
${h}
|
|
2612
2612
|
${d}
|
|
2613
|
-
`},
|
|
2613
|
+
`},Ta=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:E(mt(n,t),Je),shard:E(mt(r,t),Je)}},Na=e=>e?`${S}/**
|
|
2614
2614
|
* The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
|
|
2615
2615
|
* forward it — wrangler binds only what the entry exports:
|
|
2616
2616
|
*
|
|
@@ -2620,15 +2620,15 @@ ${d}
|
|
|
2620
2620
|
* forwards this module for you whenever it exists.
|
|
2621
2621
|
*/
|
|
2622
2622
|
export { SchedulerDO } from "@lunora/scheduler";
|
|
2623
|
-
`:"",
|
|
2623
|
+
`:"",Aa=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(`
|
|
2624
2624
|
`),r=n.length>0?`
|
|
2625
2625
|
${n}
|
|
2626
|
-
`:"",
|
|
2626
|
+
`:"",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(`
|
|
2627
2627
|
`);return` ${JSON.stringify(i)}: [
|
|
2628
2628
|
${c}
|
|
2629
2629
|
],`}).join(`
|
|
2630
|
-
`),a
|
|
2631
|
-
${
|
|
2630
|
+
`),o=a.length>0?`
|
|
2631
|
+
${a}
|
|
2632
2632
|
`:"";return`${S}/**
|
|
2633
2633
|
* One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
|
|
2634
2634
|
* the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
|
|
@@ -2653,8 +2653,8 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
|
|
|
2653
2653
|
* Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
|
|
2654
2654
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2655
2655
|
*/
|
|
2656
|
-
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${
|
|
2657
|
-
`},
|
|
2656
|
+
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${o}};
|
|
2657
|
+
`},Oa=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(`
|
|
2658
2658
|
`),n=t.length>0?`
|
|
2659
2659
|
${t}
|
|
2660
2660
|
`:"";return`${S}/**
|
|
@@ -2678,4 +2678,4 @@ export interface LunoraVectorIndex {
|
|
|
2678
2678
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2679
2679
|
*/
|
|
2680
2680
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2681
|
-
`},
|
|
2681
|
+
`},Ia=e=>[...new Set(e.map(t=>t.cron))];export{ma as A,Ln as C,S as G,rr as U,fa as a,ya as b,xa as c,Aa as d,Sa as e,ga as f,Ta as g,ka as h,Na as i,wa as j,$a as k,Oa as l,va as m,Ia as n,xr as o,Ra as p,ba as q,I as r};
|