@lunora/codegen 1.0.0-alpha.79 → 1.0.0-alpha.80
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 +32 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{FLAGS_FILENAME-CQDN7BKc.mjs → FLAGS_FILENAME-UPE377GV.mjs} +1 -1
- package/dist/packem_shared/GENERATED_HEADER-BSvZOCvj.mjs +1 -0
- package/dist/packem_shared/{MUTATORS_FILENAME-3Akvs4aT.mjs → MUTATORS_FILENAME-CsAoG-d2.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-B2lXWa7r.mjs → NOTIFY_FILENAME-zA5OFFbv.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-BPT6vyLU.mjs → OPENRPC_VERSION-Dco0Fvm4.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-fCPRec_w.mjs +12 -0
- package/dist/packem_shared/{SHAPES_FILENAME-maut3z1K.mjs → SHAPES_FILENAME-DyVUZzIk.mjs} +1 -1
- package/dist/packem_shared/WORKFLOWS_FILENAME-ClsYRKXp.mjs +1 -0
- package/dist/packem_shared/{buildOpenApiDocument-D6xm3JqM.mjs → buildOpenApiDocument-CfLCgKoc.mjs} +1 -1
- package/dist/packem_shared/discover-queries-Ctpk9SA-.mjs +1 -0
- package/dist/packem_shared/{discoverAuthApiCalls-CEk3J0kc.mjs → discoverAuthApiCalls-CYdI8pkP.mjs} +1 -1
- package/dist/packem_shared/{discoverCrons-kIgM9ZJC.mjs → discoverCrons-CwtPaymU.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-CVYkUBTm.mjs +1 -0
- package/dist/packem_shared/{discoverHttpRoutes-CLn3VDRI.mjs → discoverHttpRoutes-DmTedJlp.mjs} +1 -1
- package/dist/packem_shared/{discoverInserts-Cn-CLKET.mjs → discoverInserts-CssZuKb6.mjs} +1 -1
- package/dist/packem_shared/{discoverMaskProcedures-fZtvsy8v.mjs → discoverMaskProcedures-DQ-4yUUK.mjs} +1 -1
- package/dist/packem_shared/{discoverMigrations-BH_IKdFk.mjs → discoverMigrations-qyXaVjw1.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-Cl7qNL0J.mjs → discoverNondeterministicCalls-GNP4oKrf.mjs} +1 -1
- package/dist/packem_shared/discoverQueries-2A0lbpxV.mjs +1 -0
- package/dist/packem_shared/{discoverR2sqlCalls-CMNfDWlq.mjs → discoverR2sqlCalls-B7uqLnVS.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsMetadata-Bf4_2S0t.mjs → discoverRlsMetadata-Bt0QK8VM.mjs} +1 -1
- package/dist/packem_shared/{discoverSandboxUsage-Bn1X9COt.mjs → discoverSandboxUsage-Bb2JzaIW.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-DUl8rbP3.mjs +1 -0
- package/dist/packem_shared/{discoverStorageRulesMetadata-CL8J41rX.mjs → discoverStorageRulesMetadata-VJ_uXOFe.mjs} +1 -1
- package/dist/packem_shared/{emit-BtiV37rG.mjs → emit-B6-LPmOS.mjs} +187 -179
- package/dist/packem_shared/{emitApp-Bc3G4eki.mjs → emitApp-DGiGQ1P4.mjs} +17 -12
- package/dist/packem_shared/parse-validator-_jDrFxwt.mjs +1 -0
- package/dist/packem_shared/redact-6jD4lAhq.mjs +1 -0
- package/package.json +4 -4
- package/dist/packem_shared/GENERATED_HEADER-bdSyaxCS.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-FjKlVIV5.mjs +0 -5
- package/dist/packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs +0 -1
- package/dist/packem_shared/discover-queries-LfER8HbK.mjs +0 -1
- package/dist/packem_shared/discoverFunctions-DnqHgv0t.mjs +0 -1
- package/dist/packem_shared/discoverQueries-B_2Ciq7P.mjs +0 -1
- package/dist/packem_shared/discoverSchema-Cy4OQ0Cu.mjs +0 -1
- package/dist/packem_shared/parse-validator-CSDlMEvE.mjs +0 -1
- package/dist/packem_shared/redact-CQ8-to6l.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as Ye}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as
|
|
1
|
+
import{agentComponent as Ye}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as zt,hashSchemaSnapshot as Xt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{n as S}from"./paths-BmX5O1sG.mjs";const Ze=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",serverCtxField:{field:`
|
|
2
2
|
/** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
|
|
3
3
|
readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",serverCtxField:{field:`
|
|
4
4
|
/** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
|
|
@@ -15,53 +15,53 @@ import{agentComponent as Ye}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"}],Yt=Ze,Zt=new Map(Yt.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),mr=Ze.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),et=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,en=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),tt=e=>e.column!==void 0,tn=(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
|
-
`}},Fe=(e,t,n)=>{if(!tt(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(
|
|
23
|
+
`}},nn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!et.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
|
|
24
|
+
`}},Fe=(e,t,n)=>{if(!tt(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(en.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:tn(e.kind,t)};switch(e.kind){case"array":return rn(e,t,n);case"literal":return nn(e,t);case"object":return on(e,t,n);default:return}}},rn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const a=n.next(),o=`__arr${String(a)}`,s=`__i${String(a)}`,i=`__e${String(a)}`,l=Fe(r,i,n);if(!l)return;const u=`if (!Array.isArray(${t})) return DEFER;
|
|
25
25
|
const ${o} = new Array(${t}.length);
|
|
26
26
|
for (let ${s} = 0; ${s} < ${t}.length; ${s}++) {
|
|
27
27
|
const ${i} = ${t}[${s}];
|
|
28
28
|
${l.pre}${o}[${s}] = ${l.out};
|
|
29
29
|
}
|
|
30
|
-
`;return{out:o,pre:u}},
|
|
30
|
+
`;return{out:o,pre:u}},an=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||tt(t))return;const{inner:s}=t;if(!s)return;const i=Fe(s,n,r);if(!i)return;const l=r.next(),u=`__has${String(l)}`,p=`__val${String(l)}`,f=`let ${u} = false;
|
|
31
31
|
let ${p};
|
|
32
32
|
if (${n} !== undefined) {
|
|
33
33
|
${i.pre}${p} = ${i.out};
|
|
34
34
|
${u} = true;
|
|
35
35
|
}
|
|
36
|
-
`;return{entry:`...(${u} ? { ${a}: ${p} } : {})`,pre:
|
|
36
|
+
`;return{entry:`...(${u} ? { ${a}: ${p} } : {})`,pre:f}}const o=Fe(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},nt=(e,t,n)=>{let r="";const a=[];for(const o of Object.keys(e)){const s=e[o];if(!s)return;const i=an(o,s,t(o),n);if(!i)return;r+=i.pre,a.push(i.entry)}return{entries:a.join(", "),pre:r}},on=(e,t,n)=>{const r=e.shape??{},a=nt(r,l=>`${t}[${JSON.stringify(l)}]`,n);if(!a)return;const o=n.next(),s=`__obj${String(o)}`,i=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
|
|
37
37
|
${a.pre}const ${s} = { ${a.entries} };
|
|
38
|
-
`;return{out:s,pre:i}},
|
|
38
|
+
`;return{out:s,pre:i}},sn=e=>{let t=0;const n=nt(e,r=>`source[${JSON.stringify(r)}]`,{next:()=>(t+=1,t)});if(n)return`(source) => {
|
|
39
39
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
40
40
|
${n.pre}return { ${n.entries} };
|
|
41
41
|
}`},k=`// GENERATED by @lunora/codegen — do not edit.
|
|
42
42
|
// Run \`lunora codegen\` to regenerate.
|
|
43
43
|
|
|
44
|
-
`,H=(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"},rt=/^[A-Za-z_$][\w$]*$/u,
|
|
44
|
+
`,H=(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"},rt=/^[A-Za-z_$][\w$]*$/u,ln=/^[\w./-]+$/u,m=(e,t)=>{if(!rt.test(e))throw new Z("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ee=e=>e.charAt(0).toUpperCase()+e.slice(1),D=e=>rt.test(e)?e:JSON.stringify(e),dn={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},cn=e=>{if(e===void 0)return"unknown";if(!et.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},O=e=>{const t=dn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?O(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return m(n,"v.id() table name"),`Id<"${n}">`}case"literal":return cn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([n,r])=>`${D(n)}: ${O(r)}`).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?O(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?O(e.keyType):"string",r=e.valueType?O(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>O(n)).join(" | "):"never";default:return"unknown"}},me=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>{const a=D(n);if(r.kind==="optional"){const o=r.inner?O(r.inner):"unknown";return`${a}?: ${o}`}return`${a}: ${O(r)}`}).join("; ")} }`},un=e=>e.kind==="optional"||!!e.column?.hasDefault,pn=e=>{m(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=a.kind==="optional"&&a.inner?a.inner:a,s=O(o),i=D(r);return un(a)?` ${i}?: ${s};`:` ${i}: ${s};`}).join(`
|
|
45
45
|
`),n=t?`
|
|
46
46
|
${t}
|
|
47
47
|
`:"";return`export interface Insert_${e.name} {
|
|
48
48
|
_id?: Id<"${e.name}">;
|
|
49
|
-
_creationTime?: number;${n}}`},
|
|
50
|
-
`),
|
|
49
|
+
_creationTime?: number;${n}}`},fr=(e,t=!1)=>{const n=H(t);for(const c of e.tables)m(c.name,"table name");const r=e.tables.map(c=>`"${c.name}"`).join(" | ")||"never",a=e.tables.filter(c=>c.extensionKey===void 0).map(c=>`"${c.name}"`).join(" | ")||"never",o=e.tables.map(c=>{const g=Object.entries(c.shape).map(([x,v])=>{const A=D(x);if(v.kind==="optional"){const N=v.inner?O(v.inner):"unknown";return` ${A}?: ${N};`}return` ${A}: ${O(v)};`}).join(`
|
|
50
|
+
`),b=g?`
|
|
51
51
|
${g}
|
|
52
52
|
`:"";return`export interface Doc_${c.name} {
|
|
53
53
|
_id: Id<"${c.name}">;
|
|
54
|
-
_creationTime: number;${
|
|
54
|
+
_creationTime: number;${b}}`}).join(`
|
|
55
55
|
|
|
56
56
|
`),s=e.tables.map(c=>` ${c.name}: Doc_${c.name};`).join(`
|
|
57
|
-
`),i=e.tables.map(c=>{const g=c.indexes.map(
|
|
58
|
-
`),l=e.tables.map(c=>{const g=c.searchIndexes.map(
|
|
59
|
-
`),u=e.tables.map(c=>{const g=c.rankIndexes.map(
|
|
60
|
-
`),p=e.tables.map(c=>{const g=c.shardMode==="global"?"":(c.geoIndexes??[]).map(
|
|
61
|
-
`),
|
|
62
|
-
|
|
63
|
-
`)
|
|
64
|
-
`),d=e.tables.map(c=>{const g=c.relations.map(
|
|
57
|
+
`),i=e.tables.map(c=>{const g=c.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
58
|
+
`),l=e.tables.map(c=>{const g=c.searchIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
59
|
+
`),u=e.tables.map(c=>{const g=c.rankIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
60
|
+
`),p=e.tables.map(c=>{const g=c.shardMode==="global"?"":(c.geoIndexes??[]).map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
61
|
+
`),f=e.vectorIndexes.map(c=>JSON.stringify(c.name)).join(" | ")||"never",y=e.tables.map(c=>pn(c)).join(`
|
|
62
|
+
|
|
63
|
+
`),R=e.tables.map(c=>` ${c.name}: Insert_${c.name};`).join(`
|
|
64
|
+
`),d=e.tables.map(c=>{const g=c.relations.map(b=>(m(b.table,"relation target table"),` ${D(b.name)}: ${b.kind==="one"?"OneRelation":"ManyRelation"}<"${b.table}">;`)).join(`
|
|
65
65
|
`);return g?` ${c.name}: {
|
|
66
66
|
${g}
|
|
67
67
|
};`:` ${c.name}: {};`}).join(`
|
|
@@ -158,13 +158,13 @@ ${p}
|
|
|
158
158
|
export type GeoIndexName<T extends keyof DataModel> = GeoIndexNamesByTable[T];
|
|
159
159
|
|
|
160
160
|
/** Union of declared vector index names. \`never\` when none are declared. */
|
|
161
|
-
export type VectorIndexName = ${
|
|
161
|
+
export type VectorIndexName = ${f};
|
|
162
162
|
|
|
163
163
|
${y}
|
|
164
164
|
|
|
165
165
|
/** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
|
|
166
166
|
export interface InsertModel {
|
|
167
|
-
${
|
|
167
|
+
${R}
|
|
168
168
|
}
|
|
169
169
|
|
|
170
170
|
export type Insert<T extends keyof DataModel> = InsertModel[T];
|
|
@@ -234,11 +234,11 @@ export interface OrmWriter extends OrmReader {
|
|
|
234
234
|
replace: <T extends keyof DataModel>(table: T, id: Id<T>) => OrmReplaceBuilder<T>;
|
|
235
235
|
update: <T extends keyof DataModel>(table: T, id: Id<T>) => OrmUpdateBuilder<T>;
|
|
236
236
|
}
|
|
237
|
-
`},
|
|
238
|
-
`);return` ${
|
|
237
|
+
`},hn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,gn=/^(?:\.\.?\/)*_generated\//u,mn=/\.[A-Za-z]\w*$/u,Me=e=>e.replaceAll(hn,(t,n)=>{const r=n.replace(gn,"./");return`import("${mn.test(r)?r:`${r}.js`}")`}),fn=/import\("@lunora\/(?<pkg>client|do|runtime|server|values)(?<subpath>\/[^"]*)?"\)/gu,at=(e,t)=>t?e.replaceAll(fn,(n,r,a)=>`import("lunorash/${r}${a??""}")`):e,qe=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),bn=e=>e.output===void 0||e.output.kind==="any"?e.returnType:O(e.output),ze=e=>{const t=new Map;for(const r of e){const a=t.get(r.filePath)??[];a.push(r),t.set(r.filePath,a)}const n=([r,a])=>{const o=a.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=me(s.args),l=Me(bn(s));return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${l}>;`}).join(`
|
|
238
|
+
`);return` ${D(S(r))}: {
|
|
239
239
|
${o}
|
|
240
240
|
};`};return[...t.entries()].toSorted(([r],[a])=>r.localeCompare(a)).map(r=>n(r)).join(`
|
|
241
|
-
`)},
|
|
241
|
+
`)},yn=(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+=`
|
|
242
242
|
/** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
|
|
243
243
|
export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
244
244
|
readonly isLunoraWorkflow: true;
|
|
@@ -270,7 +270,7 @@ export const agents: AgentsRef = {
|
|
|
270
270
|
${s}
|
|
271
271
|
};
|
|
272
272
|
`,n.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
273
|
-
`)}return{block:r,importLine:n.join("")}},
|
|
273
|
+
`)}return{block:r,importLine:n.join("")}},wn=()=>Object.keys(Ye().functions).toSorted((e,t)=>e.localeCompare(t)),ot=e=>new Set(e.filter(t=>S(t.filePath)==="agents").map(t=>t.exportName)),xn=()=>new Set(Object.entries(Ye().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),kn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=ot(t),a=xn(),o=t.find(i=>S(i.filePath)==="agents"&&a.has(i.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 s=wn().filter(i=>!r.has(i));return s.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
274
274
|
`,lines:s.map(i=>` "agents:${i}": lunoraAgentRuntimeFunctions.${i} as unknown as RegisteredLunoraFunction,`).join(`
|
|
275
275
|
`),prelude:`
|
|
276
276
|
/**
|
|
@@ -279,13 +279,13 @@ ${s}
|
|
|
279
279
|
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
280
280
|
*/
|
|
281
281
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
282
|
-
`}},
|
|
283
|
-
`,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"}}
|
|
284
|
-
`);return` ${
|
|
282
|
+
`}},vn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>S(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";
|
|
283
|
+
`,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"}},$n=(e,t)=>{if(e.length===0)return[];const n=ot(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))},Sn=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>S(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}))},Rn=e=>{const t=e.filter(s=>s.stream);if(t.length===0)return{block:"",body:""};const n=new Map;for(const s of t){const i=n.get(s.filePath)??[];i.push(s),n.set(s.filePath,i)}const r=[...n.entries()].toSorted(([s],[i])=>s.localeCompare(i)),a=r.map(([s,i])=>{const l=i.map(u=>{const p=Me(u.chunkType??"unknown");return` ${D(u.exportName)}: HttpStreamRef<${p}, ${me(u.searchParams)}, ${me(u.params)}>;`}).join(`
|
|
284
|
+
`);return` ${D(S(s))}: {
|
|
285
285
|
${l}
|
|
286
286
|
};`}).join(`
|
|
287
|
-
`),o=r.map(([s,i])=>{const l=i.map(u=>` ${
|
|
288
|
-
`);return` ${
|
|
287
|
+
`),o=r.map(([s,i])=>{const l=i.map(u=>` ${D(u.exportName)}: { method: ${JSON.stringify(u.method)}, path: ${JSON.stringify(u.path)} },`).join(`
|
|
288
|
+
`);return` ${D(S(s))}: {
|
|
289
289
|
${l}
|
|
290
290
|
},`}).join(`
|
|
291
291
|
`);return{block:`
|
|
@@ -297,26 +297,26 @@ ${a}
|
|
|
297
297
|
export const httpStreams: HttpStreamsRef = {
|
|
298
298
|
${o}
|
|
299
299
|
};
|
|
300
|
-
`,body:a}},
|
|
301
|
-
${
|
|
302
|
-
${y.body}`,d=qe(
|
|
300
|
+
`,body:a}},br=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:s=[]}=e,i=H(o),l=[...n.filter($=>$.visibility!=="internal"),...$n(t,n),...Sn(a,n)],u=n.filter($=>$.visibility==="internal"),p=ze(l),f=ze(u),y=Rn(r),R=`${p}
|
|
301
|
+
${f}
|
|
302
|
+
${y.body}`,d=qe(R),c=d.length>0?`
|
|
303
303
|
import type { ${d.join(", ")} } from "./dataModel.js";
|
|
304
304
|
`:"",g=p?`
|
|
305
305
|
${p}
|
|
306
|
-
`:"",f
|
|
307
|
-
${
|
|
308
|
-
`:"",x=
|
|
309
|
-
import type { ${S} } from "${i.client}";
|
|
310
|
-
${x.importLine}${c}
|
|
311
|
-
export interface ApiTypes {${g}}
|
|
306
|
+
`:"",b=f?`
|
|
307
|
+
${f}
|
|
308
|
+
`:"",x=yn(s,t),v=`export interface ApiTypes {${g}}
|
|
312
309
|
|
|
313
310
|
export const api = anyApi as unknown as ApiTypes;
|
|
314
311
|
|
|
315
312
|
/** Internal functions — callable only server-side via \`ctx.run*\`, never from a client. */
|
|
316
|
-
export interface InternalApiTypes {${
|
|
313
|
+
export interface InternalApiTypes {${b}}
|
|
317
314
|
|
|
318
315
|
export const internal = anyApi as unknown as InternalApiTypes;
|
|
319
|
-
${x.block}${y.block}`,
|
|
316
|
+
${x.block}${y.block}`,A=[...v.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],N=A.length>0?`import type { ${A.join(", ")} } from "${i.client}";
|
|
317
|
+
`:"";return at(`${k}import { anyApi } from "${i.serverTypes}";
|
|
318
|
+
${N}${x.importLine}${c}
|
|
319
|
+
${v}`,o)},yr=e=>e?`${k}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
320
320
|
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
321
321
|
|
|
322
322
|
import schema from "../schema.js";
|
|
@@ -333,7 +333,7 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
333
333
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
334
334
|
*/
|
|
335
335
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
336
|
-
`:"",
|
|
336
|
+
`:"",wr=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=H(n),a=l=>l.table===void 0?"Row":`Doc<${JSON.stringify(l.table)}> & Row`,o=e.map(l=>{m(l.exportName,"shape export name");const u=a(l),p=me(l.args),f=Object.keys(l.args).length>0,y=f?` args: ${p};`:` args?: ${p};`,R=f?`(args: ${p}) => void`:`(args?: ${p}) => void`,d=`${l.exportName}CollectionOptions`;return`/** Options for the \`${l.exportName}\` shape binding. */
|
|
337
337
|
export interface ${Ee(d)} {
|
|
338
338
|
${y}
|
|
339
339
|
/**
|
|
@@ -373,7 +373,7 @@ export const ${l.exportName}CollectionOptions = (options: ${Ee(d)}): LunoraColle
|
|
|
373
373
|
/** Live collection for the \`${l.exportName}\` shape, with its sync controls. */
|
|
374
374
|
export const ${l.exportName}Collection = (
|
|
375
375
|
options: ${Ee(d)},
|
|
376
|
-
): { checkpoints: CheckpointRegistry; collection: Collection<${u}, string>; scope: ${
|
|
376
|
+
): { checkpoints: CheckpointRegistry; collection: Collection<${u}, string>; scope: ${R} } => {
|
|
377
377
|
const { checkpoints, config, scope } = ${l.exportName}CollectionOptions(options);
|
|
378
378
|
|
|
379
379
|
return { checkpoints, collection: createCollection(config), scope };
|
|
@@ -387,7 +387,7 @@ import type { Collection } from "@tanstack/db";
|
|
|
387
387
|
import { createCollection } from "@tanstack/db";
|
|
388
388
|
${i}
|
|
389
389
|
${o}
|
|
390
|
-
`},
|
|
390
|
+
`},Nn=(e,t)=>`lunora_${S(e)}_${String(t)}`,On=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
391
391
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
392
392
|
|
|
393
393
|
if (!registered) {
|
|
@@ -395,45 +395,45 @@ ${o}
|
|
|
395
395
|
}
|
|
396
396
|
|
|
397
397
|
return (await registered.handler(context, args ?? {})) as R;
|
|
398
|
-
};`,
|
|
399
|
-
`),i=e.map(d=>` "${
|
|
398
|
+
};`,An=(e,t,n=[],r=[])=>{const a=new Map,o=d=>{a.has(d)||a.set(d,Nn(d,a.size))};for(const d of e)o(d.filePath);for(const d of t)o(d.filePath);for(const d of n)o(d.filePath);for(const d of r)o(d.filePath);const s=[...a.entries()].map(([d,c])=>{if(!ln.test(d))throw new Z("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(d)}`);return`import * as ${c} from "../${d}.js";`}).join(`
|
|
399
|
+
`),i=e.map(d=>` "${S(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
400
400
|
`),l=t.map(d=>` ${JSON.stringify(d.id)}: ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
401
|
-
`),u=n.map(d=>` "${
|
|
401
|
+
`),u=n.map(d=>` "${S(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
402
402
|
`),p=r.map(d=>` "${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredShape,`).join(`
|
|
403
|
-
`),
|
|
404
|
-
`)
|
|
403
|
+
`),f=n.map(d=>`${S(d.filePath)}:${d.exportName}`),y=[i,u].filter(d=>d.length>0).join(`
|
|
404
|
+
`),R=e.map(d=>{if(d.lifecycle||Object.keys(d.args).length===0)return;const c=sn(d.args);return c===void 0?void 0:`installCompiledValidatorMap(${a.get(d.filePath)??""}.${d.exportName}.args, ${c});`}).filter(d=>d!==void 0).join(`
|
|
405
405
|
`);return{dispatchBody:y.length>0?`
|
|
406
406
|
${y}
|
|
407
407
|
`:"",importBlock:s.length>0?`${s}
|
|
408
408
|
|
|
409
|
-
`:"",installBlock
|
|
409
|
+
`:"",installBlock:R,migrationBody:l.length>0?`
|
|
410
410
|
${l}
|
|
411
|
-
`:"",mutatorPaths:
|
|
411
|
+
`:"",mutatorPaths:f,shapeBody:p.length>0?`
|
|
412
412
|
${p}
|
|
413
|
-
`:""}},
|
|
414
|
-
`);return` ${
|
|
413
|
+
`:""}},Tn=e=>{const t=new Map;for(const a of e){const o=t.get(a.filePath)??[];o.push(a),t.set(a.filePath,o)}const n=[...t.entries()].toSorted(([a],[o])=>a.localeCompare(o)),r=n.map(([a,o])=>{const s=o.map(i=>{const l=me(i.args),u=l==="{}"?"?":"",p=Me(i.returnType);return i.kind==="stream"?` ${i.exportName}: (args${u}: ${l}) => Promise<AsyncIterable<${p}>>;`:` ${i.exportName}: (args${u}: ${l}) => Promise<${p}>;`}).join(`
|
|
414
|
+
`);return` ${D(S(a))}: {
|
|
415
415
|
${s}
|
|
416
416
|
};`}).join(`
|
|
417
|
-
`);return{implementation:n.map(([a,o])=>{const s=
|
|
418
|
-
`);return` ${
|
|
417
|
+
`);return{implementation:n.map(([a,o])=>{const s=S(a),i=o.map(l=>` ${l.exportName}: (args) => callRegistered(context, "${s}:${l.exportName}", args),`).join(`
|
|
418
|
+
`);return` ${D(s)}: {
|
|
419
419
|
${i}
|
|
420
420
|
},`}).join(`
|
|
421
|
-
`),types:r}},
|
|
421
|
+
`),types:r}},Ln=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=a.kind==="optional"&&a.inner?a.inner: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))]},xr=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:s=!1,hasFlags:i=!1,hasHyperdrive:l=!1,hasImages:u=!1,hasKv:p=!1,hasNotify:f=!1,hasPayments:y=!1,hasPipelines:R=!1,hasR2sql:d=!1,hasX402:c=!1,identity:g,queues:b=[],schema:x,storageRuleBuckets:v=[],useUmbrella:A=!1,workflows:N=[]}={})=>{const $=H(A),w=Ln(x??{tables:[]},v).map(h=>JSON.stringify(h)).join(" | "),E=a?`import type { LunoraAi } from "@lunora/ai";
|
|
422
422
|
`:"",ee=a?`
|
|
423
423
|
readonly ai: LunoraAi;`:"",F=y?`import type { LunoraPayment } from "@lunora/payment";
|
|
424
424
|
`:"",te=y?`
|
|
425
425
|
readonly payments: LunoraPayment;`:"",ne=c?`import type { X402Pay } from "@lunora/x402/pay";
|
|
426
426
|
`:"",B=c?`
|
|
427
|
-
readonly x402: X402Pay;`:"",
|
|
427
|
+
readonly x402: X402Pay;`:"",T=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
|
|
428
428
|
`:"",z=t.length>0?`
|
|
429
429
|
readonly containers: {${t.map(h=>`
|
|
430
430
|
readonly ${h.exportName}: ContainerAccessor;`).join("")}
|
|
431
|
-
};`:"",
|
|
432
|
-
readonly ${h.bindingName}?: unknown;`)),...
|
|
433
|
-
readonly ${h.bindingName}?: unknown;`)),...
|
|
431
|
+
};`:"",L=[...a?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(h=>(m(h.bindingName,`container binding "${h.bindingName}"`),` /** Durable Object namespace for the \`${h.exportName}\` container. */
|
|
432
|
+
readonly ${h.bindingName}?: unknown;`)),...N.map(h=>(m(h.bindingName,`workflow binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` workflow. */
|
|
433
|
+
readonly ${h.bindingName}?: unknown;`)),...b.map(h=>(m(h.bindingName,`queue binding "${h.bindingName}"`),` /** Queue producer binding for the \`${h.exportName}\` queue. */
|
|
434
434
|
readonly ${h.bindingName}?: unknown;`)),...e.map(h=>(m(h.bindingName,`agent binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` agent. */
|
|
435
435
|
readonly ${h.bindingName}?: unknown;`))].join(`
|
|
436
|
-
`),
|
|
436
|
+
`),_=`
|
|
437
437
|
|
|
438
438
|
/**
|
|
439
439
|
* This project's Cloudflare bindings, as far as codegen can discover them from
|
|
@@ -446,24 +446,24 @@ ${i}
|
|
|
446
446
|
* surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
|
|
447
447
|
*/
|
|
448
448
|
export interface CloudflareBindings {
|
|
449
|
-
readonly [binding: string]: unknown;${
|
|
450
|
-
${
|
|
449
|
+
readonly [binding: string]: unknown;${L?`
|
|
450
|
+
${L}`:""}
|
|
451
451
|
}
|
|
452
452
|
|
|
453
453
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
454
|
-
export type Env = CloudflareBindings;`,M=(h,_e)=>_e?
|
|
454
|
+
export type Env = CloudflareBindings;`,M=(h,_e)=>_e?Zt.get(h)?.field??"":"",re=M("kv",p),ae=M("analytics",o),xe=M("hyperdrive",l),ke=M("browser",s),ve=M("images",u),oe=M("pipelines",R),K=M("r2sql",d),P=(x?.vectorIndexes.length??0)>0,Q=P?' | "vectors"':"",X=P?`
|
|
455
455
|
readonly vectors: VectorSearch<VectorIndexName>;`:"",ie=P?`
|
|
456
|
-
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",V=P?`import type { VectorSearch, VectorSearchReader } from "${
|
|
456
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",V=P?`import type { VectorSearch, VectorSearchReader } from "${$.server}";
|
|
457
457
|
import type { VectorIndexName } from "./dataModel.js";
|
|
458
458
|
`:"",j=r?`
|
|
459
459
|
/** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
|
|
460
460
|
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",W=i?`
|
|
461
461
|
/** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
|
|
462
|
-
readonly flags: import("${
|
|
462
|
+
readonly flags: import("${$.flags}").LunoraFlags;`:"",U=f?`
|
|
463
463
|
/** 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. */
|
|
464
464
|
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
465
465
|
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
466
|
-
readonly push: import("@lunora/notify").LunoraPush;`:"",q=
|
|
466
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",q=N.length>0,Y=q?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
467
467
|
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
468
468
|
`:"",$e=q?`
|
|
469
469
|
|
|
@@ -476,10 +476,10 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
476
476
|
|
|
477
477
|
/** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
|
|
478
478
|
export interface LunoraWorkflows {
|
|
479
|
-
${
|
|
479
|
+
${N.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
|
|
480
480
|
`)}
|
|
481
481
|
}`:"",fe=q?' | "workflows"':"",be=q?`
|
|
482
|
-
readonly workflows: LunoraWorkflows;`:"",se=
|
|
482
|
+
readonly workflows: LunoraWorkflows;`:"",se=b.length>0,Se=se?`import type { QueueProducer } from "@lunora/queue";
|
|
483
483
|
import type * as lunoraQueueDefinitions from "../queues.js";
|
|
484
484
|
`:"",Re=se?`
|
|
485
485
|
|
|
@@ -488,7 +488,7 @@ type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body }
|
|
|
488
488
|
|
|
489
489
|
/** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
|
|
490
490
|
export interface LunoraQueues {
|
|
491
|
-
${
|
|
491
|
+
${b.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${h.exportName}>>;`).join(`
|
|
492
492
|
`)}
|
|
493
493
|
}`:"",ye=se?`
|
|
494
494
|
readonly queues: LunoraQueues;`:"",le=e.length>0,Ne=le?`import type { AgentHandle } from "@lunora/agent";
|
|
@@ -499,7 +499,7 @@ export interface LunoraAgents {
|
|
|
499
499
|
${e.map(h=>(m(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
|
|
500
500
|
`)}
|
|
501
501
|
}`:"",we=le?`
|
|
502
|
-
readonly agents: LunoraAgents;`:"",Ae=g?`import type { InferIdentity } from "${
|
|
502
|
+
readonly agents: LunoraAgents;`:"",Ae=g?`import type { InferIdentity } from "${$.server}";
|
|
503
503
|
import type * as lunoraIdentityContract from "../identity.js";
|
|
504
504
|
`:"",Te=g?`
|
|
505
505
|
|
|
@@ -512,7 +512,7 @@ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: (
|
|
|
512
512
|
`:"",De=n?`
|
|
513
513
|
|
|
514
514
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
515
|
-
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",ue=n?' | "env"':"",pe=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`${k}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${
|
|
515
|
+
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",ue=n?' | "env"':"",pe=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`${k}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${$.server}";
|
|
516
516
|
import type {
|
|
517
517
|
ActionBuilder,
|
|
518
518
|
ActionCtx as ActionCtxBase,
|
|
@@ -533,14 +533,14 @@ import type {
|
|
|
533
533
|
Storage as StorageBase,
|
|
534
534
|
TableReader,
|
|
535
535
|
Validator,
|
|
536
|
-
} from "${
|
|
536
|
+
} from "${$.server}";
|
|
537
537
|
|
|
538
538
|
import type { DataModel, DatabaseReaderFacade, DatabaseWriterFacade, Doc, Id as IdOfTable, OrmReader, OrmWriter, Relations, TableName } from "./dataModel.js";
|
|
539
|
-
${V}${E}${F}${ne}${
|
|
539
|
+
${V}${E}${F}${ne}${T}${Y}${Se}${Ne}${Ae}${Ce}
|
|
540
540
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
541
541
|
|
|
542
542
|
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
543
|
-
export type StorageBucketName = ${w};${
|
|
543
|
+
export type StorageBucketName = ${w};${_}${$e}${Re}${Oe}${Te}${De}
|
|
544
544
|
|
|
545
545
|
/**
|
|
546
546
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -642,7 +642,7 @@ export const internalAction = lunoraBuilders.internalAction as unknown as Intern
|
|
|
642
642
|
/**
|
|
643
643
|
* \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
|
|
644
644
|
* custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
|
|
645
|
-
* \`${
|
|
645
|
+
* \`${$.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
|
|
646
646
|
* schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
|
|
647
647
|
* \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
|
|
648
648
|
* no \`as unknown as\` cast. Runtime-identical to the package export; only the
|
|
@@ -684,13 +684,13 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Le}>();
|
|
|
684
684
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
685
685
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
686
686
|
};
|
|
687
|
-
`},
|
|
688
|
-
`);let
|
|
687
|
+
`},Cn=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${S(n.filePath)}:${n.exportName}`);return t},kr=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:s=!1,usesSandbox:i=!1}=e,l=n.length>0,u=H(s),{dispatchBody:p,importBlock:f,installBlock:y,migrationBody:R,mutatorPaths:d,shapeBody:c}=An(n,r,a,o),g=kn(t,n),b=vn(i,n),x=[g.lines,b.lines].filter(_=>_.length>0).join(`
|
|
688
|
+
`);let v=p;x.length>0&&(v=p.length>0?`${p.trimEnd()}
|
|
689
689
|
${x}
|
|
690
690
|
`:`
|
|
691
691
|
${x}
|
|
692
|
-
`);const
|
|
693
|
-
`:""
|
|
692
|
+
`);const A=Cn(n),N=o.length>0?`import type { RegisteredShape } from "${u.server}";
|
|
693
|
+
`:"",$=o.length>0?`
|
|
694
694
|
/**
|
|
695
695
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
696
696
|
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
@@ -704,7 +704,7 @@ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${c}};
|
|
|
704
704
|
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
705
705
|
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
706
706
|
*/
|
|
707
|
-
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(
|
|
707
|
+
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(_=>JSON.stringify(_)).join(", ")}]);
|
|
708
708
|
`:"",E=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
|
|
709
709
|
`:"",ee=y.length>0?`
|
|
710
710
|
/**
|
|
@@ -713,16 +713,16 @@ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(D=>JSO
|
|
|
713
713
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
714
714
|
*/
|
|
715
715
|
${y}
|
|
716
|
-
`:"",F=
|
|
716
|
+
`:"",F=Tn(n),te=F.types?`
|
|
717
717
|
${F.types}
|
|
718
718
|
`:"",ne=F.implementation?`
|
|
719
719
|
${F.implementation}
|
|
720
|
-
`:"",B=qe(F.types),
|
|
721
|
-
`:"",z=l?"context":"_context",
|
|
720
|
+
`:"",B=qe(F.types),T=B.length>0?`import type { ${B.join(", ")} } from "./dataModel.js";
|
|
721
|
+
`:"",z=l?"context":"_context",L=l?`${On}
|
|
722
722
|
|
|
723
|
-
`:"";return at(`${k}${
|
|
723
|
+
`:"";return at(`${k}${f}${g.importLine}${b.importLine}${E}${N}import { LunoraError } from "${u.server}";
|
|
724
724
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
725
|
-
${
|
|
725
|
+
${T}
|
|
726
726
|
/**
|
|
727
727
|
* Single registered function, narrowed to the shape \`handleRpc\` needs.
|
|
728
728
|
* The real argument validators / return types are checked elsewhere — at
|
|
@@ -741,13 +741,13 @@ export interface RegisteredLunoraFunction {
|
|
|
741
741
|
/** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
|
|
742
742
|
visibility?: "internal" | "public";
|
|
743
743
|
}
|
|
744
|
-
${g.prelude}${
|
|
744
|
+
${g.prelude}${b.prelude}
|
|
745
745
|
/**
|
|
746
746
|
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
747
747
|
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
748
748
|
*/
|
|
749
|
-
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${
|
|
750
|
-
${ee}${
|
|
749
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${v}};
|
|
750
|
+
${ee}${$}${w}
|
|
751
751
|
/**
|
|
752
752
|
* Connection-lifecycle manifest: the function paths the generated ShardDO
|
|
753
753
|
* dispatches when a client's WebSocket connects (\`connect\`) or disconnects
|
|
@@ -755,8 +755,8 @@ ${ee}${I}${w}
|
|
|
755
755
|
* DO runs every hook under the socket's verified identity via system dispatch.
|
|
756
756
|
*/
|
|
757
757
|
export const LUNORA_LIFECYCLE_HOOKS: { connect: readonly string[]; disconnect: readonly string[] } = {
|
|
758
|
-
connect: [${
|
|
759
|
-
disconnect: [${
|
|
758
|
+
connect: [${A.connect.map(_=>JSON.stringify(_)).join(", ")}],
|
|
759
|
+
disconnect: [${A.disconnect.map(_=>JSON.stringify(_)).join(", ")}],
|
|
760
760
|
};
|
|
761
761
|
|
|
762
762
|
/**
|
|
@@ -789,7 +789,7 @@ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
|
789
789
|
*/
|
|
790
790
|
export interface Caller {${te}}
|
|
791
791
|
|
|
792
|
-
${
|
|
792
|
+
${L}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
793
793
|
export const createCaller = (${z}: CallerCtx): Caller => ({${ne}});
|
|
794
794
|
|
|
795
795
|
/**
|
|
@@ -809,8 +809,8 @@ export interface RegisteredDataMigration {
|
|
|
809
809
|
* Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
|
|
810
810
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
811
811
|
*/
|
|
812
|
-
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${
|
|
813
|
-
`,s)},
|
|
812
|
+
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${R}};
|
|
813
|
+
`,s)},Dn=e=>{const t={};for(const n of e.tables){const r={};for(const[a,o]of Object.entries(n.shape)){const s=o.kind==="optional"&&o.inner?o.inner:o;s.kind==="id"&&s.tableName!==void 0&&(r[a]=s.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},_n=e=>{const t={};for(const n of e.tables){const r=[];for(const[a,o]of Object.entries(n.shape))(o.kind==="optional"&&o.inner?o.inner:o).kind==="storage"&&r.push(a);r.length>0&&(t[n.name]=r)}return t},In=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},Pn=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},En=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"}];for(const[a,o]of Object.entries(n.shape)){const s=o.kind==="optional"||!!o.column?.hasDefault,i=o.kind==="optional"&&o.inner?o.inner:o,l={name:a,optional:s,type:i.kind};i.kind==="id"&&i.tableName!==void 0&&(l.ref=i.tableName),i.kind==="storage"&&(l.isStorage=!0),r.push(l)}t[n.name]=r}return t},Fn=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
814
814
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
815
815
|
this.ensureMigrated();
|
|
816
816
|
|
|
@@ -818,7 +818,7 @@ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${$}}
|
|
|
818
818
|
|
|
819
819
|
return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
|
|
820
820
|
}
|
|
821
|
-
`}:{importFragment:"",override:""},
|
|
821
|
+
`}:{importFragment:"",override:""},Mn=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:`
|
|
822
822
|
const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
|
|
823
823
|
// Correlate AI-Gateway-routed calls with the Lunora trace: thread the
|
|
824
824
|
// function path + trace id into createAi, which folds them into the
|
|
@@ -849,7 +849,7 @@ const aiStub: LunoraAi = {
|
|
|
849
849
|
${t}
|
|
850
850
|
}) as unknown as LunoraAi["workersai"],
|
|
851
851
|
};
|
|
852
|
-
`}},
|
|
852
|
+
`}},I={build:"",configField:"",contextField:"",importLines:[],stub:""},qn=e=>{if(!e)return I;const t='throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");';return{build:`
|
|
853
853
|
const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
|
|
854
854
|
const kv: Kv = kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub;
|
|
855
855
|
`,configField:`
|
|
@@ -875,7 +875,7 @@ const kvStub: Kv = {
|
|
|
875
875
|
${t}
|
|
876
876
|
},
|
|
877
877
|
};
|
|
878
|
-
`}},
|
|
878
|
+
`}},Bn=(e,t)=>e?{build:`
|
|
879
879
|
const flags: import("${t}").LunoraFlags = createFlags({
|
|
880
880
|
hooks: flagsConfig.hooks,
|
|
881
881
|
logger: flagsConfig.logger,
|
|
@@ -884,17 +884,17 @@ const kvStub: Kv = {
|
|
|
884
884
|
});
|
|
885
885
|
`,configField:`
|
|
886
886
|
flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
|
|
887
|
-
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:
|
|
887
|
+
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:I,jn=e=>e?{build:`
|
|
888
888
|
const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
|
|
889
889
|
`,configField:"",contextField:`
|
|
890
890
|
notify,
|
|
891
|
-
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:
|
|
891
|
+
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:I,Wn=e=>e?{build:`
|
|
892
892
|
const envConfig = lunoraEnvContract.${e.exportName}(env);
|
|
893
893
|
`,configField:"",contextField:`
|
|
894
|
-
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:
|
|
894
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:I,Un=e=>e?{build:`
|
|
895
895
|
const access = accessFacade(identity, userId);
|
|
896
896
|
`,configField:"",contextField:`
|
|
897
|
-
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:
|
|
897
|
+
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:I,Kn=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=i=>`
|
|
898
898
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
899
899
|
const flags: import("${n}").LunoraFlags = createFlags({
|
|
900
900
|
hooks: flagsConfig.hooks,
|
|
@@ -958,7 +958,7 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
958
958
|
|
|
959
959
|
return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
|
|
960
960
|
}
|
|
961
|
-
`;return{constant:a,evaluateOverride:o,subscriptionOverride:s}},
|
|
961
|
+
`;return{constant:a,evaluateOverride:o,subscriptionOverride:s}},Qn=e=>{if(!e)return I;const t='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().");';return{build:`
|
|
962
962
|
const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
|
|
963
963
|
const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
|
|
964
964
|
`,configField:`
|
|
@@ -972,7 +972,7 @@ const analyticsStub: AnalyticsClient = {
|
|
|
972
972
|
${t}
|
|
973
973
|
},
|
|
974
974
|
};
|
|
975
|
-
`}},
|
|
975
|
+
`}},Vn=e=>{if(!e)return I;const t='throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");';return{build:`
|
|
976
976
|
const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
|
|
977
977
|
const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
|
|
978
978
|
`,configField:`
|
|
@@ -986,7 +986,7 @@ const imagesStub: Images = {
|
|
|
986
986
|
${t}
|
|
987
987
|
},
|
|
988
988
|
};
|
|
989
|
-
`}},
|
|
989
|
+
`}},Jn=e=>e?{build:`
|
|
990
990
|
const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
|
|
991
991
|
`,configField:`
|
|
992
992
|
sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
|
|
@@ -996,12 +996,15 @@ const sqlStub: SqlClient = {
|
|
|
996
996
|
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))\\\`.");
|
|
997
997
|
},
|
|
998
998
|
};
|
|
999
|
-
`}:
|
|
999
|
+
`}:I,Gn=e=>{if(!e)return I;const t="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.\");";return{build:`
|
|
1000
1000
|
const browser: Browser = config.browser ? config.browser(env) : browserStub;
|
|
1001
1001
|
`,configField:`
|
|
1002
1002
|
browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
|
|
1003
1003
|
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:`
|
|
1004
1004
|
const browserStub: Browser = {
|
|
1005
|
+
connect: async () => {
|
|
1006
|
+
${t}
|
|
1007
|
+
},
|
|
1005
1008
|
content: async () => {
|
|
1006
1009
|
${t}
|
|
1007
1010
|
},
|
|
@@ -1017,8 +1020,11 @@ const browserStub: Browser = {
|
|
|
1017
1020
|
screenshot: async () => {
|
|
1018
1021
|
${t}
|
|
1019
1022
|
},
|
|
1023
|
+
sessions: async () => {
|
|
1024
|
+
${t}
|
|
1025
|
+
},
|
|
1020
1026
|
};
|
|
1021
|
-
`}},
|
|
1027
|
+
`}},Hn=e=>{if(!e)return I;const t='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().");';return{build:`
|
|
1022
1028
|
const r2sqlEnv = env as Record<string, unknown>;
|
|
1023
1029
|
const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
|
|
1024
1030
|
const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
|
|
@@ -1050,7 +1056,7 @@ const r2sqlStub: R2SqlClient = {
|
|
|
1050
1056
|
${t}
|
|
1051
1057
|
},
|
|
1052
1058
|
};
|
|
1053
|
-
`}},
|
|
1059
|
+
`}},zn=e=>e?{build:`
|
|
1054
1060
|
const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
|
|
1055
1061
|
const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
|
|
1056
1062
|
`,configField:`
|
|
@@ -1060,7 +1066,7 @@ const pipelinesStub: PipelineClient = {
|
|
|
1060
1066
|
throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\\`pipelines\\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\\`pipelines\\\` to createShardDO().");
|
|
1061
1067
|
},
|
|
1062
1068
|
};
|
|
1063
|
-
`}:
|
|
1069
|
+
`}:I,vr=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(o=>(m(o.exportName,`container export "${o.exportName}"`),m(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
|
|
1064
1070
|
export class ${o.className} extends LunoraContainer {
|
|
1065
1071
|
public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
|
|
1066
1072
|
super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
|
|
@@ -1085,7 +1091,7 @@ import { ${a} } from "../containers.js";
|
|
|
1085
1091
|
|
|
1086
1092
|
export { ContainerProxy } from "@lunora/container/do";
|
|
1087
1093
|
|
|
1088
|
-
${r}`},
|
|
1094
|
+
${r}`},Xn=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)m(r.exportName,`container export "${r.exportName}"`),m(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(`
|
|
1089
1095
|
`);return{build:`
|
|
1090
1096
|
const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
|
|
1091
1097
|
`,contextField:`
|
|
@@ -1094,7 +1100,7 @@ ${r}`},Hn=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1094
1100
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1095
1101
|
${n}
|
|
1096
1102
|
];
|
|
1097
|
-
`}}
|
|
1103
|
+
`}},$r=e=>{if(e.length===0)return"";const t=e.map(r=>(m(r.exportName,`workflow export "${r.exportName}"`),m(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
|
|
1098
1104
|
export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
|
|
1099
1105
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1100
1106
|
super(ctx, env, ${r.exportName}, "${r.exportName}");
|
|
@@ -1122,7 +1128,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
1122
1128
|
/** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
|
|
1123
1129
|
type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
|
|
1124
1130
|
|
|
1125
|
-
${t}`},
|
|
1131
|
+
${t}`},Sr=e=>{if(e.length===0)return"";const t=e.filter(a=>a.voice).length>0,n=e.map(a=>{m(a.exportName,`agent export "${a.exportName}"`),m(a.className,`agent class "${a.className}"`);const o=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
|
|
1126
1132
|
export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
1127
1133
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1128
1134
|
super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
|
|
@@ -1150,7 +1156,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
|
|
|
1150
1156
|
|
|
1151
1157
|
import { ${r} } from "../agents.js";
|
|
1152
1158
|
|
|
1153
|
-
${n}`},
|
|
1159
|
+
${n}`},Rr=e=>{const t=e.filter(a=>a.mode==="push");if(t.length===0)return"";for(const a of t)m(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(`
|
|
1154
1160
|
`);return`${k}/**
|
|
1155
1161
|
* Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
|
|
1156
1162
|
* composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
|
|
@@ -1165,7 +1171,7 @@ import { ${n} } from "../queues.js";
|
|
|
1165
1171
|
export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
|
|
1166
1172
|
${r}
|
|
1167
1173
|
};
|
|
1168
|
-
`},
|
|
1174
|
+
`},Yn=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`workflow export "${n.exportName}"`),m(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
|
|
1169
1175
|
`);return{build:`
|
|
1170
1176
|
const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
|
|
1171
1177
|
`,contextField:`
|
|
@@ -1174,7 +1180,7 @@ ${r}
|
|
|
1174
1180
|
const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
|
|
1175
1181
|
${t}
|
|
1176
1182
|
];
|
|
1177
|
-
`}},
|
|
1183
|
+
`}},Zn=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`queue export "${n.exportName}"`),m(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
|
|
1178
1184
|
`);return{build:`
|
|
1179
1185
|
const queues = createQueueContext(env, LUNORA_QUEUES);
|
|
1180
1186
|
`,contextField:`
|
|
@@ -1183,7 +1189,7 @@ ${t}
|
|
|
1183
1189
|
const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
|
|
1184
1190
|
${t}
|
|
1185
1191
|
];
|
|
1186
|
-
`}},
|
|
1192
|
+
`}},er=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`agent export "${n.exportName}"`),m(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
|
|
1187
1193
|
`);return{build:`
|
|
1188
1194
|
const agents = createAgentContext(env, LUNORA_AGENTS);
|
|
1189
1195
|
`,contextField:`
|
|
@@ -1192,21 +1198,21 @@ ${t}
|
|
|
1192
1198
|
const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
|
|
1193
1199
|
${t}
|
|
1194
1200
|
];
|
|
1195
|
-
`}},
|
|
1201
|
+
`}},tr=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{constant:`
|
|
1196
1202
|
/** Read-only declared-workflow metadata (discovered from \`lunora/workflows.ts\`) served via \`__lunora_admin__:listWorkflows\` for the studio's workflows view. */
|
|
1197
1203
|
const LUNORA_WORKFLOWS_INFO: WorkflowsResult = ${JSON.stringify(t,void 0,4)};
|
|
1198
1204
|
`,override:`
|
|
1199
1205
|
protected override workflowsMetadata(): WorkflowsResult {
|
|
1200
1206
|
return LUNORA_WORKFLOWS_INFO;
|
|
1201
1207
|
}
|
|
1202
|
-
`}},
|
|
1208
|
+
`}},nr=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{constant:`
|
|
1203
1209
|
/** Read-only declared-queue metadata (discovered from \`lunora/queues.ts\`) served via \`__lunora_admin__:listQueues\` for the studio's queues view. */
|
|
1204
1210
|
const LUNORA_QUEUES_INFO: QueuesResult = ${JSON.stringify(t,void 0,4)};
|
|
1205
1211
|
`,override:`
|
|
1206
1212
|
protected override queuesMetadata(): QueuesResult {
|
|
1207
1213
|
return LUNORA_QUEUES_INFO;
|
|
1208
1214
|
}
|
|
1209
|
-
`}},
|
|
1215
|
+
`}},rr=e=>{if(!e)return{build:"",configField:"",contextField:"",imports:[],stub:""};const t='throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");';return{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
|
|
1210
1216
|
const payments: LunoraPayment = config.payment
|
|
1211
1217
|
? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
|
|
1212
1218
|
: paymentStub;
|
|
@@ -1242,7 +1248,7 @@ const paymentStub: LunoraPayment = {
|
|
|
1242
1248
|
${t}
|
|
1243
1249
|
},
|
|
1244
1250
|
} as unknown as LunoraPayment;
|
|
1245
|
-
`}},
|
|
1251
|
+
`}},ar=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
|
|
1246
1252
|
const x402: X402Pay = config.x402
|
|
1247
1253
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1248
1254
|
: x402Stub;
|
|
@@ -1254,10 +1260,10 @@ const x402Stub: X402Pay = {
|
|
|
1254
1260
|
throw new Error("ctx.x402: no pay rail configured. Pass \\\`x402\\\` to createShardDO().");
|
|
1255
1261
|
},
|
|
1256
1262
|
} as unknown as X402Pay;
|
|
1257
|
-
`}:{build:"",configField:"",contextField:"",imports:[],stub:""},
|
|
1263
|
+
`}:{build:"",configField:"",contextField:"",imports:[],stub:""},or=(e,t,n,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike",...r?["FlagsResult"]:[],"MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],Nr=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:s=!1,hasAi:i=!1,hasAnalytics:l=!1,hasBrowser:u=!1,hasFlags:p=!1,hasHyperdrive:f=!1,hasImages:y=!1,hasKv:R=!1,hasNotify:d=!1,hasPayments:c=!1,hasPipelines:g=!1,hasR2sql:b=!1,hasX402:x=!1,maskMetadata:v,mutators:A=[],queues:N=[],rlsMetadata:$,schema:w,schemaSnapshot:E,shapes:ee=[],storageRules:F,studioFeatures:te,useUmbrella:ne=!1,workflows:B=[]})=>{const T=H(ne),z=A.length>0,L=ee.length>0,_=E===void 0?"":zt(E),M=E===void 0?"":`
|
|
1258
1264
|
/** 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. */
|
|
1259
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1260
|
-
`,re=E===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:ae,configField:xe,contextField:ke,stub:ve}=
|
|
1265
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Xt(E))}, json: ${JSON.stringify(_)} };
|
|
1266
|
+
`,re=E===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:ae,configField:xe,contextField:ke,stub:ve}=Mn(i),oe=Un(s),K=qn(R),P=Bn(p,T.flags),Q=Kn(o,p,T.flags),X=jn(d),ie=Wn(a),V=Qn(l),j=Vn(y),W=Jn(f),U=Gn(u),q=Hn(b),Y=zn(g),{build:$e,contextField:fe,importLines:be,specs:se}=Zn(N),{build:Se,contextField:Re,importLines:ye,specs:le}=Xn(r,w.jurisdiction),{build:Ne,contextField:Oe,importLines:we,specs:Ae}=Yn(B),{build:Te,contextField:de,importLines:ce,specs:Le}=er(n),{build:Ce,configField:De,contextField:ue,imports:pe,stub:h}=rr(c),{build:_e,configField:st,imports:lt,stub:dt}=ar(x),ct=e,ut=t,pt=$??{policies:[],roles:[]},ht=v??{columns:[]},gt=F??{rules:[]},mt=te??{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:ft,override:bt}=tr(B),{constant:yt,override:wt}=nr(N),J=w.vectorIndexes.length>0,he=w.tables.some(C=>C.shardMode==="global"),Ie=w.tables.some(C=>C.shardMode==="global"&&C.globalBackend==="hyperdrive"),je=w.tables.some(C=>C.shardMode==="global"&&C.globalBackend!=="hyperdrive"),G=w.tables.some(C=>C.externalSource!==void 0);if(je&&Ie)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 Pe=w.tables.length>0,xt=Dn(w),kt=In(w),vt=En(w),$t=_n(w),We=Pn(w),Ue=or(J,B.length>0,N.length>0,p);L&&Ue.push("WhereInput");const Ke=Fn(he),St=L?`
|
|
1261
1267
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
1262
1268
|
const shape = LUNORA_SHAPES[name];
|
|
1263
1269
|
|
|
@@ -1310,15 +1316,15 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1310
1316
|
|
|
1311
1317
|
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
1312
1318
|
}
|
|
1313
|
-
`:"",
|
|
1319
|
+
`:"",Rt=z?`
|
|
1314
1320
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1315
1321
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1316
1322
|
}
|
|
1317
|
-
`:"",
|
|
1318
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
1319
|
-
d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1320
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1321
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
1323
|
+
`:"",Nt=L?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Ot=L?"assertShapeShardable, ":"",ge=[`import type { ${Ue.join(", ")} } from "${T.do}";`,`import { applyCdcChanges, ${Ot}createShardCtxDb, ${G?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}runDataMigration, runShardMigrations, ${Ke.importFragment}ShardDO as ShardDOBase } from "${T.do}";`,...G?[`import type { ExternalSourceLike, SourceClientLike } from "${T.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${T.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${T.server}";`];Pe&&ge.push(`import { bindOrm, bindTableFacade } from "${T.server}";`),J&&ge.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),i&&ge.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ge.push(...oe.importLines,...K.importLines,...P.importLines,...X.importLines,...ie.importLines,...V.importLines,...j.importLines,...W.importLines,...U.importLines,...q.importLines,...Y.importLines,...ye,...we,...be,...ce,...pe,...lt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...z?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const At=J?`
|
|
1324
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Tt=je?`
|
|
1325
|
+
d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Lt=Ie?`
|
|
1326
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ct=G?`
|
|
1327
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Dt=he?'\nconst globalDbStub: DatabaseWriterLike = {\n aggregate: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n count: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n delete: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findFirst: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findFirstOrThrow: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findMany: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n get: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n groupBy: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n insert: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n normalizeId: () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n patch: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n query: () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n rank: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n rankPage: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n replace: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n};\n':"",_t=J?`
|
|
1322
1328
|
const vectorsStub: VectorSearchLike = {
|
|
1323
1329
|
deleteByIds: async () => {
|
|
1324
1330
|
throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
|
|
@@ -1336,7 +1342,7 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1336
1342
|
throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
|
|
1337
1343
|
},
|
|
1338
1344
|
};
|
|
1339
|
-
`:"",
|
|
1345
|
+
`:"",It=J?`
|
|
1340
1346
|
let vectors: VectorSearchLike;
|
|
1341
1347
|
let onWrite: WriteHook | undefined;
|
|
1342
1348
|
|
|
@@ -1351,7 +1357,7 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1351
1357
|
}
|
|
1352
1358
|
`:"",Qe=he?`
|
|
1353
1359
|
globalDb,`:"",Ve=`
|
|
1354
|
-
auth: { identity: identity ?? null, userId: userId ?? null },`,
|
|
1360
|
+
auth: { identity: identity ?? null, userId: userId ?? null },`,Pt=J?`{${Ve}
|
|
1355
1361
|
broadcast: (delta) => {
|
|
1356
1362
|
this.recordChangedTable(delta.table);
|
|
1357
1363
|
},
|
|
@@ -1376,10 +1382,10 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1376
1382
|
schema: schema as unknown as SchemaLike,
|
|
1377
1383
|
sql: this.sql as SqlExec,
|
|
1378
1384
|
storage,${Qe}
|
|
1379
|
-
}`,
|
|
1380
|
-
vectors,`:"",
|
|
1381
|
-
orm: bindOrm(facade),`:"",
|
|
1382
|
-
`:"",
|
|
1385
|
+
}`,Et=J?`
|
|
1386
|
+
vectors,`:"",Ft=Pe?`
|
|
1387
|
+
orm: bindOrm(facade),`:"",Mt="",Je=Ie?"config.hyperdriveGlobal":"config.d1",qt=he?` const globalDb: DatabaseWriterLike = ${Je}?.(env, { identity, userId }) ?? globalDbStub;
|
|
1388
|
+
`:"",Bt=L&&he?`
|
|
1383
1389
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1384
1390
|
const env = this.env as Record<string, unknown>;
|
|
1385
1391
|
const globalDb: DatabaseWriterLike = ${Je}?.(env, identity) ?? globalDbStub;
|
|
@@ -1409,10 +1415,10 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1409
1415
|
|
|
1410
1416
|
return rows;
|
|
1411
1417
|
}
|
|
1412
|
-
`:"",
|
|
1418
|
+
`:"",jt=G?`
|
|
1413
1419
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1414
1420
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1415
|
-
`:"",
|
|
1421
|
+
`:"",Wt=G?`
|
|
1416
1422
|
protected override async pollExternalSources(): Promise<number | undefined> {
|
|
1417
1423
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1418
1424
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1513,7 +1519,7 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1513
1519
|
|
|
1514
1520
|
return nextDueAt;
|
|
1515
1521
|
}
|
|
1516
|
-
`:"",Ge=We.length>0,
|
|
1522
|
+
`:"",Ge=We.length>0,Ut=G||Ge?`
|
|
1517
1523
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1518
1524
|
super(state, env);
|
|
1519
1525
|
${G?`
|
|
@@ -1531,21 +1537,21 @@ ${G?`
|
|
|
1531
1537
|
void this.scheduleTtlSweep();
|
|
1532
1538
|
}
|
|
1533
1539
|
`:""} }
|
|
1534
|
-
`:"",
|
|
1540
|
+
`:"",Kt=Pe?`
|
|
1535
1541
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1536
|
-
${w.tables.map(
|
|
1542
|
+
${w.tables.map(C=>` facade[${JSON.stringify(C.name)}] = bindTableFacade(db, ${JSON.stringify(C.name)});`).join(`
|
|
1537
1543
|
`)}
|
|
1538
|
-
`:"",
|
|
1544
|
+
`:"",Qt=`${oe.build}${K.build}${P.build}${V.build}${ie.build}
|
|
1539
1545
|
const secrets = createSecrets(env);
|
|
1540
|
-
`,
|
|
1541
|
-
secrets,`,
|
|
1546
|
+
`,Vt=`${oe.contextField}${K.contextField}${P.contextField}${X.contextField}${V.contextField}${ie.contextField}
|
|
1547
|
+
secrets,`,Jt=X.build,He=y||f||u||b||g||x,Gt=He?`
|
|
1542
1548
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1543
1549
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
1544
1550
|
if (isAction) {
|
|
1545
|
-
${j.build}${W.build}${U.build}${q.build}${Y.build}${_e}${[...y?[" ctx.images = images;"]:[],...
|
|
1551
|
+
${j.build}${W.build}${U.build}${q.build}${Y.build}${_e}${[...y?[" ctx.images = images;"]:[],...f?[" ctx.sql = sql;"]:[],...u?[" ctx.browser = browser;"]:[],...b?[" ctx.r2sql = r2sql;"]:[],...g?[" ctx.pipelines = pipelines;"]:[],...x?[" ctx.x402 = x402;"]:[]].join(`
|
|
1546
1552
|
`)}
|
|
1547
1553
|
}
|
|
1548
|
-
`:"",
|
|
1554
|
+
`:"",Ht=He?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
|
|
1549
1555
|
`:"";return`${k}${ge.join(`
|
|
1550
1556
|
`)}
|
|
1551
1557
|
|
|
@@ -1556,45 +1562,45 @@ interface FunctionReference {
|
|
|
1556
1562
|
}
|
|
1557
1563
|
|
|
1558
1564
|
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1559
|
-
const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(
|
|
1565
|
+
const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(xt,void 0,4)};
|
|
1560
1566
|
|
|
1561
1567
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1562
|
-
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(
|
|
1568
|
+
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(kt,void 0,4)};
|
|
1563
1569
|
|
|
1564
1570
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1565
|
-
const LUNORA_TABLE_COLUMNS: Record<string, Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }>> = ${JSON.stringify(
|
|
1571
|
+
const LUNORA_TABLE_COLUMNS: Record<string, Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }>> = ${JSON.stringify(vt,void 0,4)};
|
|
1566
1572
|
|
|
1567
1573
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1568
|
-
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(
|
|
1574
|
+
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify($t,void 0,4)};
|
|
1569
1575
|
|
|
1570
1576
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1571
1577
|
const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(We,void 0,4)};
|
|
1572
1578
|
|
|
1573
1579
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1574
|
-
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(
|
|
1580
|
+
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(ct,void 0,4)};
|
|
1575
1581
|
|
|
1576
1582
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1577
|
-
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(
|
|
1583
|
+
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(ut,void 0,4)};
|
|
1578
1584
|
|
|
1579
1585
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1580
|
-
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(
|
|
1586
|
+
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(pt,void 0,4)};
|
|
1581
1587
|
|
|
1582
1588
|
/** 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. */
|
|
1583
|
-
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(
|
|
1589
|
+
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(ht,void 0,4)};
|
|
1584
1590
|
|
|
1585
1591
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1586
|
-
const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(
|
|
1592
|
+
const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(gt,void 0,4)};
|
|
1587
1593
|
|
|
1588
1594
|
/** 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. */
|
|
1589
|
-
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(
|
|
1590
|
-
${M}${Q.constant}${
|
|
1595
|
+
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(mt,void 0,4)};
|
|
1596
|
+
${M}${Q.constant}${Nt}${ft}${yt}${le}${Ae}${se}${Le}
|
|
1591
1597
|
export interface ShardDOConfig {
|
|
1592
1598
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1593
1599
|
cdc?: boolean;
|
|
1594
1600
|
/** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
|
|
1595
1601
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1596
1602
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1597
|
-
storage?: (env: Record<string, unknown>) => unknown;${
|
|
1603
|
+
storage?: (env: Record<string, unknown>) => unknown;${At}${xe}${K.configField}${P.configField}${V.configField}${j.configField}${W.configField}${U.configField}${q.configField}${Y.configField}${De}${st}${Tt}${Lt}${Ct}
|
|
1598
1604
|
}
|
|
1599
1605
|
|
|
1600
1606
|
const schedulerStub = {
|
|
@@ -1632,7 +1638,7 @@ const storageStub = {
|
|
|
1632
1638
|
throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
|
|
1633
1639
|
},
|
|
1634
1640
|
};
|
|
1635
|
-
${
|
|
1641
|
+
${Dt}${jt}${_t}${ve}${K.stub}${P.stub}${V.stub}${j.stub}${W.stub}${U.stub}${q.stub}${Y.stub}${h}${dt}${Mt}
|
|
1636
1642
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1637
1643
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1638
1644
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -1669,7 +1675,7 @@ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: R
|
|
|
1669
1675
|
* from the worker entry so wrangler binds it by name.
|
|
1670
1676
|
*/
|
|
1671
1677
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1672
|
-
class extends ShardDOBase {${
|
|
1678
|
+
class extends ShardDOBase {${Ut}
|
|
1673
1679
|
private migrated = false;
|
|
1674
1680
|
|
|
1675
1681
|
public override async handleRpc(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
@@ -1745,7 +1751,7 @@ ${Ke.override}
|
|
|
1745
1751
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
|
|
1746
1752
|
};
|
|
1747
1753
|
}
|
|
1748
|
-
${
|
|
1754
|
+
${Rt}${St}${Bt}${Wt}
|
|
1749
1755
|
protected override lifecycleHookPaths(event: "connect" | "disconnect"): readonly string[] {
|
|
1750
1756
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1751
1757
|
}
|
|
@@ -1785,7 +1791,7 @@ ${St}${$t}${qt}${jt}
|
|
|
1785
1791
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1786
1792
|
return LUNORA_STUDIO_FEATURES;
|
|
1787
1793
|
}
|
|
1788
|
-
${Q.evaluateOverride}${Q.subscriptionOverride}${
|
|
1794
|
+
${Q.evaluateOverride}${Q.subscriptionOverride}${bt}${wt}
|
|
1789
1795
|
protected override advisories(): AdvisoryFinding[] {
|
|
1790
1796
|
return LUNORA_ADVISORIES;
|
|
1791
1797
|
}
|
|
@@ -2011,7 +2017,7 @@ ${Q.evaluateOverride}${Q.subscriptionOverride}${ft}${yt}
|
|
|
2011
2017
|
// dispatch path) fall back to the per-request fields as before.
|
|
2012
2018
|
const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
|
|
2013
2019
|
const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
|
|
2014
|
-
${
|
|
2020
|
+
${It}${ae}${Qt}${Se}${Ne}${$e}${Te}
|
|
2015
2021
|
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
2016
2022
|
// Build the storage adapter once and share it between \`ctx.storage\`
|
|
2017
2023
|
// and \`ctx.db.system._storage\` so both read the same R2 binding. The
|
|
@@ -2038,13 +2044,13 @@ ${_t}${ae}${Kt}${Se}${Ne}${$e}${Te}
|
|
|
2038
2044
|
// so both write to the same trace.
|
|
2039
2045
|
const span = this.makeDispatchSpan(traceAnchor, observability);
|
|
2040
2046
|
|
|
2041
|
-
${
|
|
2047
|
+
${qt} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
|
|
2042
2048
|
// adds aggregate counters (call count, total time, per-operation
|
|
2043
2049
|
// breakdown) to the wide event rather than a span per call, so a
|
|
2044
2050
|
// handler making hundreds of queries stays readable. See
|
|
2045
2051
|
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
2046
|
-
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${
|
|
2047
|
-
${
|
|
2052
|
+
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${Pt}), logFunctionPath, traceAnchor, observability);
|
|
2053
|
+
${Kt}${Ce}
|
|
2048
2054
|
|
|
2049
2055
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
2050
2056
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -2052,7 +2058,7 @@ ${Ut}${Ce}
|
|
|
2052
2058
|
// writing mutation's trace from the shared per-request field.
|
|
2053
2059
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
|
|
2054
2060
|
const metrics = this.makeMetrics(logFunctionPath, observability);
|
|
2055
|
-
${
|
|
2061
|
+
${Jt}
|
|
2056
2062
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
2057
2063
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
2058
2064
|
// Query/mutation handlers must be deterministic (they may be re-run on
|
|
@@ -2075,13 +2081,13 @@ ${Vt}
|
|
|
2075
2081
|
ip: this.getCurrentIp(),
|
|
2076
2082
|
log,
|
|
2077
2083
|
metrics,
|
|
2078
|
-
now,${
|
|
2084
|
+
now,${Ft}
|
|
2079
2085
|
scheduler,
|
|
2080
2086
|
span,
|
|
2081
2087
|
storage,
|
|
2082
|
-
trace,${
|
|
2088
|
+
trace,${Et}${ke}${Vt}${ue}${Re}${Oe}${fe}${de}
|
|
2083
2089
|
};
|
|
2084
|
-
${
|
|
2090
|
+
${Ht}${Gt}
|
|
2085
2091
|
ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
|
|
2086
2092
|
ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
|
|
2087
2093
|
ctx.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("query", reference.__lunoraRef, fnArgs, ctx);
|
|
@@ -2089,22 +2095,24 @@ ${Gt}${Jt}
|
|
|
2089
2095
|
return ctx;
|
|
2090
2096
|
}
|
|
2091
2097
|
};
|
|
2092
|
-
`},Be=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:
|
|
2098
|
+
`},Be=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:O(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"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?Be(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=e.kind==="optional"&&e.inner?e.inner:e;return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},ir=(e,t,n)=>{m(e,"drizzle column name");const r=Be(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const s=it(t,n);return s!==void 0&&(o+=`.references((): AnySQLiteColumn => ${s}._id)`),r.notNull&&(o+=".notNull()"),o},sr=e=>{m(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(m(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},lr=(e,t)=>{m(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([a,o])=>` ${a}: ${ir(a,o,t)},`)].join(`
|
|
2093
2099
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2094
|
-
${e.indexes.map(a=>
|
|
2100
|
+
${e.indexes.map(a=>sr(a)).join(`
|
|
2095
2101
|
`)}
|
|
2096
2102
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2097
2103
|
${n}
|
|
2098
|
-
}${r});`},
|
|
2099
|
-
`;const n=H(t),{columns:
|
|
2100
|
-
|
|
2101
|
-
`);return`${k}import { ${o.join(", ")} } from "${n.serverDrizzle}";
|
|
2104
|
+
}${r});`},dr=e=>e.typeAnnotation?.includes('Id<"')??!1,cr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let a=!1,o=!1;for(const s of e){for(const i of Object.values(s.shape)){const l=Be(i);n.add(l.builder),o=o||dr(l),a=a||it(i,t)!==void 0}for(const i of s.indexes)r.add(i.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((s,i)=>s.localeCompare(i)),indexes:[...r].toSorted((s,i)=>s.localeCompare(i)),needsAnyColumn:a,needsId:o}},Xe=(e,t=!1)=>{if(e.length===0)return`${k}export {};
|
|
2105
|
+
`;const n=H(t),r=new Set(e.map(f=>f.name)),{columns:a,indexes:o,needsAnyColumn:s,needsId:i}=cr(e,r),l=[...o,...a].toSorted((f,y)=>f.localeCompare(y)),u=e.map(f=>lr(f,r)).join(`
|
|
2102
2106
|
|
|
2103
|
-
${
|
|
2104
|
-
|
|
2107
|
+
`),p=[s?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2108
|
+
`:"",i?`import type { Id } from "./dataModel.js";
|
|
2109
|
+
`:""].join("");return`${k}import { ${l.join(", ")} } from "${n.serverDrizzle}";
|
|
2110
|
+
${p}
|
|
2111
|
+
${u}
|
|
2112
|
+
`},Or=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:Xe(n,t),shard:Xe(r,t)}},Ar=e=>{const t=[],n=new Map;for(const i of e){const l=n.get(i.cron);l?l.push(i):(n.set(i.cron,[i]),t.push(i.cron))}const r=t.map(i=>` ${JSON.stringify(i)},`).join(`
|
|
2105
2113
|
`),a=r.length>0?`
|
|
2106
2114
|
${r}
|
|
2107
|
-
`:"",o=[...n.entries()].map(([i,l])=>{const u=l.map(p=>{const
|
|
2115
|
+
`:"",o=[...n.entries()].map(([i,l])=>{const u=l.map(p=>{const f=p.workflow?`workflow: ${JSON.stringify(p.workflow.binding)}`:`functionPath: ${JSON.stringify(p.functionPath)}`;return` { name: ${JSON.stringify(p.name)}, ${f}, args: ${JSON.stringify(p.args)} },`}).join(`
|
|
2108
2116
|
`);return` ${JSON.stringify(i)}: [
|
|
2109
2117
|
${u}
|
|
2110
2118
|
],`}).join(`
|
|
@@ -2135,7 +2143,7 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${a}];
|
|
|
2135
2143
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2136
2144
|
*/
|
|
2137
2145
|
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
|
|
2138
|
-
`},
|
|
2146
|
+
`},Tr=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(`
|
|
2139
2147
|
`),n=t.length>0?`
|
|
2140
2148
|
${t}
|
|
2141
2149
|
`:"";return`${k}/**
|
|
@@ -2159,4 +2167,4 @@ export interface LunoraVectorIndex {
|
|
|
2159
2167
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2160
2168
|
*/
|
|
2161
2169
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2162
|
-
`},
|
|
2170
|
+
`},Lr=e=>{const t=new Set,n=[];for(const r of e)t.has(r.cron)||(t.add(r.cron),n.push(r.cron));return n};export{$r as G,Sr as J,vr as K,kr as N,xr as S,Nr as a,br as b,_n as c,mr as d,Tr as g,Lr as m,fr as n,Ar as p,Yt as r,Or as u,k as w,wr as x,yr as y,Rr as z};
|