@lunora/codegen 1.0.0-alpha.382 → 1.0.0-alpha.384
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 +207 -94
- package/dist/index.d.ts +207 -94
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AGENTS_FILENAME-BedyJsOT.mjs → AGENTS_FILENAME-5mDMAMWy.mjs} +1 -1
- package/dist/packem_shared/{CONTAINERS_FILENAME-T1v8pyHN.mjs → CONTAINERS_FILENAME-BJYrxnq2.mjs} +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-DPEvCN8Z.mjs → GENERATED_HEADER-Bzf6ZJ9r.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-Ipxibja6.mjs → MUTATORS_FILENAME-DlSftsvY.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-B-t7jQSm.mjs → NOTIFY_FILENAME-SKk8x0VM.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-DA0ZNkhl.mjs → OPENRPC_VERSION-CSjT8wJW.mjs} +1 -1
- package/dist/packem_shared/{QUEUES_FILENAME-Dt5RG_P0.mjs → QUEUES_FILENAME-BeGwgqcw.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Dle_pfr9.mjs +31 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs +2 -0
- package/dist/packem_shared/SHAPES_FILENAME-rSSihffV.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-ycDz8gOB.mjs +17 -0
- package/dist/packem_shared/{WORKFLOWS_FILENAME-VAXgqqP-.mjs → WORKFLOWS_FILENAME--RWiu_Vy.mjs} +1 -1
- package/dist/packem_shared/{attribution-DUbGYT4N.mjs → attribution-CTMkuBkn.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-Ct2wK_Tj.mjs → buildOpenApiDocument-afHH7rN5.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-DKMO9ShK.mjs → context-property-calls-CYaejv5r.mjs} +1 -1
- package/dist/packem_shared/{context-root-BPfMNAJM.mjs → context-root-TiLodrRO.mjs} +1 -1
- package/dist/packem_shared/{database-calls-hLzaOquW.mjs → database-calls-QqsrkDMs.mjs} +1 -1
- package/dist/packem_shared/{discoverAuthApiCalls-Ce3BdKQr.mjs → discoverAuthApiCalls-DZMYREsq.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-DdHysjy1.mjs +1 -0
- package/dist/packem_shared/{discoverHttpRoutes-DHDfKLoa.mjs → discoverHttpRoutes-5iA7gI_Q.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-BJRaIvLx.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-IAa3lRR4.mjs → discoverInserts-Dw7fvL7s.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-BLKjuD-A.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-C649uAWL.mjs +1 -0
- package/dist/packem_shared/{discoverNondeterministicCalls-DZ_kIie5.mjs → discoverNondeterministicCalls-DQgVTcLv.mjs} +1 -1
- package/dist/packem_shared/{discoverQueries-DZOGiEPs.mjs → discoverQueries-DVFZJER7.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-BEBdqXi_.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-Dq6iSXnC.mjs → discoverRlsMetadata-DqZpiGts.mjs} +1 -1
- package/dist/packem_shared/discoverRlsProcedures-C2lkSLPn.mjs +1 -0
- package/dist/packem_shared/{discoverSchema-DmkjooXZ.mjs → discoverSchema-Cycd1-H0.mjs} +1 -1
- package/dist/packem_shared/{discoverStorageRulesMetadata-CJ7h6SPK.mjs → discoverStorageRulesMetadata-H3RJzkH_.mjs} +1 -1
- package/dist/packem_shared/{emitAgents-D8TkTpNh.mjs → emitAgents-BeM6PZv4.mjs} +1 -1
- package/dist/packem_shared/{emitApi-D6uqyYd_.mjs → emitApi-GFmStqmq.mjs} +1 -1
- package/dist/packem_shared/{emitApp-D9kGG9Mu.mjs → emitApp-D-6FIpYb.mjs} +10 -6
- package/dist/packem_shared/{emitCrons-C3RiGYk7.mjs → emitCrons-Drdn8Mjn.mjs} +1 -1
- package/dist/packem_shared/{emitDataModel-BMMht_iZ.mjs → emitDataModel-LTnwnhV6.mjs} +1 -1
- package/dist/packem_shared/{emitDrizzleSchema-BmCxM6tO.mjs → emitDrizzleSchema-CM9jh_F0.mjs} +1 -1
- package/dist/packem_shared/{emitFunctions-NGByI1FZ.mjs → emitFunctions-DRAuiKPv.mjs} +90 -83
- package/dist/packem_shared/{emitServer-4NV3vaOg.mjs → emitServer-4l7MPmK0.mjs} +1 -1
- package/dist/packem_shared/emitShard-DqEvyZPZ.mjs +1 -0
- package/dist/packem_shared/{exported-procedure-chains-BaCIhnJ7.mjs → exported-procedure-chains-CRM-MVfP.mjs} +1 -1
- package/dist/packem_shared/handler-reference-90LXJART.mjs +1 -0
- package/dist/packem_shared/index-BhsJzv9r.mjs +1 -0
- package/dist/packem_shared/{index-BjDVAPNW.mjs → index-iw3axJ5Y.mjs} +1 -1
- package/dist/packem_shared/ip-reads-BVXbFgzV.mjs +1 -0
- package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
- package/dist/packem_shared/{qualifiers-CPQCkXC4.mjs → qualifiers-D1Q_3wo2.mjs} +1 -1
- package/dist/packem_shared/{server-BY1v1bTx.mjs → server-D69SOfX8.mjs} +1 -1
- package/dist/packem_shared/{shard-DNXF9VZ5.mjs → shard-L3gYZnC9.mjs} +94 -91
- package/dist/packem_shared/{shard-runtime-Bg8MOBzw.mjs → shard-runtime-lkQU8trx.mjs} +1 -1
- package/dist/packem_shared/{shared-BErjtci3.mjs → shared-A1XHcT4t.mjs} +1 -1
- package/package.json +8 -8
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CQyAtphV.mjs +0 -31
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs +0 -2
- package/dist/packem_shared/SHAPES_FILENAME-mgEi072Z.mjs +0 -1
- package/dist/packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs +0 -18
- package/dist/packem_shared/discoverFunctions-a0IT8OSb.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-i8Zcf64H.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-Bj6fPF4u.mjs +0 -1
- package/dist/packem_shared/discoverMigrations-Bv8kNIgy.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-Lq6G--TZ.mjs +0 -1
- package/dist/packem_shared/discoverRlsProcedures-B0DYk-gW.mjs +0 -1
- package/dist/packem_shared/emitShard-9NVueN79.mjs +0 -1
- package/dist/packem_shared/handler-reference-D1wpw_qR.mjs +0 -1
- package/dist/packem_shared/parse-validator-CP5CL6Q7.mjs +0 -1
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{L as pe,s as j,G as U,d as J,I as E,b as I,r as me,c as ge}from"./shared-A1XHcT4t.mjs";import{v as fe}from"./parse-validator-BisfC8bR.mjs";import{renderAgentFunctionRegistry as ye,renderSandboxFunctionRegistry as $e}from"./emitApi-GFmStqmq.mjs";import{b as we,a as Re,r as C,c as ke}from"./qualifiers-D1Q_3wo2.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const be=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),B=r=>r.column!==void 0,ve=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
|
|
2
2
|
`;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
|
|
3
3
|
`;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
|
|
4
4
|
`;case"null":return`if (${t} !== null) return DEFER;
|
|
5
5
|
`;default:return`if (typeof ${t} !== "string") return DEFER;
|
|
6
|
-
`}},
|
|
7
|
-
`,
|
|
8
|
-
`}},
|
|
6
|
+
`}},Ne=(r,t)=>r.stringMaxLength===void 0?"":`if (${t}.length > ${String(r.stringMaxLength)}) return DEFER;
|
|
7
|
+
`,Oe=(r,t)=>{const n=r.literalValue?.trim();if(!(n===void 0||!pe.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
|
|
8
|
+
`}},_=(r,t,n)=>{if(!B(r)&&!(r.unmodelledRefinement||r.sourceText!==void 0)){if(be.has(r.kind))return r.kind==="any"?{out:t,pre:""}:{out:t,pre:ve(r.kind,t)+Ne(r,t)};switch(r.kind){case"array":return Se(r,t,n);case"literal":return Oe(r,t);case"object":return Ae(r,t,n);default:return}}},Se=(r,t,n)=>{const{inner:o}=r;if(!o)return;const a=n.next(),i=`__arr${String(a)}`,s=`__i${String(a)}`,c=`__e${String(a)}`,u=_(o,c,n);if(!u)return;const l=`if (!Array.isArray(${t})) return DEFER;
|
|
9
9
|
const ${i} = new Array(${t}.length);
|
|
10
10
|
for (let ${s} = 0; ${s} < ${t}.length; ${s}++) {
|
|
11
11
|
const ${c} = ${t}[${s}];
|
|
12
|
-
${
|
|
12
|
+
${u.pre}${i}[${s}] = ${u.out};
|
|
13
13
|
}
|
|
14
|
-
`;return{out:i,pre:l}},
|
|
15
|
-
let ${
|
|
14
|
+
`;return{out:i,pre:l}},Pe=(r,t,n,o)=>{const a=JSON.stringify(r);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||B(t))return;const{inner:s}=t;if(!s)return;const c=_(s,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
16
|
if (${n} !== undefined) {
|
|
17
|
-
${c.pre}${
|
|
17
|
+
${c.pre}${d} = ${c.out};
|
|
18
18
|
${l} = true;
|
|
19
19
|
}
|
|
20
|
-
`;return{entry:`...(${l} ? { ${a}: ${
|
|
21
|
-
`,d
|
|
22
|
-
`},
|
|
23
|
-
${
|
|
24
|
-
`;return{out:s,pre:c}},
|
|
20
|
+
`;return{entry:`...(${l} ? { ${a}: ${d} } : {})`,pre:f}}const i=_(t,n,o);if(i)return{entry:`${a}: ${i.out}`,pre:i.pre}},xe=new Set(Object.getOwnPropertyNames(Object.prototype)),q=(r,t,n)=>{let o="";const a=[];for(const i of Object.keys(r)){const s=r[i];if(!s)return;const c=JSON.stringify(i);let u=`${t}[${c}]`;if(xe.has(i)){const d=`__f${String(n.next())}`;o+=`const ${d} = Object.hasOwn(${t}, ${c}) ? ${t}[${c}] : undefined;
|
|
21
|
+
`,u=d}const l=Pe(i,s,u,n);if(!l)return;o+=l.pre,a.push(l.entry)}return{entries:a.join(", "),pre:o}},H=r=>{const t=`Object.getPrototypeOf(${r})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
|
|
22
|
+
`},Ae=(r,t,n)=>{const o=r.shape??{},a=q(o,t,n);if(!a)return;const i=n.next(),s=`__obj${String(i)}`,c=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
|
|
23
|
+
${H(t)}${a.pre}const ${s} = { ${a.entries} };
|
|
24
|
+
`;return{out:s,pre:c}},z=r=>{let t=0;const o=q(r,"source",{next:()=>(t+=1,t)});if(o)return`(source) => {
|
|
25
25
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
26
|
-
${
|
|
27
|
-
}`},
|
|
26
|
+
${H("source")}${o.pre}return { ${o.entries} };
|
|
27
|
+
}`},Le=(r,t)=>`lunora_${g(r)}_${String(t)}`,D=r=>JSON.stringify(Object.entries(r).toSorted(([t],[n])=>t.localeCompare(n)).map(([t,n])=>{const o=n.kind==="optional",a=o?n.inner??{kind:"unknown"}:n,i=a.kind==="array"?a.inner?.kind:void 0,s=a.kind==="id"?a.tableName:void 0;return{kind:a.kind,name:t,optional:o,...fe(n)?{sensitive:!0}:{},...s===void 0?{}:{table:s},...i===void 0||i==="unknown"?{}:{element:i}}})),W=(r,t,n,o)=>{const a=new Map,i=s=>{a.has(s)||a.set(s,Le(s,a.size))};for(const s of r)i(s.filePath);for(const s of t)i(s.filePath);for(const s of n)i(s.filePath);for(const s of o)i(s.filePath);return a},Q=(r,t,n)=>new Set([...r.map(o=>o.filePath),...t.map(o=>o.filePath),...n.map(o=>o.filePath)]),S=r=>`${r}[functionPath]`,Te=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
28
28
|
const registered = await loadFunction(functionPath);
|
|
29
29
|
|
|
30
30
|
if (!registered) {
|
|
@@ -57,29 +57,29 @@ ${q("source")}${o.pre}return { ${o.entries} };
|
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
return (await registered.handler(context, args ?? {})) as R;
|
|
60
|
-
};`,
|
|
61
|
-
`),
|
|
60
|
+
};`,Ee=(r,t,n=[],o=[],a=!1)=>{const i=W(r,t,n,o),s=Q(t,n,o),c=[...i.entries()].filter(([e])=>!a||s.has(e)?!0:r.some(m=>m.filePath===e&&m.channel?.kind==="room")).map(([e,m])=>{if(!E.test(e))throw new L("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);return`import ${a&&!s.has(e)?"type ":""}* as ${m} from "../${e}.js";`}).join(`
|
|
61
|
+
`),u=r.map(e=>{if(!a||s.has(e.filePath))return` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`;const m=j(e.args);return` "${g(e.filePath)}:${e.exportName}": { args: {}, handler: unloadedFunctionHandler, ...${JSON.stringify({argumentDescriptors:JSON.parse(D(e.args)),kind:e.kind,...m.length===0?{}:{sensitiveArgs:m},...e.channel?{channel:e.channel}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}},...e.socket===void 0?{}:{auth:e.socket.auth,socketPath:e.socket.path}})} } satisfies RegisteredLunoraFunction & Pick<FunctionManifestEntry, "argumentDescriptors" | "channel" | "expose">,`}).join(`
|
|
62
62
|
`),l=t.map(e=>` ${JSON.stringify(e.id)}: ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
63
|
-
`),
|
|
63
|
+
`),d=n.map(e=>` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
64
64
|
`),f=o.map(e=>` "${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredShape,`).join(`
|
|
65
|
-
`)
|
|
66
|
-
`),
|
|
67
|
-
`),
|
|
68
|
-
`),
|
|
69
|
-
`):"",
|
|
70
|
-
`):"";return{dispatchBody:
|
|
71
|
-
${
|
|
65
|
+
`),y=n.map(e=>`${g(e.filePath)}:${e.exportName}`),$=[...r.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(`
|
|
66
|
+
`),P=r.filter(e=>!a||s.has(e.filePath)).map(e=>{if(e.lifecycle||Object.keys(e.args).length===0)return;const m=z(e.args);return m===void 0?void 0:`installCompiledValidatorMap(${i.get(e.filePath)??""}.${e.exportName}.args, ${m});`}).filter(e=>e!==void 0).join(`
|
|
67
|
+
`),x=r.filter(e=>e.channel?.kind==="room").map(e=>` ${JSON.stringify(e.channel?.name??"")}: RoomMessageOf<typeof ${i.get(e.filePath)??""}[${JSON.stringify(e.exportName)}]>;`).join(`
|
|
68
|
+
`),v=[...r.map(e=>({args:e.args,definition:e,path:`${g(e.filePath)}:${e.exportName}`})),...n.map(e=>({args:e.args,definition:{...e,expose:void 0,kind:"mutation",lifecycle:void 0,visibility:void 0,x402:void 0},path:`${g(e.filePath)}:${e.exportName}`}))],N=a?v.filter(({definition:e})=>!s.has(e.filePath)):[];for(const{definition:e}of v)if(a&&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 p=a?N.map(({definition:e,path:m})=>{const k=i.get(e.filePath)??"",A="channel"in e?e.channel:void 0,b={argumentDescriptors:JSON.parse(D(e.args)),exportName:e.exportName,kind:e.kind,moduleId:k,...A?{channel:A}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}}};return` ${JSON.stringify(m)}: ${JSON.stringify(b)},`}).join(`
|
|
69
|
+
`):"",w=[...new Set(N.map(({definition:e})=>e.filePath))],O=a?w.map(e=>{if(!E.test(e))throw new L("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);const m=i.get(e)??"";return` ${JSON.stringify(m)}: () => import(${JSON.stringify(`./fn/${m}.js`)}),`}).join(`
|
|
70
|
+
`):"";return{dispatchBody:R.length>0?`
|
|
71
|
+
${R}
|
|
72
72
|
`:"",importBlock:c.length>0?`${c}
|
|
73
73
|
|
|
74
|
-
`:"",installBlock:
|
|
75
|
-
${
|
|
74
|
+
`:"",installBlock:P,manifestBody:p.length>0?`
|
|
75
|
+
${p}
|
|
76
76
|
`:"",migrationBody:l.length>0?`
|
|
77
77
|
${l}
|
|
78
|
-
`:"",moduleLoaders:
|
|
79
|
-
${
|
|
80
|
-
`:"",mutatorPaths
|
|
78
|
+
`:"",moduleLoaders:O.length>0?`
|
|
79
|
+
${O}
|
|
80
|
+
`:"",ipReaderPaths:$,mutatorPaths:y,roomMessagesBody:x,shapeBody:f.length>0?`
|
|
81
81
|
${f}
|
|
82
|
-
`:""}},
|
|
82
|
+
`:""}},_e=r=>{const t=I(r,o=>{const a=C(me(o.args),o.filePath),i=a==="{}"?"?":"",s=C(ke(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${i}: ${a}) => Promise<AsyncIterable<${s}>>;`:`${o.exportName}: (args${i}: ${a}) => Promise<${s}>;`},"type");return{implementation:I(r,o=>`${ge(o.exportName)}: (args) => callRegistered(context, "${g(o.filePath)}:${o.exportName}", args),`,"value"),types:t}},Fe=r=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of r)!n.lifecycle||n.lifecycle==="socket"||t[n.lifecycle].push(`${g(n.filePath)}:${n.exportName}`);return t},Me=r=>{const t=new Map,n=[];for(const o of r){if(o.lifecycle!=="socket"||o.socket===void 0)continue;const{auth:a,origin:i,path:s}=o.socket,c=`${g(o.filePath)}:${o.exportName}`,u=t.get(s);if(!(u?.origin!==void 0&&u.origin===i)){if(u!==void 0)throw new L("DUPLICATE_SOCKET_PATH",`two defineWebSocket routes serve "${s}" (${u.functionPath} and ${c}); socket paths must be unique.`);t.set(s,{functionPath:c,origin:i}),n.push(` ${JSON.stringify(s)}: { auth: ${String(a)}, functionPath: ${JSON.stringify(c)} },`)}}return`
|
|
83
83
|
/**
|
|
84
84
|
* Socket registry: the URL path of each \`defineWebSocket\` route → its function path + auth requirement.
|
|
85
85
|
* Static, so building the worker never evaluates a route's module. The generated ShardDO's \`socketRoute\` override
|
|
@@ -89,7 +89,7 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
|
|
|
89
89
|
${n.join(`
|
|
90
90
|
`)}
|
|
91
91
|
};
|
|
92
|
-
`},
|
|
92
|
+
`},Ie=(r,t)=>{const n=r.some(c=>c.lifecycle==="socket"),a=n&&t?Me(r):n&&!t?`
|
|
93
93
|
/**
|
|
94
94
|
* Socket registry: the URL path of each \`defineWebSocket\` route → its function
|
|
95
95
|
* path + auth requirement. The generated ShardDO's \`socketRoute\` override
|
|
@@ -133,7 +133,7 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
|
|
|
133
133
|
* Set on a \`defineWebSocket\` registration: whether the route refuses an
|
|
134
134
|
* anonymous upgrade. Read into \`LUNORA_SOCKETS\` alongside \`socketPath\`.
|
|
135
135
|
*/
|
|
136
|
-
auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:a}},
|
|
136
|
+
auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:a}},Ce=(r,t,n)=>r?{channelField:` /**
|
|
137
137
|
* Set on a \`defineRoom\` registration: the room's name (without the \`room:\`
|
|
138
138
|
* topic prefix). The generated \`LUNORA_ROOMS\` map keys it on the room's
|
|
139
139
|
* \`room:<name>\` whisper topic so the ShardDO resolves a room topic to this
|
|
@@ -148,7 +148,7 @@ export type LunoraRoomMessages = {
|
|
|
148
148
|
${n}
|
|
149
149
|
};
|
|
150
150
|
`,typeImport:`import type { RoomMessageOf } from "${t}";
|
|
151
|
-
`}:{channelField:"",messagesBlock:"",typeImport:""},
|
|
151
|
+
`}:{channelField:"",messagesBlock:"",typeImport:""},De=(r,t,n)=>r?t?`
|
|
152
152
|
/**
|
|
153
153
|
* Room routes are static metadata so building the worker never evaluates user handlers.
|
|
154
154
|
*/
|
|
@@ -208,69 +208,76 @@ export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
|
|
|
208
208
|
|
|
209
209
|
return registry;
|
|
210
210
|
})();
|
|
211
|
-
`:"",
|
|
211
|
+
`:"",je=(r,t)=>{const n=_e(r),o=n.types?`
|
|
212
212
|
${n.types}
|
|
213
213
|
`:"",a=n.implementation?`
|
|
214
214
|
${n.implementation}
|
|
215
|
-
`:"",i
|
|
216
|
-
`:"",c=r.length>0?"context":"_context";let
|
|
215
|
+
`:"",i=Re(n.types),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
|
|
216
|
+
`:"",c=r.length>0?"context":"_context";let u="";if(r.length>0){let l=Te;t||(l=l.replace("await loadFunction(functionPath)",S("LUNORA_FUNCTIONS"))),u=`${l}
|
|
217
217
|
|
|
218
|
-
`}return{callRegisteredHelper:
|
|
218
|
+
`}return{callRegisteredHelper:u,dataModelImport:s,implementation:a,parameter:c,types:o}},We=r=>{const{agents:t=[],functions:n,lazyFunctions:o=!1,migrations:a=[],mutators:i=[],shapes:s=[],useUmbrella:c=!1,usesSandbox:u=!1}=r,l=J(c),{dispatchBody:d,importBlock:f,installBlock:y,ipReaderPaths:$,manifestBody:R,migrationBody:P,moduleLoaders:x,mutatorPaths:v,roomMessagesBody:N,shapeBody:p}=Ee(n,a,i,s,o),w=ye(t,n),O=$e(u,n),m=t.length>0||n.some(h=>j(h.args).length>0)?` /**
|
|
219
219
|
* Names of the arguments whose validators carry a \`v.sensitive\` marker. Read by the
|
|
220
220
|
* shard before any validator is loaded, so a lazy function's secret args are
|
|
221
221
|
* masked even on a dispatch that fails before its module evaluates.
|
|
222
222
|
*/
|
|
223
223
|
sensitiveArgs?: readonly string[];
|
|
224
|
-
`:"",
|
|
225
|
-
`);let
|
|
226
|
-
${
|
|
224
|
+
`:"",k=[w.lines,O.lines].filter(h=>h.length>0).join(`
|
|
225
|
+
`);let A=d;k.length>0&&(A=d.length>0?`${d.trimEnd()}
|
|
226
|
+
${k}
|
|
227
227
|
`:`
|
|
228
|
-
${
|
|
229
|
-
`);const b=Fe(n),
|
|
228
|
+
${k}
|
|
229
|
+
`);const b=Fe(n),G=o?"await loadFunction(functionPath)":S("LUNORA_FUNCTIONS"),V=o?` if (${S("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
|
|
230
230
|
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
231
231
|
}
|
|
232
232
|
|
|
233
|
-
`:"",
|
|
234
|
-
`:"",
|
|
233
|
+
`:"",K=s.length>0?`import type { RegisteredShape } from "${l.server}";
|
|
234
|
+
`:"",F=n.some(h=>h.channel?.kind==="room"),T=Ce(F,l.server,N),Y=s.length>0?`
|
|
235
235
|
/**
|
|
236
236
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
237
237
|
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
238
238
|
* evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
|
|
239
239
|
* \`shape_subscribe\` (reads-as-permissions).
|
|
240
240
|
*/
|
|
241
|
-
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${
|
|
242
|
-
`:"",
|
|
241
|
+
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${p}};
|
|
242
|
+
`:"",Z=v.length>0?`
|
|
243
243
|
/**
|
|
244
244
|
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
245
245
|
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
246
246
|
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
247
247
|
*/
|
|
248
|
-
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${
|
|
249
|
-
`:"",
|
|
250
|
-
|
|
248
|
+
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${v.map(h=>JSON.stringify(h)).join(", ")}]);
|
|
249
|
+
`:"",X=$.length>0?`
|
|
250
|
+
/**
|
|
251
|
+
* Queries and shapes that may read \`ctx.ip\`, decided statically (failing closed). The generated ShardDO marks them
|
|
252
|
+
* address-keyed from its first run, so it never resumes one warm: its rows can depend on the address the cursor
|
|
253
|
+
* was read at, which a claims fingerprint leaves out.
|
|
254
|
+
*/
|
|
255
|
+
export const LUNORA_IP_READER_PATHS: ReadonlySet<string> = new Set([${$.map(h=>JSON.stringify(h)).join(", ")}]);
|
|
256
|
+
`:"",ee=De(F,o,n),{fields:te,lifecycleMember:M,registry:re}=Ie(n,o),ne=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${l.values}";
|
|
257
|
+
`:"",oe=y.length>0?`
|
|
251
258
|
/**
|
|
252
259
|
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
253
260
|
* onto its function's live \`.args\` object and consulted by the interpreted
|
|
254
261
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
255
262
|
*/
|
|
256
|
-
${
|
|
257
|
-
`:"",
|
|
263
|
+
${y}
|
|
264
|
+
`:"",se=je(n,o),{callRegisteredHelper:ae,dataModelImport:ie,implementation:ce,parameter:le,types:de}=se,ue=o?`
|
|
258
265
|
export interface FunctionManifestEntry {
|
|
259
266
|
argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; table?: string }>;
|
|
260
267
|
channel?: { kind: "room"; name: string };
|
|
261
268
|
exportName: string;
|
|
262
269
|
expose?: { cache?: { credentialHeaders?: ReadonlyArray<string>; maxAge?: number; scope?: "private" | "public"; staleWhileRevalidate?: number; tag?: string; vary?: string }; rest?: boolean };
|
|
263
270
|
kind: "action" | "mutation" | "query" | "stream";
|
|
264
|
-
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${
|
|
271
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${M};
|
|
265
272
|
moduleId: string;
|
|
266
273
|
visibility?: "internal" | "public";
|
|
267
274
|
x402?: { readonly price: number | string };
|
|
268
275
|
}
|
|
269
276
|
|
|
270
277
|
/** Static, codegen-derived facts. Request gates can inspect these without evaluating a user module. */
|
|
271
|
-
export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${
|
|
278
|
+
export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${R}};
|
|
272
279
|
|
|
273
|
-
const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${
|
|
280
|
+
const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${x}};
|
|
274
281
|
const loadedModules = new Map<string, Promise<Record<string, unknown>>>();
|
|
275
282
|
const resolvedModules = new Map<string, Record<string, unknown>>();
|
|
276
283
|
const boundFunctions = new Set<string>();
|
|
@@ -280,8 +287,8 @@ const unloadedFunctionHandler = (): never => {
|
|
|
280
287
|
|
|
281
288
|
/** Reuse an evaluated module synchronously, so dispatch does not yield after restoring request scope. */
|
|
282
289
|
export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunction | undefined => {
|
|
283
|
-
const registered = ${
|
|
284
|
-
const manifest = ${
|
|
290
|
+
const registered = ${S("LUNORA_FUNCTIONS")};
|
|
291
|
+
const manifest = ${S("LUNORA_FUNCTION_MANIFEST")};
|
|
285
292
|
|
|
286
293
|
if (!registered || !manifest) {
|
|
287
294
|
return registered;
|
|
@@ -312,7 +319,7 @@ export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunctio
|
|
|
312
319
|
/** Load one function's owning module once per isolate, then merge its live builder result into the registry entry. */
|
|
313
320
|
export const loadFunction = async (functionPath: string): Promise<RegisteredLunoraFunction | undefined> => {
|
|
314
321
|
const registered = getLoadedFunction(functionPath);
|
|
315
|
-
const manifest = ${
|
|
322
|
+
const manifest = ${S("LUNORA_FUNCTION_MANIFEST")};
|
|
316
323
|
|
|
317
324
|
if (registered || !manifest) {
|
|
318
325
|
return registered;
|
|
@@ -339,7 +346,7 @@ export const loadFunction = async (functionPath: string): Promise<RegisteredLuno
|
|
|
339
346
|
return getLoadedFunction(functionPath);
|
|
340
347
|
};
|
|
341
348
|
|
|
342
|
-
`:"",
|
|
349
|
+
`:"",he=o&&R!==""?`
|
|
343
350
|
/**
|
|
344
351
|
* Evaluate every lazy module now and report the ones that fail, keyed by function path. A lazy
|
|
345
352
|
* registry defers a broken module's error to its first call; \`lunora build\` and \`deploy\` run this
|
|
@@ -365,9 +372,9 @@ export const loadAllFunctions = async (): Promise<{ checked: number; failures: R
|
|
|
365
372
|
|
|
366
373
|
return { checked: functionPaths.length, failures };
|
|
367
374
|
};
|
|
368
|
-
`:"";return
|
|
375
|
+
`:"";return we(`${U}${f}${w.importLine}${O.importLine}${ne}${K}${T.typeImport}import { LunoraError } from "${l.server}";
|
|
369
376
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
370
|
-
${
|
|
377
|
+
${ie}
|
|
371
378
|
/**
|
|
372
379
|
* Single registered function, narrowed to the shape \`handleRpc\` needs.
|
|
373
380
|
* The real argument validators / return types are checked elsewhere — at
|
|
@@ -396,8 +403,8 @@ export interface RegisteredLunoraFunction {
|
|
|
396
403
|
* \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
|
|
397
404
|
* to. \`whisper\` does have one — it runs under the asking socket's identity.
|
|
398
405
|
*/
|
|
399
|
-
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${
|
|
400
|
-
${
|
|
406
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${M};${te}
|
|
407
|
+
${T.channelField} /**
|
|
401
408
|
* Hoisted by the builder when the \`.use()\` chain carries a step with a
|
|
402
409
|
* per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
|
|
403
410
|
* captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
|
|
@@ -413,13 +420,13 @@ ${L.channelField} /**
|
|
|
413
420
|
*/
|
|
414
421
|
x402?: { readonly price: number | string };
|
|
415
422
|
${m}}
|
|
416
|
-
${
|
|
423
|
+
${w.prelude}${O.prelude}${ue}${he}
|
|
417
424
|
/**
|
|
418
425
|
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
419
426
|
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
420
427
|
*/
|
|
421
|
-
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${
|
|
422
|
-
${
|
|
428
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${A}};
|
|
429
|
+
${oe}${Y}${Z}${X}${ee}${T.messagesBlock}${re}
|
|
423
430
|
/**
|
|
424
431
|
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
425
432
|
* client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
|
|
@@ -437,11 +444,11 @@ export const LUNORA_LIFECYCLE_HOOKS: {
|
|
|
437
444
|
reactor: readonly string[];
|
|
438
445
|
whisper: readonly string[];
|
|
439
446
|
} = {
|
|
440
|
-
connect: [${b.connect.map(
|
|
441
|
-
disconnect: [${b.disconnect.map(
|
|
442
|
-
init: [${b.init.map(
|
|
443
|
-
reactor: [${b.reactor.map(
|
|
444
|
-
whisper: [${b.whisper.map(
|
|
447
|
+
connect: [${b.connect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
448
|
+
disconnect: [${b.disconnect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
449
|
+
init: [${b.init.map(h=>JSON.stringify(h)).join(", ")}],
|
|
450
|
+
reactor: [${b.reactor.map(h=>JSON.stringify(h)).join(", ")}],
|
|
451
|
+
whisper: [${b.whisper.map(h=>JSON.stringify(h)).join(", ")}],
|
|
445
452
|
};
|
|
446
453
|
|
|
447
454
|
/**
|
|
@@ -451,7 +458,7 @@ export const LUNORA_LIFECYCLE_HOOKS: {
|
|
|
451
458
|
* functions are treated as not-found so their existence never leaks to clients.
|
|
452
459
|
*/
|
|
453
460
|
export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
|
|
454
|
-
${
|
|
461
|
+
${V} const registered = ${G};
|
|
455
462
|
|
|
456
463
|
if (!registered || registered.visibility === "internal") {
|
|
457
464
|
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
@@ -472,10 +479,10 @@ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
|
472
479
|
* with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
|
|
473
480
|
* \`runAction\` but without re-stating the function path.
|
|
474
481
|
*/
|
|
475
|
-
export interface Caller {${
|
|
482
|
+
export interface Caller {${de}}
|
|
476
483
|
|
|
477
|
-
${
|
|
478
|
-
export const createCaller = (${
|
|
484
|
+
${ae}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
485
|
+
export const createCaller = (${le}: CallerCtx): Caller => ({${ce}});
|
|
479
486
|
|
|
480
487
|
/**
|
|
481
488
|
* Single registered data migration, narrowed to the shape the per-shard runner
|
|
@@ -494,13 +501,13 @@ export interface RegisteredDataMigration {
|
|
|
494
501
|
* Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
|
|
495
502
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
496
503
|
*/
|
|
497
|
-
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${
|
|
498
|
-
`,c)},
|
|
499
|
-
`:"",
|
|
500
|
-
`:"",
|
|
504
|
+
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${P}};
|
|
505
|
+
`,c)},Qe="fn",Ge=r=>{if(r.lazyFunctions!==!0)return{};const{functions:t}=r,n=r.migrations??[],o=r.mutators??[],a=r.shapes??[],i=W(t,n,o,a),s=Q(n,o,a),c=[...new Set(t.filter(d=>!s.has(d.filePath)).map(d=>d.filePath))],u=J(r.useUmbrella??!1),l={};for(const d of c){if(!E.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`,$=t.filter(p=>p.filePath===d&&!p.lifecycle&&Object.keys(p.args).length>0).flatMap(p=>{const w=z(p.args);return w===void 0?[]:[`installCompiledValidatorMap(${f}.${p.exportName}.args, ${w});`]}),R=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
|
|
506
|
+
`:"",P=$.length>0?`import * as ${f} from "${y}";
|
|
507
|
+
`:"",x=$.length>0?`
|
|
501
508
|
/** Install the precompiled argument parsers before the module is dispatched. */
|
|
502
|
-
${
|
|
509
|
+
${$.join(`
|
|
503
510
|
`)}
|
|
504
|
-
`:"",
|
|
505
|
-
`:"";l[`${f}.ts`]=`${
|
|
506
|
-
${
|
|
511
|
+
`:"",N=t.some(p=>p.filePath===d&&p.exportName==="default")||n.some(p=>p.filePath===d&&p.exportName==="default")?`export { default } from "${y}";
|
|
512
|
+
`:"";l[`${f}.ts`]=`${U}${R}${P}${x}export * from "${y}";
|
|
513
|
+
${N}`}return l};export{Qe as LAZY_FUNCTION_DIRECTORY,We as emitFunctions,Ge as emitLazyFunctionModules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{e}from"./server-
|
|
1
|
+
import"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{e}from"./server-D69SOfX8.mjs";import"./shared-A1XHcT4t.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-L3gYZnC9.mjs";import"./shard-runtime-lkQU8trx.mjs";import"./shared-A1XHcT4t.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s}from"ts-morph";import{
|
|
1
|
+
import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-CTMkuBkn.mjs";import{c as n}from"./classify-procedure-call-DtqiTjPg.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{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-JdN4KXhV.mjs";import{r as v,h}from"./attribution-CTMkuBkn.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{LunoraError as d}from"@lunora/errors";import{Node as s,SyntaxKind as k}from"ts-morph";import{d as I}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as f,bindingKeyName as C,listLunoraSourceFiles as F,lunoraRelativePath as R}from"./isTestPath-JdN4KXhV.mjs";import{e as _,i as V}from"./attribution-CTMkuBkn.mjs";import{u as N,p as z,c as A,r as $}from"./unwrap-handler-return-eQRIZSOX.mjs";import{m as j}from"./ip-reads-BVXbFgzV.mjs";import{b as v,s as D,c as M}from"./classify-procedure-call-DtqiTjPg.mjs";import{r as O,p as S,a as H}from"./parse-validator-BisfC8bR.mjs";import{s as W}from"./dispatch-namespace-DwTjD7BU.mjs";const P=t=>t!==void 0&&(s.isArrowFunction(t)||s.isFunctionExpression(t))?t:void 0,B=t=>{const i=t.getArguments()[0],e=P(i);if(e!==void 0)return e;if(i===void 0||!s.isObjectLiteralExpression(i))return;const r=f(i,"handler");return r!==void 0&&s.isPropertyAssignment(r)?P(r.getInitializer()):void 0},K=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const e=f(i,"handler");if(!e||!s.isPropertyAssignment(e))return"unknown";const r=e.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":N(r)},q=t=>{const i=t.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":N(i)},U=t=>{let i={};for(const e of v(t)){if(e.name!=="input")continue;const r=e.call.getArguments()[0],o=r!==void 0&&s.isExpression(r)?O(r):void 0;o!==void 0&&(i={...S(o),...i})}return i},J=t=>{const i=v(t).find(r=>r.name==="output");if(!i)return;const e=i.call.getArguments()[0];return e&&s.isExpression(e)?z(i.call,()=>H(e)):void 0},x=(t,i)=>{const e=f(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isStringLiteral(r)?r.getLiteralValue():void 0},E=(t,i)=>{const e=f(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isNumericLiteral(r)?r.getLiteralValue():void 0},X=t=>{const i=f(t,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const e=i.getInitializer();if(e===void 0||!s.isObjectLiteralExpression(e))return;const r=x(e,"scope"),o=E(e,"maxAge"),n=E(e,"staleWhileRevalidate"),a=x(e,"tag"),l=x(e,"vary"),c={...o===void 0?{}:{maxAge:o},...r==="private"||r==="public"?{scope:r}:{},...n===void 0?{}:{staleWhileRevalidate:n},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},G=t=>{if(t===void 0||!s.isObjectLiteralExpression(t))return{};const i=X(t),e=f(t,"rest");return e!==void 0&&s.isPropertyAssignment(e)?{...i===void 0?{}:{cache:i},rest:e.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},Q=t=>{const i=v(t).find(e=>e.name==="expose");return i?G(i.call.getArguments()[0]):void 0},Y=t=>{const i=v(t).find(n=>n.name==="x402");if(!i)return;const e=i.call.getArguments()[0];if(e===void 0||!s.isObjectLiteralExpression(e))return{};const r=f(e,"price");if(r===void 0||!s.isPropertyAssignment(r))return{};const o=r.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},Z=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const e=f(i,"args");if(!e||!s.isPropertyAssignment(e))return{};const r=e.getInitializer(),o=r===void 0?void 0:O(r);return o===void 0?{}:S(o)},p=(t,i)=>{throw new d("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${t.getSourceFile().getFilePath()}:${String(t.getStartLineNumber())}`)},b=(t,i,e)=>{if(!t||!s.isObjectLiteralExpression(t))return p(i,"metadata objects");const r=new Set;for(const o of t.getProperties()){if(!s.isPropertyAssignment(o))return p(o,"metadata fields without spreads, getters, or shorthand");const n=o.getNameNode(),a=s.isStringLiteral(n)?n.getLiteralValue():n.getText();if(!s.isIdentifier(n)&&!s.isStringLiteral(n)||!e.includes(a)||r.has(a))return p(o,"supported, unique metadata fields");r.add(a)}return t},g=(t,i)=>{const e=t.getProperty(i);return e&&s.isPropertyAssignment(e)?e.getInitializer():void 0},ee=t=>{const i=b(t,t,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),e={};for(const n of["maxAge","staleWhileRevalidate"]){const a=g(i,n);if(!(a===void 0&&n!=="maxAge")){if(!a||!s.isNumericLiteral(a))return p(t,`cache.${n}`);e[n]=a.getLiteralValue()}}const r=g(i,"scope");if(!r||!s.isStringLiteral(r)||!["private","public"].includes(r.getLiteralValue()))return p(t,"cache.scope");e.scope=r.getLiteralValue();for(const n of["tag","vary"]){const a=g(i,n);if(a!==void 0){if(!s.isStringLiteral(a))return p(a,`cache.${n}`);e[n]=a.getLiteralValue()}}const o=g(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return p(o,"cache.credentialHeaders");e.credentialHeaders=o.getElements().map(n=>s.isStringLiteral(n)?n.getLiteralValue():p(n,"cache.credentialHeaders string entries"))}return e},te=t=>{const i=b(t.getArguments()[0],t,["rest","cache"]),e=g(i,"rest"),r=g(i,"cache");return e!==void 0&&!s.isTrueLiteral(e)&&!s.isFalseLiteral(e)?p(e,".expose({ rest })"):{...e?{rest:s.isTrueLiteral(e)}:{},...r?{cache:ee(r)}:{}}},ie=t=>{const i=b(t.getArguments()[0],t,["price"]),e=g(i,"price");return!e||!s.isStringLiteral(e)&&!s.isNumericLiteral(e)?p(t,"`.x402({ price })` value"):{price:e.getLiteralValue()}},re=t=>{const{factory:i,steps:e}=D(t);if(!i)return p(t,"metadata from a resolvable Lunora factory root");const r={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:o,name:n}of e){if(!["expose","input","meta","output","use","x402"].includes(n))return p(o,`known builder modifiers, got .${n}()`);n==="expose"&&r.expose===void 0&&(r.expose=te(o)),n==="x402"&&r.x402===void 0&&(r.x402=ie(o))}return r},ne=8,h=(t,i=0)=>{if(i>ne)return;if(s.isCallExpression(t))return t;if(s.isParenthesizedExpression(t)||s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isNonNullExpression(t))return h(t.getExpression(),i+1);if(!s.isIdentifier(t)&&!s.isPropertyAccessExpression(t))return;const e=t.getSymbol()?.getValueDeclaration();return e?L(e,i+1):void 0},L=(t,i)=>{if(s.isVariableDeclaration(t)||s.isPropertyAssignment(t)){const e=t.getInitializer();return e?h(e,i):void 0}if(s.isShorthandPropertyAssignment(t)){const e=t.getValueSymbol()?.getValueDeclaration();return e?L(e,i+1):void 0}if(s.isBindingElement(t)){const e=C(t),n=t.getFirstAncestorByKind(k.VariableDeclaration)?.getInitializer()?.getType().getProperty(e)?.getValueDeclaration();return n?L(n,i+1):void 0}},se=(t,i=()=>!0)=>{const e=t.getNameNode();if(s.isObjectBindingPattern(e)){const n=[];for(const a of e.getElements().filter(l=>i(l.getName()))){const l=h(a.getNameNode());l&&n.push([a.getName(),l])}return n}if(!i(t.getName()))return[];const r=t.getInitializer(),o=r&&(s.isCallExpression(r)?r:h(r));return o?[[t.getName(),o]]:[]},oe=t=>{const i=t.getArguments()[0],e=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return r.getLiteralValue()},ae=t=>t.startsWith("/")&&new URL(t,"https://lunora.invalid").pathname===t&&t!=="/_lunora"&&!t.startsWith("/_lunora/"),ce=t=>{const i=t.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new d("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const e=i.getProperty("path"),r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=r.getLiteralValue();if(!ae(o))throw new d("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 d("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 d("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}},le=(t,i,e,r)=>{const o=r?re(i):void 0,n=r?o?.expose:Q(i),a=r?o?.x402:Y(i),l=A(()=>J(i)),c=A(()=>q(t)),u=I({kind:e.kind,output:l.value});return $(u?l.erased:c.erased),{args:U(i),...n?{expose:n}:{},...a?{x402:a}:{},...e.adminOnly?{adminOnly:!0}:{},kind:e.kind,...l.value?{output:l.value}:{},returnType:c.value,visibility:o?.visibility==="internal"||e.visibility==="internal"?"internal":"public"}},ue=(t,i)=>{const e=M(t,i);if(!e)return;if(e.channel)return{args:{},channel:{kind:e.channel,name:oe(t)},kind:e.kind,returnType:"void",visibility:e.visibility};const{receiver:r}=e;return r?le(t,r,e,i):e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",...e.lifecycle==="socket"?{socket:{...ce(t),origin:`${t.getSourceFile().getFilePath()}@${String(t.getStart())}`}}:{},visibility:e.visibility}:{args:Z(t),kind:e.kind,returnType:K(t),visibility:e.visibility}},T=t=>{const i=t?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},pe=t=>T(t.getFirstAncestor(i=>s.isVariableStatement(i))),de=(t,i)=>T(t.getVariableStatements().find(e=>e.isExported()&&e.getDeclarations().some(r=>r.getName()===i))),w=(t,i,e,r,o)=>{const n=ue(t,r);if(!n)return;const a=o??pe(t);return{args:n.args,...a?{description:a}:{},exportName:i,filePath:e,kind:n.kind,returnType:n.returnType,...n.output?{output:n.output}:{},visibility:n.visibility,...n.adminOnly?{adminOnly:!0}:{},...n.kind==="query"&&(B(t)===void 0||j(t))?{readsIp:!0}:{},...n.expose?{expose:n.expose}:{},...n.x402?{x402:n.x402}:{},...n.lifecycle?{lifecycle:n.lifecycle}:{},...n.channel?{channel:n.channel}:{},...n.socket?{socket:n.socket}:{}}},fe=(t,i,e)=>{const r=[];for(const o of t.getExportAssignments()){if(o.isExportEquals())continue;const n=h(o.getExpression()),a=n?w(n,"default",i,e):void 0;n&&a&&r.push({call:n,entry:a})}return r},me=(t,i,e)=>{const r=_(t),o=new Map,n=(c,u)=>{if(c?.channel?.kind!=="room")return;const m=o.get(c.channel.name);if(m!==void 0&&m!==u)throw new d("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=t.getVariableStatements().flatMap(c=>c.getDeclarations()).flatMap(c=>se(c,u=>r.has(u))).flatMap(([c,u])=>(r.get(c)??[]).filter(m=>V(m)).flatMap(m=>{const y=w(u,m,i,e,de(t,m));return n(y,u),y?[y]:[]})),l=new Set(a.map(c=>c.exportName));for(const{call:c,entry:u}of fe(t,i,e))l.has(u.exportName)||(n(u,c),a.push(u));return a},ge=t=>{const i=new Map;for(const e of t){if(e.channel?.kind!=="room")continue;const r=i.get(e.channel.name);if(r!==void 0&&r.file!==e.filePath)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${e.channel.name}": defined in ${r.origin} and ${e.filePath}:${e.exportName}. Room names must be unique across the project.`);r===void 0&&i.set(e.channel.name,{file:e.filePath,origin:`${e.filePath}:${e.exportName}`})}},he=t=>{const i=new Map;for(const e of t){const r=W(e.filePath),o=i.get(r);if(o&&o!==e.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${e.filePath}" both resolve to "${r}". 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,e.filePath],status:500});i.set(r,e.filePath)}},Se=(t,i,e={})=>{const r=F(i),o=[];for(const n of r){const a=t.getSourceFile(n)??t.addSourceFileAtPath(n),l=R(i,n);o.push(...me(a,l,e.lazyFunctions===!0))}return o.sort((n,a)=>`${n.filePath}:${n.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),he(o),ge(o),o};export{Se as d,P as i,B as p};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-JdN4KXhV.mjs";import{
|
|
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-QqsrkDMs.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{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-TiLodrRO.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{Node as i,VariableDeclarationKind as E}from"ts-morph";import{diagnosticAt as h}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{s as A}from"./property-name-7cBlgK_O.mjs";let g;const q=e=>{g=e},k=/^[A-Za-z_$][\w$]*$/u,p=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","serverDefault","unique"]),N=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":case"serverDefault":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},T=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","email","int","length","max","min","pattern","positive","url"]),I=new Set(["meta"]),L=new Set(["strip"]),l=new Set,f=new Set,v=e=>{const t=e.getSymbol();let r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(r!==void 0&&i.isShorthandPropertyAssignment(r)){const n=r.getValueSymbol();r=(n?.getAliasedSymbol()??n)?.getValueDeclaration()}if(!(r===void 0||!i.isVariableDeclaration(r)))return r.getInitializer()},w=e=>{const t=e.getParent();return!i.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===E.Const},u=e=>{if(i.isParenthesizedExpression(e)||i.isAsExpression(e)||i.isSatisfiesExpression(e))return u(e.getExpression());if(i.isObjectLiteralExpression(e))return e;if(i.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),n=r!==void 0&&i.isPropertyAssignment(r)?r.getInitializer():void 0;return n===void 0?void 0:u(n)}if(!i.isIdentifier(e)||l.has(e))return;const t=v(e);if(!(t===void 0||!w(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},D="v",R=e=>{if(i.isIdentifier(e))return!0;let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return i.isIdentifier(t)&&t.getText()===D},d=e=>{if(i.isIdentifier(e)&&!l.has(e)){const t=v(e);if(t!==void 0&&R(t)){l.add(e);try{return d(t)}finally{l.delete(e)}}}return i.isCallExpression(e)?C(e):{kind:"any",sourceText:e.getText()}},S=e=>{const t=u(e);if(t===void 0||f.has(t))return{};f.add(t);try{return x(t)}finally{f.delete(t)}},b=(e,t=new Set)=>{const r=u(e);if(r===void 0||t.has(r))return!1;t.add(r);try{return r.getProperties().every(n=>i.isSpreadAssignment(n)?b(n.getExpression(),t):i.isPropertyAssignment(n)||i.isShorthandPropertyAssignment(n))}finally{t.delete(r)}},P=e=>{if(e===void 0||!i.isExpression(e))return{kind:"object",shape:{},unresolvedShape:!0};const t=S(e);return b(e)?{kind:"object",shape:t}:{kind:"object",shape:t,unresolvedShape:!0}},V=e=>{throw h(e,`computed property name ${e.getText()} must be a string literal — codegen resolves object keys statically.`)},x=e=>{const t={};for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){Object.assign(t,S(r.getExpression()));continue}const n=i.isShorthandPropertyAssignment(r);if(!n&&!i.isPropertyAssignment(r))continue;const a=n?r.getNameNode():r.getInitializer();if(!a)continue;const s=r.getNameNode(),o=A(s)??V(s);if(!k.test(o))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(o)}`);t[o]=d(a)}return t},c=(e,t)=>e&&i.isExpression(e)?d(e):t,O=e=>e.sensitive===!0?!0:[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(r=>r!==void 0&&O(r)),M=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),$=e=>{const t=e&&g?g(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},F=(e,t,r)=>{if(T.has(e))return{kind:e};const[n,a]=t;switch(e){case"array":return{inner:c(n,{kind:"any"}),kind:"array"};case"from":return $(n);case"id":{if(!n||!i.isStringLiteral(n))throw h(n??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${n?n.getText():"no argument"}.`);return{kind:"id",tableName:n.getLiteralText()}}case"literal":return{kind:"literal",literalValue:M(n)};case"object":return P(n);case"optional":return{inner:c(n,{kind:"any"}),kind:"optional"};case"record":return{keyType:c(n,{kind:"string"}),kind:"record",valueType:c(a,{kind:"any"})};case"sensitive":return{...c(n,{kind:"any"}),sensitive:!0};case"storage":return n&&i.isStringLiteral(n)?{bucket:n.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(s=>i.isExpression(s)).map(s=>d(s))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},j=e=>{const[t]=e;if(e.length!==1||t===void 0||!i.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},C=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),n=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||L.has(r)){const a=t.getExpression(),s=i.isExpression(a)?d(a):{kind:"any"};if(p.has(r))return N(s,r);if(!m.has(r))return s;const o=r==="max"&&s.kind==="string"?j(n):void 0;return o!==void 0?{...s,hasRefinement:!0,stringMaxLength:Math.min(s.stringMaxLength??o,o)}:{...s,hasRefinement:!0,unmodelledRefinement:!0}}return F(r,n,e)};export{d as a,x as p,u as r,q as s,O as v};
|
|
@@ -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-A1XHcT4t.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-A1XHcT4t.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=>`
|