@lunora/codegen 1.0.0-alpha.42 → 1.0.0-alpha.420
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/LICENSE.md +201 -104
- package/README.md +4 -4
- package/dist/index.d.mts +4583 -2045
- package/dist/index.d.ts +4583 -2045
- package/dist/index.mjs +1 -35
- package/dist/packem_shared/AGENTS_FILENAME-C4tHmiZZ.mjs +1 -0
- package/dist/packem_shared/ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs +1 -0
- package/dist/packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs +25 -0
- package/dist/packem_shared/COMPANION_BINDING-Da_v9XpC.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-d3XTFcqV.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs +1 -0
- package/dist/packem_shared/ENV_FILENAME-DJ11PXN5.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-DeSjFBWq.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-DgrhC3Iv.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-C0ZV0hh6.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-BOBo0zdQ.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-DbuJZnrY.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BljJJD8u.mjs +56 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
- package/dist/packem_shared/SHAPES_FILENAME-C-hrGfJ2.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs +17 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-7FysJsMZ.mjs +1 -0
- package/dist/packem_shared/attribution-Cwt30DDJ.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-DmV_PBFv.mjs +3 -0
- package/dist/packem_shared/capabilitiesUsedBy-BNvoiCu1.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-BmEirzc_.mjs +1 -0
- package/dist/packem_shared/companionServiceBinding-BZjm486n.mjs +1 -0
- package/dist/packem_shared/context-property-calls-BT1J7BqY.mjs +1 -0
- package/dist/packem_shared/context-root-BpDEhvNE.mjs +1 -0
- package/dist/packem_shared/createCodegenProject-dC6oJh5H.mjs +1 -0
- package/dist/packem_shared/database-calls-d-Sssc-3.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-CuqaLRa0.mjs +1 -0
- package/dist/packem_shared/discoverCrons-bT8F5GyL.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-C9HUlfiV.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-CesuhqW1.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-BmAoOGGq.mjs +1 -0
- package/dist/packem_shared/discoverInserts-DIarYU2P.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-jkRrWS86.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-C9AlZYFi.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-ZeZDQJAI.mjs +1 -0
- package/dist/packem_shared/discoverQueries-DLZHcDzB.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-D_HWbbky.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-C0UkQkWd.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-BbSdCvmA.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-Dgvv6F_7.mjs +1 -0
- package/dist/packem_shared/discoverSchema-BLTROO8Z.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-DeBgC7po.mjs +1 -0
- package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
- package/dist/packem_shared/emitAgents-vWoT8-Yb.mjs +1 -0
- package/dist/packem_shared/emitApi-lwadq5G7.mjs +147 -0
- package/dist/packem_shared/emitApp-LFKtDRYu.mjs +1162 -0
- package/dist/packem_shared/emitCrons-CCRKs482.mjs +138 -0
- package/dist/packem_shared/emitDataModel-BvCZS4Yq.mjs +114 -0
- package/dist/packem_shared/emitDrizzleSchema-BzOChEYW.mjs +15 -0
- package/dist/packem_shared/emitFunctions-ppMX7E3X.mjs +528 -0
- package/dist/packem_shared/emitServer-CGRV_uIq.mjs +1 -0
- package/dist/packem_shared/emitShard-CDWgekIG.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains-CfH5jrzD.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-TN-rU6Of.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-Bue5tbp6.mjs +2 -0
- package/dist/packem_shared/handler-reference-BkOkxxg8.mjs +1 -0
- package/dist/packem_shared/index-CfSmiylg.mjs +1 -0
- package/dist/packem_shared/index-DtJBMdZ4.mjs +1 -0
- package/dist/packem_shared/ip-reads-D2qhKEb6.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTestPath-Uwb5a6Kq.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CDv3pJB6.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
- package/dist/packem_shared/module-specifiers-BctA0m_p.mjs +1 -0
- package/dist/packem_shared/modules-DdOd-7Wp.mjs +1 -0
- package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
- package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
- package/dist/packem_shared/policies-Dn_tuTZd.mjs +1 -0
- package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
- package/dist/packem_shared/property-name-7cBlgK_O.mjs +1 -0
- package/dist/packem_shared/qualifiers-qqH8fRTo.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-RHhGiz0k.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-CByOxuZb.mjs +1 -0
- package/dist/packem_shared/server-Dfxmm5Zw.mjs +377 -0
- package/dist/packem_shared/shard-CWAD5mYy.mjs +1897 -0
- package/dist/packem_shared/shard-runtime-G5mZQjY0.mjs +351 -0
- package/dist/packem_shared/shared-Cn7dMQ_u.mjs +13 -0
- package/dist/packem_shared/unwrap-handler-return-DvbyiLjc.mjs +1 -0
- package/dist/sdk/index.d.mts +288 -0
- package/dist/sdk/index.d.ts +288 -0
- package/dist/sdk/index.mjs +394 -0
- package/package.json +22 -9
- 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-fEZtzWXi.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-D6RK1WF1.mjs +0 -3
- package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
- package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-CzhfvCIQ.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cl1EBMdR.mjs +0 -3438
- 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-B2By8S4s.mjs +0 -152
- package/dist/packem_shared/buildOpenApiDocument-bg-NnLka.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-WMx8L2FG.mjs +0 -62
- package/dist/packem_shared/discoverCrons-D-jrpm97.mjs +0 -256
- package/dist/packem_shared/discoverFunctions-CZ91aenA.mjs +0 -518
- package/dist/packem_shared/discoverHttpRoutes-DNZLDCmm.mjs +0 -131
- package/dist/packem_shared/discoverInserts-DFRJhmCv.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-B5iFnZ-X.mjs +0 -273
- package/dist/packem_shared/discoverMigrations-CdKtMlBc.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C_PrQPkA.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B8W9UPrt.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-Bm7Rfnf4.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-B4GL4ZKm.mjs +0 -280
- package/dist/packem_shared/discoverSchema-DFWVgU5o.mjs +0 -874
- package/dist/packem_shared/discoverStorageRulesMetadata-nosjYcvN.mjs +0 -97
- package/dist/packem_shared/emit-31Yg1Ee5.mjs +0 -3474
- package/dist/packem_shared/emitApp-DCP7Pr6M.mjs +0 -668
- package/dist/packem_shared/formatAdvisories-DRhEiJUz.mjs +0 -114
- package/dist/packem_shared/parse-validator-BSJo1HGP.mjs +0 -144
- 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,528 @@
|
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{L as pe,i as ge,G as U,d as J,I as F,s as fe,b as C,r as ye,c as $e}from"./shared-Cn7dMQ_u.mjs";import{v as we}from"./parse-validator-BisfC8bR.mjs";import{renderAgentFunctionRegistry as be,renderSandboxFunctionRegistry as Re}from"./emitApi-lwadq5G7.mjs";import{b as ke,a as Ne,r as j,c as ve}from"./qualifiers-qqH8fRTo.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const Oe=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),B=t=>t.column!==void 0,Se=(t,r)=>{switch(t){case"bigint":return`if (typeof ${r} !== "bigint") return DEFER;
|
|
2
|
+
`;case"boolean":return`if (typeof ${r} !== "boolean") return DEFER;
|
|
3
|
+
`;case"date":case"number":case"timestamp":return`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return DEFER;
|
|
4
|
+
`;case"null":return`if (${r} !== null) return DEFER;
|
|
5
|
+
`;default:return`if (typeof ${r} !== "string") return DEFER;
|
|
6
|
+
`}},Pe=(t,r)=>t.stringMaxLength===void 0?"":`if (${r}.length > ${String(t.stringMaxLength)}) return DEFER;
|
|
7
|
+
`,xe=(t,r)=>{const n=t.literalValue?.trim();if(!(n===void 0||!pe.test(n)))return{out:r,pre:`if (${r} !== ${n}) return DEFER;
|
|
8
|
+
`}},E=(t,r,n)=>{if(!B(t)&&!(t.unmodelledRefinement||t.sourceText!==void 0)){if(Oe.has(t.kind))return t.kind==="any"?{out:r,pre:""}:{out:r,pre:Se(t.kind,r)+Pe(t,r)};switch(t.kind){case"array":return Ae(t,r,n);case"literal":return xe(t,r);case"object":return Fe(t,r,n);default:return}}},Ae=(t,r,n)=>{const{inner:o}=t;if(!o)return;const s=n.next(),i=`__arr${String(s)}`,a=`__i${String(s)}`,c=`__e${String(s)}`,u=E(o,c,n);if(!u)return;const l=`if (!Array.isArray(${r})) return DEFER;
|
|
9
|
+
const ${i} = new Array(${r}.length);
|
|
10
|
+
for (let ${a} = 0; ${a} < ${r}.length; ${a}++) {
|
|
11
|
+
const ${c} = ${r}[${a}];
|
|
12
|
+
${u.pre}${i}[${a}] = ${u.out};
|
|
13
|
+
}
|
|
14
|
+
`;return{out:i,pre:l}},Le=(t,r,n,o)=>{const s=JSON.stringify(t);if(r.kind==="optional"){if(r.hasRefinement||r.sourceText!==void 0||B(r))return;const{inner:a}=r;if(!a)return;const c=E(a,n,o);if(!c)return;const u=o.next(),l=`__has${String(u)}`,d=`__val${String(u)}`,f=`let ${l} = false;
|
|
15
|
+
let ${d};
|
|
16
|
+
if (${n} !== undefined) {
|
|
17
|
+
${c.pre}${d} = ${c.out};
|
|
18
|
+
${l} = true;
|
|
19
|
+
}
|
|
20
|
+
`;return{entry:`...(${l} ? { ${s}: ${d} } : {})`,pre:f}}const i=E(r,n,o);if(i)return{entry:`${s}: ${i.out}`,pre:i.pre}},Te=new Set(Object.getOwnPropertyNames(Object.prototype)),q=(t,r,n)=>{let o="";const s=[];for(const i of Object.keys(t)){const a=t[i];if(!a)return;const c=JSON.stringify(i);let u=`${r}[${c}]`;if(Te.has(i)){const d=`__f${String(n.next())}`;o+=`const ${d} = Object.hasOwn(${r}, ${c}) ? ${r}[${c}] : undefined;
|
|
21
|
+
`,u=d}const l=Le(i,a,u,n);if(!l)return;o+=l.pre,s.push(l.entry)}return{entries:s.join(", "),pre:o}},z=t=>{const r=`Object.getPrototypeOf(${t})`;return`if (${r} !== Object.prototype && ${r} !== null) return DEFER;
|
|
22
|
+
`},Fe=(t,r,n)=>{const o=t.shape??{},s=q(o,r,n);if(!s)return;const i=n.next(),a=`__obj${String(i)}`,c=`if (typeof ${r} !== "object" || ${r} === null || Array.isArray(${r})) return DEFER;
|
|
23
|
+
${z(r)}${s.pre}const ${a} = { ${s.entries} };
|
|
24
|
+
`;return{out:a,pre:c}},H=t=>{let r=0;const o=q(t,"source",{next:()=>(r+=1,r)});if(o)return`(source) => {
|
|
25
|
+
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
26
|
+
${z("source")}${o.pre}return { ${o.entries} };
|
|
27
|
+
}`},Ee=(t,r)=>`lunora_${g(t)}_${String(r)}`,D=t=>JSON.stringify(Object.entries(t).toSorted(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{const o=n.kind==="optional",s=o?n.inner??{kind:"unknown"}:n,i=s.kind==="array"?s.inner?.kind:void 0,a=s.kind==="id"?s.tableName:void 0;return{kind:s.kind,name:r,optional:o,...we(n)?{sensitive:!0}:{},...a===void 0?{}:{table:a},...i===void 0||i==="unknown"?{}:{element:i}}})),_e=t=>t?"sensitive?: true; ":"",Me=t=>t?` /** Lazy-mode stub only: the manifest's argument descriptors, read before the module loads. */
|
|
28
|
+
argumentDescriptors?: FunctionManifestEntry["argumentDescriptors"];
|
|
29
|
+
/** Lazy-mode stub only: the manifest's cache and REST exposure. */
|
|
30
|
+
expose?: FunctionManifestEntry["expose"];
|
|
31
|
+
`:"",W=(t,r,n,o)=>{const s=new Map,i=a=>{s.has(a)||s.set(a,Ee(a,s.size))};for(const a of t)i(a.filePath);for(const a of r)i(a.filePath);for(const a of n)i(a.filePath);for(const a of o)i(a.filePath);return s},Q=(t,r,n,o)=>new Set([...t.filter(s=>s.typeDerivedArgs).map(s=>s.filePath),...r.map(s=>s.filePath),...n.map(s=>s.filePath),...o.map(s=>s.filePath)]),_=t=>Array.isArray(t)?`Object.freeze([${t.map(r=>_(r)).join(", ")}])`:t!==null&&typeof t=="object"?`Object.freeze({ ${Object.entries(t).map(([n,o])=>`${JSON.stringify(n)}: ${_(o)}`).join(", ")} })`:typeof t=="number"&&(!Number.isFinite(t)||Object.is(t,-0))?Object.is(t,-0)?"-0":String(t):JSON.stringify(t),P=t=>`${t}[functionPath]`,Ie=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
32
|
+
const registered = await loadFunction(functionPath);
|
|
33
|
+
|
|
34
|
+
if (!registered) {
|
|
35
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// A mutation is routed through the caller's own \`ctx.runMutation\` rather than
|
|
39
|
+
// invoked directly, so \`createCaller(ctx).ns.someMutation()\` gets exactly what
|
|
40
|
+
// \`ctx.runMutation(api.ns.someMutation)\` gets: the BEGIN/COMMIT span (or the
|
|
41
|
+
// enclosing one, when the caller is already inside a transaction), the jobs it
|
|
42
|
+
// schedules held until that span commits, and the deferred object deletes
|
|
43
|
+
// flushed only once it has. Called straight, a mutation composed from an action
|
|
44
|
+
// or a stream had none of the three — its writes autocommitted one row at a
|
|
45
|
+
// time and its \`ctx.scheduler\` calls dispatched immediately, so a mid-handler
|
|
46
|
+
// throw left the earlier writes durable and the job already enqueued.
|
|
47
|
+
//
|
|
48
|
+
// The fallback covers a context that is not a shard dispatch (\`runMutation\` is
|
|
49
|
+
// installed by \`buildCtx\` on every kind but a query's TYPE omits it); there is
|
|
50
|
+
// no transaction to join in that case, so a direct call is all there is.
|
|
51
|
+
//
|
|
52
|
+
// A query is routed through \`ctx.runQuery\` for the same reason: that is what
|
|
53
|
+
// hands it a query view of a mutation's or action's ctx (no request origin,
|
|
54
|
+
// query-guarded \`run*\`) instead of the caller's own.
|
|
55
|
+
if (registered.kind === "mutation" || registered.kind === "query") {
|
|
56
|
+
const run = (context as { runMutation?: unknown; runQuery?: unknown })[registered.kind === "mutation" ? "runMutation" : "runQuery"];
|
|
57
|
+
|
|
58
|
+
if (typeof run === "function") {
|
|
59
|
+
return (await run.call(context, { __lunoraRef: functionPath }, args ?? {})) as R;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return (await registered.handler(context, args ?? {})) as R;
|
|
64
|
+
};`,Ce=(t,r,n=[],o=[],s=!1)=>{const i=W(t,r,n,o),a=Q(t,r,n,o),c=[...i.entries()].filter(([e])=>!s||a.has(e)?!0:t.some(p=>p.filePath===e&&p.channel?.kind==="room")).map(([e,p])=>{if(!F.test(e))throw new L("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);return`import ${s&&!a.has(e)?"type ":""}* as ${p} from "../${e}.js";`}).join(`
|
|
65
|
+
`),u=t.map(e=>{if(!s||a.has(e.filePath))return` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`;const p=fe(e.args),w=JSON.stringify({argumentDescriptors:JSON.parse(D(e.args)),kind:e.kind,...p.length===0?{}:{sensitiveArgs:p},...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}}).slice(1,-1),k=e.meta===void 0?"":`, [Symbol.for("lunora.procedure.meta")]: ${_(e.meta)}`;return` "${g(e.filePath)}:${e.exportName}": { args: {}, handler: unloadedFunctionHandler, ${w}${k} } satisfies RegisteredLunoraFunction & Pick<FunctionManifestEntry, "argumentDescriptors" | "channel" | "expose">,`}).join(`
|
|
66
|
+
`),l=r.map(e=>` ${JSON.stringify(e.id)}: ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
67
|
+
`),d=n.map(e=>` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
68
|
+
`),f=o.map(e=>` "${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredShape,`).join(`
|
|
69
|
+
`),y=n.map(e=>`${g(e.filePath)}:${e.exportName}`),$=[...t.filter(e=>e.readsIp===!0).map(e=>`${g(e.filePath)}:${e.exportName}`),...o.filter(e=>e.readsIp===!0).map(e=>e.exportName)],R=[u,d].filter(e=>e.length>0).join(`
|
|
70
|
+
`),x=t.filter(e=>!s||a.has(e.filePath)).map(e=>{if(e.lifecycle||e.typeDerivedArgs||Object.keys(e.args).length===0)return;const p=H(e.args);return p===void 0?void 0:`installCompiledValidatorMap(${i.get(e.filePath)??""}.${e.exportName}.args, ${p});`}).filter(e=>e!==void 0).join(`
|
|
71
|
+
`),A=t.filter(e=>e.channel?.kind==="room").map(e=>` ${JSON.stringify(e.channel?.name??"")}: RoomMessageOf<typeof ${i.get(e.filePath)??""}[${JSON.stringify(e.exportName)}]>;`).join(`
|
|
72
|
+
`),v=[...t.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}`}))],O=s?v.filter(({definition:e})=>!a.has(e.filePath)):[];for(const{definition:e}of v)if(s&&e.x402&&e.x402.price===void 0)throw new L("INTERNAL",`@lunora/codegen: lazy function registry needs a literal \`.x402({ price })\` value in ${e.filePath}:${e.exportName}`);const m=s?O.map(({definition:e,path:p})=>{const w=i.get(e.filePath)??"",k="channel"in e?e.channel:void 0,N={argumentDescriptors:JSON.parse(D(e.args)),exportName:e.exportName,kind:e.kind,moduleId:w,...k?{channel:k}:{},...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(p)}: ${JSON.stringify(N)},`}).join(`
|
|
73
|
+
`):"",b=[...new Set(O.map(({definition:e})=>e.filePath))],S=s?b.map(e=>{if(!F.test(e))throw new L("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);const p=i.get(e)??"";return` ${JSON.stringify(p)}: () => import(${JSON.stringify(`./fn/${p}.js`)}),`}).join(`
|
|
74
|
+
`):"";return{dispatchBody:R.length>0?`
|
|
75
|
+
${R}
|
|
76
|
+
`:"",importBlock:c.length>0?`${c}
|
|
77
|
+
|
|
78
|
+
`:"",installBlock:x,manifestBody:m.length>0?`
|
|
79
|
+
${m}
|
|
80
|
+
`:"",migrationBody:l.length>0?`
|
|
81
|
+
${l}
|
|
82
|
+
`:"",moduleLoaders:S.length>0?`
|
|
83
|
+
${S}
|
|
84
|
+
`:"",ipReaderPaths:$,mutatorPaths:y,roomMessagesBody:A,shapeBody:f.length>0?`
|
|
85
|
+
${f}
|
|
86
|
+
`:""}},je=t=>{const r=C(t,o=>{const s=j(ye(o.args),o.filePath),i=s==="{}"?"?":"",a=j(ve(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${i}: ${s}) => Promise<AsyncIterable<${a}>>;`:`${o.exportName}: (args${i}: ${s}) => Promise<${a}>;`},"type");return{implementation:C(t,o=>`${$e(o.exportName)}: (args) => callRegistered(context, "${g(o.filePath)}:${o.exportName}", args),`,"value"),types:r}},De=t=>{const r={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of t)!n.lifecycle||n.lifecycle==="socket"||r[n.lifecycle].push(`${g(n.filePath)}:${n.exportName}`);return r},Ue=t=>{const r=new Map,n=[];for(const o of t){if(o.lifecycle!=="socket"||o.socket===void 0)continue;const{auth:s,origin:i,path:a}=o.socket,c=`${g(o.filePath)}:${o.exportName}`,u=r.get(a);if(!(u?.origin!==void 0&&u.origin===i)){if(u!==void 0)throw new L("DUPLICATE_SOCKET_PATH",`two defineWebSocket routes serve "${a}" (${u.functionPath} and ${c}); socket paths must be unique.`);r.set(a,{functionPath:c,origin:i}),n.push(` ${JSON.stringify(a)}: { auth: ${String(s)}, functionPath: ${JSON.stringify(c)} },`)}}return`
|
|
87
|
+
/**
|
|
88
|
+
* Socket registry: the URL path of each \`defineWebSocket\` route → its function path + auth requirement.
|
|
89
|
+
* Static, so building the worker never evaluates a route's module. The generated ShardDO's \`socketRoute\` override
|
|
90
|
+
* resolves an upgraded socket through this map.
|
|
91
|
+
*/
|
|
92
|
+
export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPath: string }>> = {
|
|
93
|
+
${n.join(`
|
|
94
|
+
`)}
|
|
95
|
+
};
|
|
96
|
+
`},Je=(t,r)=>{const n=t.some(c=>c.lifecycle==="socket"),s=n&&r?Ue(t):n&&!r?`
|
|
97
|
+
/**
|
|
98
|
+
* Socket registry: the URL path of each \`defineWebSocket\` route → its function
|
|
99
|
+
* path + auth requirement. The generated ShardDO's \`socketRoute\` override
|
|
100
|
+
* resolves an upgraded socket through this map so a route's typed
|
|
101
|
+
* \`onOpen\`/\`onMessage\`/\`onClose\` dispatch server-side under the socket's
|
|
102
|
+
* verified identity. Two routes on one path throw at module load rather than letting
|
|
103
|
+
* the map silently keep whichever came last.
|
|
104
|
+
*/
|
|
105
|
+
export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPath: string }>> = (() => {
|
|
106
|
+
const registry: Record<string, { auth: boolean; functionPath: string }> = {};
|
|
107
|
+
const owners = new Map<string, unknown>();
|
|
108
|
+
|
|
109
|
+
for (const [path, fn] of Object.entries(LUNORA_FUNCTIONS)) {
|
|
110
|
+
if (fn.lifecycle !== "socket" || typeof fn.socketPath !== "string") {
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const owner = owners.get(fn.socketPath);
|
|
115
|
+
|
|
116
|
+
// The same registration exported under two names (an alias) is one route.
|
|
117
|
+
if (owner !== undefined && owner !== fn) {
|
|
118
|
+
throw new Error(\`two defineWebSocket routes serve "\${fn.socketPath}"; socket paths must be unique\`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (owner === undefined) {
|
|
122
|
+
owners.set(fn.socketPath, fn);
|
|
123
|
+
registry[fn.socketPath] = { auth: fn.auth === true, functionPath: path };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return registry;
|
|
128
|
+
})();
|
|
129
|
+
`:"";return{fields:n?`
|
|
130
|
+
/**
|
|
131
|
+
* Set on a \`defineWebSocket\` registration: the URL path the route serves.
|
|
132
|
+
* The generated \`LUNORA_SOCKETS\` map keys it on this path so the ShardDO
|
|
133
|
+
* resolves an upgraded socket to this registration.
|
|
134
|
+
*/
|
|
135
|
+
socketPath?: string;
|
|
136
|
+
/**
|
|
137
|
+
* Set on a \`defineWebSocket\` registration: whether the route refuses an
|
|
138
|
+
* anonymous upgrade. Read into \`LUNORA_SOCKETS\` alongside \`socketPath\`.
|
|
139
|
+
*/
|
|
140
|
+
auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:s}},Be=(t,r,n)=>t?{channelField:` /**
|
|
141
|
+
* Set on a \`defineRoom\` registration: the room's name (without the \`room:\`
|
|
142
|
+
* topic prefix). The generated \`LUNORA_ROOMS\` map keys it on the room's
|
|
143
|
+
* \`room:<name>\` whisper topic so the ShardDO resolves a room topic to this
|
|
144
|
+
* path.
|
|
145
|
+
*/
|
|
146
|
+
channel?: { readonly kind: "room"; readonly name: string };
|
|
147
|
+
`,messagesBlock:`
|
|
148
|
+
/**
|
|
149
|
+
* The message type each \`defineRoom\` carries, read off the room's own registration. The generated \`rooms\` references type a client's \`connectRoom\` from it.
|
|
150
|
+
*/
|
|
151
|
+
export type LunoraRoomMessages = {
|
|
152
|
+
${n}
|
|
153
|
+
};
|
|
154
|
+
`,typeImport:`import type { RoomMessageOf } from "${r}";
|
|
155
|
+
`}:{channelField:"",messagesBlock:"",typeImport:""},qe=(t,r,n)=>t?r?`
|
|
156
|
+
/**
|
|
157
|
+
* Room routes are static metadata so building the worker never evaluates user handlers.
|
|
158
|
+
*/
|
|
159
|
+
export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
|
|
160
|
+
const registry: Record<string, string> = {};
|
|
161
|
+
const owners = new Map<string, string>();
|
|
162
|
+
|
|
163
|
+
for (const { owner, path, topic } of [
|
|
164
|
+
${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(`
|
|
165
|
+
`)}
|
|
166
|
+
]) {
|
|
167
|
+
const prior = owners.get(topic);
|
|
168
|
+
|
|
169
|
+
if (prior !== undefined && prior !== owner) {
|
|
170
|
+
throw new Error(\`two defineRoom registrations are named "\${topic.slice("room:".length)}"; room names must be unique\`);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (prior === undefined) {
|
|
174
|
+
owners.set(topic, owner);
|
|
175
|
+
registry[topic] = path;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return registry;
|
|
180
|
+
})();
|
|
181
|
+
`:`
|
|
182
|
+
/**
|
|
183
|
+
* Room registry: the whisper topic of each \`defineRoom\` registration → its
|
|
184
|
+
* function path. The generated ShardDO's \`roomHandlerPath\` override resolves a
|
|
185
|
+
* room topic through this map so a room's typed \`onJoin\`/\`onMessage\`/\`onLeave\`
|
|
186
|
+
* dispatch server-side, reusing the whisper channel for membership and fan-out.
|
|
187
|
+
* Two registrations under one name throw at module load: the map would otherwise
|
|
188
|
+
* silently keep whichever came last.
|
|
189
|
+
*/
|
|
190
|
+
export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
|
|
191
|
+
const registry: Record<string, string> = {};
|
|
192
|
+
const owners = new Map<string, unknown>();
|
|
193
|
+
|
|
194
|
+
for (const [path, fn] of Object.entries(LUNORA_FUNCTIONS)) {
|
|
195
|
+
if (fn.channel?.kind !== "room") {
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const topic = \`room:\${fn.channel.name}\`;
|
|
200
|
+
const owner = owners.get(topic);
|
|
201
|
+
|
|
202
|
+
// The same registration exported under two names (an alias) is one room.
|
|
203
|
+
if (owner !== undefined && owner !== fn) {
|
|
204
|
+
throw new Error(\`two defineRoom registrations are named "\${fn.channel.name}"; room names must be unique\`);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (owner === undefined) {
|
|
208
|
+
owners.set(topic, fn);
|
|
209
|
+
registry[topic] = path;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return registry;
|
|
214
|
+
})();
|
|
215
|
+
`:"",ze=(t,r)=>{const n=je(t),o=n.types?`
|
|
216
|
+
${n.types}
|
|
217
|
+
`:"",s=n.implementation?`
|
|
218
|
+
${n.implementation}
|
|
219
|
+
`:"",i=Ne(n.types),a=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
|
|
220
|
+
`:"",c=t.length>0?"context":"_context";let u="";if(t.length>0){let l=Ie;r||(l=l.replace("await loadFunction(functionPath)",P("LUNORA_FUNCTIONS"))),u=`${l}
|
|
221
|
+
|
|
222
|
+
`}return{callRegisteredHelper:u,dataModelImport:a,implementation:s,parameter:c,types:o}},Ye=t=>{const{agents:r=[],functions:n,lazyFunctions:o=!1,migrations:s=[],mutators:i=[],shapes:a=[],useUmbrella:c=!1,usesSandbox:u=!1}=t,l=J(c),{dispatchBody:d,importBlock:f,installBlock:y,ipReaderPaths:$,manifestBody:R,migrationBody:x,moduleLoaders:A,mutatorPaths:v,roomMessagesBody:O,shapeBody:m}=Ce(n,s,i,a,o),b=be(r,n),S=Re(u,n),e=r.length>0||n.some(h=>ge(h)),p=e?` /**
|
|
223
|
+
* Names of the arguments whose validators carry a \`v.sensitive\` marker. Read by the
|
|
224
|
+
* shard before any validator is loaded, so a lazy function's secret args are
|
|
225
|
+
* masked even on a dispatch that fails before its module evaluates.
|
|
226
|
+
*/
|
|
227
|
+
sensitiveArgs?: readonly string[];
|
|
228
|
+
`:"",w=[b.lines,S.lines].filter(h=>h.length>0).join(`
|
|
229
|
+
`);let k=d;w.length>0&&(k=d.length>0?`${d.trimEnd()}
|
|
230
|
+
${w}
|
|
231
|
+
`:`
|
|
232
|
+
${w}
|
|
233
|
+
`);const N=De(n),G=o?"await loadFunction(functionPath)":P("LUNORA_FUNCTIONS"),V=o?` if (${P("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
|
|
234
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
`:"",K=a.length>0?`import type { RegisteredShape } from "${l.server}";
|
|
238
|
+
`:"",M=n.some(h=>h.channel?.kind==="room"),T=Be(M,l.server,O),Y=a.length>0?`
|
|
239
|
+
/**
|
|
240
|
+
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
241
|
+
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
242
|
+
* evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
|
|
243
|
+
* \`shape_subscribe\` (reads-as-permissions).
|
|
244
|
+
*/
|
|
245
|
+
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${m}};
|
|
246
|
+
`:"",Z=v.length>0?`
|
|
247
|
+
/**
|
|
248
|
+
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
249
|
+
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
250
|
+
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
251
|
+
*/
|
|
252
|
+
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${v.map(h=>JSON.stringify(h)).join(", ")}]);
|
|
253
|
+
`:"",X=$.length>0?`
|
|
254
|
+
/**
|
|
255
|
+
* Queries and shapes that may read \`ctx.ip\`, decided statically (failing closed). The generated ShardDO marks them
|
|
256
|
+
* address-keyed from its first run, so it never resumes one warm: its rows can depend on the address the cursor
|
|
257
|
+
* was read at, which a claims fingerprint leaves out.
|
|
258
|
+
*/
|
|
259
|
+
export const LUNORA_IP_READER_PATHS: ReadonlySet<string> = new Set([${$.map(h=>JSON.stringify(h)).join(", ")}]);
|
|
260
|
+
`:"",ee=qe(M,o,n),{fields:te,lifecycleMember:I,registry:re}=Je(n,o),ne=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${l.values}";
|
|
261
|
+
`:"",oe=y.length>0?`
|
|
262
|
+
/**
|
|
263
|
+
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
264
|
+
* onto its function's live \`.args\` object and consulted by the interpreted
|
|
265
|
+
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
266
|
+
*/
|
|
267
|
+
${y}
|
|
268
|
+
`:"",se=ze(n,o),{callRegisteredHelper:ae,dataModelImport:ie,implementation:ce,parameter:le,types:de}=se,ue=Me(o),he=o?`
|
|
269
|
+
export interface FunctionManifestEntry {
|
|
270
|
+
argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; ${_e(e)}table?: string }>;
|
|
271
|
+
channel?: { kind: "room"; name: string };
|
|
272
|
+
exportName: string;
|
|
273
|
+
expose?: { cache?: { credentialHeaders?: ReadonlyArray<string>; maxAge: number; scope: "private" | "public"; staleWhileRevalidate?: number; tag?: string; vary?: string }; rest?: boolean };
|
|
274
|
+
kind: "action" | "mutation" | "query" | "stream";
|
|
275
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${I};
|
|
276
|
+
moduleId: string;
|
|
277
|
+
visibility?: "internal" | "public";
|
|
278
|
+
x402?: { readonly price: number | string };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Static, codegen-derived facts. Request gates can inspect these without evaluating a user module. */
|
|
282
|
+
export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${R}};
|
|
283
|
+
|
|
284
|
+
const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${A}};
|
|
285
|
+
const settledLoads = new Map<string, Promise<Record<string, unknown>>>();
|
|
286
|
+
const resolvedModules = new Map<string, Record<string, unknown>>();
|
|
287
|
+
const boundFunctions = new Set<string>();
|
|
288
|
+
const unloadedFunctionHandler = (): never => {
|
|
289
|
+
throw new Error("a lazy function was invoked before it was prepared");
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
/** Reuse an evaluated module synchronously, so dispatch does not yield after restoring request scope. */
|
|
293
|
+
export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunction | undefined => {
|
|
294
|
+
const registered = ${P("LUNORA_FUNCTIONS")};
|
|
295
|
+
const manifest = ${P("LUNORA_FUNCTION_MANIFEST")};
|
|
296
|
+
|
|
297
|
+
if (!registered || !manifest) {
|
|
298
|
+
return registered;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (boundFunctions.has(functionPath)) {
|
|
302
|
+
return registered;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const module = resolvedModules.get(manifest.moduleId);
|
|
306
|
+
|
|
307
|
+
if (module === undefined) {
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const loaded = module[manifest.exportName];
|
|
312
|
+
|
|
313
|
+
if (typeof loaded !== "object" || loaded === null) {
|
|
314
|
+
throw new Error(\`lazy module export for "\${functionPath}" is not a registered function\`);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
Object.assign(registered, loaded);
|
|
318
|
+
boundFunctions.add(functionPath);
|
|
319
|
+
|
|
320
|
+
return registered;
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
/** Load one function's owning module once per isolate, then merge its live builder result into the registry entry. */
|
|
324
|
+
export const loadFunction = async (functionPath: string): Promise<RegisteredLunoraFunction | undefined> => {
|
|
325
|
+
const registered = getLoadedFunction(functionPath);
|
|
326
|
+
const manifest = ${P("LUNORA_FUNCTION_MANIFEST")};
|
|
327
|
+
|
|
328
|
+
if (registered || !manifest) {
|
|
329
|
+
return registered;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Only a SETTLED load is shared. An in-flight one is not: a Durable Object holds its other events
|
|
333
|
+
// back while a cold load runs (\`holdShardWhileLoading\`), and workerd only lets through I/O that
|
|
334
|
+
// began inside that hold, so awaiting an import another request started would wait out the hold's
|
|
335
|
+
// timeout and reset the object. A second \`import()\` still evaluates the module only once.
|
|
336
|
+
let pending = settledLoads.get(manifest.moduleId);
|
|
337
|
+
|
|
338
|
+
if (pending === undefined) {
|
|
339
|
+
const loader = MODULE_LOADERS[manifest.moduleId];
|
|
340
|
+
|
|
341
|
+
if (loader === undefined) {
|
|
342
|
+
throw new Error(\`no lazy module loader registered for "\${functionPath}"\`);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const started = loader();
|
|
346
|
+
const settle = (): void => {
|
|
347
|
+
if (!settledLoads.has(manifest.moduleId)) {
|
|
348
|
+
settledLoads.set(manifest.moduleId, started);
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
started.then(settle, settle);
|
|
353
|
+
pending = started;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// A module that failed to evaluate stays failed for the isolate: the runtime has already cached
|
|
357
|
+
// the failed evaluation, and a bundler's lazy initializer can hand a retry a half-initialized
|
|
358
|
+
// namespace, so every later call rethrows the original error instead.
|
|
359
|
+
resolvedModules.set(manifest.moduleId, await pending);
|
|
360
|
+
|
|
361
|
+
return getLoadedFunction(functionPath);
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
`:"",me=o&&R!==""?`
|
|
365
|
+
/**
|
|
366
|
+
* Evaluate every lazy module now and report the ones that fail, keyed by function path. A lazy
|
|
367
|
+
* registry defers a broken module's error to its first call; \`lunora build\` and \`deploy\` run this
|
|
368
|
+
* inside workerd so the error surfaces before the Worker ships instead of in front of a user.
|
|
369
|
+
*/
|
|
370
|
+
export const loadAllFunctions = async (): Promise<{ checked: number; failures: ReadonlyArray<{ functionPath: string; message: string }> }> => {
|
|
371
|
+
const functionPaths = Object.keys(LUNORA_FUNCTION_MANIFEST);
|
|
372
|
+
// Concurrent, so the total is bounded by the slowest module rather than by all of them added up. A module
|
|
373
|
+
// shared by several functions is evaluated once (the module registry dedupes concurrent imports), and failures keep manifest order.
|
|
374
|
+
const failures = (
|
|
375
|
+
await Promise.all(
|
|
376
|
+
functionPaths.map(async (functionPath) => {
|
|
377
|
+
try {
|
|
378
|
+
await loadFunction(functionPath);
|
|
379
|
+
|
|
380
|
+
return undefined;
|
|
381
|
+
} catch (error) {
|
|
382
|
+
return { functionPath, message: error instanceof Error ? error.message : String(error) };
|
|
383
|
+
}
|
|
384
|
+
}),
|
|
385
|
+
)
|
|
386
|
+
).filter((failure) => failure !== undefined);
|
|
387
|
+
|
|
388
|
+
return { checked: functionPaths.length, failures };
|
|
389
|
+
};
|
|
390
|
+
`:"";return ke(`${U}${f}${b.importLine}${S.importLine}${ne}${K}${T.typeImport}import { LunoraError } from "${l.server}";
|
|
391
|
+
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
392
|
+
${ie}
|
|
393
|
+
/**
|
|
394
|
+
* Single registered function, narrowed to the shape \`handleRpc\` needs.
|
|
395
|
+
* The real argument validators / return types are checked elsewhere — at
|
|
396
|
+
* the dispatch site we erase to \`unknown\` so a single map can host every
|
|
397
|
+
* registered function.
|
|
398
|
+
*/
|
|
399
|
+
export interface RegisteredLunoraFunction {
|
|
400
|
+
kind: "action" | "mutation" | "query" | "stream";
|
|
401
|
+
args: Record<string, unknown>;
|
|
402
|
+
/**
|
|
403
|
+
* Present on a \`"stream"\` declared \`durable\`: its run is persisted and
|
|
404
|
+
* survives the socket that opened it. Absent on every other kind, and on an
|
|
405
|
+
* ephemeral stream.
|
|
406
|
+
*/
|
|
407
|
+
durable?: { ttlMs?: number };
|
|
408
|
+
/**
|
|
409
|
+
* For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
|
|
410
|
+
* For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
|
|
411
|
+
* \`AbortSignal\` as a third argument — the runtime drives it frame-by-frame.
|
|
412
|
+
*/
|
|
413
|
+
handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
|
|
414
|
+
/**
|
|
415
|
+
* The lifecycle moment a hook fires on, when this registration came from
|
|
416
|
+
* \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`/\`onWhisper\`.
|
|
417
|
+
* Read at dispatch to decide whether the function runs system-trusted:
|
|
418
|
+
* \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
|
|
419
|
+
* to. \`whisper\` does have one — it runs under the asking socket's identity.
|
|
420
|
+
*/
|
|
421
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${I};${te}
|
|
422
|
+
${T.channelField} /**
|
|
423
|
+
* Hoisted by the builder when the \`.use()\` chain carries a step with a
|
|
424
|
+
* per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
|
|
425
|
+
* captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
|
|
426
|
+
* inside the dispatch callback, and a reactive-cache HIT skips that
|
|
427
|
+
* callback, so such a query must never be memoized.
|
|
428
|
+
*/
|
|
429
|
+
perDispatch?: boolean;
|
|
430
|
+
/** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
|
|
431
|
+
visibility?: "internal" | "public";
|
|
432
|
+
/**
|
|
433
|
+
* \`.x402({ price })\` tag on a paid public procedure. The origin worker
|
|
434
|
+
* paywalls it; the shard refuses to subscribe it (\`isPaidFunction\`).
|
|
435
|
+
*/
|
|
436
|
+
x402?: { readonly price: number | string };
|
|
437
|
+
${ue}${p}}
|
|
438
|
+
${b.prelude}${S.prelude}${he}${me}
|
|
439
|
+
/**
|
|
440
|
+
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
441
|
+
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
442
|
+
*/
|
|
443
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${k}};
|
|
444
|
+
${oe}${Y}${Z}${X}${ee}${T.messagesBlock}${re}
|
|
445
|
+
/**
|
|
446
|
+
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
447
|
+
* client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
|
|
448
|
+
* per Durable Object instance before any handler runs (\`init\`), after a
|
|
449
|
+
* write flush when a watched read's result changed (\`reactor\`), and before a
|
|
450
|
+
* socket joins or broadcasts to a whisper topic (\`whisper\`). Each path also
|
|
451
|
+
* resolves through {@link LUNORA_FUNCTIONS}. The socket-scoped moments run under
|
|
452
|
+
* the socket's verified identity; \`init\` and \`reactor\` have no caller, so they
|
|
453
|
+
* run anonymous — all via system dispatch.
|
|
454
|
+
*/
|
|
455
|
+
export const LUNORA_LIFECYCLE_HOOKS: {
|
|
456
|
+
connect: readonly string[];
|
|
457
|
+
disconnect: readonly string[];
|
|
458
|
+
init: readonly string[];
|
|
459
|
+
reactor: readonly string[];
|
|
460
|
+
whisper: readonly string[];
|
|
461
|
+
} = {
|
|
462
|
+
connect: [${N.connect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
463
|
+
disconnect: [${N.disconnect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
464
|
+
init: [${N.init.map(h=>JSON.stringify(h)).join(", ")}],
|
|
465
|
+
reactor: [${N.reactor.map(h=>JSON.stringify(h)).join(", ")}],
|
|
466
|
+
whisper: [${N.whisper.map(h=>JSON.stringify(h)).join(", ")}],
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Resolve and invoke a registered function from an external caller. Throws a
|
|
471
|
+
* LunoraError-shaped object (404) when the path is unknown — the runtime's
|
|
472
|
+
* structural error mapper turns that into the right HTTP status. Internal
|
|
473
|
+
* functions are treated as not-found so their existence never leaks to clients.
|
|
474
|
+
*/
|
|
475
|
+
export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
|
|
476
|
+
${V} const registered = ${G};
|
|
477
|
+
|
|
478
|
+
if (!registered || registered.visibility === "internal") {
|
|
479
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
return registered.handler(context, args);
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* A handler context accepted by {@link createCaller}. The runtime context the
|
|
487
|
+
* shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
|
|
488
|
+
*/
|
|
489
|
+
export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Typed, in-process server-to-server caller. Every registered function — public
|
|
493
|
+
* *and* internal — is reachable; each call dispatches against the same shard
|
|
494
|
+
* with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
|
|
495
|
+
* \`runAction\` but without re-stating the function path.
|
|
496
|
+
*/
|
|
497
|
+
export interface Caller {${de}}
|
|
498
|
+
|
|
499
|
+
${ae}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
500
|
+
export const createCaller = (${le}: CallerCtx): Caller => ({${ce}});
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Single registered data migration, narrowed to the shape the per-shard runner
|
|
504
|
+
* consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
|
|
505
|
+
* validation lives in \`defineMigration\`.
|
|
506
|
+
*/
|
|
507
|
+
export interface RegisteredDataMigration {
|
|
508
|
+
batchSize?: number;
|
|
509
|
+
down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
|
|
510
|
+
id: string;
|
|
511
|
+
table: string;
|
|
512
|
+
up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
|
|
517
|
+
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
518
|
+
*/
|
|
519
|
+
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${x}};
|
|
520
|
+
`,c)},Ze="fn",Xe=t=>{if(t.lazyFunctions!==!0)return{};const{functions:r}=t,n=t.migrations??[],o=t.mutators??[],s=t.shapes??[],i=W(r,n,o,s),a=Q(r,n,o,s),c=[...new Set(r.filter(d=>!a.has(d.filePath)).map(d=>d.filePath))],u=J(t.useUmbrella??!1),l={};for(const d of c){if(!F.test(d))throw new L("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(d)}`);const f=i.get(d)??"",y=`../../${d}.js`,$=r.filter(m=>m.filePath===d&&!m.lifecycle&&Object.keys(m.args).length>0).flatMap(m=>{const b=H(m.args);return b===void 0?[]:[`installCompiledValidatorMap(${f}.${m.exportName}.args, ${b});`]}),R=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
|
|
521
|
+
`:"",x=$.length>0?`import * as ${f} from "${y}";
|
|
522
|
+
`:"",A=$.length>0?`
|
|
523
|
+
/** Install the precompiled argument parsers before the module is dispatched. */
|
|
524
|
+
${$.join(`
|
|
525
|
+
`)}
|
|
526
|
+
`:"",O=r.some(m=>m.filePath===d&&m.exportName==="default")||n.some(m=>m.filePath===d&&m.exportName==="default")?`export { default } from "${y}";
|
|
527
|
+
`:"";l[`${f}.ts`]=`${U}${R}${x}${A}export * from "${y}";
|
|
528
|
+
${O}`}return l};export{Ze as LAZY_FUNCTION_DIRECTORY,Ye as emitFunctions,Xe as emitLazyFunctionModules};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{e}from"./server-Dfxmm5Zw.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-CWAD5mYy.mjs";import"./shard-runtime-G5mZQjY0.mjs";import"./shared-Cn7dMQ_u.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{j as t,h as c}from"./attribution-Cwt30DDJ.mjs";import{c as n}from"./classify-procedure-call-BmEirzc_.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-Uwb5a6Kq.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 d}from"@lunora/advisor";const t=n=>n===void 0?{}:{file:n.file,line:n.line},m=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique,...t(e.site)})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name,...t(e.site)})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name,...t(e.site)})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name,...t(e.site)})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name,...t(e.site)}))],c=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},u=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,...t(e.site),columnKinds:c(e),fields:Object.keys(e.shape),indexes:m(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},...t(r.site)}:{...t(r.site),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}))}),f=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,table:e.table})),h=n=>n.map(e=>({exportName:e.exportName,file:e.filePath,line:e.line})),p=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,owner:e.owner})),v=n=>{const{argumentValidators:e,mutators:r,queries:s,schema:i,shapes:o,topics:a,...l}=n;return{...l,argValidators:e,mutators:r===void 0?void 0:p(r),queries:s??[],schema:u(i),shapes:o===void 0?void 0:f(o),topics:a===void 0?void 0:h(a)}},S=n=>d(v(n),{source:"static"}),x=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{x as formatAdvisories,S as lintSchema,v 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-Uwb5a6Kq.mjs";import{r as v,h}from"./attribution-Cwt30DDJ.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(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=h(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,declarationLineOf as m}from"./isTestPath-Uwb5a6Kq.mjs";import{j as p,h as d}from"./attribution-Cwt30DDJ.mjs";import{t as g}from"./database-calls-d-Sssc-3.mjs";import{w as h,c as k}from"./classify-procedure-call-BmEirzc_.mjs";import{a as v}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return v(e)},P=e=>h(e,"use","mask"),E=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"},y=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},C=e=>{const s=P(e);return{maskColumns:s.flatMap(t=>y(t)),usesMask:s.length>0}},M=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),x=new Set(["delete","insert","patch","replace"]),A=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=k(t);if(!i)return;const o=i.receiver?C(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=g(e,M,x);return{exportName:d(e)??e.getName(),file:s,line:m(e),maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},z=(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 p(o)){const c=A(a,n);c&&t.push(c)}}return t};export{l as a,z as d,P as m,E as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-Uwb5a6Kq.mjs";import{e as K,i as O}from"./attribution-Cwt30DDJ.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-DvbyiLjc.mjs";import{m as J}from"./ip-reads-D2qhKEb6.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-BmEirzc_.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DR7xrrNB.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
|