@lunora/codegen 1.0.0-alpha.34 → 1.0.0-alpha.340
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.d.mts +4336 -2185
- package/dist/index.d.ts +4336 -2185
- package/dist/index.mjs +1 -35
- package/dist/packem_shared/AGENTS_FILENAME-isdHqPIt.mjs +1 -0
- package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-mK4cZpcz.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-BQk3SX8D.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-BXK9A_wP.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-CIAJQeKB.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-Cy9h3EVW.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-9to_l_Kh.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-l4HD4osw.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-Civ-7SiI.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Ba_rzi5K.mjs +31 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs +2 -0
- package/dist/packem_shared/SHAPES_FILENAME-DVJbfDZ8.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-H9eQX4ui.mjs +18 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-kXq07aGl.mjs +1 -0
- package/dist/packem_shared/attribution-CG8-kUcl.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-DWdj2jvW.mjs +3 -0
- package/dist/packem_shared/capabilitiesUsedBy-C-7D7vlH.mjs +1 -0
- package/dist/packem_shared/chain-74gjwZMP.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-BkaeM9Ej.mjs +1 -0
- package/dist/packem_shared/context-property-calls-dFjpeIlP.mjs +1 -0
- package/dist/packem_shared/context-root-CNR6TAsP.mjs +1 -0
- package/dist/packem_shared/createCodegenProject-R4so-yTU.mjs +1 -0
- package/dist/packem_shared/database-calls-UPlhi3Ks.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-CScPrUD-.mjs +1 -0
- package/dist/packem_shared/discoverCrons-B1_NUt19.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-DkPOc8b9.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-DCDgDIYv.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-CL-d0IVo.mjs +1 -0
- package/dist/packem_shared/discoverInserts-BcoTjXqI.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-Bw-BOIbA.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-BWxx8Wv9.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-3INW8oqs.mjs +1 -0
- package/dist/packem_shared/discoverQueries-CxQRVuIV.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-B4oeTYEM.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-D0B4nCmG.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-Cl6UKT7L.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage--Z1vx7GM.mjs +1 -0
- package/dist/packem_shared/discoverSchema-Cwt-DQgh.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-CitX6ziW.mjs +1 -0
- package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
- package/dist/packem_shared/emitAgents--VDKoet4.mjs +1 -0
- package/dist/packem_shared/emitApi-c14__tie.mjs +147 -0
- package/dist/packem_shared/emitApp-BL16wvE9.mjs +986 -0
- package/dist/packem_shared/emitCrons-lc-hnJYn.mjs +96 -0
- package/dist/packem_shared/emitDataModel-CuFqq97x.mjs +114 -0
- package/dist/packem_shared/emitDrizzleSchema-bct1OuH5.mjs +15 -0
- package/dist/packem_shared/emitFunctions-CkBPtGDF.mjs +506 -0
- package/dist/packem_shared/emitServer-CGUhLmlG.mjs +1 -0
- package/dist/packem_shared/emitShard-hzuG9fUo.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains-D1WlRfqJ.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-BKXkgkj4.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
- package/dist/packem_shared/handler-reference-CClSR4bi.mjs +1 -0
- package/dist/packem_shared/index-CN8FVvr-.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTestPath-C3QumE88.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-B7RmxIeD.mjs +1 -0
- package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
- package/dist/packem_shared/modules-l-Db0C4S.mjs +1 -0
- package/dist/packem_shared/parse-validator-iVTounLK.mjs +1 -0
- package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
- package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
- package/dist/packem_shared/qualifiers-Bl5fSmav.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
- package/dist/packem_shared/readServiceBindings-BA49C6aN.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
- package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/dist/packem_shared/server-B6VhYK7m.mjs +368 -0
- package/dist/packem_shared/shard-CBG10DT5.mjs +1776 -0
- package/dist/packem_shared/shard-runtime-ByYXjCKY.mjs +333 -0
- package/dist/packem_shared/shared-8vTRkL2-.mjs +13 -0
- package/dist/packem_shared/unwrap-handler-return-CGdJGvGh.mjs +1 -0
- package/dist/sdk/index.d.mts +288 -0
- package/dist/sdk/index.d.ts +288 -0
- package/dist/sdk/index.mjs +372 -0
- package/package.json +21 -8
- package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
- package/dist/packem_shared/FLAGS_FILENAME-BjpS5w08.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-CLwPlCQe.mjs +0 -3
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-4YIeMkOI.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-BF0iUmx7.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DnD-_HwA.mjs +0 -3425
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
- package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-CCC_42o3.mjs +0 -124
- package/dist/packem_shared/buildOpenApiDocument-bp1pYSV6.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-URDoTADN.mjs +0 -62
- package/dist/packem_shared/discoverCrons-DdZOeroL.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BJdF7lRs.mjs +0 -514
- package/dist/packem_shared/discoverHttpRoutes-CcwP-Rkr.mjs +0 -131
- package/dist/packem_shared/discoverInserts-BpFhM32L.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-DT-v8wvj.mjs +0 -273
- package/dist/packem_shared/discoverMigrations-cG1idBVM.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-CEOjmfk4.mjs +0 -122
- package/dist/packem_shared/discoverQueries-DeVBQVAG.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-CWCAU-xJ.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BL0oukaK.mjs +0 -280
- package/dist/packem_shared/discoverSchema-CeXJWVKV.mjs +0 -874
- package/dist/packem_shared/discoverStorageRulesMetadata-CFHByjIl.mjs +0 -97
- package/dist/packem_shared/emit-CBwEvCXQ.mjs +0 -3451
- package/dist/packem_shared/emitApp-nQ2oC-8G.mjs +0 -668
- package/dist/packem_shared/formatAdvisories-DLIqHq5l.mjs +0 -114
- package/dist/packem_shared/parse-validator-D6zI2i85.mjs +0 -134
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{L as de,s as j,G as D,d as U,I as T,b as M,r as he,c as me}from"./shared-8vTRkL2-.mjs";import{v as pe}from"./parse-validator-iVTounLK.mjs";import{renderAgentFunctionRegistry as ge,renderSandboxFunctionRegistry as fe}from"./emitApi-c14__tie.mjs";import{b as ye,a as $e,r as I,c as we}from"./qualifiers-Bl5fSmav.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const ke=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),J=r=>r.column!==void 0,Re=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
|
|
2
|
+
`;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
|
|
3
|
+
`;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
|
|
4
|
+
`;case"null":return`if (${t} !== null) return DEFER;
|
|
5
|
+
`;default:return`if (typeof ${t} !== "string") return DEFER;
|
|
6
|
+
`}},be=(r,t)=>r.stringMaxLength===void 0?"":`if (${t}.length > ${String(r.stringMaxLength)}) return DEFER;
|
|
7
|
+
`,ve=(r,t)=>{const n=r.literalValue?.trim();if(!(n===void 0||!de.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
|
|
8
|
+
`}},F=(r,t,n)=>{if(!J(r)&&!(r.unmodelledRefinement||r.sourceText!==void 0)){if(ke.has(r.kind))return r.kind==="any"?{out:t,pre:""}:{out:t,pre:Re(r.kind,t)+be(r,t)};switch(r.kind){case"array":return Ne(r,t,n);case"literal":return ve(r,t);case"object":return Pe(r,t,n);default:return}}},Ne=(r,t,n)=>{const{inner:o}=r;if(!o)return;const a=n.next(),i=`__arr${String(a)}`,s=`__i${String(a)}`,c=`__e${String(a)}`,d=F(o,c,n);if(!d)return;const l=`if (!Array.isArray(${t})) return DEFER;
|
|
9
|
+
const ${i} = new Array(${t}.length);
|
|
10
|
+
for (let ${s} = 0; ${s} < ${t}.length; ${s}++) {
|
|
11
|
+
const ${c} = ${t}[${s}];
|
|
12
|
+
${d.pre}${i}[${s}] = ${d.out};
|
|
13
|
+
}
|
|
14
|
+
`;return{out:i,pre:l}},Oe=(r,t,n,o)=>{const a=JSON.stringify(r);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||J(t))return;const{inner:s}=t;if(!s)return;const c=F(s,n,o);if(!c)return;const d=o.next(),l=`__has${String(d)}`,u=`__val${String(d)}`,f=`let ${l} = false;
|
|
15
|
+
let ${u};
|
|
16
|
+
if (${n} !== undefined) {
|
|
17
|
+
${c.pre}${u} = ${c.out};
|
|
18
|
+
${l} = true;
|
|
19
|
+
}
|
|
20
|
+
`;return{entry:`...(${l} ? { ${a}: ${u} } : {})`,pre:f}}const i=F(t,n,o);if(i)return{entry:`${a}: ${i.out}`,pre:i.pre}},Se=new Set(Object.getOwnPropertyNames(Object.prototype)),B=(r,t,n)=>{let o="";const a=[];for(const i of Object.keys(r)){const s=r[i];if(!s)return;const c=JSON.stringify(i);let d=`${t}[${c}]`;if(Se.has(i)){const u=`__f${String(n.next())}`;o+=`const ${u} = Object.hasOwn(${t}, ${c}) ? ${t}[${c}] : undefined;
|
|
21
|
+
`,d=u}const l=Oe(i,s,d,n);if(!l)return;o+=l.pre,a.push(l.entry)}return{entries:a.join(", "),pre:o}},q=r=>{const t=`Object.getPrototypeOf(${r})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
|
|
22
|
+
`},Pe=(r,t,n)=>{const o=r.shape??{},a=B(o,t,n);if(!a)return;const i=n.next(),s=`__obj${String(i)}`,c=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
|
|
23
|
+
${q(t)}${a.pre}const ${s} = { ${a.entries} };
|
|
24
|
+
`;return{out:s,pre:c}},H=r=>{let t=0;const o=B(r,"source",{next:()=>(t+=1,t)});if(o)return`(source) => {
|
|
25
|
+
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
26
|
+
${q("source")}${o.pre}return { ${o.entries} };
|
|
27
|
+
}`},xe=(r,t)=>`lunora_${g(r)}_${String(t)}`,C=r=>JSON.stringify(Object.entries(r).toSorted(([t],[n])=>t.localeCompare(n)).map(([t,n])=>{const o=n.kind==="optional",a=o?n.inner??{kind:"unknown"}:n,i=a.kind==="array"?a.inner?.kind:void 0,s=a.kind==="id"?a.tableName:void 0;return{kind:a.kind,name:t,optional:o,...pe(n)?{sensitive:!0}:{},...s===void 0?{}:{table:s},...i===void 0||i==="unknown"?{}:{element:i}}})),z=(r,t,n,o)=>{const a=new Map,i=s=>{a.has(s)||a.set(s,xe(s,a.size))};for(const s of r)i(s.filePath);for(const s of t)i(s.filePath);for(const s of n)i(s.filePath);for(const s of o)i(s.filePath);return a},W=(r,t,n)=>new Set([...r.map(o=>o.filePath),...t.map(o=>o.filePath),...n.map(o=>o.filePath)]),N=r=>`${r}[functionPath]`,Ae=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
28
|
+
const registered = await loadFunction(functionPath);
|
|
29
|
+
|
|
30
|
+
if (!registered) {
|
|
31
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// A mutation is routed through the caller's own \`ctx.runMutation\` rather than
|
|
35
|
+
// invoked directly, so \`createCaller(ctx).ns.someMutation()\` gets exactly what
|
|
36
|
+
// \`ctx.runMutation(api.ns.someMutation)\` gets: the BEGIN/COMMIT span (or the
|
|
37
|
+
// enclosing one, when the caller is already inside a transaction), the jobs it
|
|
38
|
+
// schedules held until that span commits, and the deferred object deletes
|
|
39
|
+
// flushed only once it has. Called straight, a mutation composed from an action
|
|
40
|
+
// or a stream had none of the three — its writes autocommitted one row at a
|
|
41
|
+
// time and its \`ctx.scheduler\` calls dispatched immediately, so a mid-handler
|
|
42
|
+
// throw left the earlier writes durable and the job already enqueued.
|
|
43
|
+
//
|
|
44
|
+
// The fallback covers a context that is not a shard dispatch (\`runMutation\` is
|
|
45
|
+
// installed by \`buildCtx\` on every kind but a query's TYPE omits it); there is
|
|
46
|
+
// no transaction to join in that case, so a direct call is all there is.
|
|
47
|
+
//
|
|
48
|
+
// A query is routed through \`ctx.runQuery\` for the same reason: that is what
|
|
49
|
+
// hands it a query view of a mutation's or action's ctx (no request origin,
|
|
50
|
+
// query-guarded \`run*\`) instead of the caller's own.
|
|
51
|
+
if (registered.kind === "mutation" || registered.kind === "query") {
|
|
52
|
+
const run = (context as { runMutation?: unknown; runQuery?: unknown })[registered.kind === "mutation" ? "runMutation" : "runQuery"];
|
|
53
|
+
|
|
54
|
+
if (typeof run === "function") {
|
|
55
|
+
return (await run.call(context, { __lunoraRef: functionPath }, args ?? {})) as R;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return (await registered.handler(context, args ?? {})) as R;
|
|
60
|
+
};`,Le=(r,t,n=[],o=[],a=!1)=>{const i=z(r,t,n,o),s=W(t,n,o),c=[...i.entries()].filter(([e])=>!a||s.has(e)?!0:r.some(m=>m.filePath===e&&m.channel?.kind==="room")).map(([e,m])=>{if(!T.test(e))throw new A("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);return`import ${a&&!s.has(e)?"type ":""}* as ${m} from "../${e}.js";`}).join(`
|
|
61
|
+
`),d=r.map(e=>{if(!a||s.has(e.filePath))return` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`;const m=j(e.args);return` "${g(e.filePath)}:${e.exportName}": { args: {}, handler: unloadedFunctionHandler, ...${JSON.stringify({argumentDescriptors:JSON.parse(C(e.args)),kind:e.kind,...m.length===0?{}:{sensitiveArgs:m},...e.channel?{channel:e.channel}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}},...e.socket===void 0?{}:{auth:e.socket.auth,socketPath:e.socket.path}})} } satisfies RegisteredLunoraFunction & Pick<FunctionManifestEntry, "argumentDescriptors" | "channel" | "expose">,`}).join(`
|
|
62
|
+
`),l=t.map(e=>` ${JSON.stringify(e.id)}: ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
63
|
+
`),u=n.map(e=>` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
64
|
+
`),f=o.map(e=>` "${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredShape,`).join(`
|
|
65
|
+
`),$=n.map(e=>`${g(e.filePath)}:${e.exportName}`),y=[d,u].filter(e=>e.length>0).join(`
|
|
66
|
+
`),O=r.filter(e=>!a||s.has(e.filePath)).map(e=>{if(e.lifecycle||Object.keys(e.args).length===0)return;const m=H(e.args);return m===void 0?void 0:`installCompiledValidatorMap(${i.get(e.filePath)??""}.${e.exportName}.args, ${m});`}).filter(e=>e!==void 0).join(`
|
|
67
|
+
`),S=r.filter(e=>e.channel?.kind==="room").map(e=>` ${JSON.stringify(e.channel?.name??"")}: RoomMessageOf<typeof ${i.get(e.filePath)??""}[${JSON.stringify(e.exportName)}]>;`).join(`
|
|
68
|
+
`),k=[...r.map(e=>({args:e.args,definition:e,path:`${g(e.filePath)}:${e.exportName}`})),...n.map(e=>({args:e.args,definition:{...e,expose:void 0,kind:"mutation",lifecycle:void 0,visibility:void 0,x402:void 0},path:`${g(e.filePath)}:${e.exportName}`}))],P=a?k.filter(({definition:e})=>!s.has(e.filePath)):[];for(const{definition:e}of k)if(a&&e.x402&&e.x402.price===void 0)throw new A("INTERNAL",`@lunora/codegen: lazy function registry needs a literal \`.x402({ price })\` value in ${e.filePath}:${e.exportName}`);const v=a?P.map(({definition:e,path:m})=>{const R=i.get(e.filePath)??"",x="channel"in e?e.channel:void 0,b={argumentDescriptors:JSON.parse(C(e.args)),exportName:e.exportName,kind:e.kind,moduleId:R,...x?{channel:x}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}}};return` ${JSON.stringify(m)}: ${JSON.stringify(b)},`}).join(`
|
|
69
|
+
`):"",h=[...new Set(P.map(({definition:e})=>e.filePath))],w=a?h.map(e=>{if(!T.test(e))throw new A("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);const m=i.get(e)??"";return` ${JSON.stringify(m)}: () => import(${JSON.stringify(`./fn/${m}.js`)}),`}).join(`
|
|
70
|
+
`):"";return{dispatchBody:y.length>0?`
|
|
71
|
+
${y}
|
|
72
|
+
`:"",importBlock:c.length>0?`${c}
|
|
73
|
+
|
|
74
|
+
`:"",installBlock:O,manifestBody:v.length>0?`
|
|
75
|
+
${v}
|
|
76
|
+
`:"",migrationBody:l.length>0?`
|
|
77
|
+
${l}
|
|
78
|
+
`:"",moduleLoaders:w.length>0?`
|
|
79
|
+
${w}
|
|
80
|
+
`:"",mutatorPaths:$,roomMessagesBody:S,shapeBody:f.length>0?`
|
|
81
|
+
${f}
|
|
82
|
+
`:""}},Te=r=>{const t=M(r,o=>{const a=I(he(o.args),o.filePath),i=a==="{}"?"?":"",s=I(we(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${i}: ${a}) => Promise<AsyncIterable<${s}>>;`:`${o.exportName}: (args${i}: ${a}) => Promise<${s}>;`},"type");return{implementation:M(r,o=>`${me(o.exportName)}: (args) => callRegistered(context, "${g(o.filePath)}:${o.exportName}", args),`,"value"),types:t}},Fe=r=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of r)!n.lifecycle||n.lifecycle==="socket"||t[n.lifecycle].push(`${g(n.filePath)}:${n.exportName}`);return t},Ee=r=>{const t=new Map,n=[];for(const o of r){if(o.lifecycle!=="socket"||o.socket===void 0)continue;const{auth:a,origin:i,path:s}=o.socket,c=`${g(o.filePath)}:${o.exportName}`,d=t.get(s);if(!(d?.origin!==void 0&&d.origin===i)){if(d!==void 0)throw new A("DUPLICATE_SOCKET_PATH",`two defineWebSocket routes serve "${s}" (${d.functionPath} and ${c}); socket paths must be unique.`);t.set(s,{functionPath:c,origin:i}),n.push(` ${JSON.stringify(s)}: { auth: ${String(a)}, functionPath: ${JSON.stringify(c)} },`)}}return`
|
|
83
|
+
/**
|
|
84
|
+
* Socket registry: the URL path of each \`defineWebSocket\` route → its function path + auth requirement.
|
|
85
|
+
* Static, so building the worker never evaluates a route's module. The generated ShardDO's \`socketRoute\` override
|
|
86
|
+
* resolves an upgraded socket through this map.
|
|
87
|
+
*/
|
|
88
|
+
export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPath: string }>> = {
|
|
89
|
+
${n.join(`
|
|
90
|
+
`)}
|
|
91
|
+
};
|
|
92
|
+
`},_e=(r,t)=>{const n=r.some(c=>c.lifecycle==="socket"),a=n&&t?Ee(r):n&&!t?`
|
|
93
|
+
/**
|
|
94
|
+
* Socket registry: the URL path of each \`defineWebSocket\` route → its function
|
|
95
|
+
* path + auth requirement. The generated ShardDO's \`socketRoute\` override
|
|
96
|
+
* resolves an upgraded socket through this map so a route's typed
|
|
97
|
+
* \`onOpen\`/\`onMessage\`/\`onClose\` dispatch server-side under the socket's
|
|
98
|
+
* verified identity. Two routes on one path throw at module load rather than letting
|
|
99
|
+
* the map silently keep whichever came last.
|
|
100
|
+
*/
|
|
101
|
+
export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPath: string }>> = (() => {
|
|
102
|
+
const registry: Record<string, { auth: boolean; functionPath: string }> = {};
|
|
103
|
+
const owners = new Map<string, unknown>();
|
|
104
|
+
|
|
105
|
+
for (const [path, fn] of Object.entries(LUNORA_FUNCTIONS)) {
|
|
106
|
+
if (fn.lifecycle !== "socket" || typeof fn.socketPath !== "string") {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const owner = owners.get(fn.socketPath);
|
|
111
|
+
|
|
112
|
+
// The same registration exported under two names (an alias) is one route.
|
|
113
|
+
if (owner !== undefined && owner !== fn) {
|
|
114
|
+
throw new Error(\`two defineWebSocket routes serve "\${fn.socketPath}"; socket paths must be unique\`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (owner === undefined) {
|
|
118
|
+
owners.set(fn.socketPath, fn);
|
|
119
|
+
registry[fn.socketPath] = { auth: fn.auth === true, functionPath: path };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return registry;
|
|
124
|
+
})();
|
|
125
|
+
`:"";return{fields:n?`
|
|
126
|
+
/**
|
|
127
|
+
* Set on a \`defineWebSocket\` registration: the URL path the route serves.
|
|
128
|
+
* The generated \`LUNORA_SOCKETS\` map keys it on this path so the ShardDO
|
|
129
|
+
* resolves an upgraded socket to this registration.
|
|
130
|
+
*/
|
|
131
|
+
socketPath?: string;
|
|
132
|
+
/**
|
|
133
|
+
* Set on a \`defineWebSocket\` registration: whether the route refuses an
|
|
134
|
+
* anonymous upgrade. Read into \`LUNORA_SOCKETS\` alongside \`socketPath\`.
|
|
135
|
+
*/
|
|
136
|
+
auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:a}},Me=(r,t,n)=>r?{channelField:` /**
|
|
137
|
+
* Set on a \`defineRoom\` registration: the room's name (without the \`room:\`
|
|
138
|
+
* topic prefix). The generated \`LUNORA_ROOMS\` map keys it on the room's
|
|
139
|
+
* \`room:<name>\` whisper topic so the ShardDO resolves a room topic to this
|
|
140
|
+
* path.
|
|
141
|
+
*/
|
|
142
|
+
channel?: { readonly kind: "room"; readonly name: string };
|
|
143
|
+
`,messagesBlock:`
|
|
144
|
+
/**
|
|
145
|
+
* The message type each \`defineRoom\` carries, read off the room's own registration. The generated \`rooms\` references type a client's \`connectRoom\` from it.
|
|
146
|
+
*/
|
|
147
|
+
export type LunoraRoomMessages = {
|
|
148
|
+
${n}
|
|
149
|
+
};
|
|
150
|
+
`,typeImport:`import type { RoomMessageOf } from "${t}";
|
|
151
|
+
`}:{channelField:"",messagesBlock:"",typeImport:""},Ie=(r,t,n)=>r?t?`
|
|
152
|
+
/**
|
|
153
|
+
* Room routes are static metadata so building the worker never evaluates user handlers.
|
|
154
|
+
*/
|
|
155
|
+
export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
|
|
156
|
+
const registry: Record<string, string> = {};
|
|
157
|
+
const owners = new Map<string, string>();
|
|
158
|
+
|
|
159
|
+
for (const { owner, path, topic } of [
|
|
160
|
+
${n.filter(o=>o.channel?.kind==="room").map(o=>` { owner: ${JSON.stringify(o.filePath)}, path: ${JSON.stringify(`${g(o.filePath)}:${o.exportName}`)}, topic: ${JSON.stringify(`room:${o.channel?.name??""}`)} },`).join(`
|
|
161
|
+
`)}
|
|
162
|
+
]) {
|
|
163
|
+
const prior = owners.get(topic);
|
|
164
|
+
|
|
165
|
+
if (prior !== undefined && prior !== owner) {
|
|
166
|
+
throw new Error(\`two defineRoom registrations are named "\${topic.slice("room:".length)}"; room names must be unique\`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (prior === undefined) {
|
|
170
|
+
owners.set(topic, owner);
|
|
171
|
+
registry[topic] = path;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return registry;
|
|
176
|
+
})();
|
|
177
|
+
`:`
|
|
178
|
+
/**
|
|
179
|
+
* Room registry: the whisper topic of each \`defineRoom\` registration → its
|
|
180
|
+
* function path. The generated ShardDO's \`roomHandlerPath\` override resolves a
|
|
181
|
+
* room topic through this map so a room's typed \`onJoin\`/\`onMessage\`/\`onLeave\`
|
|
182
|
+
* dispatch server-side, reusing the whisper channel for membership and fan-out.
|
|
183
|
+
* Two registrations under one name throw at module load: the map would otherwise
|
|
184
|
+
* silently keep whichever came last.
|
|
185
|
+
*/
|
|
186
|
+
export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
|
|
187
|
+
const registry: Record<string, string> = {};
|
|
188
|
+
const owners = new Map<string, unknown>();
|
|
189
|
+
|
|
190
|
+
for (const [path, fn] of Object.entries(LUNORA_FUNCTIONS)) {
|
|
191
|
+
if (fn.channel?.kind !== "room") {
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const topic = \`room:\${fn.channel.name}\`;
|
|
196
|
+
const owner = owners.get(topic);
|
|
197
|
+
|
|
198
|
+
// The same registration exported under two names (an alias) is one room.
|
|
199
|
+
if (owner !== undefined && owner !== fn) {
|
|
200
|
+
throw new Error(\`two defineRoom registrations are named "\${fn.channel.name}"; room names must be unique\`);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (owner === undefined) {
|
|
204
|
+
owners.set(topic, fn);
|
|
205
|
+
registry[topic] = path;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return registry;
|
|
210
|
+
})();
|
|
211
|
+
`:"",Ce=(r,t)=>{const n=Te(r),o=n.types?`
|
|
212
|
+
${n.types}
|
|
213
|
+
`:"",a=n.implementation?`
|
|
214
|
+
${n.implementation}
|
|
215
|
+
`:"",i=$e(n.types),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
|
|
216
|
+
`:"",c=r.length>0?"context":"_context";let d="";if(r.length>0){let l=Ae;t||(l=l.replace("await loadFunction(functionPath)",N("LUNORA_FUNCTIONS"))),d=`${l}
|
|
217
|
+
|
|
218
|
+
`}return{callRegisteredHelper:d,dataModelImport:s,implementation:a,parameter:c,types:o}},He=r=>{const{agents:t=[],functions:n,lazyFunctions:o=!1,migrations:a=[],mutators:i=[],shapes:s=[],useUmbrella:c=!1,usesSandbox:d=!1}=r,l=U(c),{dispatchBody:u,importBlock:f,installBlock:$,manifestBody:y,migrationBody:O,moduleLoaders:S,mutatorPaths:k,roomMessagesBody:P,shapeBody:v}=Le(n,a,i,s,o),h=ge(t,n),w=fe(d,n),m=t.length>0||n.some(p=>j(p.args).length>0)?` /**
|
|
219
|
+
* Names of the arguments whose validators carry a \`v.sensitive\` marker. Read by the
|
|
220
|
+
* shard before any validator is loaded, so a lazy function's secret args are
|
|
221
|
+
* masked even on a dispatch that fails before its module evaluates.
|
|
222
|
+
*/
|
|
223
|
+
sensitiveArgs?: readonly string[];
|
|
224
|
+
`:"",R=[h.lines,w.lines].filter(p=>p.length>0).join(`
|
|
225
|
+
`);let x=u;R.length>0&&(x=u.length>0?`${u.trimEnd()}
|
|
226
|
+
${R}
|
|
227
|
+
`:`
|
|
228
|
+
${R}
|
|
229
|
+
`);const b=Fe(n),Q=o?"await loadFunction(functionPath)":N("LUNORA_FUNCTIONS"),G=o?` if (${N("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
|
|
230
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
`:"",V=s.length>0?`import type { RegisteredShape } from "${l.server}";
|
|
234
|
+
`:"",E=n.some(p=>p.channel?.kind==="room"),L=Me(E,l.server,P),K=s.length>0?`
|
|
235
|
+
/**
|
|
236
|
+
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
237
|
+
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
238
|
+
* evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
|
|
239
|
+
* \`shape_subscribe\` (reads-as-permissions).
|
|
240
|
+
*/
|
|
241
|
+
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${v}};
|
|
242
|
+
`:"",Y=k.length>0?`
|
|
243
|
+
/**
|
|
244
|
+
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
245
|
+
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
246
|
+
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
247
|
+
*/
|
|
248
|
+
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${k.map(p=>JSON.stringify(p)).join(", ")}]);
|
|
249
|
+
`:"",Z=Ie(E,o,n),{fields:X,lifecycleMember:_,registry:ee}=_e(n,o),te=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${l.values}";
|
|
250
|
+
`:"",re=$.length>0?`
|
|
251
|
+
/**
|
|
252
|
+
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
253
|
+
* onto its function's live \`.args\` object and consulted by the interpreted
|
|
254
|
+
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
255
|
+
*/
|
|
256
|
+
${$}
|
|
257
|
+
`:"",ne=Ce(n,o),{callRegisteredHelper:oe,dataModelImport:se,implementation:ae,parameter:ie,types:ce}=ne,le=o?`
|
|
258
|
+
export interface FunctionManifestEntry {
|
|
259
|
+
argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; table?: string }>;
|
|
260
|
+
channel?: { kind: "room"; name: string };
|
|
261
|
+
exportName: string;
|
|
262
|
+
expose?: { cache?: { credentialHeaders?: ReadonlyArray<string>; maxAge?: number; scope?: "private" | "public"; staleWhileRevalidate?: number; tag?: string; vary?: string }; rest?: boolean };
|
|
263
|
+
kind: "action" | "mutation" | "query" | "stream";
|
|
264
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${_};
|
|
265
|
+
moduleId: string;
|
|
266
|
+
visibility?: "internal" | "public";
|
|
267
|
+
x402?: { readonly price: number | string };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Static, codegen-derived facts. Request gates can inspect these without evaluating a user module. */
|
|
271
|
+
export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${y}};
|
|
272
|
+
|
|
273
|
+
const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${S}};
|
|
274
|
+
const loadedModules = new Map<string, Promise<Record<string, unknown>>>();
|
|
275
|
+
const resolvedModules = new Map<string, Record<string, unknown>>();
|
|
276
|
+
const boundFunctions = new Set<string>();
|
|
277
|
+
const unloadedFunctionHandler = (): never => {
|
|
278
|
+
throw new Error("a lazy function was invoked before it was prepared");
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
/** Reuse an evaluated module synchronously, so dispatch does not yield after restoring request scope. */
|
|
282
|
+
export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunction | undefined => {
|
|
283
|
+
const registered = ${N("LUNORA_FUNCTIONS")};
|
|
284
|
+
const manifest = ${N("LUNORA_FUNCTION_MANIFEST")};
|
|
285
|
+
|
|
286
|
+
if (!registered || !manifest) {
|
|
287
|
+
return registered;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (boundFunctions.has(functionPath)) {
|
|
291
|
+
return registered;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const module = resolvedModules.get(manifest.moduleId);
|
|
295
|
+
|
|
296
|
+
if (module === undefined) {
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const loaded = module[manifest.exportName];
|
|
301
|
+
|
|
302
|
+
if (typeof loaded !== "object" || loaded === null) {
|
|
303
|
+
throw new Error(\`lazy module export for "\${functionPath}" is not a registered function\`);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
Object.assign(registered, loaded);
|
|
307
|
+
boundFunctions.add(functionPath);
|
|
308
|
+
|
|
309
|
+
return registered;
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
/** Load one function's owning module once per isolate, then merge its live builder result into the registry entry. */
|
|
313
|
+
export const loadFunction = async (functionPath: string): Promise<RegisteredLunoraFunction | undefined> => {
|
|
314
|
+
const registered = getLoadedFunction(functionPath);
|
|
315
|
+
const manifest = ${N("LUNORA_FUNCTION_MANIFEST")};
|
|
316
|
+
|
|
317
|
+
if (registered || !manifest) {
|
|
318
|
+
return registered;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
let pending = loadedModules.get(manifest.moduleId);
|
|
322
|
+
|
|
323
|
+
if (pending === undefined) {
|
|
324
|
+
const loader = MODULE_LOADERS[manifest.moduleId];
|
|
325
|
+
|
|
326
|
+
if (loader === undefined) {
|
|
327
|
+
throw new Error(\`no lazy module loader registered for "\${functionPath}"\`);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
pending = loader();
|
|
331
|
+
loadedModules.set(manifest.moduleId, pending);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// A module that failed to evaluate stays failed for the isolate: the runtime has already cached
|
|
335
|
+
// the failed evaluation, and a bundler's lazy initializer can hand a retry a half-initialized
|
|
336
|
+
// namespace, so every later call rethrows the original error instead.
|
|
337
|
+
resolvedModules.set(manifest.moduleId, await pending);
|
|
338
|
+
|
|
339
|
+
return getLoadedFunction(functionPath);
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
`:"",ue=o&&y!==""?`
|
|
343
|
+
/**
|
|
344
|
+
* Evaluate every lazy module now and report the ones that fail, keyed by function path. A lazy
|
|
345
|
+
* registry defers a broken module's error to its first call; \`lunora build\` and \`deploy\` run this
|
|
346
|
+
* inside workerd so the error surfaces before the Worker ships instead of in front of a user.
|
|
347
|
+
*/
|
|
348
|
+
export const loadAllFunctions = async (): Promise<{ checked: number; failures: ReadonlyArray<{ functionPath: string; message: string }> }> => {
|
|
349
|
+
const functionPaths = Object.keys(LUNORA_FUNCTION_MANIFEST);
|
|
350
|
+
// Concurrent, so the total is bounded by the slowest module rather than by all of them added up. A module
|
|
351
|
+
// shared by several functions is evaluated once (loadFunction keeps its pending promise), and failures keep manifest order.
|
|
352
|
+
const failures = (
|
|
353
|
+
await Promise.all(
|
|
354
|
+
functionPaths.map(async (functionPath) => {
|
|
355
|
+
try {
|
|
356
|
+
await loadFunction(functionPath);
|
|
357
|
+
|
|
358
|
+
return undefined;
|
|
359
|
+
} catch (error) {
|
|
360
|
+
return { functionPath, message: error instanceof Error ? error.message : String(error) };
|
|
361
|
+
}
|
|
362
|
+
}),
|
|
363
|
+
)
|
|
364
|
+
).filter((failure) => failure !== undefined);
|
|
365
|
+
|
|
366
|
+
return { checked: functionPaths.length, failures };
|
|
367
|
+
};
|
|
368
|
+
`:"";return ye(`${D}${f}${h.importLine}${w.importLine}${te}${V}${L.typeImport}import { LunoraError } from "${l.server}";
|
|
369
|
+
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
370
|
+
${se}
|
|
371
|
+
/**
|
|
372
|
+
* Single registered function, narrowed to the shape \`handleRpc\` needs.
|
|
373
|
+
* The real argument validators / return types are checked elsewhere — at
|
|
374
|
+
* the dispatch site we erase to \`unknown\` so a single map can host every
|
|
375
|
+
* registered function.
|
|
376
|
+
*/
|
|
377
|
+
export interface RegisteredLunoraFunction {
|
|
378
|
+
kind: "action" | "mutation" | "query" | "stream";
|
|
379
|
+
args: Record<string, unknown>;
|
|
380
|
+
/**
|
|
381
|
+
* Present on a \`"stream"\` declared \`durable\`: its run is persisted and
|
|
382
|
+
* survives the socket that opened it. Absent on every other kind, and on an
|
|
383
|
+
* ephemeral stream.
|
|
384
|
+
*/
|
|
385
|
+
durable?: { ttlMs?: number };
|
|
386
|
+
/**
|
|
387
|
+
* For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
|
|
388
|
+
* For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
|
|
389
|
+
* \`AbortSignal\` as a third argument — the runtime drives it frame-by-frame.
|
|
390
|
+
*/
|
|
391
|
+
handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
|
|
392
|
+
/**
|
|
393
|
+
* The lifecycle moment a hook fires on, when this registration came from
|
|
394
|
+
* \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`/\`onWhisper\`.
|
|
395
|
+
* Read at dispatch to decide whether the function runs system-trusted:
|
|
396
|
+
* \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
|
|
397
|
+
* to. \`whisper\` does have one — it runs under the asking socket's identity.
|
|
398
|
+
*/
|
|
399
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${_};${X}
|
|
400
|
+
${L.channelField} /**
|
|
401
|
+
* Hoisted by the builder when the \`.use()\` chain carries a step with a
|
|
402
|
+
* per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
|
|
403
|
+
* captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
|
|
404
|
+
* inside the dispatch callback, and a reactive-cache HIT skips that
|
|
405
|
+
* callback, so such a query must never be memoized.
|
|
406
|
+
*/
|
|
407
|
+
perDispatch?: boolean;
|
|
408
|
+
/** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
|
|
409
|
+
visibility?: "internal" | "public";
|
|
410
|
+
/**
|
|
411
|
+
* \`.x402({ price })\` tag on a paid public procedure. The origin worker
|
|
412
|
+
* paywalls it; the shard refuses to subscribe it (\`isPaidFunction\`).
|
|
413
|
+
*/
|
|
414
|
+
x402?: { readonly price: number | string };
|
|
415
|
+
${m}}
|
|
416
|
+
${h.prelude}${w.prelude}${le}${ue}
|
|
417
|
+
/**
|
|
418
|
+
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
419
|
+
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
420
|
+
*/
|
|
421
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${x}};
|
|
422
|
+
${re}${K}${Y}${Z}${L.messagesBlock}${ee}
|
|
423
|
+
/**
|
|
424
|
+
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
425
|
+
* client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
|
|
426
|
+
* per Durable Object instance before any handler runs (\`init\`), after a
|
|
427
|
+
* write flush when a watched read's result changed (\`reactor\`), and before a
|
|
428
|
+
* socket joins or broadcasts to a whisper topic (\`whisper\`). Each path also
|
|
429
|
+
* resolves through {@link LUNORA_FUNCTIONS}. The socket-scoped moments run under
|
|
430
|
+
* the socket's verified identity; \`init\` and \`reactor\` have no caller, so they
|
|
431
|
+
* run anonymous — all via system dispatch.
|
|
432
|
+
*/
|
|
433
|
+
export const LUNORA_LIFECYCLE_HOOKS: {
|
|
434
|
+
connect: readonly string[];
|
|
435
|
+
disconnect: readonly string[];
|
|
436
|
+
init: readonly string[];
|
|
437
|
+
reactor: readonly string[];
|
|
438
|
+
whisper: readonly string[];
|
|
439
|
+
} = {
|
|
440
|
+
connect: [${b.connect.map(p=>JSON.stringify(p)).join(", ")}],
|
|
441
|
+
disconnect: [${b.disconnect.map(p=>JSON.stringify(p)).join(", ")}],
|
|
442
|
+
init: [${b.init.map(p=>JSON.stringify(p)).join(", ")}],
|
|
443
|
+
reactor: [${b.reactor.map(p=>JSON.stringify(p)).join(", ")}],
|
|
444
|
+
whisper: [${b.whisper.map(p=>JSON.stringify(p)).join(", ")}],
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Resolve and invoke a registered function from an external caller. Throws a
|
|
449
|
+
* LunoraError-shaped object (404) when the path is unknown — the runtime's
|
|
450
|
+
* structural error mapper turns that into the right HTTP status. Internal
|
|
451
|
+
* functions are treated as not-found so their existence never leaks to clients.
|
|
452
|
+
*/
|
|
453
|
+
export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
|
|
454
|
+
${G} const registered = ${Q};
|
|
455
|
+
|
|
456
|
+
if (!registered || registered.visibility === "internal") {
|
|
457
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
return registered.handler(context, args);
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* A handler context accepted by {@link createCaller}. The runtime context the
|
|
465
|
+
* shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
|
|
466
|
+
*/
|
|
467
|
+
export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Typed, in-process server-to-server caller. Every registered function — public
|
|
471
|
+
* *and* internal — is reachable; each call dispatches against the same shard
|
|
472
|
+
* with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
|
|
473
|
+
* \`runAction\` but without re-stating the function path.
|
|
474
|
+
*/
|
|
475
|
+
export interface Caller {${ce}}
|
|
476
|
+
|
|
477
|
+
${oe}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
478
|
+
export const createCaller = (${ie}: CallerCtx): Caller => ({${ae}});
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Single registered data migration, narrowed to the shape the per-shard runner
|
|
482
|
+
* consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
|
|
483
|
+
* validation lives in \`defineMigration\`.
|
|
484
|
+
*/
|
|
485
|
+
export interface RegisteredDataMigration {
|
|
486
|
+
batchSize?: number;
|
|
487
|
+
down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
|
|
488
|
+
id: string;
|
|
489
|
+
table: string;
|
|
490
|
+
up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
|
|
495
|
+
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
496
|
+
*/
|
|
497
|
+
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${O}};
|
|
498
|
+
`,c)},ze="fn",We=r=>{if(r.lazyFunctions!==!0)return{};const{functions:t}=r,n=r.migrations??[],o=r.mutators??[],a=r.shapes??[],i=z(t,n,o,a),s=W(n,o,a),c=[...new Set(t.filter(u=>!s.has(u.filePath)).map(u=>u.filePath))],d=U(r.useUmbrella??!1),l={};for(const u of c){if(!T.test(u))throw new A("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(u)}`);const f=i.get(u)??"",$=`../../${u}.js`,y=t.filter(h=>h.filePath===u&&!h.lifecycle&&Object.keys(h.args).length>0).flatMap(h=>{const w=H(h.args);return w===void 0?[]:[`installCompiledValidatorMap(${f}.${h.exportName}.args, ${w});`]}),O=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
|
|
499
|
+
`:"",S=y.length>0?`import * as ${f} from "${$}";
|
|
500
|
+
`:"",k=y.length>0?`
|
|
501
|
+
/** Install the precompiled argument parsers before the module is dispatched. */
|
|
502
|
+
${y.join(`
|
|
503
|
+
`)}
|
|
504
|
+
`:"",v=t.some(h=>h.filePath===u&&h.exportName==="default")||n.some(h=>h.filePath===u&&h.exportName==="default")?`export { default } from "${$}";
|
|
505
|
+
`:"";l[`${f}.ts`]=`${D}${O}${S}${k}export * from "${$}";
|
|
506
|
+
${v}`}return l};export{ze as LAZY_FUNCTION_DIRECTORY,He as emitFunctions,We as emitLazyFunctionModules};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./CAPABILITY_PROBES-brcmKenl.mjs";import{e}from"./server-B6VhYK7m.mjs";import"./shared-8vTRkL2-.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-C7Um0EnM.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-CBG10DT5.mjs";import"./shard-runtime-ByYXjCKY.mjs";import"./shared-8vTRkL2-.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as s}from"ts-morph";import{b as t,d as c}from"./attribution-CG8-kUcl.mjs";import{c as n}from"./classify-procedure-call-BkaeM9Ej.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-C3QumE88.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{runAdvisor as i}from"@lunora/advisor";const d=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],l=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},m=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:l(e),fields:Object.keys(e.shape),indexes:d(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>r.through!==void 0?{kind:"many",name:r.name,table:r.table,through:{...r.through}}:{field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table}),commitOrdered:e.commitOrdered,shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),u=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,owner:e.owner})),f=n=>{const{argumentValidators:e,mutators:r,queries:s,schema:t,shapes:o,...a}=n;return{...a,argValidators:e,mutators:r===void 0?void 0:u(r),queries:s??[],schema:m(t),shapes:o===void 0?void 0:c(o)}},p=n=>i(f(n),{source:"static"}),v=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
|
|
2
|
+
`)};export{v as formatAdvisories,p as lintSchema,f as toAdvisorContext};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-C3QumE88.mjs";import{r as v,d as b}from"./attribution-CG8-kUcl.mjs";const h=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:h(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=b(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-C3QumE88.mjs";import{b as m,d as p}from"./attribution-CG8-kUcl.mjs";import{t as d}from"./database-calls-UPlhi3Ks.mjs";import{w as g,c as h}from"./classify-procedure-call-BkaeM9Ej.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=l=>l.shardMode==="global"&&l.globalBackend!=="hyperdrive",o=l=>l.shardMode==="global"&&l.globalBackend==="hyperdrive";export{e as isD1GlobalTable,o as isHyperdriveGlobalTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{statSync as y,readdirSync as v,realpathSync as b,lstatSync as C}from"node:fs";import{dirname as P,join as m,relative as A,sep as F,extname as w,basename as I}from"node:path";import{matcher as D}from"@visulima/fs";import{SyntaxKind as p,Node as s,VariableDeclarationKind as k}from"ts-morph";import{diagnosticAt as j}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{readProjectConfigLiterals as z}from"./loadProjectConfig-B7RmxIeD.mjs";import{findProjectConfigFile as V,findCodegenConfigFile as K}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{p as $,a as M}from"./property-name-7cBlgK_O.mjs";const B=/\.ts$/u,g=(e,t)=>A(e,t).split(F).join("/").replace(B,""),U=new Set(["_generated","node_modules"]),O=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),N=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,me=e=>{const t=e.split("/");return N.test(t.at(-1)??"")||t.slice(0,-1).some(i=>O.has(i))},f=(e,t,i)=>t?U.has(e)||!i&&O.has(e):!i&&N.test(e),S=new Map,d=()=>!1,W=e=>{const t=K(e),i=t===void 0?void 0:y(t,{throwIfNoEntry:!1});if(t===void 0||i===void 0)return d;const n=`${String(i.mtimeMs)}:${String(i.size)}`,r=S.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=z(P(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?D(o.exclude):d;return S.set(t,{isExcluded:c,key:n}),c},X=(e,t,i)=>e==="schema.ts"&&t===i,G=e=>{try{return y(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},L=(e,t,i,n,r)=>{let o,c;try{o=v(e),c=b(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const l of o){const u=m(e,l),a=G(u);a===void 0||r(l,A(i,u).split(F).join("/"),a.isDirectory())||(a.isDirectory()?L(u,t,i,n,r):a.isFile()&&w(l)===".ts"&&!X(l,e,i)&&t.push(u))}return t},_=(e,t={})=>{const i=t.includeSkipped??!1,n=i?d:W(e);return L(e,[],e,new Set,(r,o,c)=>f(r,c,i)||n(o))},H=["src/server","src/index.ts","src/worker.ts"],Y=new Set([".ts",".tsx"]),R=(e,t=[])=>{let i;try{i=C(e)}catch{return t}if(i.isFile())return Y.has(w(e))&&!f(I(e),!1,!1)&&t.push(e),t;if(!i.isDirectory())return t;for(const n of v(e))f(n,!0,!1)||R(m(e,n),t);return t},q=e=>{const t=P(e),i=_(e).map(o=>({displayPath:g(e,o),filePath:o})),n=new Set(i.map(o=>o.filePath)),r=V(t);for(const o of[...H.flatMap(c=>R(m(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),i.push({displayPath:g(t,o),filePath:o}));return i},Q=e=>Array.isArray(e),T=(e,t,i,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const l=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const u of l.getDescendantsOfKind(i)){const a=n(u,o);Q(a)?r.push(...a):a!==void 0&&r.push(a)}}return r},J=e=>_(e).map(t=>({displayPath:g(e,t),filePath:t})),Z=(e,t,i,n)=>T(e,J(t),i,n),xe=(e,t,i)=>Z(e,t,p.CallExpression,i),Se=(e,t,i)=>T(e,q(t),p.CallExpression,i),he=e=>$(e.getPropertyNameNode()??e.getNameNode()),x=(e,t)=>e?.getProperties().find(i=>!s.isSpreadAssignment(i)&&M(i)===t),ye=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0}const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=x(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0},ve=(e,t)=>{if(!e||!s.isObjectLiteralExpression(e))return;const i=x(e,t);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},ee=e=>{const t=e?.getParent();return s.isVariableDeclaration(e)&&s.isVariableDeclarationList(t)&&t.getDeclarationKind()===k.Const},te=e=>{let t=e,i=t.getParent();for(;i!==void 0&&(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isTypeAssertion(i)||s.isNonNullExpression(i));)t=i,i=t.getParent();return t},h=e=>{const t=te(e),i=t.getParent();if(i===void 0)return!1;if(s.isBinaryExpression(i)){const r=i.getOperatorToken().getKind();return i.getLeft()===t&&r>=p.FirstAssignment&&r<=p.LastAssignment}if(s.isPrefixUnaryExpression(i)||s.isPostfixUnaryExpression(i)){const r=i.getOperatorToken();return r===p.PlusPlusToken||r===p.MinusMinusToken}return s.isDeleteExpression(i)?!0:s.isForOfStatement(i)||s.isForInStatement(i)?i.getInitializer()===t:s.isPropertyAssignment(i)?i.getInitializer()===t&&h(i):(s.isShorthandPropertyAssignment(i)||s.isSpreadAssignment(i)||s.isSpreadElement(i)||s.isObjectLiteralExpression(i)||s.isArrayLiteralExpression(i))&&h(i)},ie=e=>{const t=e?.getDeclarations().find(n=>s.isVariableDeclaration(n));if(!ee(t))return;const i=t.getParent().getParent();return s.isVariableStatement(i)&&s.isSourceFile(i.getParent())?t.getInitializer():void 0},se=e=>ie(e.getSymbol()),Pe=e=>{if(!e)return;if(s.isObjectLiteralExpression(e))return e;if(!s.isIdentifier(e))return;const t=se(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},E=e=>{let t=e;for(;t&&(s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isParenthesizedExpression(t)||s.isNonNullExpression(t));)t=t.getExpression();return t},ne=(e,t)=>{let i=E(e);for(;s.isAwaitExpression(i)||s.isPropertyAccessExpression(i)||s.isElementAccessExpression(i)||s.isCallExpression(i);){const n=s.isCallExpression(i)?t?.(i):void 0;if(n!==void 0)return{verdict:n};i=E(i.getExpression())}return{root:i}},Ae=e=>ne(e).root,Fe=e=>s.isArrowFunction(e)||s.isConstructorDeclaration(e)||s.isFunctionDeclaration(e)||s.isFunctionExpression(e)||s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)||s.isSetAccessorDeclaration(e),we=(e,t)=>e?.compilerNode===t.compilerNode,Oe=e=>{if(s.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=s.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return s.isElementAccessExpression(e)&&s.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},Ne=e=>{const t=e.getParent();return s.isReturnStatement(t)||s.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>s.isFunctionLikeDeclaration(n)||s.isArrowFunction(n)):void 0},Le=e=>{const t=E(e);return t&&s.isCallExpression(t)?t:void 0},_e=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const i=t.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},Re=e=>{const t=e.getArguments()[1];return t&&s.isStringLiteral(t)?t.getLiteralValue():""},Te=(e,t)=>{if(!s.isObjectLiteralExpression(e))return;const i=x(e,t);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},re=e=>{const t=e.getStatements(),[i]=t;if(t.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},be=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isParenthesizedExpression(e)){const t=e.getExpression();return s.isObjectLiteralExpression(t)?t:void 0}return s.isBlock(e)?re(e):void 0},Ce=e=>(t,i,n)=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw j(t,`${e} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},oe=new Set(["api","internal"]),Ie=new Set(["run","runAction","runMutation","runQuery"]),ce=e=>{if(e===void 0||!s.isPropertyAccessExpression(e))return;const t=[];let i=e;for(;s.isPropertyAccessExpression(i);)t.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&oe.has(i.getText())&&t.length>=2?t:void 0},De=e=>{const t=ce(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{Ie as RUN_METHODS,B as TS_EXTENSION_RE,he as bindingKeyName,Ae as chainRootOf,xe as collectCallRows,Z as collectNodeRows,Se as collectSecurityCallRows,_e as defaultExportExpression,x as findObjectProperty,De as functionKeyOf,ce as functionReferenceSegments,ye as handlerOf,ee as isConstDeclaration,Fe as isFunctionLike,we as isSameNode,me as isTestPath,h as isWriteTarget,Re as limitNameOf,_ as listLunoraSourceFiles,q as listSecurityScanFiles,g as lunoraRelativePath,Oe as memberAccessOf,be as objectLiteralFromCallbackBody,Pe as optionsObjectLiteral,te as outermostValueWrapper,ve as propertyInitializer,M as propertyKeyName,$ as propertyNameText,Ne as returningFunctionOf,Ce as stringPropertyFor,Te as stringPropertyOf,ie as symbolConstInitializer,E as unwrapExpression,Le as unwrapToCallExpression,ne as walkChain};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
const g=/[^a-zA-Z0-9]+/gu,T=/([a-z0-9])([A-Z])/gu,p=t=>t.split(g).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),R=t=>t.replaceAll(T,"$1_$2").replaceAll(g,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),j=t=>t==="query"?"query":t==="action"?"action":"mutation",l=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>l(o,e+1));const n=t;if(n.format==="int64"&&(n.type===void 0||n.type==="string")||n.type==="string"&&n.contentEncoding==="base64")return!0;const{properties:r}=n;return r!==null&&typeof r=="object"&&Object.values(r).some(o=>l(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>l(n[o],e+1))},I=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),E=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
+
`,"\\n").replaceAll("\r","\\r"),C=["$","{","'","$","'","}"].join(""),x=t=>E(t).split("$").join(C),z=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,b=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const n=t;return n.type==="null"||Array.isArray(n.type)&&n.type.includes("null")?!0:["anyOf","oneOf"].some(r=>{const o=n[r];return Array.isArray(o)&&o.some(s=>b(s,e+1))})},N=(t,e,n)=>e.length===0?n===0?[]:[t]:e.map(r=>({properties:{...t.properties,...r.properties},required:new Set([...t.required,...r.required])})),P=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const n=t.required;return[{properties:e,required:new Set(Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}]},m=(t,e,n)=>{const r=t[e];return Array.isArray(r)?r.flatMap(o=>A(o,n+1)):[]},A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[...P(n),...m(n,"allOf",e)],o={properties:Object.assign({},...r.map(a=>a.properties)),required:new Set(r.flatMap(a=>[...a.required]))},s=[...m(n,"anyOf",e),...m(n,"oneOf",e)];return N(o,s,r.length)},w=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[n];for(const o of["anyOf","oneOf","allOf"]){const s=n[o];if(Array.isArray(s))for(const a of s)r.push(...w(a,e+1))}return r},y=(t,e,n,r=0)=>{if(r>f||t===null||typeof t!="object")return;const o=A(t),s=[...new Set(o.flatMap(a=>Object.keys(a.properties)))].toSorted((a,c)=>a.localeCompare(c));for(const a of s){const c=[...e,a],u=o.every(i=>i.required.has(a)),h=o.map(i=>i.properties[a]).filter(i=>i!==void 0);u?h.some(i=>b(i))&&n.nullable.push(c):n.optional.push(c);for(const i of h)y(i,c,n,r+1)}for(const a of w(t))for(const c of["additionalProperties","items"]){const u=a[c];u!==null&&typeof u=="object"&&y(u,[...e,"*"],n,r+1)}},k=(t,e)=>t.join("\0").localeCompare(e.join("\0")),q=t=>{const e={nullable:[],optional:[]};y(t,[],e);const n=r=>[...new Map(r.map(o=>[o.join("\0"),o])).values()].toSorted(k);return{nullable:n(e.nullable),optional:n(e.optional)}},$=t=>{const[e="",n=""]=t.name.split(":"),r=`${p(e)}${p(n)}`,o=t.params?.[0]?.schema,s=t.result?.schema;return{argsNullPaths:q(o),argsType:d(o)&&!l(o)?`${r}Args`:void 0,takesArgs:d(o),functionName:n,functionPath:t.name,namespace:e,resultType:d(s)&&!l(s)?`${r}Result`:void 0,summary:t.summary??t.name,verb:j(t["x-lunora-function-kind"])}},H=t=>{const e=new Map;for(const n of t.methods){const r=$(n),o=e.get(r.namespace);o===void 0?e.set(r.namespace,[r]):o.push(r)}return[...e.entries()].toSorted(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({methods:r.toSorted((o,s)=>o.functionName.localeCompare(s.functionName)),name:n}))},U=t=>t.methods.flatMap(e=>{const n=$(e);return[{name:n.argsType,schema:e.params?.[0]?.schema},{name:n.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,n)=>e.name.localeCompare(n.name)),L=/^[A-Za-z][A-Za-z0-9]*$/u,S=t=>L.test(t),D=t=>{const e=new Map;for(const n of t.methods){const r=p(n.functionName);if(!S(r))throw new Error(`sdk: function "${n.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const o=n.verb==="query"?[r,`Subscribe${r}`,`Watch${r}`]:[r];for(const s of o){const a=e.get(s);if(a!==void 0){const c=s.startsWith("Watch")?' (the Dart target emits a "watch" Stream member for every query)':"";throw new Error(`sdk: functions "${a}" and "${n.functionPath}" both generate "${s}"${c} — rename one so the generated methods stay distinct.`)}e.set(s,n.functionPath)}}},W=t=>{const e=new Map;for(const n of t){const r=p(n.name);if(!S(r))throw new Error(`sdk: namespace "${n.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const o=e.get(r);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${n.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,n.name),D(n)}},Z=(t,e,n)=>{for(const r of t){const o=new Map;for(const s of r.methods)for(const a of n(s)){const c=o.get(a);if(c!==void 0&&c!==s.functionPath)throw new Error(`sdk: functions "${c}" and "${s.functionPath}" both generate the ${e} member "${a}" — rename one so the generated methods stay distinct.`);o.set(a,s.functionPath)}}},M=t=>t.flatMap(e=>e.methods),F=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],_=/^\s*(?:#|\/\/|\/\*|\*)/u,v=t=>t.split(`
|
|
3
|
+
`).filter(e=>!_.test(e)).join(`
|
|
4
|
+
`),O=(t,e)=>new RegExp(String.raw`\b${e}\b`,"u").test(t),G=(t,e)=>{const n=v(e),r=o=>o!==void 0&&O(n,o)?o:void 0;return t.map(o=>({methods:o.methods.map(s=>({...s,argsType:r(s.argsType),resultType:r(s.resultType)})),name:o.name}))},B=t=>t.methods.filter(e=>l(e.params?.[0]?.schema)||l(e.result?.schema)).map(e=>e.name).toSorted((e,n)=>e.localeCompare(n)),V=(t,e)=>{const n=v(e);return[...new Set(M(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!O(n,r)))].toSorted((r,o)=>r.localeCompare(o))},K=t=>[...new Set(M(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,n)=>e.localeCompare(n));export{M as allMethods,z as argsChoice,Z as assertDistinctMembers,W as assertGeneratable,I as commentText,F as generatedHeaderLines,l as hasUnrepresentableWireType,d as isTypedSchema,x as kotlinLiteral,U as modelSources,q as nullPathsOf,$ as parseMethod,H as parseSpec,K as referencedModels,E as stringLiteral,p as toPascalCase,R as toSnakeCase,V as undeclaredModels,B as unrepresentableFunctions,j as verbForKind,G as withDeclaredModels};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=(r,s)=>`JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${s}`;export{a as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{statSync as E,readFileSync as y}from"node:fs";import{basename as P}from"node:path";import{createJiti as x}from"jiti";import{Project as S,Node as i}from"ts-morph";import{a as d}from"./property-name-7cBlgK_O.mjs";import{findProjectConfigFile as v}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{PROJECT_CONFIG_FILENAMES as q}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";const f=new Map,U=async t=>{const r=v(t);if(r===void 0)return{};let e;try{const a=E(r);e=`${String(a.mtimeMs)}:${String(a.size)}`}catch{return{}}const n=f.get(r);if(n?.key===e)return n.value;const s=(async()=>{try{const o=(await x(r,{interopDefault:!1,moduleCache:!1}).import(r))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(a){return{error:a instanceof Error?a.message:String(a)}}})();return f.set(r,{key:e,value:s}),s},j=t=>{let e=t.getExportAssignments().find(n=>!n.isExportEquals())?.getExpression();for(;e!==void 0&&(i.isSatisfiesExpression(e)||i.isAsExpression(e)||i.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&i.isIdentifier(e))for(e=t.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(i.isSatisfiesExpression(e)||i.isAsExpression(e));)e=e.getExpression();return e!==void 0&&i.isObjectLiteralExpression(e)?e:void 0},g=(t,r)=>i.isPropertyAssignment(t)?t.getInitializer():r.getVariableDeclaration(d(t))?.getInitializer(),b=t=>{let r=t;for(;r!==void 0&&(i.isSatisfiesExpression(r)||i.isAsExpression(r)||i.isParenthesizedExpression(r));)r=r.getExpression();return r},m=(t,r,e)=>{const n=b(t);if(n===void 0||!i.isObjectLiteralExpression(n))return{unreadable:!0};const s=n.getProperties(),a=s.filter(u=>i.isPropertyAssignment(u)&&!i.isComputedPropertyName(u.getNameNode())||i.isShorthandPropertyAssignment(u));if(a.length!==s.length)return{unreadable:!0};const o=a.findLast(u=>d(u)===e);if(o===void 0)return{absent:!0};const l=g(o,r);return l===void 0?{unreadable:!0}:{literal:l}},A=["exportName","file","reason","rule"],h=t=>{const r=b(t);if(r===void 0||!i.isObjectLiteralExpression(r))return;const e={};for(const l of r.getProperties()){if(!i.isPropertyAssignment(l)||i.isComputedPropertyName(l.getNameNode()))return;const u=d(l),c=b(l.getInitializer());if(!A.includes(u)||c===void 0||!i.isStringLiteral(c)&&!i.isNoSubstitutionTemplateLiteral(c))return;e[u]=c.getLiteralValue()}const{exportName:n,file:s,reason:a,rule:o}=e;return n?.trim()&&s?.trim()&&a?.trim()&&o?.trim()?{exportName:n,file:s,reason:a,rule:o}:void 0},O=(t,r)=>{const e=m(t,r,"accept");if("absent"in e)return{};const n="literal"in e?b(e.literal):void 0;if(n===void 0||!i.isArrayLiteralExpression(n))return{acceptUnreadable:!0};const s=[];for(const a of n.getElements()){const o=h(a);if(o===void 0)return{acceptUnreadable:!0};s.push(o)}return{accept:s}},N=(t,r)=>{const e=m(t,r,"minSeverity"),n=O(t,r);return"absent"in e?{advisor:n}:"literal"in e&&i.isStringLiteral(e.literal)?{advisor:{...n,minSeverity:e.literal.getLiteralValue()}}:{advisor:{...n,unreadable:!0}}},C=(t,r)=>{const e=m(t,r,"exclude");if("absent"in e)return{codegen:{}};if(!("literal"in e)||!i.isArrayLiteralExpression(e.literal))return{codegen:{unreadable:!0}};const n=[];for(const s of e.literal.getElements()){if(!i.isStringLiteral(s)&&!i.isNoSubstitutionTemplateLiteral(s)||s.getLiteralValue().startsWith("!"))return{codegen:{unreadable:!0}};n.push(s.getLiteralValue())}return{codegen:{exclude:n}}},z=(t,r)=>{const e=m(t,r,"merge");return"absent"in e?{durableObjects:{}}:"literal"in e&&(i.isTrueLiteral(e.literal)||i.isFalseLiteral(e.literal))?{durableObjects:{merge:e.literal.getLiteralValue()}}:{durableObjects:{unreadable:!0}}},w=new Map([["advisor",{advisor:{unreadable:!0}}],["codegen",{codegen:{unreadable:!0}}],["durableObjects",{durableObjects:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),L=(t,r)=>{const e=t.getProperty(r);if(e!==void 0)return(i.isPropertyAssignment(e)?e.getInitializer():void 0)??"unreadable"},p=(t,r)=>{const e=L(t,r);if(e!==void 0)return e!=="unreadable"&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():!1},I=t=>{const r=L(t,"rpc");if(r!==void 0)return r!=="unreadable"&&i.isFalseLiteral(r)?!1:"unreadable"},D=t=>{const r=b(t);if(r===void 0||!i.isObjectLiteralExpression(r))return{services:{unreadable:!0}};const e={};for(const n of r.getProperties()){if(!i.isPropertyAssignment(n)||i.isComputedPropertyName(n.getNameNode()))return{services:{unreadable:!0}};const s=b(n.getInitializer());if(s===void 0||!i.isObjectLiteralExpression(s)||s.getProperties().some(u=>!i.isPropertyAssignment(u)))return{services:{unreadable:!0}};const a=p(s,"dir"),o=p(s,"entrypoint"),l=I(s);if(typeof a!="string"||o===!1||l==="unreadable")return{services:{unreadable:!0}};e[d(n)]={dir:a,...o===void 0?{}:{entrypoint:o},...l===void 0?{}:{rpc:l}}}return{services:{declared:e}}},M=(t,r)=>{if(i.isGetAccessorDeclaration(t)||i.isMethodDeclaration(t))return w.get(d(t))??{};if(!i.isPropertyAssignment(t)&&!i.isShorthandPropertyAssignment(t))return{};const e=d(t);if(e==="advisor")return N(g(t,r),r);if(e==="services")return D(g(t,r));if(e==="codegen")return C(g(t,r),r);if(e==="durableObjects")return z(g(t,r),r);if(e!=="target"&&e!=="remote")return{};const n=g(t,r);return n===void 0?{unreadable:!0}:e==="target"?i.isStringLiteral(n)?{target:n.getLiteralValue()}:{unreadable:!0}:i.isTrueLiteral(n)||i.isFalseLiteral(n)?{remote:n.getLiteralValue()}:i.isObjectLiteralExpression(n)?{remote:!0}:{unreadable:!0}},V=t=>{const r=v(t);if(r===void 0)return{};let e;try{e=y(r,"utf8")}catch{return{unreadable:!0}}const s=new S({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(P(r),e,{overwrite:!0}),a=j(s);if(a===void 0)return{unreadable:!0};if(a.getProperties().some(l=>i.isSpreadAssignment(l))){const l=u=>a.getProperties().some(c=>!i.isSpreadAssignment(c)&&d(c)===u);return{...l("advisor")?{advisor:{unreadable:!0}}:{},...l("codegen")?{codegen:{unreadable:!0}}:{},...l("durableObjects")?{durableObjects:{unreadable:!0}}:{},...l("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let o={};for(const l of a.getProperties())o={...o,...M(l,s)};return o},G=t=>{const{durableObjects:r}=V(t);return r?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),r?.merge===!0};export{q as PROJECT_CONFIG_FILENAMES,v as findProjectConfigFile,U as loadProjectConfig,G as readMergeDurableObjects,V as readProjectConfigLiterals};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=/(?:^|\/)_generated\/server(?:\.js)?$/u,s=new Set(["@lunora/server","lunorash/server"]),o=e=>s.has(e),n=e=>r.test(e),t=e=>o(e)||n(e),a=new Set(["@lunora/scheduler",...s]),E=e=>a.has(e);export{o as a,t as b,E as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-C3QumE88.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
|