@lunora/codegen 1.0.0-alpha.384 → 1.0.0-alpha.386
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +32 -6
- package/dist/index.d.ts +32 -6
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-Bzf6ZJ9r.mjs → GENERATED_HEADER-B-tYRlRG.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-DlSftsvY.mjs → MUTATORS_FILENAME-D9WbOFm7.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-SKk8x0VM.mjs → NOTIFY_FILENAME-CRU_TEKs.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-CSjT8wJW.mjs → OPENRPC_VERSION-CT_E2DcI.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DqUXDvki.mjs +31 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
- package/dist/packem_shared/{SHAPES_FILENAME-rSSihffV.mjs → SHAPES_FILENAME-D9beIrs1.mjs} +1 -1
- package/dist/packem_shared/{SchemaSnapshotParseError-ycDz8gOB.mjs → SchemaSnapshotParseError-DnAuFdpl.mjs} +8 -8
- package/dist/packem_shared/{buildOpenApiDocument-afHH7rN5.mjs → buildOpenApiDocument-67-fasdW.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-CYaejv5r.mjs → context-property-calls-ZK1UcTQR.mjs} +1 -1
- package/dist/packem_shared/{context-root-TiLodrRO.mjs → context-root-DtpwprsY.mjs} +1 -1
- package/dist/packem_shared/{database-calls-QqsrkDMs.mjs → database-calls-Cn47SfSU.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-DdHysjy1.mjs → discoverFunctions-DU5ylqVC.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-5iA7gI_Q.mjs → discoverHttpRoutes-D9Q0lBBb.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DlyCZKX3.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-Dw7fvL7s.mjs → discoverInserts-7Xdawmuk.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-D6kAKDZG.mjs +1 -0
- package/dist/packem_shared/{discoverQueries-DVFZJER7.mjs → discoverQueries-C75OdGHl.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-BrDIti5c.mjs +1 -0
- package/dist/packem_shared/{discoverRlsProcedures-C2lkSLPn.mjs → discoverRlsProcedures-BiyDg2ej.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-Bs5JUiOE.mjs +1 -0
- package/dist/packem_shared/{emitAgents-BeM6PZv4.mjs → emitAgents-iTKWSKan.mjs} +1 -1
- package/dist/packem_shared/{emitApi-GFmStqmq.mjs → emitApi-DWJW8Vu9.mjs} +1 -1
- package/dist/packem_shared/{emitApp-D-6FIpYb.mjs → emitApp-L7PnfjJK.mjs} +1 -1
- package/dist/packem_shared/{emitCrons-Drdn8Mjn.mjs → emitCrons-BvqxeNRr.mjs} +1 -1
- package/dist/packem_shared/{emitDataModel-LTnwnhV6.mjs → emitDataModel-MjAOi3KM.mjs} +1 -1
- package/dist/packem_shared/{emitDrizzleSchema-CM9jh_F0.mjs → emitDrizzleSchema-Dszoyymv.mjs} +1 -1
- package/dist/packem_shared/{emitFunctions-DRAuiKPv.mjs → emitFunctions-C4PzKb4H.mjs} +84 -80
- package/dist/packem_shared/{emitServer-4l7MPmK0.mjs → emitServer-BgI9yXW1.mjs} +1 -1
- package/dist/packem_shared/emitShard-D4sAFu7Z.mjs +1 -0
- package/dist/packem_shared/{index-iw3axJ5Y.mjs → index-CNI4vSyc.mjs} +1 -1
- package/dist/packem_shared/index-o449rQLQ.mjs +1 -0
- package/dist/packem_shared/{ip-reads-BVXbFgzV.mjs → ip-reads-Dotjify6.mjs} +1 -1
- package/dist/packem_shared/{qualifiers-D1Q_3wo2.mjs → qualifiers-ClaCHu0X.mjs} +1 -1
- package/dist/packem_shared/{server-D69SOfX8.mjs → server-qWq5nN-R.mjs} +1 -1
- package/dist/packem_shared/{shard-L3gYZnC9.mjs → shard-BqfSKnmG.mjs} +1 -1
- package/dist/packem_shared/{shard-runtime-lkQU8trx.mjs → shard-runtime-C1P_uVye.mjs} +1 -1
- package/dist/packem_shared/{shared-A1XHcT4t.mjs → shared-DhqnD5R3.mjs} +6 -6
- package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +1 -0
- package/dist/packem_shared/{unwrap-handler-return-eQRIZSOX.mjs → unwrap-handler-return-c2s2-nk9.mjs} +1 -1
- package/package.json +8 -8
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Dle_pfr9.mjs +0 -31
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs +0 -2
- package/dist/packem_shared/discoverHyperdriveCalls-BJRaIvLx.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-BLKjuD-A.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-BEBdqXi_.mjs +0 -1
- package/dist/packem_shared/discoverSchema-Cycd1-H0.mjs +0 -1
- package/dist/packem_shared/emitShard-DqEvyZPZ.mjs +0 -1
- package/dist/packem_shared/index-BhsJzv9r.mjs +0 -1
|
@@ -1,30 +1,34 @@
|
|
|
1
|
-
import{LunoraError as L}from"@lunora/errors";import{L as pe,
|
|
2
|
-
`;case"boolean":return`if (typeof ${
|
|
3
|
-
`;case"date":case"number":case"timestamp":return`if (typeof ${
|
|
4
|
-
`;case"null":return`if (${
|
|
5
|
-
`;default:return`if (typeof ${
|
|
6
|
-
`}},
|
|
7
|
-
`,
|
|
8
|
-
`}},
|
|
9
|
-
const ${i} = new Array(${
|
|
10
|
-
for (let ${
|
|
11
|
-
const ${c} = ${
|
|
12
|
-
${u.pre}${i}[${
|
|
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-DhqnD5R3.mjs";import{v as we}from"./parse-validator-BisfC8bR.mjs";import{renderAgentFunctionRegistry as Re,renderSandboxFunctionRegistry as be}from"./emitApi-DWJW8Vu9.mjs";import{b as ke,a as Ne,r as j,c as ve}from"./qualifiers-ClaCHu0X.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
13
|
}
|
|
14
|
-
`;return{out:i,pre:l}},
|
|
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
15
|
let ${d};
|
|
16
16
|
if (${n} !== undefined) {
|
|
17
17
|
${c.pre}${d} = ${c.out};
|
|
18
18
|
${l} = true;
|
|
19
19
|
}
|
|
20
|
-
`;return{entry:`...(${l} ? { ${
|
|
21
|
-
`,u=d}const l=
|
|
22
|
-
`},
|
|
23
|
-
${
|
|
24
|
-
`;return{out:
|
|
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)),z=(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}},q=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=z(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
|
+
${q(r)}${s.pre}const ${a} = { ${s.entries} };
|
|
24
|
+
`;return{out:a,pre:c}},H=t=>{let r=0;const o=z(t,"source",{next:()=>(r+=1,r)});if(o)return`(source) => {
|
|
25
25
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
26
|
-
${
|
|
27
|
-
}`},
|
|
26
|
+
${q("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}}})),Me=t=>t?"sensitive?: true; ":"",_e=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)]),M=t=>Array.isArray(t)?`Object.freeze([${t.map(r=>M(r)).join(", ")}])`:t!==null&&typeof t=="object"?`Object.freeze({ ${Object.entries(t).map(([n,o])=>`${JSON.stringify(n)}: ${M(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> => {
|
|
28
32
|
const registered = await loadFunction(functionPath);
|
|
29
33
|
|
|
30
34
|
if (!registered) {
|
|
@@ -57,29 +61,29 @@ ${H("source")}${o.pre}return { ${o.entries} };
|
|
|
57
61
|
}
|
|
58
62
|
|
|
59
63
|
return (await registered.handler(context, args ?? {})) as R;
|
|
60
|
-
};`,
|
|
61
|
-
`),u=
|
|
62
|
-
`),l=
|
|
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")]: ${M(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(`
|
|
63
67
|
`),d=n.map(e=>` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
64
68
|
`),f=o.map(e=>` "${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredShape,`).join(`
|
|
65
|
-
`),y=n.map(e=>`${g(e.filePath)}:${e.exportName}`),$=[...
|
|
66
|
-
`),
|
|
67
|
-
`),
|
|
68
|
-
`),v=[...
|
|
69
|
-
`):"",
|
|
70
|
-
`):"";return{dispatchBody:
|
|
71
|
-
${
|
|
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)],b=[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
|
+
`):"",R=[...new Set(O.map(({definition:e})=>e.filePath))],S=s?R.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:b.length>0?`
|
|
75
|
+
${b}
|
|
72
76
|
`:"",importBlock:c.length>0?`${c}
|
|
73
77
|
|
|
74
|
-
`:"",installBlock:
|
|
75
|
-
${
|
|
78
|
+
`:"",installBlock:x,manifestBody:m.length>0?`
|
|
79
|
+
${m}
|
|
76
80
|
`:"",migrationBody:l.length>0?`
|
|
77
81
|
${l}
|
|
78
|
-
`:"",moduleLoaders:
|
|
79
|
-
${
|
|
80
|
-
`:"",ipReaderPaths:$,mutatorPaths:y,roomMessagesBody:
|
|
82
|
+
`:"",moduleLoaders:S.length>0?`
|
|
83
|
+
${S}
|
|
84
|
+
`:"",ipReaderPaths:$,mutatorPaths:y,roomMessagesBody:A,shapeBody:f.length>0?`
|
|
81
85
|
${f}
|
|
82
|
-
`:""}},
|
|
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`
|
|
83
87
|
/**
|
|
84
88
|
* Socket registry: the URL path of each \`defineWebSocket\` route → its function path + auth requirement.
|
|
85
89
|
* Static, so building the worker never evaluates a route's module. The generated ShardDO's \`socketRoute\` override
|
|
@@ -89,7 +93,7 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
|
|
|
89
93
|
${n.join(`
|
|
90
94
|
`)}
|
|
91
95
|
};
|
|
92
|
-
`},
|
|
96
|
+
`},Je=(t,r)=>{const n=t.some(c=>c.lifecycle==="socket"),s=n&&r?Ue(t):n&&!r?`
|
|
93
97
|
/**
|
|
94
98
|
* Socket registry: the URL path of each \`defineWebSocket\` route → its function
|
|
95
99
|
* path + auth requirement. The generated ShardDO's \`socketRoute\` override
|
|
@@ -133,7 +137,7 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
|
|
|
133
137
|
* Set on a \`defineWebSocket\` registration: whether the route refuses an
|
|
134
138
|
* anonymous upgrade. Read into \`LUNORA_SOCKETS\` alongside \`socketPath\`.
|
|
135
139
|
*/
|
|
136
|
-
auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:
|
|
140
|
+
auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:s}},Be=(t,r,n)=>t?{channelField:` /**
|
|
137
141
|
* Set on a \`defineRoom\` registration: the room's name (without the \`room:\`
|
|
138
142
|
* topic prefix). The generated \`LUNORA_ROOMS\` map keys it on the room's
|
|
139
143
|
* \`room:<name>\` whisper topic so the ShardDO resolves a room topic to this
|
|
@@ -147,8 +151,8 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
|
|
|
147
151
|
export type LunoraRoomMessages = {
|
|
148
152
|
${n}
|
|
149
153
|
};
|
|
150
|
-
`,typeImport:`import type { RoomMessageOf } from "${
|
|
151
|
-
`}:{channelField:"",messagesBlock:"",typeImport:""},
|
|
154
|
+
`,typeImport:`import type { RoomMessageOf } from "${r}";
|
|
155
|
+
`}:{channelField:"",messagesBlock:"",typeImport:""},ze=(t,r,n)=>t?r?`
|
|
152
156
|
/**
|
|
153
157
|
* Room routes are static metadata so building the worker never evaluates user handlers.
|
|
154
158
|
*/
|
|
@@ -208,37 +212,37 @@ export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
|
|
|
208
212
|
|
|
209
213
|
return registry;
|
|
210
214
|
})();
|
|
211
|
-
`:"",
|
|
215
|
+
`:"",qe=(t,r)=>{const n=je(t),o=n.types?`
|
|
212
216
|
${n.types}
|
|
213
|
-
`:"",
|
|
217
|
+
`:"",s=n.implementation?`
|
|
214
218
|
${n.implementation}
|
|
215
|
-
`:"",i=
|
|
216
|
-
`:"",c=
|
|
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}
|
|
217
221
|
|
|
218
|
-
`}return{callRegisteredHelper:u,dataModelImport:
|
|
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:b,migrationBody:x,moduleLoaders:A,mutatorPaths:v,roomMessagesBody:O,shapeBody:m}=Ce(n,s,i,a,o),R=Re(r,n),S=be(u,n),e=r.length>0||n.some(h=>ge(h)),p=e?` /**
|
|
219
223
|
* Names of the arguments whose validators carry a \`v.sensitive\` marker. Read by the
|
|
220
224
|
* shard before any validator is loaded, so a lazy function's secret args are
|
|
221
225
|
* masked even on a dispatch that fails before its module evaluates.
|
|
222
226
|
*/
|
|
223
227
|
sensitiveArgs?: readonly string[];
|
|
224
|
-
`:"",
|
|
225
|
-
`);let
|
|
226
|
-
${
|
|
228
|
+
`:"",w=[R.lines,S.lines].filter(h=>h.length>0).join(`
|
|
229
|
+
`);let k=d;w.length>0&&(k=d.length>0?`${d.trimEnd()}
|
|
230
|
+
${w}
|
|
227
231
|
`:`
|
|
228
|
-
${
|
|
229
|
-
`);const
|
|
232
|
+
${w}
|
|
233
|
+
`);const N=De(n),G=o?"await loadFunction(functionPath)":P("LUNORA_FUNCTIONS"),V=o?` if (${P("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
|
|
230
234
|
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
231
235
|
}
|
|
232
236
|
|
|
233
|
-
`:"",K=
|
|
234
|
-
`:"",
|
|
237
|
+
`:"",K=a.length>0?`import type { RegisteredShape } from "${l.server}";
|
|
238
|
+
`:"",_=n.some(h=>h.channel?.kind==="room"),T=Be(_,l.server,O),Y=a.length>0?`
|
|
235
239
|
/**
|
|
236
240
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
237
241
|
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
238
242
|
* evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
|
|
239
243
|
* \`shape_subscribe\` (reads-as-permissions).
|
|
240
244
|
*/
|
|
241
|
-
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${
|
|
245
|
+
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${m}};
|
|
242
246
|
`:"",Z=v.length>0?`
|
|
243
247
|
/**
|
|
244
248
|
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
@@ -253,7 +257,7 @@ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${v.map(h=>JSO
|
|
|
253
257
|
* was read at, which a claims fingerprint leaves out.
|
|
254
258
|
*/
|
|
255
259
|
export const LUNORA_IP_READER_PATHS: ReadonlySet<string> = new Set([${$.map(h=>JSON.stringify(h)).join(", ")}]);
|
|
256
|
-
`:"",ee=
|
|
260
|
+
`:"",ee=ze(_,o,n),{fields:te,lifecycleMember:I,registry:re}=Je(n,o),ne=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${l.values}";
|
|
257
261
|
`:"",oe=y.length>0?`
|
|
258
262
|
/**
|
|
259
263
|
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
@@ -261,23 +265,23 @@ export const LUNORA_IP_READER_PATHS: ReadonlySet<string> = new Set([${$.map(h=>J
|
|
|
261
265
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
262
266
|
*/
|
|
263
267
|
${y}
|
|
264
|
-
`:"",se=
|
|
268
|
+
`:"",se=qe(n,o),{callRegisteredHelper:ae,dataModelImport:ie,implementation:ce,parameter:le,types:de}=se,ue=_e(o),he=o?`
|
|
265
269
|
export interface FunctionManifestEntry {
|
|
266
|
-
argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; table?: string }>;
|
|
270
|
+
argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; ${Me(e)}table?: string }>;
|
|
267
271
|
channel?: { kind: "room"; name: string };
|
|
268
272
|
exportName: string;
|
|
269
273
|
expose?: { cache?: { credentialHeaders?: ReadonlyArray<string>; maxAge?: number; scope?: "private" | "public"; staleWhileRevalidate?: number; tag?: string; vary?: string }; rest?: boolean };
|
|
270
274
|
kind: "action" | "mutation" | "query" | "stream";
|
|
271
|
-
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${
|
|
275
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${I};
|
|
272
276
|
moduleId: string;
|
|
273
277
|
visibility?: "internal" | "public";
|
|
274
278
|
x402?: { readonly price: number | string };
|
|
275
279
|
}
|
|
276
280
|
|
|
277
281
|
/** Static, codegen-derived facts. Request gates can inspect these without evaluating a user module. */
|
|
278
|
-
export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${
|
|
282
|
+
export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${b}};
|
|
279
283
|
|
|
280
|
-
const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${
|
|
284
|
+
const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${A}};
|
|
281
285
|
const loadedModules = new Map<string, Promise<Record<string, unknown>>>();
|
|
282
286
|
const resolvedModules = new Map<string, Record<string, unknown>>();
|
|
283
287
|
const boundFunctions = new Set<string>();
|
|
@@ -287,8 +291,8 @@ const unloadedFunctionHandler = (): never => {
|
|
|
287
291
|
|
|
288
292
|
/** Reuse an evaluated module synchronously, so dispatch does not yield after restoring request scope. */
|
|
289
293
|
export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunction | undefined => {
|
|
290
|
-
const registered = ${
|
|
291
|
-
const manifest = ${
|
|
294
|
+
const registered = ${P("LUNORA_FUNCTIONS")};
|
|
295
|
+
const manifest = ${P("LUNORA_FUNCTION_MANIFEST")};
|
|
292
296
|
|
|
293
297
|
if (!registered || !manifest) {
|
|
294
298
|
return registered;
|
|
@@ -319,7 +323,7 @@ export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunctio
|
|
|
319
323
|
/** Load one function's owning module once per isolate, then merge its live builder result into the registry entry. */
|
|
320
324
|
export const loadFunction = async (functionPath: string): Promise<RegisteredLunoraFunction | undefined> => {
|
|
321
325
|
const registered = getLoadedFunction(functionPath);
|
|
322
|
-
const manifest = ${
|
|
326
|
+
const manifest = ${P("LUNORA_FUNCTION_MANIFEST")};
|
|
323
327
|
|
|
324
328
|
if (registered || !manifest) {
|
|
325
329
|
return registered;
|
|
@@ -346,7 +350,7 @@ export const loadFunction = async (functionPath: string): Promise<RegisteredLuno
|
|
|
346
350
|
return getLoadedFunction(functionPath);
|
|
347
351
|
};
|
|
348
352
|
|
|
349
|
-
`:"",
|
|
353
|
+
`:"",me=o&&b!==""?`
|
|
350
354
|
/**
|
|
351
355
|
* Evaluate every lazy module now and report the ones that fail, keyed by function path. A lazy
|
|
352
356
|
* registry defers a broken module's error to its first call; \`lunora build\` and \`deploy\` run this
|
|
@@ -372,7 +376,7 @@ export const loadAllFunctions = async (): Promise<{ checked: number; failures: R
|
|
|
372
376
|
|
|
373
377
|
return { checked: functionPaths.length, failures };
|
|
374
378
|
};
|
|
375
|
-
`:"";return
|
|
379
|
+
`:"";return ke(`${U}${f}${R.importLine}${S.importLine}${ne}${K}${T.typeImport}import { LunoraError } from "${l.server}";
|
|
376
380
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
377
381
|
${ie}
|
|
378
382
|
/**
|
|
@@ -403,7 +407,7 @@ export interface RegisteredLunoraFunction {
|
|
|
403
407
|
* \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
|
|
404
408
|
* to. \`whisper\` does have one — it runs under the asking socket's identity.
|
|
405
409
|
*/
|
|
406
|
-
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${
|
|
410
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${I};${te}
|
|
407
411
|
${T.channelField} /**
|
|
408
412
|
* Hoisted by the builder when the \`.use()\` chain carries a step with a
|
|
409
413
|
* per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
|
|
@@ -419,13 +423,13 @@ ${T.channelField} /**
|
|
|
419
423
|
* paywalls it; the shard refuses to subscribe it (\`isPaidFunction\`).
|
|
420
424
|
*/
|
|
421
425
|
x402?: { readonly price: number | string };
|
|
422
|
-
${
|
|
423
|
-
${
|
|
426
|
+
${ue}${p}}
|
|
427
|
+
${R.prelude}${S.prelude}${he}${me}
|
|
424
428
|
/**
|
|
425
429
|
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
426
430
|
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
427
431
|
*/
|
|
428
|
-
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${
|
|
432
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${k}};
|
|
429
433
|
${oe}${Y}${Z}${X}${ee}${T.messagesBlock}${re}
|
|
430
434
|
/**
|
|
431
435
|
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
@@ -444,11 +448,11 @@ export const LUNORA_LIFECYCLE_HOOKS: {
|
|
|
444
448
|
reactor: readonly string[];
|
|
445
449
|
whisper: readonly string[];
|
|
446
450
|
} = {
|
|
447
|
-
connect: [${
|
|
448
|
-
disconnect: [${
|
|
449
|
-
init: [${
|
|
450
|
-
reactor: [${
|
|
451
|
-
whisper: [${
|
|
451
|
+
connect: [${N.connect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
452
|
+
disconnect: [${N.disconnect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
453
|
+
init: [${N.init.map(h=>JSON.stringify(h)).join(", ")}],
|
|
454
|
+
reactor: [${N.reactor.map(h=>JSON.stringify(h)).join(", ")}],
|
|
455
|
+
whisper: [${N.whisper.map(h=>JSON.stringify(h)).join(", ")}],
|
|
452
456
|
};
|
|
453
457
|
|
|
454
458
|
/**
|
|
@@ -501,13 +505,13 @@ export interface RegisteredDataMigration {
|
|
|
501
505
|
* Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
|
|
502
506
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
503
507
|
*/
|
|
504
|
-
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${
|
|
505
|
-
`,c)},
|
|
506
|
-
`:"",
|
|
507
|
-
`:"",
|
|
508
|
+
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${x}};
|
|
509
|
+
`,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 R=H(m.args);return R===void 0?[]:[`installCompiledValidatorMap(${f}.${m.exportName}.args, ${R});`]}),b=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
|
|
510
|
+
`:"",x=$.length>0?`import * as ${f} from "${y}";
|
|
511
|
+
`:"",A=$.length>0?`
|
|
508
512
|
/** Install the precompiled argument parsers before the module is dispatched. */
|
|
509
513
|
${$.join(`
|
|
510
514
|
`)}
|
|
511
|
-
`:"",
|
|
512
|
-
`:"";l[`${f}.ts`]=`${U}${
|
|
513
|
-
${
|
|
515
|
+
`:"",O=r.some(m=>m.filePath===d&&m.exportName==="default")||n.some(m=>m.filePath===d&&m.exportName==="default")?`export { default } from "${y}";
|
|
516
|
+
`:"";l[`${f}.ts`]=`${U}${b}${x}${A}export * from "${y}";
|
|
517
|
+
${O}`}return l};export{Ze as LAZY_FUNCTION_DIRECTORY,Ye as emitFunctions,Xe as emitLazyFunctionModules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{e}from"./server-
|
|
1
|
+
import"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{e}from"./server-qWq5nN-R.mjs";import"./shared-DhqnD5R3.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-BqfSKnmG.mjs";import"./shard-runtime-C1P_uVye.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-JdN4KXhV.mjs";import{j as m,h as p}from"./attribution-CTMkuBkn.mjs";import{t as d}from"./database-calls-
|
|
1
|
+
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-JdN4KXhV.mjs";import{j as m,h as p}from"./attribution-CTMkuBkn.mjs";import{t as d}from"./database-calls-Cn47SfSU.mjs";import{w as g,c as h}from"./classify-procedure-call-DtqiTjPg.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
|
+
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-JdN4KXhV.mjs";import{e as K,i as S}from"./attribution-CTMkuBkn.mjs";import{u as R,p as q,r as Y,c as O,a as G}from"./unwrap-handler-return-c2s2-nk9.mjs";import{m as J}from"./ip-reads-Dotjify6.mjs";import{b as N,s as X,c as Q}from"./classify-procedure-call-DtqiTjPg.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./static-literal-BwDHHjEJ.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const w=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=w(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)?w(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 N(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=N(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},A=(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},I=(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=A(t,"scope"),o=I(t,"maxAge"),r=I(t,"staleWhileRevalidate"),a=A(t,"tag"),l=A(t,"vary"),c={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},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=N(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=N(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)},p=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},x=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return p(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return p(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 p(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=x(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 p(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return p(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 p(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return p(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():p(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=x(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?p(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=x(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?p(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 p(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 p(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"]),b=(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=b(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")},tt=(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(d=>U(d.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(d=>be(d)))continue;const c=n.getName(),u=a.map(d=>d.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${c} ships functions (${u}) that nothing re-exports, so none is in the generated api. Add \`export const { ${u} } = ${c}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,E=(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:v(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)]))}},v=(e,i,t)=>{if(t>Ae)return E(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()?b(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?E(e,i):{inner:v(a,i,t+1),kind:"array"}}return Te(e,i,t)??E(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(c=>c.isBooleanLiteral()).map(c=>c.getText(i))).size===Ee.size,r=e.filter(c=>!(o&&c.isBooleanLiteral())).map(c=>v(c,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[l]=a;return a.length===1&&l!==void 0?l:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(c=>!c.isUndefined());if(!i&&r.length===o.length)return v(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?v(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 l=b(o,"lifecycle",e),c=o.getProperty("lifecycle");if(l===void 0&&c!==void 0&&!c.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(l!==void 0){if(!Ne.has(l))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${l}" 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:l,returnType:"void",visibility:"internal"}}const u=b(o,"visibility",e);if(u!=="internal"&&u!=="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(u==="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 d=o.getProperty("args")?.getTypeAtLocation(e);if(d===void 0||d.isAny()||d.isUnknown()||d.getStringIndexType()!==void 0||d.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 f=Object.fromEntries(d.getProperties().map(m=>[m.getName(),xe(m.getTypeAtLocation(e),e)]));return{...a,args:f,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:u}},ke=8,L=(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 L(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?P(t,i+1):void 0},P=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?L(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?P(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?P(r,i+1):void 0}return{deadEnd:e}},T=e=>{const i=L(e);return i!==void 0&&"call"in i?i.call:void 0},k=e=>{const i=L(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(l=>i(l.getName()))){const l=T(a.getNameNode());l&&r.push([a.getName(),l])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:T(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())&&k(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&k(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(c=>s.isSpreadAssignment(c)||s.isPropertyAssignment(c)&&s.isComputedPropertyName(c.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 l=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(l===void 0||!(s.isTrueLiteral(l)||s.isFalseLiteral(l)))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(l),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),l=O(()=>ae(i)),c=O(()=>oe(e)),u=z({kind:t.kind,output:l.value});return G(u?l.erased:c.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...l.value?{output:l.value}:{},returnType:c.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))),_=(e,i)=>V(e.getVariableStatements().find(t=>t.isExported()&&t.getDeclarations().some(n=>n.getName()===i))),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}:{}}},je=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=T(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},Be=(e,i,t)=>{const n=K(e),o=new Map,r=(c,u)=>{if(c?.channel?.kind!=="room")return;const d=o.get(c.channel.name);if(d!==void 0&&d!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${c.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);o.set(c.channel.name,u)},a=e.getVariableStatements().flatMap(c=>c.getDeclarations()).flatMap(c=>_e(c,u=>n.has(u))).flatMap(([c,u])=>(n.get(c)??[]).filter(d=>S(d)).flatMap(d=>{const f=j(u,d,i,t,_(e,d));return r(f,u),f?[f]:[]})),l=new Set(a.map(c=>c.exportName));for(const c of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,d]of Re(c,f=>n.has(f)))for(const f of(n.get(u)??[]).filter(m=>S(m)&&!l.has(m))){const m=Ie(d,f,i,_(e,f));m&&(a.push(m),l.add(f))}for(const{call:c,entry:u}of je(e,i,t))l.has(u.exportName)||(r(u,c),a.push(u));return a},ze=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}`})}},He=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)}},it=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),l=W(i,r);o.push(...Be(a,l,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),He(o),ze(o),o};export{it as d,w as i,ne as p,tt as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-
|
|
1
|
+
import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-DtpwprsY.mjs";const o=/rate|limit|\bip\b|geo|throttle/iu,a=/^run[A-Z]/u,l=t=>s.isIdentifier(t)?(t.getSymbol()?.getDeclarations()??[]).some(r=>r.getFirstAncestorByKind(i.ImportDeclaration)?.getModuleSpecifierValue().startsWith("@lunora/")===!0):!1,c=t=>{const e=s.isCallExpression(t)?t.getExpression():t;let r;return s.isIdentifier(e)?r=e:s.isPropertyAccessExpression(e)&&(r=e.getNameNode()),r!==void 0&&l(s.isPropertyAccessExpression(e)?e.getExpression():r)&&!o.test(r.getText())},p=t=>{const e=s.isCallExpression(t)?t.getExpression():void 0;if(s.isElementAccessExpression(e)){const r=e.getArgumentExpression();return(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))&&r.getLiteralText()==="use"}return s.isPropertyAccessExpression(e)&&e.getName()==="use"},g=t=>{const e=t.getParent();return s.isPropertyAccessExpression(e)&&e.getExpression()===t?!a.test(e.getName()):s.isElementAccessExpression(e)&&e.getExpression()===t?s.isStringLiteral(e.getArgumentExpression())||s.isNoSubstitutionTemplateLiteral(e.getArgumentExpression()):s.isVariableDeclaration(e)&&e.getInitializer()?.getText()===t.getText()},u=t=>{if(s.isPropertyAccessExpression(t))return t.getName()==="ip";if(s.isElementAccessExpression(t)){const e=t.getArgumentExpression();return(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralText()==="ip"}return s.isBindingElement(t)?t.getDotDotDotToken()!==void 0||(t.getPropertyNameNode()?.getText()??t.getName())==="ip":s.isShorthandPropertyAssignment(t)&&t.getName()==="ip"},A=t=>{for(const e of t.getDescendants()){if(u(e)||p(e)&&!c(e.getArguments()[0]))return!0;if(s.isIdentifier(e)&&n(e)&&!g(e)){const r=e.getParent();if(!(s.isParameterDeclaration(r)||s.isBindingElement(r)||s.isVariableDeclaration(r)))return!0}}return!1};export{A as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-
|
|
1
|
+
import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-DhqnD5R3.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as N,u as Ke,d as Ue}from"./shared-
|
|
1
|
+
import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as N,u as Ke,d as Ue}from"./shared-DhqnD5R3.mjs";import{p as Je}from"./platform-8oj7iXQy.mjs";const me=/(?:\.d)?\.([cm]?)tsx?$/u,ze=t=>t.replace(me,".d.$1ts"),ye=(t,o)=>{const a=y(t,o).split(ue).join("/").replace(me,".$1js");return a.startsWith(".")?a:`./${a}`},he=t=>t.replaceAll("\\","/"),Y=(t,o,a)=>he(h(t,ze(y(o,a)))),Ye=t=>ye(".",h("services",t.name,y(d(t.wranglerPath),t.main))),Xe=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},T=t=>{const{mtimeMs:o,size:a}=Le(t);return`${String(o)}:${String(a)}`},Ze=new Set([".git",".wrangler","dist","node_modules","target"]),fe=t=>de(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${ce(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${T(a)}`,...fe(a)]:[]}),be=t=>[`${t}:${T(t)}`,...fe(t)],ge=t=>{const o=h(t,"node_modules"),a=D(o)?be(o):[],e=d(t);return e===t?a:[...a,...ge(e)]},et=(t,o)=>{const a=[];try{const e=s=>{for(const n of de(s,{withFileTypes:!0})){const l=h(s,n.name);if(l!==o)if(n.isSymbolicLink())a.push(`${l}->${ce(l)}`);else if(n.isDirectory()){if(n.name==="node_modules")a.push(...be(l));else if(!Ze.has(n.name)){if(!qe(l).isDirectory())throw new Error(`${l} changed during the scan`);e(l)}}else a.push(`${l}:${T(l)}`)}};e(t),a.push(...ge(t))}catch{return}return[...new Set(a)].toSorted((e,s)=>e.localeCompare(s)).join(`
|
|
2
2
|
`)},tt=t=>Ge(d(t)).startsWith("@")?d(d(t)):d(t),se=(t,o)=>!y(o,t).startsWith("..")&&!t.split(ue).includes("node_modules"),ie=(t,o)=>{const a=[];let e=t;for(;e!==d(e)&&!D(h(e,"package.json"));)a.push(e),e=d(e);if(D(h(e,"package.json"))){for(const s of[...a,e,h(e,"package.json")])o.add(s);return e}},at=(t,o,a)=>{let e=t;for(;y(e,o).startsWith("..")&&e!==d(e);)a.add(e),e=d(e);a.add(e)},rt=(t,o)=>{const a=new Set;t.some(e=>se(e,o))&&ie(o,a);for(const e of t){if(se(e,o)){for(let n=d(e);n!==o&&n!==d(n);n=d(n))a.add(n);continue}const s=ie(d(e),a);s===void 0?at(d(e),o,a):a.add(tt(s))}return[...a].map(e=>[e,T(e)])},xe=new Map,le=([t,o])=>{try{return T(t)===o}catch{return!1}},ot=(t,o,a)=>{const e=xe.get(t);return e?.optionsKey===o&&e.stamps.every(n=>le(n))&&e.directories.every(n=>le(n))&&a!==void 0&&e.tree===a?e.files:void 0},nt=(t,o,a)=>{const e=[...o.stamps,...o.directories].every(([,s])=>Math.floor(Number.parseFloat(s))<=a);o.tree!==void 0&&e&&xe.set(t,{...o,tree:o.tree})},st=(t,o)=>({directories:rt(o,t),stamps:o.map(a=>[a,T(a)])}),ht=(t,o)=>{const a=d(t.wranglerPath),e=y(a,t.main);if(e.startsWith("..")||_e(e))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const s=h(o,"services",t.name),n=c.findConfigFile(a,i=>c.sys.fileExists(i)),l=new He({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:s,rootDir:a},skipAddingFilesFromTsConfig:!0,...n===void 0?{}:{tsConfigFilePath:n}}),m=JSON.stringify([t.name,t.main,t.wranglerPath,o]),v=JSON.stringify(l.getCompilerOptions()),w=et(a,Ve(o)),g=ot(m,v,w);if(g!==void 0)return g;const A=Date.now();l.addSourceFileAtPath(t.main),l.resolveSourceFileDependencies();const $=l.getProgram().compilerObject.getSourceFiles().map(i=>i.fileName).filter(i=>D(i)),{directories:F,stamps:S}=st(a,$),u={...l.getCompilerOptions(),preserveSymlinks:!0},O=new Map(l.getSourceFiles().map(i=>i.getFilePath()).filter(i=>!i.endsWith(".d.ts")&&!y(a,i).startsWith("..")).map(i=>[Y(s,a,i),i])),f={};for(const i of l.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const B=O.get(he(i.filePath));if(B===void 0)continue;const R=c.createSourceFile(i.filePath,i.text,c.ScriptTarget.Latest,!1);let{text:b}=i;for(const k of Xe(R).toReversed()){const x=c.resolveModuleName(k.text,B,u,c.sys).resolvedModule?.resolvedFileName;if(x===void 0)continue;const I=Y(s,a,x),W=O.has(I)?I:x;b=`${b.slice(0,k.getStart(R))}${JSON.stringify(ye(d(i.filePath),W))}${b.slice(k.getEnd())}`}f[y(o,i.filePath)]=`${pe}${b}`}if(f[y(o,Y(s,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return nt(m,{files:f,optionsKey:v,directories:F,stamps:S,tree:w},A),f},it=(t,o=[])=>{const a=new Set;for(const e of t.tables)for(const s of Object.values(e.shape)){const n=Ke(s);n.kind==="storage"&&typeof n.bucket=="string"&&n.bucket!==""&&a.add(n.bucket)}for(const e of o)e!==""&&e!=="default"&&a.add(e);return["default",...[...a].toSorted((e,s)=>e.localeCompare(s))]},ft=({agents:t=[],capabilities:o=new Set,containers:a=[],env:e,hasVectors:s=!0,hasFlags:n=!1,hasNotify:l=!1,identity:m,queues:v=[],schema:w,services:g=[],storageRuleBuckets:A=[],topics:$=[],useUmbrella:F=!1,workflows:S=[]}={})=>{const u=Ue(F),O=it(w??{tables:[]},A).map(r=>JSON.stringify(r)).join(" | "),f=r=>r.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",i=[...new Set(a.map(r=>f(r)))].toSorted((r,p)=>r.localeCompare(p)),B=a.length>0?`import type { ${i.join(", ")} } from "@lunora/container";
|
|
3
3
|
`:"",R=a.length>0?`
|
|
4
4
|
readonly containers: {${a.map(r=>`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as me}from"@lunora/errors";import{serializeSchemaSnapshot as Zt,hashSchemaSnapshot as er}from"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{LunoraError as me}from"@lunora/errors";import{serializeSchemaSnapshot as Zt,hashSchemaSnapshot as er}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{isHyperdriveGlobalTable as tr,isD1GlobalTable as rr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as nr}from"./json-data-Chfs2Cz5.mjs";import{r as M,e as ar,a as sr,b as or,c as ir,d as dr,f as cr,g as lr,h as ur,i as hr,j as pr,k as mr,l as fr,m as gr,n as br,o as yr,p as wr,q as vr,s as kr}from"./shard-runtime-C1P_uVye.mjs";import{u as q,h as Sr,s as Rr,a as xr,I as Ar,c as Or,G as Dr,d as Tr}from"./shared-DhqnD5R3.mjs";import{p as _r}from"./platform-8oj7iXQy.mjs";import{i as Ir}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,fe=["categories","description","facing","level","remediation","title"],Er=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(fe.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!fe.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Cr=` /**
|
|
2
2
|
* The bare writer every admin/maintenance entry point writes through.
|
|
3
3
|
*
|
|
4
4
|
* Admin and maintenance writes go through the SAME reactive-cache hooks as a
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as k}from"@lunora/errors";import{r as b}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as R}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{a as l,G as f,I as w}from"./shared-
|
|
1
|
+
import{LunoraError as k}from"@lunora/errors";import{r as b}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as R}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{a as l,G as f,I as w}from"./shared-DhqnD5R3.mjs";import{s as S}from"./platform-8oj7iXQy.mjs";const Q=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
2
2
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
3
3
|
this.ensureServable();
|
|
4
4
|
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{v as _}from"./parse-validator-BisfC8bR.mjs";import{R as k}from"./reserved-words-CW1QFbTd.mjs";import{acceptsAbsentIr as I}from"./LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{n as E}from"./dispatch-namespace-DwTjD7BU.mjs";const R=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,O=e=>Object.keys(e).filter(n=>_(e[n])),B=e=>e.typeDerivedArgs===!0&&Object.keys(e.args).length>0||O(e.args).length>0,F=`// GENERATED by @lunora/codegen — do not edit.
|
|
2
2
|
// Run \`lunora codegen\` to regenerate.
|
|
3
3
|
|
|
4
|
-
`,G=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},b=/^[A-Za-z_$][\w$]*$/u,U=/^[\w./-]+$/u,w=(e,n)=>{if(!b.test(e)||
|
|
5
|
-
${p(f,
|
|
4
|
+
`,G=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},b=/^[A-Za-z_$][\w$]*$/u,U=/^[\w./-]+$/u,w=(e,n)=>{if(!b.test(e)||k.has(e))throw new $("INTERNAL",`@lunora/codegen: ${n} is not a valid JS identifier: ${JSON.stringify(e)}`)},V=(e,n)=>{if(!b.test(e))throw new $("INTERNAL",`@lunora/codegen: ${n} is not a valid JS identifier: ${JSON.stringify(e)}`)},H=e=>e.charAt(0).toUpperCase()+e.slice(1),g=e=>b.test(e)?e:JSON.stringify(e),j=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:g(e),D=e=>{const n=new Map;for(const r of e){const t=n.get(r.filePath)??[];t.push(r),n.set(r.filePath,t)}return[...n.entries()].toSorted(([r],[t])=>r.localeCompare(t))},Y=(e,n,r)=>{const[t,l]=r==="type"?[g,";"]:[j,","],h={children:new Map};for(const[o,d]of D(e)){let a=h;for(const m of E(o)){let c=a.children.get(m);c===void 0&&(c={children:new Map},a.children.set(m,c)),a=c}a.file={entries:d,path:o}}const u=o=>o.file?.path??u(o.children.values().next().value),p=(o,d)=>{const a=" ".repeat(d),{entries:m=[],path:c=""}=o.file??{},y=m.find(s=>o.children.has(s.exportName));if(y!==void 0){const s=u(o.children.get(y.exportName));throw new $("NAMESPACE_COLLISION",`Namespace collision: the export "${y.exportName}" of "${c}" and "${s}" both resolve to api.${[...E(c),y.exportName].join(".")}. Rename the export or the folder.`)}const A=m.toSorted((s,f)=>s.exportName.localeCompare(f.exportName)).map(s=>`${a}${n(s)}`),S=[...o.children.entries()].toSorted(([s],[f])=>s.localeCompare(f)).map(([s,f])=>`${a}${t(s)}: {
|
|
5
|
+
${p(f,d+1).join(`
|
|
6
6
|
`)}
|
|
7
|
-
${a}}${l}`);return[...S
|
|
8
|
-
`)},x={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},L=e=>{if(e===void 0)return"unknown";if(!
|
|
7
|
+
${a}}${l}`);return[...A,...S]};return p(h,1).join(`
|
|
8
|
+
`)},x={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},L=e=>{if(e===void 0)return"unknown";if(!R.test(e))throw new $("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},i=e=>e.column?.notNull===!1?`${T(e)} | null`:T(e),T=e=>{const n=x[e.kind];if(n!==void 0)return n;switch(e.kind){case"array":return`Array<${e.inner?i(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const r=e.tableName??"_unknown_";return w(r,"v.id() table name"),`Id<"${r}">`}case"literal":return L(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([t,l])=>N(t,l)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?i(e.inner):"unknown"} | undefined`;case"record":{const r=e.keyType?i(e.keyType):"string",t=e.valueType?i(e.valueType):"unknown";return`Record<${r}, ${t}>`}case"union":return e.members&&e.members.length>0?e.members.map(r=>i(r)).join(" | "):"never";default:return"unknown"}},N=(e,n)=>{const r=g(e);if(n.kind==="optional"){const t=n.inner?i(n.inner):"unknown";return`${r}?: ${t}`}return I(n)?`${r}?: ${i(n)}`:`${r}: ${i(n)}`},W=e=>{const n=Object.entries(e);return n.length===0?"{}":`{ ${n.map(([r,t])=>N(r,t)).join("; ")} }`},z=e=>e.kind==="optional"||!!e.column?.hasDefault,C=e=>e.kind==="optional"&&e.inner?e.inner:e,Z=e=>{w(e.name,"table name");const n=Object.entries(e.shape).map(([t,l])=>{const h=C(l),u=i(h),p=g(t);return z(l)?` ${p}?: ${u};`:` ${p}: ${u};`}).join(`
|
|
9
9
|
`),r=n?`
|
|
10
10
|
${n}
|
|
11
11
|
`:"";return`export interface Insert_${e.name} {
|
|
12
12
|
_id?: Id<"${e.name}">;
|
|
13
|
-
_creationTime?: number;${r}}`};export{F as G,U as I,
|
|
13
|
+
_creationTime?: number;${r}}`};export{F as G,U as I,R as L,w as a,Y as b,j as c,G as d,g as e,Z as f,V as g,z as h,B as i,H as p,W as r,O as s,C as u,i as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i,SyntaxKind as a}from"ts-morph";const n=Symbol("not-literal"),p=e=>Number(e.getText().replaceAll("_","")),f=e=>i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?e.getLiteralValue():i.isNumericLiteral(e)?p(e):i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===a.MinusToken&&i.isNumericLiteral(e.getOperand())?-p(e.getOperand()):i.isTrueLiteral(e)||i.isFalseLiteral(e)?e.getLiteralValue():i.isBinaryExpression(e)?m(e):i.isNullLiteral(e)?null:n,g={[a.AsteriskAsteriskToken]:(e,t)=>e**t,[a.AsteriskToken]:(e,t)=>e*t,[a.MinusToken]:(e,t)=>e-t,[a.PercentToken]:(e,t)=>e%t,[a.PlusToken]:(e,t)=>e+t,[a.SlashToken]:(e,t)=>e/t},m=e=>{const t=g[e.getOperatorToken().getKind()],[r,s]=[l(e.getLeft()),l(e.getRight())];return t!==void 0&&typeof r=="number"&&typeof s=="number"&&Number.isFinite(r)&&Number.isFinite(s)?t(r,s):n},l=e=>{if(i.isParenthesizedExpression(e)||i.isAsExpression(e)||i.isSatisfiesExpression(e))return l(e.getExpression());if(i.isArrayLiteralExpression(e)){const t=e.getElements().map(r=>l(r));return t.includes(n)?n:t}return i.isObjectLiteralExpression(e)?L(e):f(e)},L=e=>{const t=[];for(const r of e.getProperties()){const s=i.isPropertyAssignment(r)?r.getNameNode():void 0,o=i.isPropertyAssignment(r)?r.getInitializer():void 0,u=o===void 0?n:l(o);if(s===void 0||u===n||!(i.isIdentifier(s)||i.isStringLiteral(s)))return n;const c=i.isStringLiteral(s)?s.getLiteralValue():s.getText();if(c==="__proto__")return n;t.push([c,u])}return Object.fromEntries(t)};export{n as N,l};
|