@lunora/codegen 1.0.0-alpha.406 → 1.0.0-alpha.407

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.
Files changed (35) hide show
  1. package/dist/index.d.mts +24 -1
  2. package/dist/index.d.ts +24 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-DPxI0EHQ.mjs → ALL_NOTIFY_CHANNELS-D1LVGz6_.mjs} +1 -1
  5. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DslD_cFq.mjs +54 -0
  6. package/dist/packem_shared/{SHAPES_FILENAME-CH0KrAdb.mjs → SHAPES_FILENAME-BYnZ1Xw-.mjs} +1 -1
  7. package/dist/packem_shared/chain-CONXUmWW.mjs +1 -0
  8. package/dist/packem_shared/{classify-procedure-call-BZ164dkJ.mjs → classify-procedure-call-n9urVsqb.mjs} +1 -1
  9. package/dist/packem_shared/{context-property-calls-Ggrmu3UL.mjs → context-property-calls-DXzNVV1P.mjs} +1 -1
  10. package/dist/packem_shared/{context-root-DnvrQxae.mjs → context-root-DP9WbBI_.mjs} +1 -1
  11. package/dist/packem_shared/{database-calls-BRI5W-Mp.mjs → database-calls-Do0YbPCL.mjs} +1 -1
  12. package/dist/packem_shared/discoverFunctions-CeHY4_ii.mjs +1 -0
  13. package/dist/packem_shared/discoverHyperdriveCalls-W96s1VgA.mjs +1 -0
  14. package/dist/packem_shared/{discoverInserts-DmSa4WKU.mjs → discoverInserts-BtyJbg8A.mjs} +1 -1
  15. package/dist/packem_shared/discoverMaskProcedures-BFm9rkZ7.mjs +1 -0
  16. package/dist/packem_shared/{discoverNondeterministicCalls-BoF6ob-B.mjs → discoverNondeterministicCalls-DR0S5Xb4.mjs} +1 -1
  17. package/dist/packem_shared/{discoverQueries-spxu-wHR.mjs → discoverQueries-BLyL2qzX.mjs} +1 -1
  18. package/dist/packem_shared/discoverR2sqlCalls-Cb4AmcY8.mjs +1 -0
  19. package/dist/packem_shared/{discoverRlsMetadata-Cc0zA-gZ.mjs → discoverRlsMetadata-Cf4gZvxW.mjs} +1 -1
  20. package/dist/packem_shared/{discoverRlsProcedures-mjiA0I4S.mjs → discoverRlsProcedures-_Dh3Xb9Z.mjs} +1 -1
  21. package/dist/packem_shared/{discoverStorageRulesMetadata-CtE5trUR.mjs → discoverStorageRulesMetadata-ZKW6DInk.mjs} +1 -1
  22. package/dist/packem_shared/{emitApp-BsXqg0CQ.mjs → emitApp-BSeuQrKr.mjs} +65 -64
  23. package/dist/packem_shared/{emitServer-DsSAaZaT.mjs → emitServer-CbcZN_Ug.mjs} +1 -1
  24. package/dist/packem_shared/{exported-procedure-chains-h8Y7xDjq.mjs → exported-procedure-chains-DomRzs5_.mjs} +1 -1
  25. package/dist/packem_shared/{index-jtzAVdUp.mjs → index-BH3e-J44.mjs} +1 -1
  26. package/dist/packem_shared/{index-mFEIaT45.mjs → index-D03C6Kao.mjs} +1 -1
  27. package/dist/packem_shared/{ip-reads-BPDWkzEu.mjs → ip-reads-ByzaRhd2.mjs} +1 -1
  28. package/dist/packem_shared/{server-CRFaUMKQ.mjs → server-5ph4hltf.mjs} +63 -55
  29. package/package.json +1 -1
  30. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DfLhJQrR.mjs +0 -54
  31. package/dist/packem_shared/chain-CXiqZFUk.mjs +0 -1
  32. package/dist/packem_shared/discoverFunctions-mAWlAiuj.mjs +0 -1
  33. package/dist/packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs +0 -1
  34. package/dist/packem_shared/discoverMaskProcedures-CyjXtZgc.mjs +0 -1
  35. package/dist/packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs +0 -1
@@ -1 +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-DRIdZaij.mjs";import{e as K,i as O}from"./attribution-BhGR_h0Z.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-DUzluwPj.mjs";import{m as J}from"./ip-reads-BPDWkzEu.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-BZ164dkJ.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DR7xrrNB.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
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-DRIdZaij.mjs";import{e as K,i as O}from"./attribution-BhGR_h0Z.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-DUzluwPj.mjs";import{m as J}from"./ip-reads-ByzaRhd2.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-n9urVsqb.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DR7xrrNB.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
@@ -1 +1 @@
1
- import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-DRIdZaij.mjs";import{j as m,h as p}from"./attribution-BhGR_h0Z.mjs";import{t as d}from"./database-calls-BRI5W-Mp.mjs";import{w as g,c as h}from"./classify-procedure-call-BZ164dkJ.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};
1
+ import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-DRIdZaij.mjs";import{j as m,h as p}from"./attribution-BhGR_h0Z.mjs";import{t as d}from"./database-calls-Do0YbPCL.mjs";import{w as g,c as h}from"./classify-procedure-call-n9urVsqb.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};
@@ -1 +1 @@
1
- import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-DnvrQxae.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
+ import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-DP9WbBI_.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,12 +1,12 @@
1
- import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-BuNEmlCO.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 C,u as Ke,d as Ue}from"./shared-Cn7dMQ_u.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{ctimeMs:o,mtimeMs:a,size:e}=Le(t);return`${String(a)}:${String(o)}:${String(e)}`},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
- `)},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
- `:"",R=a.length>0?`
4
- readonly containers: {${a.map(r=>`
5
- readonly ${r.exportName}: ${f(r)};`).join("")}
6
- };`:"",b=[...o.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...a.map(r=>(C(r.bindingName,`container binding "${r.bindingName}"`),` /** Durable Object namespace for the \`${r.exportName}\` container. */
7
- readonly ${r.bindingName}?: unknown;`)),...v.map(r=>(C(r.bindingName,`queue binding "${r.bindingName}"`),` /** Queue producer binding for the \`${r.exportName}\` queue. */
1
+ import{CAPABILITIES as ze}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{existsSync as W,readdirSync as ue,readlinkSync as pe,lstatSync as Ke,statSync as Ue}from"node:fs";import{join as h,relative as y,dirname as l,sep as me,isAbsolute as Je,resolve as Ye,basename as Xe}from"node:path";import{ts as c,Project as Ze}from"ts-morph";import{G as ye,a as F,u as et,d as tt}from"./shared-Cn7dMQ_u.mjs";import{p as at}from"./platform-8oj7iXQy.mjs";const he=/(?:\.d)?\.([cm]?)tsx?$/u,rt=t=>t.replace(he,".d.$1ts"),fe=(t,o)=>{const a=y(t,o).split(me).join("/").replace(he,".$1js");return a.startsWith(".")?a:`./${a}`},be=t=>t.replaceAll("\\","/"),Z=(t,o,a)=>be(h(t,rt(y(o,a)))),ot=t=>fe(".",h("services",t.name,y(l(t.wranglerPath),t.main))),nt=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},x=t=>{const{ctimeMs:o,mtimeMs:a,size:e}=Ue(t);return`${String(a)}:${String(o)}:${String(e)}`},st=new Set([".git",".wrangler","dist","node_modules","target"]),ge=t=>ue(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${pe(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${x(a)}`,...ge(a)]:[]}),xe=t=>[`${t}:${x(t)}`,...ge(t)],Te=t=>{const o=h(t,"node_modules"),a=W(o)?xe(o):[],e=l(t);return e===t?a:[...a,...Te(e)]},it=(t,o)=>{const a=[];try{const e=n=>{for(const s of ue(n,{withFileTypes:!0})){const d=h(n,s.name);if(d!==o)if(s.isSymbolicLink())a.push(`${d}->${pe(d)}`);else if(s.isDirectory()){if(s.name==="node_modules")a.push(...xe(d));else if(!st.has(s.name)){if(!Ke(d).isDirectory())throw new Error(`${d} changed during the scan`);e(d)}}else a.push(`${d}:${x(d)}`)}};e(t),a.push(...Te(t))}catch{return}return[...new Set(a)].toSorted((e,n)=>e.localeCompare(n)).join(`
2
+ `)},dt=t=>Xe(l(t)).startsWith("@")?l(l(t)):l(t),de=(t,o)=>!y(o,t).startsWith("..")&&!t.split(me).includes("node_modules"),le=(t,o)=>{const a=[];let e=t;for(;e!==l(e)&&!W(h(e,"package.json"));)a.push(e),e=l(e);if(W(h(e,"package.json"))){for(const n of[...a,e,h(e,"package.json")])o.add(n);return e}},lt=(t,o,a)=>{let e=t;for(;y(e,o).startsWith("..")&&e!==l(e);)a.add(e),e=l(e);a.add(e)},ct=(t,o)=>{const a=new Set;t.some(e=>de(e,o))&&le(o,a);for(const e of t){if(de(e,o)){for(let s=l(e);s!==o&&s!==l(s);s=l(s))a.add(s);continue}const n=le(l(e),a);n===void 0?lt(l(e),o,a):a.add(dt(n))}return[...a].map(e=>[e,x(e)])},ve=new Map,ce=([t,o])=>{try{return x(t)===o}catch{return!1}},ut=(t,o,a)=>{const e=ve.get(t);return e?.optionsKey===o&&e.stamps.every(s=>ce(s))&&e.directories.every(s=>ce(s))&&a!==void 0&&e.tree===a?e.files:void 0},pt=(t,o,a)=>{const e=[...o.stamps,...o.directories].every(([,n])=>Math.floor(Number.parseFloat(n))<=a);o.tree!==void 0&&e&&ve.set(t,{...o,tree:o.tree})},mt=(t,o)=>({directories:ct(o,t),stamps:o.map(a=>[a,x(a)])}),wt=(t,o)=>{const a=l(t.wranglerPath),e=y(a,t.main);if(e.startsWith("..")||Je(e))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const n=h(o,"services",t.name),s=c.findConfigFile(a,i=>c.sys.fileExists(i)),d=new Ze({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:n,rootDir:a},skipAddingFilesFromTsConfig:!0,...s===void 0?{}:{tsConfigFilePath:s}}),S=JSON.stringify([t.name,t.main,t.wranglerPath,o]),m=JSON.stringify(d.getCompilerOptions()),T=it(a,Ye(o)),v=ut(S,m,T);if(v!==void 0)return v;const w=Date.now();d.addSourceFileAtPath(t.main),d.resolveSourceFileDependencies();const P=d.getProgram().compilerObject.getSourceFiles().map(i=>i.fileName).filter(i=>W(i)),{directories:$,stamps:j}=mt(a,P),O={...d.getCompilerOptions(),preserveSymlinks:!0},u=new Map(d.getSourceFiles().map(i=>i.getFilePath()).filter(i=>!i.endsWith(".d.ts")&&!y(a,i).startsWith("..")).map(i=>[Z(n,a,i),i])),f={};for(const i of d.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const R=u.get(be(i.filePath));if(R===void 0)continue;const B=c.createSourceFile(i.filePath,i.text,c.ScriptTarget.Latest,!1);let{text:b}=i;for(const g of nt(B).toReversed()){const I=c.resolveModuleName(g.text,R,O,c.sys).resolvedModule?.resolvedFileName;if(I===void 0)continue;const k=Z(n,a,I),N=u.has(k)?k:I;b=`${b.slice(0,g.getStart(B))}${JSON.stringify(fe(l(i.filePath),N))}${b.slice(g.getEnd())}`}f[y(o,i.filePath)]=`${ye}${b}`}if(f[y(o,Z(n,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return pt(S,{files:f,optionsKey:m,directories:$,stamps:j,tree:T},w),f},yt=(t,o=[])=>{const a=new Set;for(const e of t.tables)for(const n of Object.values(e.shape)){const s=et(n);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&a.add(s.bucket)}for(const e of o)e!==""&&e!=="default"&&a.add(e);return["default",...[...a].toSorted((e,n)=>e.localeCompare(n))]},$t=({agents:t=[],authClaims:o=[],capabilities:a=new Set,containers:e=[],env:n,hasVectors:s=!0,hasFlags:d=!1,hasNotify:S=!1,identity:m,queues:T=[],schema:v,services:w=[],storageRuleBuckets:P=[],topics:$=[],useUmbrella:j=!1,workflows:O=[]}={})=>{const u=tt(j),f=yt(v??{tables:[]},P).map(r=>JSON.stringify(r)).join(" | "),i=r=>r.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",R=[...new Set(e.map(r=>i(r)))].toSorted((r,p)=>r.localeCompare(p)),B=e.length>0?`import type { ${R.join(", ")} } from "@lunora/container";
3
+ `:"",b=e.length>0?`
4
+ readonly containers: {${e.map(r=>`
5
+ readonly ${r.exportName}: ${i(r)};`).join("")}
6
+ };`:"",g=[...a.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...e.map(r=>(F(r.bindingName,`container binding "${r.bindingName}"`),` /** Durable Object namespace for the \`${r.exportName}\` container. */
7
+ readonly ${r.bindingName}?: unknown;`)),...T.map(r=>(F(r.bindingName,`queue binding "${r.bindingName}"`),` /** Queue producer binding for the \`${r.exportName}\` queue. */
8
8
  readonly ${r.bindingName}?: unknown;`))].join(`
9
- `),k=`
9
+ `),I=`
10
10
 
11
11
  /**
12
12
  * This project's Cloudflare bindings, as far as codegen can discover them from
@@ -19,24 +19,24 @@ import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{existsSy
19
19
  * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
20
20
  */
21
21
  export interface CloudflareBindings {
22
- readonly [binding: string]: unknown;${b?`
23
- ${b}`:""}
22
+ readonly [binding: string]: unknown;${g?`
23
+ ${g}`:""}
24
24
  }
25
25
 
26
26
  /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
27
- export type Env = CloudflareBindings;`,x=r=>Qe.map(p=>p.tier!==void 0&&r.includes(p.tier)&&o.has(p.key)?p.serverCtxField:"").join(""),I=x(["every"]),W=x(["every","action"]),N=s&&(w?.vectorIndexes.length??0)>0,P=N?' | "vectors"':"",X=N?`
28
- readonly vectors: VectorSearch<VectorIndexName>;`:"",Te=N?`
29
- readonly vectors: VectorSearchReader<VectorIndexName>;`:"",ve=N?`import type { VectorSearch, VectorSearchReader } from "${u.server}";
27
+ export type Env = CloudflareBindings;`,k=r=>ze.map(p=>p.tier!==void 0&&r.includes(p.tier)&&a.has(p.key)?p.serverCtxField:"").join(""),N=k(["every"]),we=k(["every","action"]),D=s&&(v?.vectorIndexes.length??0)>0,E=D?' | "vectors"':"",ee=D?`
28
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",$e=D?`
29
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",Ie=D?`import type { VectorSearch, VectorSearchReader } from "${u.server}";
30
30
  import type { VectorIndexName } from "./dataModel.js";
31
- `:"",j=n?`
31
+ `:"",Q=d?`
32
32
  /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
33
- readonly flags: import("${u.flags}").LunoraFlags;`:"",E=l?`
33
+ readonly flags: import("${u.flags}").LunoraFlags;`:"",q=S?`
34
34
  /** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
35
35
  readonly notify: import("@lunora/notify").LunoraNotify;
36
36
  /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
37
- readonly push: import("@lunora/notify").LunoraPush;`:"",M=S.length>0,we=M?`import type { WorkflowHandle } from "@lunora/workflow";
37
+ readonly push: import("@lunora/notify").LunoraPush;`:"",M=O.length>0,ke=M?`import type { WorkflowHandle } from "@lunora/workflow";
38
38
  import type * as lunoraWorkflowDefinitions from "../workflows.js";
39
- `:"",$e=M?`
39
+ `:"",Se=M?`
40
40
 
41
41
  /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
42
42
  type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
@@ -47,56 +47,64 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
47
47
 
48
48
  /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
49
49
  export interface LunoraWorkflows {
50
- ${S.map(r=>` get(name: ${JSON.stringify(r.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${r.exportName}>>;`).join(`
50
+ ${O.map(r=>` get(name: ${JSON.stringify(r.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${r.exportName}>>;`).join(`
51
51
  `)}
52
- }`:"",Z=M?' | "workflows"':"",ee=M?`
53
- readonly workflows: LunoraWorkflows;`:"",Q=Je(v),q=Q.length>0,L=$.length>0,_=[...q?["QueueProducer"]:[],...L?["TopicPublisher"]:[]],te=[...new Set([...Q,...$].map(r=>r.filePath))].toSorted((r,p)=>+(p==="queues")-+(r==="queues")||r.localeCompare(p)),V=r=>r==="queues"?"lunoraQueueDefinitions":`lunoraQueueDefinitions${String(te.indexOf(r))}`,ke=_.length>0?`import type { ${_.join(", ")} } from "@lunora/queue";
54
- ${te.map(r=>`import type * as ${V(r)} from "../${r}.js";
55
- `).join("")}`:"",Ie=_.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",Se=q?`
52
+ }`:"",te=M?' | "workflows"':"",ae=M?`
53
+ readonly workflows: LunoraWorkflows;`:"",L=at(T),_=L.length>0,V=$.length>0,G=[..._?["QueueProducer"]:[],...V?["TopicPublisher"]:[]],re=[...new Set([...L,...$].map(r=>r.filePath))].toSorted((r,p)=>+(p==="queues")-+(r==="queues")||r.localeCompare(p)),H=r=>r==="queues"?"lunoraQueueDefinitions":`lunoraQueueDefinitions${String(re.indexOf(r))}`,Oe=G.length>0?`import type { ${G.join(", ")} } from "@lunora/queue";
54
+ ${re.map(r=>`import type * as ${H(r)} from "../${r}.js";
55
+ `).join("")}`:"",Re=G.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",Be=_?`
56
56
 
57
57
  /** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
58
58
  export interface LunoraQueues {
59
- ${Q.map(r=>` readonly ${r.exportName}: QueueProducer<QueueBodyOf<typeof ${V(r.filePath)}.${r.exportName}>>;`).join(`
59
+ ${L.map(r=>` readonly ${r.exportName}: QueueProducer<QueueBodyOf<typeof ${H(r.filePath)}.${r.exportName}>>;`).join(`
60
60
  `)}
61
- }`:"",Oe=L?`
61
+ }`:"",Ne=V?`
62
62
 
63
63
  /** This project's declared topics, addressable from \`ctx.topics\` by their \`lunora/queues.ts\` export name. */
64
64
  export interface LunoraTopics {
65
- ${$.map(r=>` readonly ${r.exportName}: TopicPublisher<QueueBodyOf<typeof ${V(r.filePath)}.${r.exportName}>>;`).join(`
65
+ ${$.map(r=>` readonly ${r.exportName}: TopicPublisher<QueueBodyOf<typeof ${H(r.filePath)}.${r.exportName}>>;`).join(`
66
66
  `)}
67
- }`:"",Be=`${Ie}${Se}${Oe}`,ae=q?`
68
- readonly queues: LunoraQueues;`:"",re=L?`
69
- readonly topics: LunoraTopics;`:"",G=g.length>0,oe=g.filter(r=>r.rpcEntrypoint!==void 0),Re=oe.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",Ne=G?`import type { ${Re} } from "${u.server}";
70
- ${oe.map(r=>`import type * as lunoraService_${r.name} from ${JSON.stringify(Ye(r))};
71
- `).join("")}`:"",Me=G?`
67
+ }`:"",De=`${Re}${Be}${Ne}`,oe=_?`
68
+ readonly queues: LunoraQueues;`:"",ne=V?`
69
+ readonly topics: LunoraTopics;`:"",z=w.length>0,se=w.filter(r=>r.rpcEntrypoint!==void 0),Me=se.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",Ce=z?`import type { ${Me} } from "${u.server}";
70
+ ${se.map(r=>`import type * as lunoraService_${r.name} from ${JSON.stringify(ot(r))};
71
+ `).join("")}`:"",Ae=z?`
72
72
 
73
73
  /** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
74
74
  export interface LunoraServices {
75
- ${g.map(r=>{C(r.name,`service "${r.name}"`);const p=r.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${r.name}.${r.rpcEntrypoint}>`;return` readonly ${r.name}: ${p};`}).join(`
75
+ ${w.map(r=>{F(r.name,`service "${r.name}"`);const p=r.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${r.name}.${r.rpcEntrypoint}>`;return` readonly ${r.name}: ${p};`}).join(`
76
76
  `)}
77
- }`:"",Ce=G?`
78
- readonly services: LunoraServices;`:"",H=t.length>0,De=H?`import type { AgentHandle } from "@lunora/agent/core";
79
- `:"",Ae=H?`
77
+ }`:"",Fe=z?`
78
+ readonly services: LunoraServices;`:"",K=t.length>0,We=K?`import type { AgentHandle } from "@lunora/agent/core";
79
+ `:"",Pe=K?`
80
80
 
81
81
  /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
82
82
  export interface LunoraAgents {
83
- ${t.map(r=>(C(r.exportName,`agent export "${r.exportName}"`),` readonly ${r.exportName}: AgentHandle;`)).join(`
83
+ ${t.map(r=>(F(r.exportName,`agent export "${r.exportName}"`),` readonly ${r.exportName}: AgentHandle;`)).join(`
84
84
  `)}
85
- }`:"",ne=H?`
86
- readonly agents: LunoraAgents;`:"",Fe=m?`import type { InferIdentity } from "${u.server}";
85
+ }`:"",ie=K?`
86
+ readonly agents: LunoraAgents;`:"",C=m!==void 0||o.length>0,je=m?`import type { InferIdentity } from "${u.server}";
87
87
  import type * as lunoraIdentityContract from "../identity.js";
88
- `:"",We=m?`
88
+ `:"",Ee=m===void 0&&o.length>0?`import type { SessionIdentity } from "@lunora/auth";
89
+ `:"",Qe=je+Ee,qe=o.length===0?"":`
89
90
 
90
- /** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
91
- export type Identity = InferIdentity<typeof lunoraIdentityContract.${m.exportName}>;
91
+ /** App-declared user columns the session forwards as claims (\`user.additionalFields\` of \`.auth()\`). Optional: a user whose column is unset never carries it. */
92
+ export type AuthClaims = {
93
+ ${o.map(r=>` ${r.name}?: ${r.type};`).join(`
94
+ `)}
95
+ };`;let A;m===void 0?A="export type Identity = SessionIdentity & AuthClaims & Record<string, unknown>;":o.length===0?A=`export type Identity = InferIdentity<typeof lunoraIdentityContract.${m.exportName}>;`:A=`type DeclaredIdentity = InferIdentity<typeof lunoraIdentityContract.${m.exportName}>;
96
+ export type Identity = DeclaredIdentity & Omit<AuthClaims, keyof DeclaredIdentity>;`;const Le=o.length===0?"/** This app's declared identity claim contract (\\`defineIdentity\\` in \\`lunora/identity.ts\\`) — the typed shape of \\`ctx.auth.getIdentity()\\`, the RLS policy \\`ctx.auth.identity\\`, and the \\`authorizeShard\\`/\\`authorizeFanOut\\` identity argument. */":"/** This app's identity: the declared claim contract (\\`defineIdentity\\` in \\`lunora/identity.ts\\`) and the user-column claims, the typed shape of \\`ctx.auth.getIdentity()\\`, the RLS policy \\`ctx.auth.identity\\`, and the \\`authorizeShard\\`/\\`authorizeFanOut\\` identity argument. */",_e=C?`${qe}
97
+
98
+ ${Le}
99
+ ${A}
92
100
 
93
- /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
94
- type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",K=m?' | "auth"':"",U=m?`
95
- readonly auth: NarrowedAuth;`:"",Pe=m?", Identity":"",je=e?`import type * as lunoraEnvContract from "../env.js";
96
- `:"",Ee=e?`
101
+ /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} instead of the untyped claim bag. */
102
+ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",U=C?' | "auth"':"",J=C?`
103
+ readonly auth: NarrowedAuth;`:"",Ve=C?", Identity":"",Ge=n?`import type * as lunoraEnvContract from "../env.js";
104
+ `:"",He=n?`
97
105
 
98
106
  /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
99
- export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${e.exportName}>;`:"",J=e?' | "env"':"",z=e?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${pe}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${u.server}";
107
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",Y=n?' | "env"':"",X=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${ye}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${u.server}";
100
108
  import type {
101
109
  ActionBuilder,
102
110
  ActionCtx as ActionCtxBase,
@@ -153,7 +161,7 @@ export type {
153
161
  } from "${u.serverDataModel}";
154
162
 
155
163
  import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
156
- ${ve}${B}${we}${ke}${Ne}${De}${Fe}${je}
164
+ ${Ie}${B}${ke}${Oe}${Ce}${We}${Qe}${Ge}
157
165
  export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
158
166
 
159
167
  /**
@@ -213,7 +221,7 @@ export interface OrmWriter extends OrmReader {
213
221
  }
214
222
 
215
223
  /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
216
- export type StorageBucketName = ${O};${k}${$e}${Be}${Me}${Ae}${We}${Ee}
224
+ export type StorageBucketName = ${f};${I}${Se}${De}${Ae}${Pe}${_e}${He}
217
225
 
218
226
  /**
219
227
  * Project-typed contexts. The base contexts from \`@lunora/server\` are
@@ -276,22 +284,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
276
284
  */
277
285
  type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
278
286
 
279
- export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${P}${K}${J}> {
287
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${E}${U}${Y}> {
280
288
  readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
281
289
  readonly orm: OrmReader;
282
- readonly storage: ReadOnlyStorage<StorageBucketName>;${Te}${I}${j}${E}${z}${U}
290
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${$e}${N}${Q}${q}${X}${J}
283
291
  }
284
292
 
285
- export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${P}${Z}${K}${J}> {
293
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${E}${te}${U}${Y}> {
286
294
  readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
287
295
  readonly orm: OrmWriter;
288
- readonly storage: MutationStorage<StorageBucketName>;${X}${I}${j}${E}${z}${ee}${ae}${re}${ne}${U}
296
+ readonly storage: MutationStorage<StorageBucketName>;${ee}${N}${Q}${q}${X}${ae}${oe}${ne}${ie}${J}
289
297
  }
290
298
 
291
- export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${P}${Z}${K}${J}> {
299
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${E}${te}${U}${Y}> {
292
300
  readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
293
301
  readonly orm: OrmWriter;
294
- readonly storage: StorageBase<StorageBucketName>;${X}${W}${R}${j}${E}${Ce}${z}${ee}${ae}${re}${ne}${U}
302
+ readonly storage: StorageBase<StorageBucketName>;${ee}${we}${b}${Q}${q}${Fe}${X}${ae}${oe}${ne}${ie}${J}
295
303
  }
296
304
 
297
305
  /**
@@ -349,7 +357,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
349
357
  * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
350
358
  * so the \`rls()\` chain discovers a policy authored either way the same.
351
359
  */
352
- export const definePolicy = createPolicyDsl<DataModel, Relations${Pe}>();
360
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Ve}>();
353
361
 
354
362
  /**
355
363
  * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
@@ -366,4 +374,4 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Pe}>();
366
374
  export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
367
375
  id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
368
376
  };
369
- `};export{ht as a,ft as e};
377
+ `};export{wt as a,$t as e};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.406",
3
+ "version": "1.0.0-alpha.407",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",