@lunora/codegen 1.0.0-alpha.114 → 1.0.0-alpha.115
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.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-GSCh67g3.mjs → GENERATED_HEADER-hlnTcuPd.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-CRmTpN4y.mjs → MUTATORS_FILENAME-sGAt-yC1.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-BybR3Xbd.mjs → NOTIFY_FILENAME-CTZI61e3.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-DB1PSt8W.mjs → OPENRPC_VERSION-DpRms_jN.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CGCzlXbr.mjs +9 -0
- package/dist/packem_shared/{SHAPES_FILENAME-DxoIrQhA.mjs → SHAPES_FILENAME-DTp6VI6K.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-B2mW3f5a.mjs → buildOpenApiDocument-ClEtrbbS.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-h8i51Mec.mjs → discoverFunctions-4eSpCR6m.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-MX6y-iVE.mjs → discoverHttpRoutes-DOirwCWw.mjs} +1 -1
- package/dist/packem_shared/{discoverMaskProcedures-DhcK-YMG.mjs → discoverMaskProcedures-D-09Qb8S.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-CjS2Mznw.mjs → discoverNondeterministicCalls-DhNToI6C.mjs} +1 -1
- package/dist/packem_shared/{discoverR2sqlCalls-DuTuaSMM.mjs → discoverR2sqlCalls-B6e4j4rD.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsMetadata-BYVq6cVp.mjs → discoverRlsMetadata-Pw0_c1aS.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-D_wHstA-.mjs +1 -0
- package/dist/packem_shared/{discoverStorageRulesMetadata-CKPFWHT5.mjs → discoverStorageRulesMetadata-DthHu3mC.mjs} +1 -1
- package/dist/packem_shared/{emit-Ba3NiOwK.mjs → emit-CV6JjAt9.mjs} +78 -64
- package/dist/packem_shared/{emitApp-CXeJ0y98.mjs → emitApp-BBcZ_fPU.mjs} +41 -26
- package/dist/packem_shared/parse-validator-C5ycrhR3.mjs +1 -0
- package/package.json +6 -6
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DgAbfC_h.mjs +0 -9
- package/dist/packem_shared/discoverSchema-BtlNz9b_.mjs +0 -1
- package/dist/packem_shared/parse-validator-DtALyvid.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BjTV22uR.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BjTV22uR.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4eSpCR6m.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DOirwCWw.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-D-09Qb8S.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-sGAt-yC1.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-DhNToI6C.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-CTZI61e3.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/discover-queries-Dfj_0WJG.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-B6e4j4rD.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Pw0_c1aS.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-D_wHstA-.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-DthHu3mC.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs";import{G as Ne,e as ge,a as Oe,b as Re,c as Me,d as he,f as Ce,g as _e,h as Te,i as Ie,j as Le,k as Fe,l as De,m as Pe}from"./packem_shared/emit-CV6JjAt9.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-BBcZ_fPU.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-ClEtrbbS.mjs";import{OPENRPC_VERSION as je,buildOpenRpcDocument as Ke,emitOpenRpc as Ve,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-DpRms_jN.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as qe,readProjectTarget as Be,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CIH5PRk1.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Xe,createCodegenProject as Ze,findTsconfig as $e,refreshCodegenProject as er,runCodegen as rr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CGCzlXbr.mjs";import{SchemaSnapshotParseError as tr,buildSchemaSnapshot as sr,evaluateSchemaDrift as ar,parseSchemaSnapshot as ir}from"./packem_shared/SchemaSnapshotParseError-Dc1aZAph.mjs";import{schemaFromIr as dr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as cr}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as Sr,SDK_TARGETS as lr,generateSdk as Er}from"./packem_shared/SDK_LANGUAGES-DcXlLVZ1.mjs";import{redact as Ar,secretKindOf as ur}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Nr,findSolutionByMessage as gr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-BBIBMZTg.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,R as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,T as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Nr as LUNORA_SOLUTION_RULES,j as MUTATORS_FILENAME,w as NOTIFY_FILENAME,je as OPENRPC_VERSION,ee as QUEUES_FILENAME,Xe as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Sr as SDK_LANGUAGES,lr as SDK_TARGETS,ne as SHAPES_FILENAME,tr as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,be as buildOpenApiDocument,Ke as buildOpenRpcDocument,sr as buildSchemaSnapshot,Ze as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,g as discoverAuthApiCalls,M as discoverContainers,C as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,b as discoverMaskProcedures,y as discoverMigrations,K as discoverMutators,z as discoverNondeterministicCalls,q as discoverNotifyCalls,B as discoverNotifyConfig,Z as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,pe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,ge as emitAgents,Oe as emitApi,Ge as emitApp,Re as emitCollections,Me as emitContainers,he as emitCrons,Ce as emitDataModel,_e as emitDrizzleSchema,Te as emitFunctions,ke as emitOpenApi,ye as emitOpenApiModule,Ve as emitOpenRpc,ze as emitOpenRpcModule,Ie as emitServer,Le as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,ar as evaluateSchemaDrift,gr as findLunoraSolution,$e as findTsconfig,m as formatAdvisories,Er as generateSdk,Rr as isTypedSchema,d as lintSchema,ir as parseSchemaSnapshot,qe as platformMatrixIds,Y as readPackageDependencies,Be as readProjectTarget,Ar as redact,er as refreshCodegenProject,Je as resolveCodegenTarget,rr as runCodegen,dr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,cr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-CV6JjAt9.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
|
package/dist/packem_shared/{MUTATORS_FILENAME-CRmTpN4y.mjs → MUTATORS_FILENAME-sGAt-yC1.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as f}from"node:fs";import{join as p}from"node:path";import{Node as o,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapHandlerReturn as g}from"./discoverFunctions-
|
|
1
|
+
import{existsSync as f}from"node:fs";import{join as p}from"node:path";import{Node as o,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapHandlerReturn as g}from"./discoverFunctions-4eSpCR6m.mjs";import{a as d}from"./module-specifiers-WF8iAydP.mjs";import{a as x}from"./parse-validator-C5ycrhR3.mjs";const M="mutators.ts",m=d,y=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineMutator";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return m(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineMutator":!1;return!1},S=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(u.ImportDeclaration);return i!==void 0&&m(i.getModuleSpecifierValue())}return!1},N=r=>{if(o.isIdentifier(r))return y(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineMutator"&&o.isIdentifier(t)&&S(t)}return!1},I=r=>{const t=r.getArguments()[0];return t&&o.isObjectLiteralExpression(t)?t:void 0},b=r=>{const t=r?.getProperty("args");if(!t||!o.isPropertyAssignment(t))return{};const e=t.getInitializer();return e&&o.isObjectLiteralExpression(e)?x(e):{}},A=r=>{const t=r?.getProperty("server");if(!t||!o.isPropertyAssignment(t))return"unknown";const e=t.getInitializer();return!e||!(o.isArrowFunction(e)||o.isFunctionExpression(e))?"unknown":g(e)},E=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==u.CallExpression)continue;const n=i,a=n.getExpression();if(!N(a))continue;const s=e.getNameNode();if(!o.isIdentifier(s))throw l(s,"defineMutator exports must be plain named exports (no destructuring)");const c=I(n);t.push({args:b(c),exportName:s.getText(),filePath:"mutators",returnType:A(c)})}return t},w=(r,t)=>{const e=p(t,M);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=E(i);return n.sort((a,s)=>a.exportName.localeCompare(s.exportName)),n};export{M as MUTATORS_FILENAME,w as discoverMutators,N as isDefineMutatorCallee};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as m}from"node:fs";import{join as x}from"node:path";import{SyntaxKind as d,Node as c}from"ts-morph";import{l,a as g,d as P,h as E}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as S}from"./discoverFunctions-
|
|
1
|
+
import{existsSync as m}from"node:fs";import{join as x}from"node:path";import{SyntaxKind as d,Node as c}from"ts-morph";import{l,a as g,d as P,h as E}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as S}from"./discoverFunctions-4eSpCR6m.mjs";const y="notify.ts",v=new Set(["chat","inApp","send","webhook"]),p=new Set(["broadcast","send"]),N=e=>{const t=e.getInitializer();if(!t||!c.isCallExpression(t))return;const o=S(t);if(!o)return;const s=E(t,o.receiver);return s?{exportName:e.getName(),handler:s,kind:o.kind}:void 0},h=e=>{const t=[];for(const o of e.getVariableStatements())if(o.isExported())for(const s of o.getDeclarations()){const r=N(s);r&&t.push(r)}return t},f=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=e.getExpression();if((t==="notify"||t==="push")&&c.isIdentifier(o)&&o.getText()==="ctx")return t;if(t==="push"&&f(o)==="notify")return"push"},F=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=f(e.getExpression());if(o==="notify"&&v.has(t))return`ctx.notify.${t}`;if(o==="push"&&p.has(t))return`ctx.push.${t}`},A=e=>c.isPropertyAccessExpression(e)?f(e.getExpression())==="push"&&p.has(e.getName()):!1,T=(e,t)=>{const o=[];for(const s of l(t)){const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=g(t,s);for(const n of h(r))if(!(n.kind!=="query"&&n.kind!=="mutation"))for(const i of n.handler.getDescendantsOfKind(d.PropertyAccessExpression)){const u=F(i);u!==void 0&&o.push({callee:u,exportName:n.exportName,file:a,kind:n.kind,line:i.getStartLineNumber()})}}return o},O=(e,t)=>{for(const o of l(t)){const s=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const r of h(s))for(const a of r.handler.getDescendantsOfKind(d.PropertyAccessExpression))if(A(a))return!0}return!1},_=(e,t)=>{const o=x(t,y);if(!m(o))return;const s=e.getSourceFile(o)??e.addSourceFileAtPath(o),r=P(s);let a=!1,n=!1;if(r&&c.isCallExpression(r)){const i=r.getArguments()[0];i&&c.isObjectLiteralExpression(i)&&(a=i.getProperty("webPush")!==void 0,n=i.getProperty("fcm")!==void 0)}return{hasFcm:n,hasWebPush:a,usesPush:O(e,t)}};export{y as NOTIFY_FILENAME,T as discoverNotifyCalls,_ as discoverNotifyConfig};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as c}from"./emit-
|
|
1
|
+
import{G as c}from"./emit-CV6JjAt9.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
|
|
2
2
|
`,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{existsSync as N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{toAdvisorContext as Yt}from"./formatAdvisories-BjTV22uR.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ee}from"./module-specifiers-WF8iAydP.mjs";import{C as fe,i as Zt,f as Jt,n as es,a as ts,h as ss,j as ns,b as rs,c as is,l as os,e as as,o as cs,d as ls,k as us,g as ds,p as fs,m as ps}from"./emit-CV6JjAt9.mjs";import{l as h,a as E,c as y,p as S,f as xt,i as gs,r as Et,e as ms}from"./discover-ast-D33zP-NZ.mjs";import hs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as xs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as Es}from"./discoverSandboxUsage-L0lV17de.mjs";import vs from"./discoverStorageRulesMetadata-DthHu3mC.mjs";import{discoverWorkflows as Ss}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as As,resolveCodegenTarget as Ns}from"./DEFAULT_TARGET-CIH5PRk1.mjs";import{i as T,a as F,e as x,c as I,r as ys,b as bs,s as te,f as Is,g as Ps,d as ws}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Ts,procedureHandler as vt,chainUsesWrappedCall as St,isDatabaseAccessor as K,chainHasStep as Cs,discoverFunctions as Rs,resolveStandardSchemaType as Os}from"./discoverFunctions-4eSpCR6m.mjs";import Fs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Ls from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Ds}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import ks from"./discoverHttpRoutes-DOirwCWw.mjs";import Ms from"./discoverInserts-YX8AmrzL.mjs";import Ks,{discoverMaskStrategies as _s,discoverMaskMetadata as zs,discoverMaskHasNonLiteralPolicy as Us}from"./discoverMaskProcedures-D-09Qb8S.mjs";import Bs from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as qs,isDefineMutatorCallee as $s,discoverMutators as js}from"./MUTATORS_FILENAME-sGAt-yC1.mjs";import Vs from"./discoverNondeterministicCalls-DhNToI6C.mjs";import{discoverNotifyConfig as Ws,discoverNotifyCalls as Hs}from"./NOTIFY_FILENAME-CTZI61e3.mjs";import Gs from"./discoverR2sqlCalls-B6e4j4rD.mjs";import Ys,{discoverRlsMetadata as Qs}from"./discoverRlsMetadata-Pw0_c1aS.mjs";import Xs from"./discoverSchema-D_wHstA-.mjs";import{secretKindOf as Zs,redact as Js,isHeuristicSecretKind as en,isSecretishName as tn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as sn}from"./SHAPES_FILENAME-DTp6VI6K.mjs";import{emitApp as nn}from"./emitApp-BBcZ_fPU.mjs";import{buildOpenApiDocument as rn,emitOpenApiModule as on}from"./buildOpenApiDocument-ClEtrbbS.mjs";import{buildOpenRpcDocument as an,emitOpenRpcModule as cn}from"./OPENRPC_VERSION-DpRms_jN.mjs";import{s as ln}from"./parse-validator-C5ycrhR3.mjs";import{buildSchemaSnapshot as un}from"./SchemaSnapshotParseError-Dc1aZAph.mjs";const dn=e=>{const t=[],s=e.tables.filter(n=>n.shardMode==="global");return s.some(n=>n.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(n=>n.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},fn=(e,t)=>{if(t===void 0)return;const s=dn(e).filter(o=>!t.has(o.name));if(s.length===0)return;const n=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
2
|
+
`);throw new O("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
+
${n}
|
|
4
|
+
|
|
5
|
+
Install them with your package manager, then re-run codegen.`)},pn="env.ts",gn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ee(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},mn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ee(n.getModuleSpecifierValue())}return!1},hn=e=>{if(i.isIdentifier(e))return gn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&mn(t)}return!1},xn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!hn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw J(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},En=(e,t)=>{const s=f(t,pn);if(!N(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=xn(n);if(o.length!==0){if(o.length>1)throw J(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},vn=e=>{const t=n=>i.isIdentifier(n)&&n.getText()==="ctx",s=new Set;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression))t(n.getExpression())&&s.add(n.getName());for(const n of e.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getInitializer(),r=n.getNameNode();if(!(o===void 0||!t(o)||!i.isObjectBindingPattern(r)))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Sn=(e,t)=>{const s=Object.fromEntries(fe.map(n=>[n.key,!1]));for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=vn(o);for(const c of fe)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(fe.every(c=>s[c.key]))break}return s},An=["providerSubscriptionId","state"],Nn=["providerEventId","processedAt"],Xe=(e,t)=>t.every(s=>s in e.shape),yn=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Xe(t,An)&&Xe(s,Nn)},bn=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),At="identity.ts",In=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ee(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Pn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ee(n.getModuleSpecifierValue())}return!1},wn=e=>{if(i.isIdentifier(e))return In(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&Pn(t)}return!1},Tn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!wn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw J(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Cn=(e,t)=>{const s=f(t,At);if(!N(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=Tn(n);if(o.length!==0){if(o.length>1)throw J(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},Rn=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new O("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new O("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=o.get(r.className);if(u!==void 0)throw new O("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},On=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=Cn(s,t),a=En(s,t),c=Ss(s,t),u=xs(s,t),d=Qt(s,t);Rn(c,d);const v=Xt(s,t),P=vs(s,t),p=As(Sn(s,t),Ns(n,e.target)),A=p.usage,D=Es(s,t),z=A.browser||D.usesSandboxBrowser,U=hs(n),j=U??new Set,C=j.has("lunorash");fn(o,U);const k=N(f(t,"flags.ts")),B=N(f(t,"notify.ts"));return{agents:d,containers:v,dataModelContent:Jt(o),declaredDependencies:U,dependencies:j,env:a,featureUsage:A,hasBrowser:z,hasFlags:k,hasNotify:B,identity:r,platformGate:p,queues:u,serverContent:Zt({agents:d,containers:v,env:a,hasAccessFacade:A.access,hasAi:A.ai,hasAnalytics:A.analytics,hasBrowser:z,hasFlags:k,hasHyperdrive:A.hyperdrive,hasImages:A.images,hasKv:A.kv,hasNotify:B,hasPayments:A.payments,hasPipelines:A.pipelines,hasR2sql:A.r2sql,hasX402:A.x402,identity:r,queues:u,schema:o,storageRuleBuckets:P.rules.map(ne=>ne.bucket),useUmbrella:C,workflows:c}),storageRulesMetadata:P,usesSandbox:D.usesSandboxBrowser||D.usesSandboxContainer,useUmbrella:C,workflows:c}},Nt=new Set(["delete","get","head","options","patch","post","put"]),Fn=new Set(["handler","stream"]),Ln=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ze=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Dn=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Nt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},kn=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||Nt.has(n.getName()))break;s=n.getExpression()}return Dn(s)},Mn=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Ze.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Ze.has(s.getText()))return!0}return!1},Kn=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Fn.has(n.getName()))return;const o=kn(s);if(!o||!Ln.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&Mn(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},_n=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Kn(o,t);r&&s.push(r)}return s},zn=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(..._n(o,E(t,n)))}return s},Un=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Bn=(e,t)=>{if(!Un(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!T(s)||F(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},qn=(e,t)=>y(e,t,Bn),$n=new Set(["generateText","streamText"]),jn=new Set(["messages","prompt","system"]),Vn=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Wn=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of Vn)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Hn=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Wn(t);if(s!==void 0)return s}},Gn=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Yn=e=>{if(ys(e))return!0;const t=Gn(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Qn=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!jn.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Yn(s))return!0}return!1},Xn=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=I(n.getExpression());if(o===void 0||!$n.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(I(c.getExpression())==="tool"&&(a=Hn(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Qn(r)})}return s},Zn=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xn(o,E(t,n)))}return s},Jn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},er=(e,t)=>{if(!Jn(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!T(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},tr=(e,t)=>y(e,t,er),yt=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),sr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer();return!n||!i.isObjectLiteralExpression(n)?{objects:[],opaque:!0}:{objects:[n],opaque:yt(n)}},nr=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0];r&&i.isObjectLiteralExpression(r)?(t.push(r),s||=yt(r)):s=!0}n=o.getExpression()}return{objects:t,opaque:s}},bt=(e,t)=>t?nr(t):sr(e),rr=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),ir=/\.check\(|\.meta\(|length|max/iu,or=/\bv\.any\s*\(/u,ar=/\bv\.string\s*\(/u,cr=e=>or.test(e),lr=e=>ar.test(e)&&!ir.test(e),ur=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=r.getText(),c=o.getName();cr(a)?t.push(c):lr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},dr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=_(s);if(n?.visibility!=="public")return;const{objects:o}=bt(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=ur(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},fr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=dr(o,t);r&&s.push(r)}return s},pr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...fr(o,E(t,n)))}return s},pe=e=>e?.getKind()===l.TrueKeyword,gr=e=>e?.getKind()===l.FalseKeyword,mr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,hr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),xr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&I(t.getExpression())==="scim"),Er=e=>e!==void 0&&i.isCallExpression(e)&&hr.has(I(e.getExpression())??""),vr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Sr=e=>{const t=S(e,"advanced"),s=S(e,"emailAndPassword"),n=S(e,"session");return{analyzable:!0,disableCsrfCheck:pe(S(t,"disableCSRFCheck")),emailPasswordEnabled:pe(S(s,"enabled")),requireEmailVerification:pe(S(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:xr(S(e,"plugins"))&&Er(S(e,"database")),secureCookiesDisabled:gr(S(t,"useSecureCookies")),sessionFreshAgeZero:mr(S(n,"freshAge")),trustedOriginsWildcard:vr(S(e,"trustedOrigins"))}},Ar=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Nr=(e,t)=>{if(I(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?Sr(s):Ar();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...o}},yr=(e,t)=>y(e,t,Nr),br=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Ir=(e,t,s)=>{const n=br(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!T(o)||F(o))&&!(s.requireUnmodifiedReach===!0&&!bs(o)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:n}},Pr=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=Ir(o,t,s);r&&n.push(r)}return n},se=(e,t,s)=>{const n=[];for(const o of h(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Pr(r,E(t,o),s))}return n},wr=new Set(["content","pdf","scrape","screenshot"]),Tr=(e,t)=>se(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:wr}),Cr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Rr=new Set(["RateLimiter"]),Or=new Set(["extend"]),It=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Je=e=>e&&i.isObjectLiteralExpression(e)?It(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Fr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const n=s.getExpression();return n!==void 0&&i.isObjectLiteralExpression(n)?n:void 0},Lr=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?Fr(e):void 0},Dr=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Lr(t.getBody());return s?It(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},kr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=I(n.getExpression());o!==void 0&&(Cr.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Je(n.getArguments()[0])}):Or.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...Dr(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=I(n.getExpression());o===void 0||!Rr.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Je(n.getArguments()[0])})}return s},Mr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...kr(o,E(t,n)))}return s},et="ctx.containers.",Kr=e=>{if(!e.startsWith(et))return!1;const t=e.slice(et.length);return t.length>0&&!t.includes(".")},_r=(e,t)=>se(e,t,{argIndex:0,matchReceiver:Kr,methods:new Set(["get"])}),zr=new Set(["allow","deny","setAllowed"]),Ur=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Br=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Ur(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},qr=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!zr.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},$r=(e,t)=>Br(e,t)??qr(e,t),jr=(e,t)=>y(e,t,$r),Vr=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Wr=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Vr.has(s)?s:void 0},Hr=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Gr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=Wr(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?Hr(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:r,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Yr=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Qr=new Set(["dbRateLimit","rateLimit"]),Xr=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Zr=(e,t)=>{const s=I(e.getExpression());if(s===void 0)return;const n=Yr.get(s);if(n!==void 0)return{callee:s,exportName:x(e),failOpen:Xr(e.getArguments()[n]),file:t,limitName:Qr.has(s)?xt(e):"",line:e.getStartLineNumber()}},Jr=(e,t)=>y(e,t,Zr),ei=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&gs(t.getExpression())},ti=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},si=(e,t)=>{if(!ei(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=ti(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:x(e),file:t,key:o,line:e.getStartLineNumber()}},ni=(e,t)=>y(e,t,si),ri=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},ii=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},oi=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))ri(a)&&s.push({file:r,indexName:ii(a),line:a.getStartLineNumber()})}return s},ai=new Set(["delete","get","head","options","patch","post","put"]),ci=new Set(["handler","stream"]),li=new Set(["runAction","runMutation"]),ui=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,tt=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,st=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const n=s.getNameNode();if(t)return i.isIdentifier(n)?n.getText():void 0;if(i.isObjectBindingPattern(n)){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="ctx"){const a=o.getNameNode();return i.isIdentifier(a)?a.getText():void 0}}},nt=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(li.has(a)&&Q(c,t))return a;if(ui.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},rt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Q(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!Q(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},di=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ci.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(ai.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},fi=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=tt(e.getArguments()[0]),u=c&&st(c,!0);if(!c||u===void 0)return;const d=nt(c,u);return d===void 0?void 0:{exportName:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:rt(c,u),sideEffect:d}}const n=di(e);if(n===void 0)return;const o=tt(e.getArguments()[0]),r=o&&st(o,!1);if(!o||r===void 0)return;const a=nt(o,r);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:rt(o,r),sideEffect:a}},pi=(e,t)=>y(e,t,fi),gi=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),mi=new Set(["append","set"]),Ee=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",Pt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",it=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>gi.has(Ee(n.getExpression()))&&Ps(n,t)),hi=(e,t)=>{if(it(e,t))return!0;const s=te(e);return s!==void 0&&it(s,t)},he=(e,t)=>Is(e,t)&&!hi(e,t),xi=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=te(e);return t!==void 0&&i.isNewExpression(t)&&Ee(t.getExpression())==="Headers"},X=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=te(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},ve=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&he(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Pt(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();he(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=X(n.getExpression());o!==void 0&&ve(o,t,s)}},wt=(e,t)=>{const s=X(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=X(n.getInitializer());o!==void 0&&ve(o,"response-init",t)},Ei=(e,t)=>{const s=Ee(e.getExpression());if(s==="Response")wt(e.getArguments()[1],t);else if(s==="Headers"){const n=X(e.getArguments()[0]);n!==void 0&&ve(n,"headers-ctor",t)}},vi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){wt(e.getArguments()[1],t);return}if(mi.has(n)&&xi(o)){const r=e.getArguments()[1];r!==void 0&&he(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Pt(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Si=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Ei(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))vi(s,t)},Ai=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Ts(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return Si(n,{exportName:x(e),relativePath:t,requestName:r.getText(),rows:a}),a},Ni=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Ai(n,t));return s},yi=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ni(o,E(t,n)))}return s},bi=new Set(["auth","context.auth","ctx.auth"]),Ii="userId",Pi=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},wi=(e,t)=>{const s=f(t,At);if(!N(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(I(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Pi(r):void 0}},ot=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return bi.has(e.getExpression().getText())?e:void 0},Ti=e=>{if(i.isPropertyAccessExpression(e)&&ot(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&ot(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Ci=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=Ti(o);r!==void 0&&n.push({declared:r===Ii||s.has(r),exportName:x(o),file:t,key:r,line:o.getStartLineNumber()})}return n},Ri=(e,t)=>{const s=wi(e,t);if(s===void 0)return[];const n=[];for(const o of h(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Ci(r,E(t,o),s))}return n},Oi=(e,t)=>{if(I(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=S(s,"key");if(!(!n||!T(n)||F(n)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Fi=(e,t)=>y(e,t,Oi),Li=new Set(["delete","get","getRaw","getWithMetadata","put"]),Di=(e,t)=>se(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Li}),ki=new Set(["queue","send"]),at=new Set(["bcc","cc","to"]),Mi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ki.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Ki=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return at.has(t.getName())&&T(n)&&!F(n)}if(!i.isPropertyAssignment(t)||!at.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&T(s)&&!F(s)}):!1,_i=(e,t)=>{const s=Mi(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Ki(n)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},zi=(e,t)=>y(e,t,_i),Ui=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Bi=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},qi=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return $s(s.getExpression())?s:void 0},$i=e=>{const t=qi(e),s=t===void 0?void 0:Bi(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>Ui(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},ji=e=>e.getVariableDeclarations().flatMap(t=>$i(t)),Vi=(e,t)=>{const s=f(t,qs);if(!N(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return ji(n)},Wi=new Set(["delete","get","patch"]),Hi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Gi=new Set(["auth","identity","session","user"]),Yi=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Qi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!K(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Xi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},Zi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ji=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,eo=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Zi(s.getExpression(),t)&&Ji(s.getThenStatement())),to=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!Wi.has(o))continue;const r=n.getExpression();if(!(K(r)||i.isPropertyAccessExpression(r)&&K(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},so=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},no=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>so(s)==="ctx")),ro=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Yi.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),io=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Hi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Gi.has(t.getName()))return!0}return no(e)||ro(e)},oo=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=vt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&St(n.receiver,"use","rls"),a=io(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const v=Qi(d);if(v===void 0)continue;const P=Xi(d);if(P===void 0||c.has(P)||!eo(o,P))continue;const p=to(o,P);p!==void 0&&(c.add(P),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:v,usesRls:r,visibility:n.visibility}))}return u},ao=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...oo(c,r))}return s},co=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),lo=new Set(["insert","insertManyUnsafe","patch","replace"]),uo=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!lo.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},fo=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},po=(e,t,s,n)=>{const o=[];for(const r of e.getProperties()){let a,c;i.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):i.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!co.has(a))&&T(c)&&!F(c)&&o.push({exportName:x(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return o},go=(e,t)=>{const s=uo(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?fo(n,s).flatMap(o=>po(o,s,e,t)):[]},mo=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of go(o,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},ho=(e,t,s=[])=>{const n=[],o=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of h(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=E(t,r);n.push(...mo(a,c,u=>o.get(`${c}:${u}`)))}return n},xo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Eo=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,vo=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Eo(t.getInitializer()):void 0},So=(e,t)=>{const s=I(e.getExpression());if(s===void 0||!xo.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?vo(n):void 0;return{callee:s,exportName:x(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},Ao=(e,t)=>y(e,t,So),No=new Set(["defineQueue","defineWorkflow"]),yo=new Set(["run","runAction","runMutation","runQuery"]),bo=new Set(["api","internal"]),Io=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Po=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},Tt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Ct=(e,t)=>e===t||e.startsWith(`${t}.`),Rt=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},ct=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},Ot=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>ct(s));return i.isIdentifier(e)&&ct(e)&&t.push(e),t},wo=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},To=e=>{const t=Tt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},Co=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:To(e),o=new Set,r=a=>Rt(a).some(c=>n.some(u=>Ct(c.getText(),u)))?!0:Ot(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of wo(a))o.add(u)}return{names:o,prefixes:n}},Ro=(e,t)=>Rt(e).some(s=>t.prefixes.some(n=>Ct(s.getText(),n)))?!0:Ot(e).some(s=>t.names.has(s.getText())),Oo=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!bo.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Fo=(e,t,s)=>{const n=Tt(e,0);if(n===void 0)return[];const o=Co(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!yo.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!Ro(u,o))continue;const d=Oo(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},Lo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Io(n);if(o===void 0||!No.has(o))continue;const r=Po(n);r!==void 0&&s.push(...Fo(r,o==="defineQueue"?"queue":"workflow",t))}return s},Do=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Lo(o,E(t,n)))}return s},lt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},ut=new Set(["account","credential","member","passkey","session","user"]),ko=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Mo=e=>{const s=ko(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return ut.has(s)||ut.has(n)},Ko=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},_o=(e,t)=>{const{objects:s,opaque:n}=bt(e,t);return rr(s).some(o=>Ko(o))?!0:n?void 0:!1},Se=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},zo=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Uo=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},Y={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Bo=e=>{const t=Uo(e),s=t?Se(t):void 0;if(t&&s==="protectPublic"){const n=zo(t);return{...Y,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in lt?{...Y,[lt[s]]:!0}:Y},qo=e=>{const t={...Y};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=Bo(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},$o=new Set(["insert","insertMany","insertManyUnsafe","replace"]),jo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!$o.has(t.getName()))return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:Mo(o.getLiteralText())},Vo=new Set(["create","runAfter","runAt","send","sendBatch"]),Wo=new Set(["queues","scheduler","workflows"]),Ho=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Vo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Wo.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Go=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Ft=new Set(["generateObject","generateText","streamObject","streamText"]),Yo=e=>{const t=Se(e);return t!==void 0&&Ft.has(t)},Qo=e=>{const t=Se(e);if(t===void 0||!Ft.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Xo=new Set(["log","span","trace"]),Zo=new Set(["ai"]),Jo=new Set(["email","mail"]),ea=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),ge=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),ta=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),sa=new Set(["every","filter","flatMap","forEach","map","some"]),na=new Set(["all","allSettled","race"]),ra=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(sa.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&na.has(n))return t},ia=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(ta.has(t.getKind())){const s=ra(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},oa=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},aa=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ca=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!ea.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=aa(n);r&&(t=!0,!ia(r)&&!oa(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},la=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),dt="lunora-advisor-exempt",ua=/^[\s*/]+/u,da=/[\w-]/u,fa=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
|
+
`);for(const n of s.split(`
|
|
7
|
+
`)){const o=n.replace(ua,"");if(!o.startsWith(dt))continue;const r=o.slice(dt.length);if(da.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},pa=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},ga=(e,t)=>{const s=pa(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},ma=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(jo(u)&&(r=!0),Ho(u)&&(t=!0),Go(u)&&(o=!0),Yo(u)&&(s=!0),Qo(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=ca(e);return{callsMail:ge(e,Jo),emitsEvent:ge(e,Xo),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||ge(e,Zo),throwsBareError:la(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},ha=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=_(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?qo(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=ga(e,s);return{...r?ma(r):{},...fa(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:_o(s,n.receiver),kind:n.kind,visibility:n.visibility}},xa=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=ha(o,t);r&&s.push(r)}return s},Ea=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...xa(o,E(t,n)))}return s},va=new Set(["dbRateLimit","rateLimit"]),Sa=e=>i.isArrowFunction(e)?e.getBody():e,Aa=(e,t)=>{const s=I(e.getExpression());if(s===void 0||!va.has(s))return;const n=e.getArguments()[2];if(!n)return;const o=S(n,"key");if(!o)return;const r=Sa(o);if(!(!T(r)||F(r)))return{callee:s,exportName:x(e),file:t,limitName:xt(e),line:e.getStartLineNumber()}},Na=(e,t)=>y(e,t,Aa),ya=new Set(["findFirst","findFirstOrThrow","findMany","get"]),ba=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ya.has(t.getName()))return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&K(s.getExpression()))return s.getName()},Ia=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&K(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Pa=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},Lt=(e,t=!1)=>{const s=Pa(e);if(i.isIdentifier(s)){if(t)return;const n=te(s);return n===void 0?void 0:Lt(n,!0)}if(i.isCallExpression(s))return ba(s)??Ia(s)},wa=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},Ta=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query")return[];const o=vt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Cs(n.receiver,"output"),a=n.receiver!==void 0&&St(n.receiver,"use","mask"),c=new Set,u=[];for(const d of wa(o)){const v=Lt(d);v===void 0||c.has(v)||(c.add(v),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:v,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},Ca=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ta(c,r))}return s},Ra=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Oa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?_(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Et(r);if(a===void 0)continue;const c=Ra(S(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},Fa=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Oa(c,r))}return s},Z=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=Z(e.getLeft()),s=Z(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},La=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&Z(t)!==void 0},Da=/(?:^|\/)__tests__\//u,ka=/\.(?:spec|test)$/u,Ma=e=>Da.test(e)||ka.test(e),Ka=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},_a=(e,t,s)=>en(e)?!Ma(s)&&tn(Ka(t)):!0,za=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(La(r))continue;const a=Z(r);if(a===void 0)continue;const c=Zs(a);if(c===void 0||!_a(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:Js(a)}))}return s},Ua=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...za(o,E(t,n)))}return s},Ba=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?_(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Et(r);if(a===void 0)continue;const c=S(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&T(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},qa=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ba(c,r))}return s},$a=new Set(["query","unsafe"]),ja=e=>{if(!i.isPropertyAccessExpression(e)||!$a.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},Va=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Wa=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Ha=(e,t)=>{if(!ja(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Va(s)))return{exportName:Wa(e),file:t,line:s.getStartLineNumber()}},Ga=(e,t)=>y(e,t,Ha),Ya=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Qa=e=>{for(const[t,s]of Ya)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Xa=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Qa(a);c!==void 0&&s.push({file:E(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Za=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ja=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return se(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Za,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},ec=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),tc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,sc=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=tc(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},nc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=ec.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},rc=(e,t)=>{const s=nc(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...sc(e.getArguments()[s.optionsIndex])}},ic=(e,t)=>y(e,t,rc),oc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),Ae=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&oc.has(s)?s:void 0},Dt=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},kt={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},ac={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},Ne=(e,t,s,n,o)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${s}\` but was not registered — ${o.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${o.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),cc=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(s.has(`${t}:${a}`)||!Dt(r))continue;const c=Ae(r);c!==void 0&&n.push(Ne(t,a,c,r.getStartLineNumber(),kt))}return n},lc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ae(o.getExpression());r!==void 0&&n.push(Ne(t,"default",r,o.getStartLineNumber(),kt))}return n},uc=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(s.has(`${t}:${a}`))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!Dt(c))continue;const u=Ae(c);u!==void 0&&n.push(Ne(t,a,u,r.getStartLineNumber(),ac))}return n},dc=(e,t,s)=>[...cc(e,t,s),...lc(e,t,s),...uc(e,t,s)],fc=(e,t,s)=>{const n=new Set(s.map(r=>`${r.filePath}:${r.exportName}`)),o=[];for(const r of h(t)){const a=e.getSourceFile(r);a!==void 0&&o.push(...dc(a,E(t,r),n))}return o.toSorted((r,a)=>r.cacheKey.localeCompare(a.cacheKey))},pc=new Set(["when","where"]),me=new Set(["definePolicy","defineShape"]),gc=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return me.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return me.has(o)?o:void 0}const s=t.getText();return me.has(s)?s:void 0},mc=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Mt=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(mc(e))return"empty-object";if(i.isParenthesizedExpression(e))return Mt(e.getExpression())}},ye=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),hc=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>ye(t)===e),Kt=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>ye(t)===e),xc=e=>{const t=hc(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Kt(e).length>0},Ec=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>ye(t)===e),xe=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",vc=(e,t)=>xe(e)||xe(t),Sc=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),ft=e=>!xe(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),Ac=(e,t,s)=>{const n=Sc.get(e);if(n!==void 0)return vc(t,s)?n==="positive"?"negative":"positive":ft(t)||ft(s)?void 0:n},$=e=>{if(i.isParenthesizedExpression(e))return $(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Ac(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=$(e.getLeft()),o=$(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},pt=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},Nc=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},yc=e=>i.isReturnStatement(e)?e.getExpression()??e:e,bc=e=>{const t=[];for(const s of Kt(e)){const n=$(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Ec(e)){const n=$(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?pt(s.getThenStatement()):pt(s.getElseStatement())??Nc(s);o!==void 0&&t.push(yc(o))}return t},Ic=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Pc=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!pc.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&xc(a))for(const c of bc(a)){const u=Mt(c);u!==void 0&&o.push({exportName:Ic(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},wc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=gc(n);o!==void 0&&s.push(...Pc(n,o,t))}return s},Tc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wc(o,E(t,n)))}return s},Cc=new Set(["query","upsert","upsertMany"]),Rc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Cc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Oc=(e,t)=>{const s=Rc(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=S(n,"namespace");if(!(!o||!T(o)||F(o)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Fc=(e,t)=>y(e,t,Oc),Lc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},Dc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},kc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Lc(a))continue;const c=ms(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Dc(a)})}}return s},Mc=".lunora-schema.json",b=(e,t)=>{N(e)&&ht(e,"utf8")===t||Vt(e,t,"utf8")},w=(e,t)=>{if(t===""){Wt(e,{force:!0});return}b(e,t)},Kc=e=>{const t=f(e,"package.json");if(N(t))try{const s=JSON.parse(ht(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},_c=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},zc=e=>{let t=N(e)?e:ue(e);for(;t&&t!==ue(t);){const s=f(t,"tsconfig.json");if(N(s))return s;t=ue(t)}},gt=e=>e.replaceAll("\\","/"),Uc=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new O("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new O("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new O("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},mt=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Bc=e=>{const t=zc(e);return t?new Qe({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Qe({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Rl=(e,t)=>{const s=h(t),n=f(t,"schema.ts");N(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>gt(c))),r=gt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Ol=e=>{const t=_c(),s=t?de.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),o=f(n,"schema.ts");if(!N(o))throw new O("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??Bc(n);ln(Os);const a=Xs(r,o,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:v,env:P,featureUsage:p,hasBrowser:A,hasFlags:D,hasNotify:z,identity:U,platformGate:j,queues:C,serverContent:k,storageRulesMetadata:B,usesSandbox:ne,useUmbrella:M,workflows:R}=On({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),g=f(n,"_generated"),be=f(g,"dataModel.ts"),Ie=f(g,"server.ts");mt(r,be,d),mt(r,Ie,k);const L=Rs(r,n),Pe=ks(r,n),we=Bs(r,n),q=sn(r,n),re=js(r,n),ie=Ls(r,n,R,c),V=e.lint===!1?void 0:Yt({adminRoutes:zn(r,n),aiRawRuns:qn(r,n),aiToolSideEffects:Zn(r,n),argumentDerivedFetches:tr(r,n),argumentValidators:pr(r,n),authApiCalls:Fs(r,n),authConfigs:yr(r,n),browserUrlAccesses:Tr(r,n),configCalls:Mr(r,n),containerKeyAccesses:_r(r,n),containerOverrides:jr(r,n),containers:u,exportSinks:Gr(r,n),staleMigrationImports:Xa(r,n),failOpenGuards:Jr(r,n),flagSecurityDefaults:ni(r,n),geoIndexUsages:oi(r,n),httpActionGuards:pi(r,n),httpHeaderWrites:yi(r,n),identityClaimReads:Ri(r,n),imageDeliveryUrlAccesses:Fi(r,n),inserts:Ms(r,n),kvKeyAccesses:Di(r,n),mailRecipientAccesses:zi(r,n),maskProcedures:Ks(r,n),maskStrategies:_s(r,n),mutatorWrites:Vi(r,n),nondeterministicCalls:Vs(r,n),normalizeIdAuthorizations:ao(r,n),notifyCalls:Hs(r,n),notifyConfig:Ws(r,n),ownerFieldWrites:ho(r,n,L),unrestrictedWhereBranches:Tc(r,n),paymentWebhooks:Ao(r,n),privilegedDispatches:Do(r,n),procedureProtections:Ea(r,n),queries:ws(r,n),queues:C,r2sqlCalls:Gs(r,n),ratelimitKeySelectors:Na(r,n),rawRowReturns:Ca(r,n),relationLoads:Fa(r,n),rlsProcedures:Ys(r,n),schema:a,secretLiterals:Ua(r,n),shapes:q,softDeleteReads:qa(r,n),sqlInterpolations:Ga(r,n),storageKeyAccesses:Ja(r,n,L),storageUploads:ic(r,n),vectorNamespaceAccesses:Fc(r,n),workflowCalls:kc(r,n),workflows:R,wranglerVariables:e.wranglerVariables}),Te=V===void 0?[]:[...Ht(V,{source:"static"}),...fc(r,n,L)],_t=Qs(r,n),Ce=zs(r,n);Uc(q,Ce,Us(r,n));const zt=D?Ds(r,n):[],W=bn(p,{containerCount:u.length,cronCount:ie.length,dependencies:v,hasPaymentTables:yn(a.tables),queueCount:C.length,storageColumnCount:Object.keys(es(a)).length,storageRuleCount:B.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:R.length}),Re=t?de.now():0,Oe=ts({agents:c,functions:L,httpRoutes:Pe,mutators:re,useUmbrella:M,workflows:R}),Fe=ss({agents:c,functions:L,migrations:we,mutators:re,shapes:q,useUmbrella:M,usesSandbox:ne}),oe=un(a,we.map(m=>m.id)),Le=ns({advisories:Te,advisorProcedures:V?.procedureProtections??[],agents:c,containers:u,env:P,flagKeys:zt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:A,hasFlags:D,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:z,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:Ce,mutators:re,queues:C,rlsMetadata:_t,schema:a,schemaSnapshot:oe,shapes:q,storageRules:B,studioFeatures:W,useUmbrella:M,workflows:R}),De=rs(q,v.has("@lunora/db"),M),ke=is(u,a.jurisdiction),Me=os(R),Ke=as(c),_e=cs(C),ze=ls(ie),Ue=us(a.vectorIndexes),H=ds(a,M),Be=fs(v.has("@lunora/seed")),G=e.apiSpec??"openapi",ae=G==="openapi"||G==="both",ce=G==="openrpc"||G==="both",qe=nn({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:v.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:v.has("@lunora/auth"),hasBrowser:A,hasFramework:v.has("@lunora/astro")||v.has("@lunora/svelte")||v.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:p.images,hasKv:W.kv,hasNotify:z,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:C.some(m=>m.mode==="push"),hasScheduler:W.scheduler,hasStorage:W.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:R.length>0,hasX402:p.x402,identity:U,jurisdiction:a.jurisdiction,useUmbrella:M,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:ae,wantsOpenRpc:ce}),$e=Kc(e.projectRoot),je=rn({functions:L,httpRoutes:Pe,version:$e}),Ve=an({functions:L,version:$e}),We=`${JSON.stringify(je,void 0,2)}
|
|
8
|
+
`,He=`${JSON.stringify(Ve,void 0,2)}
|
|
9
|
+
`,Ge=on(je),Ye=cn(Ve),le=f(n,Mc),Ut=N(le);if(e.dryRun||(N(g)||jt(g,{recursive:!0}),b(f(g,"app.ts"),qe),b(be,d),b(f(g,"api.ts"),Oe),b(Ie,k),b(f(g,"functions.ts"),Fe),b(f(g,"shard.ts"),Le),b(f(g,"crons.ts"),ze),b(f(g,"vectors.ts"),Ue),b(f(g,"drizzle.global.ts"),H.global),b(f(g,"drizzle.shard.ts"),H.shard),w(f(g,"containers.ts"),ke),w(f(g,"workflows.ts"),Me),w(f(g,"agents.ts"),Ke),w(f(g,"queues.ts"),_e),w(f(g,"seed.ts"),Be),w(f(g,"collections.ts"),De),w(f(g,"openapi.json"),ae?We:""),w(f(g,"openapi.ts"),ae?Ge:""),w(f(g,"openrpc.json"),ce?He:""),w(f(g,"openrpc.ts"),ce?Ye:""),(!Ut||e.updateSchemaBaseline===!0)&&b(le,Gt(oe))),t){const m=de.now(),Bt=Math.round(m-s),qt=Math.round(Re-s),$t=Math.round(m-Re);console.error(`@lunora/codegen: codegen took ${Bt.toString()}ms (discovery ${qt.toString()}ms, emit ${$t.toString()}ms)`)}return{advisories:Te,advisorContext:V,agents:c,containers:u,cronTriggers:ps(ie),generated:{agents:Ke,api:Oe,app:qe,collections:De,containers:ke,crons:ze,dataModel:d,drizzleGlobal:H.global,drizzleShard:H.shard,functions:Fe,openApi:We,openApiModule:Ge,openRpc:He,openRpcModule:Ye,queues:_e,seed:Be,server:k,shard:Le,vectors:Ue,workflows:Me},outputDirectory:g,platformDiagnostics:j.diagnostics,queues:C,schemaSnapshot:oe,schemaSnapshotPath:le,workflows:R}};export{Mc as SCHEMA_SNAPSHOT_FILENAME,Bc as createCodegenProject,zc as findTsconfig,Rl as refreshCodegenProject,Ol as runCodegen};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as f}from"node:fs";import{join as l}from"node:path";import{SyntaxKind as c,Node as o}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as p}from"./module-specifiers-WF8iAydP.mjs";import{a as g}from"./parse-validator-
|
|
1
|
+
import{existsSync as f}from"node:fs";import{join as l}from"node:path";import{SyntaxKind as c,Node as o}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as p}from"./module-specifiers-WF8iAydP.mjs";import{a as g}from"./parse-validator-C5ycrhR3.mjs";const m="shapes.ts",d=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return p(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},S=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(c.ImportDeclaration);return i!==void 0&&p(i.getModuleSpecifierValue())}return!1},h=r=>{if(o.isIdentifier(r))return d(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&S(t)}return!1},x=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=t.getProperty("table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},b=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=t.getProperty("args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:g(i)},y=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==c.CallExpression)continue;const s=i,a=s.getExpression();if(!h(a))continue;const n=e.getNameNode();if(!o.isIdentifier(n))throw u(n,"defineShape exports must be plain named exports (no destructuring)");t.push({args:b(s),exportName:n.getText(),filePath:"shapes",table:x(s)})}return t},v=(r,t)=>{const e=l(t,m);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),s=y(i);return s.sort((a,n)=>a.exportName.localeCompare(n.exportName)),s};export{m as SHAPES_FILENAME,v as discoverShapes};
|
package/dist/packem_shared/{buildOpenApiDocument-B2mW3f5a.mjs → buildOpenApiDocument-ClEtrbbS.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-CV6JjAt9.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
|
|
2
2
|
`,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
|
package/dist/packem_shared/{discoverFunctions-h8i51Mec.mjs → discoverFunctions-4eSpCR6m.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as O}from"ts-morph";import{l as w,a as k}from"./discover-ast-D33zP-NZ.mjs";import{a as z}from"./module-specifiers-WF8iAydP.mjs";import{p as _,a as b}from"./parse-validator-DtALyvid.mjs";import{s as R}from"./paths-C-9fwEgQ.mjs";const y=new Set(["action","mutation","query","stream"]),P=/\bany\b(?!\s*(?:\?\s*)?:)/u,T=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,U=/^[A-Za-z_$][\w$]*$/u,j=e=>U.test(e)?e:JSON.stringify(e),N={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},$={onConnect:"connect",onDisconnect:"disconnect"},V=z,h=e=>{const t=e.getSymbol();if(!t)return e.getText();const r=t.getDeclarations();for(const i of r){if(!s.isImportSpecifier(i))continue;const o=i.getImportDeclaration().getModuleSpecifierValue();return V(o)?i.getNameNode().getText():void 0}},S=(e,t=!1)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))return;r=n.getExpression()}if(!s.isIdentifier(r))return;const i=h(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?S(o,!0):void 0}return}return y.has(i)?"public":N[i]?"internal":void 0},m=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isStringLiteral(i)?i.getLiteralValue():void 0},E=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isNumericLiteral(i)?i.getLiteralValue():void 0},M=e=>{const t=e.getProperty("cache");if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();if(r===void 0||!s.isObjectLiteralExpression(r))return;const i=m(r,"scope"),n=E(r,"maxAge"),o=E(r,"staleWhileRevalidate"),a=m(r,"tag"),c=m(r,"vary"),l={...n===void 0?{}:{maxAge:n},...i==="private"||i==="public"?{scope:i}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},B=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const t=M(e),r=e.getProperty("rest");return r!==void 0&&s.isPropertyAssignment(r)?{...t===void 0?{}:{cache:t},rest:r.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},K=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="expose")return B(t.getArguments()[0]);t=r.getExpression()}},H=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const r=t.getProperty("args");if(!r||!s.isPropertyAssignment(r))return{};const i=r.getInitializer();return!i||!s.isObjectLiteralExpression(i)?{}:b(i)},G="/_generated/",q=(e,t,r)=>{const i=t.getSourceFile(),n=(a,c)=>i.getImportDeclarations().some(l=>l.getModuleSpecifierSourceFile()!==a?!1:l.getNamespaceImport()!==void 0||l.getNamedImports().some(f=>f.getName()===c)),o=a=>{const c=a.getSourceFile();if(c.isInNodeModules()||c.isDeclarationFile()||!s.isInterfaceDeclaration(a)&&!s.isTypeAliasDeclaration(a))return!1;const l=c.getFilePath();return l.includes(G)?!1:l===r||n(c,a.getName())};return[e.getSymbol(),e.getAliasSymbol()].flatMap(a=>a?.getDeclarations()??[]).some(a=>o(a))},W=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},I=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,g=(e,t,r,i=new Set)=>i.has(e)?!1:(i.add(e),q(e,t,r)||W(e).some(n=>g(n,t,r,i))?!0:I(e)?e.getProperties().some(n=>g(n.getTypeAtLocation(t),t,r,i)):!1),X=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(s.isPropertySignature(r)||s.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(i=>i.isUndefined())},Y=8,J=(e,t,r,i,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,r,i,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},Q=(e,t,r,i,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,r,i,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},Z=(e,t,r,i,n,o)=>{if(!I(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),f=X(c,l),L=f&&l.isUnion()?l.getUnionTypes().filter(d=>!d.isUndefined()):[l],v=[];for(const d of L){const x=o(d,t,r,i+1,n);if(x===void 0)return;v.push(x)}a.push(`${j(c.getName())}${f?"?":""}: ${v.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},p=(e,t,r,i,n)=>{if(i>Y||n.has(e))return;if(!g(e,t,r))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?J(e,t,r,i,o,p):e.isUnion()?Q(e,t,r,i,o,p):Z(e,t,r,i,o,p)},C=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const n=(r.getSymbol()??r.getAliasSymbol())?.getName();if(n==="Promise"||n==="AsyncIterable"||n==="AsyncIterableIterator"||n==="AsyncGenerator"){const c=r.getTypeArguments()[0];c&&(r=c)}const o=r.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return"unknown";const a=e.getSourceFile().getFilePath();return g(r,e,a)?p(r,e,a,0,new Set)??"unknown":o},ve=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const r=t.getTypeAtLocation(e).getProperty("types");if(!r)return;const i=r.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!i)return;const n=i.getTypeAtLocation(e),o=n.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return;const a=e.getSourceFile().getFilePath();return g(n,e,a)?p(n,e,a,0,new Set):o},ee=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const r=t.getProperty("handler");if(!r||!s.isPropertyAssignment(r))return"unknown";const i=r.getInitializer();return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":C(i)},te=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":C(t)},re=e=>{let t={},r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...b(n),...t})}r=i.getExpression()}return t},ie=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="output"){const i=t.getArguments()[0];return i&&s.isExpression(i)?_(i):void 0}t=r.getExpression()}},ne=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!y.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=S(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const r=h(t);if(!r)return;if(y.has(r))return{kind:r,visibility:"public"};const i=N[r];if(i)return{kind:i,visibility:"internal"};const n=$[r];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},A=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,xe=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",Ee=e=>{const t=e.getArguments()[0],r=A(t);if(r!==void 0)return r;if(t===void 0||!s.isObjectLiteralExpression(t))return;const i=t.getProperty("handler");return i!==void 0&&s.isPropertyAssignment(i)?A(i.getInitializer()):void 0},se=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ae=(e,t)=>{let r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()===t)return!0;r=i.getExpression()}return!1},be=(e,t,r)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=i.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&se(o.getExpression())===r)return!0;i=n.getExpression()}return!1},oe=e=>{const t=ne(e);if(t){if(t.receiver){const r=K(t.receiver),i=ie(t.receiver);return{args:re(t.receiver),...r?{expose:r}:{},kind:t.kind,...i?{output:i}:{},returnType:te(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:H(e),kind:t.kind,returnType:ee(e),visibility:t.visibility}}},ae=8,u=(e,t=0)=>{if(t>ae)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const r=e.getSymbol()?.getValueDeclaration();return r?F(r,t+1):void 0},F=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const r=e.getInitializer();return r?u(r,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const r=e.getPropertyNameNode()?.getText()??e.getName(),o=e.getFirstAncestorByKind(O.VariableDeclaration)?.getInitializer()?.getType().getProperty(r)?.getValueDeclaration();return o?F(o,t+1):void 0}},ce=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const r=e.getInitializer(),i=r&&(s.isCallExpression(r)?r:u(r));return i?[[e.getName(),i]]:[]},D=(e,t,r)=>{const i=oe(e);if(i)return{args:i.args,exportName:t,filePath:r,kind:i.kind,returnType:i.returnType,...i.output?{output:i.output}:{},visibility:i.visibility,...i.expose?{expose:i.expose}:{},...i.lifecycle?{lifecycle:i.lifecycle}:{}}},le=(e,t)=>{const r=[];for(const i of e.getExportAssignments()){if(i.isExportEquals())continue;const n=u(i.getExpression()),o=n?D(n,"default",t):void 0;o&&r.push(o)}return r},ue=(e,t)=>{const r=[];for(const i of e.getVariableStatements())if(i.isExported())for(const n of i.getDeclarations())for(const[o,a]of ce(n)){const c=D(a,o,t);c&&r.push(c)}return r.push(...le(e,t)),r},pe=e=>{const t=new Map;for(const r of e){const i=R(r.filePath),n=t.get(i);if(n&&n!==r.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${r.filePath}" both resolve to "${i}". 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:[n,r.filePath],status:500});t.set(i,r.filePath)}},Pe=(e,t)=>{const r=w(t),i=[];for(const n of r){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=k(t,n);i.push(...ue(o,a))}return i.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),pe(i),i};export{Ae as chainHasStep,be as chainUsesWrappedCall,ne as classifyProcedureCall,Pe as discoverFunctions,A as inlineHandler,xe as isDatabaseAccessor,w as listLunoraSourceFiles,k as lunoraRelativePath,Ee as procedureHandler,ve as resolveStandardSchemaType,C as unwrapHandlerReturn};
|
|
1
|
+
import{Node as s,SyntaxKind as O}from"ts-morph";import{l as w,a as k}from"./discover-ast-D33zP-NZ.mjs";import{a as z}from"./module-specifiers-WF8iAydP.mjs";import{p as _,a as b}from"./parse-validator-C5ycrhR3.mjs";import{s as R}from"./paths-C-9fwEgQ.mjs";const y=new Set(["action","mutation","query","stream"]),P=/\bany\b(?!\s*(?:\?\s*)?:)/u,T=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,U=/^[A-Za-z_$][\w$]*$/u,j=e=>U.test(e)?e:JSON.stringify(e),N={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},$={onConnect:"connect",onDisconnect:"disconnect"},V=z,h=e=>{const t=e.getSymbol();if(!t)return e.getText();const r=t.getDeclarations();for(const i of r){if(!s.isImportSpecifier(i))continue;const o=i.getImportDeclaration().getModuleSpecifierValue();return V(o)?i.getNameNode().getText():void 0}},S=(e,t=!1)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))return;r=n.getExpression()}if(!s.isIdentifier(r))return;const i=h(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?S(o,!0):void 0}return}return y.has(i)?"public":N[i]?"internal":void 0},m=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isStringLiteral(i)?i.getLiteralValue():void 0},E=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isNumericLiteral(i)?i.getLiteralValue():void 0},M=e=>{const t=e.getProperty("cache");if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();if(r===void 0||!s.isObjectLiteralExpression(r))return;const i=m(r,"scope"),n=E(r,"maxAge"),o=E(r,"staleWhileRevalidate"),a=m(r,"tag"),c=m(r,"vary"),l={...n===void 0?{}:{maxAge:n},...i==="private"||i==="public"?{scope:i}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},B=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const t=M(e),r=e.getProperty("rest");return r!==void 0&&s.isPropertyAssignment(r)?{...t===void 0?{}:{cache:t},rest:r.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},K=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="expose")return B(t.getArguments()[0]);t=r.getExpression()}},H=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const r=t.getProperty("args");if(!r||!s.isPropertyAssignment(r))return{};const i=r.getInitializer();return!i||!s.isObjectLiteralExpression(i)?{}:b(i)},G="/_generated/",q=(e,t,r)=>{const i=t.getSourceFile(),n=(a,c)=>i.getImportDeclarations().some(l=>l.getModuleSpecifierSourceFile()!==a?!1:l.getNamespaceImport()!==void 0||l.getNamedImports().some(f=>f.getName()===c)),o=a=>{const c=a.getSourceFile();if(c.isInNodeModules()||c.isDeclarationFile()||!s.isInterfaceDeclaration(a)&&!s.isTypeAliasDeclaration(a))return!1;const l=c.getFilePath();return l.includes(G)?!1:l===r||n(c,a.getName())};return[e.getSymbol(),e.getAliasSymbol()].flatMap(a=>a?.getDeclarations()??[]).some(a=>o(a))},W=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},I=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,g=(e,t,r,i=new Set)=>i.has(e)?!1:(i.add(e),q(e,t,r)||W(e).some(n=>g(n,t,r,i))?!0:I(e)?e.getProperties().some(n=>g(n.getTypeAtLocation(t),t,r,i)):!1),X=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(s.isPropertySignature(r)||s.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(i=>i.isUndefined())},Y=8,J=(e,t,r,i,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,r,i,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},Q=(e,t,r,i,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,r,i,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},Z=(e,t,r,i,n,o)=>{if(!I(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),f=X(c,l),L=f&&l.isUnion()?l.getUnionTypes().filter(d=>!d.isUndefined()):[l],v=[];for(const d of L){const x=o(d,t,r,i+1,n);if(x===void 0)return;v.push(x)}a.push(`${j(c.getName())}${f?"?":""}: ${v.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},p=(e,t,r,i,n)=>{if(i>Y||n.has(e))return;if(!g(e,t,r))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?J(e,t,r,i,o,p):e.isUnion()?Q(e,t,r,i,o,p):Z(e,t,r,i,o,p)},C=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const n=(r.getSymbol()??r.getAliasSymbol())?.getName();if(n==="Promise"||n==="AsyncIterable"||n==="AsyncIterableIterator"||n==="AsyncGenerator"){const c=r.getTypeArguments()[0];c&&(r=c)}const o=r.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return"unknown";const a=e.getSourceFile().getFilePath();return g(r,e,a)?p(r,e,a,0,new Set)??"unknown":o},ve=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const r=t.getTypeAtLocation(e).getProperty("types");if(!r)return;const i=r.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!i)return;const n=i.getTypeAtLocation(e),o=n.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return;const a=e.getSourceFile().getFilePath();return g(n,e,a)?p(n,e,a,0,new Set):o},ee=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const r=t.getProperty("handler");if(!r||!s.isPropertyAssignment(r))return"unknown";const i=r.getInitializer();return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":C(i)},te=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":C(t)},re=e=>{let t={},r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...b(n),...t})}r=i.getExpression()}return t},ie=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="output"){const i=t.getArguments()[0];return i&&s.isExpression(i)?_(i):void 0}t=r.getExpression()}},ne=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!y.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=S(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const r=h(t);if(!r)return;if(y.has(r))return{kind:r,visibility:"public"};const i=N[r];if(i)return{kind:i,visibility:"internal"};const n=$[r];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},A=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,xe=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",Ee=e=>{const t=e.getArguments()[0],r=A(t);if(r!==void 0)return r;if(t===void 0||!s.isObjectLiteralExpression(t))return;const i=t.getProperty("handler");return i!==void 0&&s.isPropertyAssignment(i)?A(i.getInitializer()):void 0},se=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ae=(e,t)=>{let r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()===t)return!0;r=i.getExpression()}return!1},be=(e,t,r)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=i.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&se(o.getExpression())===r)return!0;i=n.getExpression()}return!1},oe=e=>{const t=ne(e);if(t){if(t.receiver){const r=K(t.receiver),i=ie(t.receiver);return{args:re(t.receiver),...r?{expose:r}:{},kind:t.kind,...i?{output:i}:{},returnType:te(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:H(e),kind:t.kind,returnType:ee(e),visibility:t.visibility}}},ae=8,u=(e,t=0)=>{if(t>ae)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const r=e.getSymbol()?.getValueDeclaration();return r?F(r,t+1):void 0},F=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const r=e.getInitializer();return r?u(r,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const r=e.getPropertyNameNode()?.getText()??e.getName(),o=e.getFirstAncestorByKind(O.VariableDeclaration)?.getInitializer()?.getType().getProperty(r)?.getValueDeclaration();return o?F(o,t+1):void 0}},ce=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const r=e.getInitializer(),i=r&&(s.isCallExpression(r)?r:u(r));return i?[[e.getName(),i]]:[]},D=(e,t,r)=>{const i=oe(e);if(i)return{args:i.args,exportName:t,filePath:r,kind:i.kind,returnType:i.returnType,...i.output?{output:i.output}:{},visibility:i.visibility,...i.expose?{expose:i.expose}:{},...i.lifecycle?{lifecycle:i.lifecycle}:{}}},le=(e,t)=>{const r=[];for(const i of e.getExportAssignments()){if(i.isExportEquals())continue;const n=u(i.getExpression()),o=n?D(n,"default",t):void 0;o&&r.push(o)}return r},ue=(e,t)=>{const r=[];for(const i of e.getVariableStatements())if(i.isExported())for(const n of i.getDeclarations())for(const[o,a]of ce(n)){const c=D(a,o,t);c&&r.push(c)}return r.push(...le(e,t)),r},pe=e=>{const t=new Map;for(const r of e){const i=R(r.filePath),n=t.get(i);if(n&&n!==r.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${r.filePath}" both resolve to "${i}". 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:[n,r.filePath],status:500});t.set(i,r.filePath)}},Pe=(e,t)=>{const r=w(t),i=[];for(const n of r){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=k(t,n);i.push(...ue(o,a))}return i.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),pe(i),i};export{Ae as chainHasStep,be as chainUsesWrappedCall,ne as classifyProcedureCall,Pe as discoverFunctions,A as inlineHandler,xe as isDatabaseAccessor,w as listLunoraSourceFiles,k as lunoraRelativePath,Ee as procedureHandler,ve as resolveStandardSchemaType,C as unwrapHandlerReturn};
|
package/dist/packem_shared/{discoverHttpRoutes-MX6y-iVE.mjs → discoverHttpRoutes-DOirwCWw.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as a}from"ts-morph";import{l,a as m}from"./discover-ast-D33zP-NZ.mjs";import{unwrapHandlerReturn as d}from"./discoverFunctions-
|
|
1
|
+
import{Node as a}from"ts-morph";import{l,a as m}from"./discover-ast-D33zP-NZ.mjs";import{unwrapHandlerReturn as d}from"./discoverFunctions-4eSpCR6m.mjs";import{p as h,a as f}from"./parse-validator-C5ycrhR3.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),g=new Set(["body","params","searchParams"]),E=new Set(["handler","stream"]),v=r=>{const e=r.getArguments()[0];if(e&&a.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&a.isObjectLiteralExpression(e)?f(e):{}},P=r=>{if(!a.isCallExpression(r))return;const e=r.getExpression();if(!a.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!a.isIdentifier(n)||n.getText()!=="httpRoute")return;const s=v(r);return s===void 0?void 0:{method:o.toUpperCase(),path:s}},S=(r,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},n=r.getExpression();if(!a.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;a.isCallExpression(s);){const i=s.getExpression();if(!a.isPropertyAccessExpression(i))break;const c=i.getName();if(u.has(c))break;if(g.has(c)){const p=x(s);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=s.getArguments()[0];p&&a.isExpression(p)&&(o.output=h(p))}s=i.getExpression()}const t=P(s);if(t)return o.method=t.method,o.path=t.path,o},A=r=>{const e=r.getArguments()[0];return!e||!(a.isArrowFunction(e)||a.isFunctionExpression(e))?"unknown":d(e)},T=(r,e,o,n)=>{const s=e.getName();if(!E.has(s))return;const t=S(r,s);if(!(t?.method===void 0||t.path===void 0))return{body:t.body,exportName:o,filePath:n,method:t.method,params:t.params,path:t.path,searchParams:t.searchParams,stream:t.stream,...t.stream?{chunkType:A(r)}:{},...t.output?{output:t.output}:{}}},b=(r,e)=>{const o=[];for(const n of r.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const t=s.getInitializer();if(!t||!a.isCallExpression(t))continue;const i=t.getExpression();if(!a.isPropertyAccessExpression(i))continue;const c=T(t,i,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=l(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),i=m(e,s);n.push(...b(t,i))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{l as f,a as P,t as x}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as p}from"./discoverFunctions-
|
|
1
|
+
import{Node as i}from"ts-morph";import{l as f,a as P,t as x}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as p}from"./discoverFunctions-4eSpCR6m.mjs";const A=e=>{if(!i.isCallExpression(e))return!1;const s=e.getExpression();return i.isIdentifier(s)?s.getText()==="mask":i.isPropertyAccessExpression(s)?s.getName()==="mask":!1},u=e=>{if(i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e))return e.getName()},k=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,table:o})}}return t},g=e=>{const s=[];let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const o=t.getArguments()[0];o&&A(o)&&s.push(o)}t=r.getExpression()}return s},E=e=>{const s=g(e);return{maskColumns:s.flatMap(t=>k(t)),usesMask:s.length>0}},M=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),S=new Set(["delete","insert","patch","replace"]),b=(e,s)=>{if(!i.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const r=p(t);if(!r)return;const o=r.receiver?E(r.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=x(e,M,S);return{exportName:e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:r.visibility}},w=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=b(c,n);l&&t.push(l)}}return t},h=e=>{if(i.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&i.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},C=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,strategy:h(a),table:o})}}return t},v=e=>{const s=[];for(const t of e.getVariableStatements())if(t.isExported())for(const r of t.getDeclarations()){const o=r.getInitializer(),n=o&&i.isCallExpression(o)?p(o):void 0;n?.receiver&&s.push(n.receiver)}return s},R=(e,s)=>{const t=new Map;for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of v(o))for(const a of g(n))for(const c of C(a)){const l=`${c.table}\0${c.column}`;t.has(l)||t.set(l,c)}}return{columns:[...t.values()]}},F=(e,s,t)=>{const r=e.getArguments()[0];if(!r||!i.isObjectLiteralExpression(r))return[];const o=[];for(const n of r.getProperties()){const a=u(n);if(a===void 0||!i.isPropertyAssignment(n))continue;const c=n.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const m=u(l);if(m===void 0)continue;const d=h(l);d!=="custom"&&o.push({column:m,exportName:s,file:t,line:l.getStartLineNumber(),strategy:d,table:a})}}return o},z=(e,s)=>{if(!i.isVariableDeclaration(e))return[];const t=e.getInitializer(),r=t&&i.isCallExpression(t)?p(t):void 0;return r?.receiver?g(r.receiver).flatMap(o=>F(o,e.getName(),s)):[]},T=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())t.push(...z(c,n))}return t},D=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,L=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?D(e):!0,y=(e,s=!1)=>{for(const t of e.getProperties()){if(L(t))return!0;if(s)continue;if(!i.isPropertyAssignment(t))return!0;const r=t.getInitializer();if(!r||!i.isObjectLiteralExpression(r)||y(r,!0))return!0}return!1},j=(e,s)=>{for(const t of f(s)){const r=e.getSourceFile(t)??e.addSourceFileAtPath(t);for(const o of v(r))for(const n of g(o)){const a=n.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||y(a)))return!0}}return!1};export{w as default,j as discoverMaskHasNonLiteralPolicy,R as discoverMaskMetadata,T as discoverMaskStrategies};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as a}from"ts-morph";import{l,a as c,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-
|
|
1
|
+
import{Node as s,SyntaxKind as a}from"ts-morph";import{l,a as c,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-4eSpCR6m.mjs";const u={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},m=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),p=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},h=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=p(t.getExpression());if(i!==void 0)return n==="fetch"&&m.has(i)?"fetch":u[`${i}.${n}`]},x=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},N=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=f(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=d(t,n.receiver);return i?{exportName:e.getName(),handler:i,kind:n.kind}:void 0},E=(e,t)=>{const n=[];for(const i of e.handler.getDescendantsOfKind(a.CallExpression)){const o=h(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}for(const i of e.handler.getDescendantsOfKind(a.NewExpression)){const o=x(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}return n},S=(e,t)=>{const n=[];for(const i of e.getVariableStatements())if(i.isExported())for(const o of i.getDeclarations()){const r=N(o);r&&n.push(...E(r,t))}return n},w=(e,t)=>{const n=[];for(const i of l(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,c(t,i)))}return n};export{w as default};
|
package/dist/packem_shared/{discoverR2sqlCalls-DuTuaSMM.mjs → discoverR2sqlCalls-B6e4j4rD.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o,SyntaxKind as a}from"ts-morph";import{l as c,a as l,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-
|
|
1
|
+
import{Node as o,SyntaxKind as a}from"ts-morph";import{l as c,a as l,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-4eSpCR6m.mjs";const u=t=>{const r=t.getInitializer();if(!r||!o.isCallExpression(r))return;const e=f(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const n=d(r,e.receiver);return n?{exportName:t.getName(),handler:n,kind:e.kind}:void 0},p=t=>{if(!o.isPropertyAccessExpression(t)||t.getName()!=="r2sql")return;const r=t.getExpression();if(!o.isIdentifier(r)||r.getText()!=="ctx")return;const e=t.getParent();return e&&o.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.r2sql.${e.getName()}`:"ctx.r2sql"},x=(t,r)=>{const e=[];for(const n of t.handler.getDescendantsOfKind(a.PropertyAccessExpression)){const s=p(n);s!==void 0&&e.push({callee:s,exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()})}return e},m=(t,r)=>{const e=[];for(const n of t.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const i=u(s);i&&e.push(...x(i,r))}return e},P=(t,r)=>{const e=[];for(const n of c(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);e.push(...m(s,l(r,n)))}return e};export{P as default};
|
package/dist/packem_shared/{discoverRlsMetadata-BYVq6cVp.mjs → discoverRlsMetadata-Pw0_c1aS.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as n}from"ts-morph";import{l as d,a as x,t as P,b as l}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as E}from"./discoverFunctions-
|
|
1
|
+
import{Node as n}from"ts-morph";import{l as d,a as x,t as P,b as l}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as E}from"./discoverFunctions-4eSpCR6m.mjs";const b=t=>{if(!n.isCallExpression(t))return!1;const e=t.getExpression();return n.isIdentifier(e)?e.getText()==="rls":n.isPropertyAccessExpression(e)?e.getName()==="rls":!1},v=t=>{const e=t.getArguments()[0];if(!e||!n.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements()){if(!n.isObjectLiteralExpression(r))continue;const i=r.getProperty("table");if(!i||!n.isPropertyAssignment(i))continue;const o=i.getInitializer();o&&n.isStringLiteral(o)&&s.push(o.getLiteralText())}return s},h=t=>{const e=[];let s=t;for(;n.isCallExpression(s);){const r=s.getExpression();if(!n.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const i=s.getArguments()[0];i&&b(i)&&e.push(i)}s=r.getExpression()}return e},y=t=>{const e=h(t);return{rlsTables:e.flatMap(s=>v(s)),usesRls:e.length>0}},A=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),L=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),S=(t,e)=>{if(!n.isVariableDeclaration(t))return;const s=t.getInitializer();if(!s||!n.isCallExpression(s))return;const r=E(s);if(!r)return;const i=r.receiver?y(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:o,tablesWritten:a}=P(t,A,L);return{exportName:t.getName(),file:e,rlsTables:i.rlsTables,tablesRead:o,tablesWritten:a,usesRls:i.usesRls,visibility:r.visibility}},w=(t,e)=>{const s=[];for(const r of d(e)){const i=t.getSourceFile(r)??t.addSourceFileAtPath(r),o=x(e,r);for(const a of i.getVariableStatements())if(a.isExported())for(const u of a.getDeclarations()){const c=S(u,o);c&&s.push(c)}}return s},C=new Set(["delete","insert","read","update"]),T=(t,e,s)=>{const r=t.getArguments()[0];if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){if(!n.isObjectLiteralExpression(o))continue;const a=l(o,"on");a===void 0||!C.has(a)||i.push({file:e,on:a,procedure:s,table:l(o,"table")??""})}return i},g=t=>{if(!n.isObjectLiteralExpression(t))return[];const e=t.getProperty("permissions");if(!e||!n.isPropertyAssignment(e))return[];const s=e.getInitializer();if(!s||!n.isArrayLiteralExpression(s))return[];const r=[];for(const i of s.getElements()){if(n.isStringLiteral(i)){r.push(i.getLiteralText());continue}if(n.isCallExpression(i)){const o=i.getArguments()[0];o&&n.isStringLiteral(o)&&r.push(o.getLiteralText())}}return r},m=(t,e)=>e===void 0?t:{...t,description:e},R=t=>{if(n.isCallExpression(t)){const e=t.getArguments()[0];if(!e||!n.isStringLiteral(e))return;const s=t.getArguments()[1],r=s?l(s,"description"):void 0,i=s?g(s):[];return m({name:e.getLiteralText(),permissions:i},r)}if(n.isObjectLiteralExpression(t)){const e=l(t,"name");return e===void 0?void 0:m({name:e,permissions:g(t)},l(t,"description"))}},F=t=>{const e=t.getArguments()[1];if(!e||!n.isObjectLiteralExpression(e))return[];const s=e.getProperty("roles");if(!s||!n.isPropertyAssignment(s))return[];const r=s.getInitializer();if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){const a=R(o);a&&i.push(a)}return i},I=(t,e,s)=>{const r=h(t);return{policies:r.flatMap(i=>T(i,e,s)),roles:r.flatMap(i=>F(i))}},M=t=>{const e=[];for(const s of t.getVariableStatements())if(s.isExported())for(const r of s.getDeclarations()){const i=r.getInitializer(),o=i&&n.isCallExpression(i)?E(i):void 0;o?.receiver&&e.push({name:r.getName(),receiver:o.receiver})}return e},D=(t,e)=>{const s=[],r=new Map;for(const i of d(e)){const o=t.getSourceFile(i)??t.addSourceFileAtPath(i),a=x(e,i);for(const{name:u,receiver:c}of M(o)){const p=I(c,a,u);s.push(...p.policies);for(const f of p.roles)r.has(f.name)||r.set(f.name,f)}}return{policies:s,roles:[...r.values()]}};export{w as default,D as discoverRlsMetadata};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";import{Node as i,SyntaxKind as j}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as $}from"./parse-validator-C5ycrhR3.mjs";import{createRequire as z}from"node:module";import{join as D}from"node:path";const C=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},R=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),p=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:R(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=p(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=C(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,p(a)]));break}case"record":{s.valueType=p(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=p(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(o=>p(o));break}}return s},M=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",F=(e,n)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},B=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return F(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(t).map(([r,o])=>[r,p(o)])),shardMode:M(e.shardMode),vectorIndexes:[]}},V=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([a,l])=>B(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:n}},q=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},J=e=>{const n=q(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===n)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},U=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},K=(e,n)=>{const t=J(e);if(t)try{const s=z(D(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),o=s(r),a=U(o,t);return typeof a!="object"||a===null?void 0:V(a)}catch{return}},G=new Set(["cosine","dot-product","euclidean"]),Z=new Set(["cascade","restrict","set null"]),I=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),Q=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),W=/^[A-Za-z_$][\w$]*$/u,k=e=>e.replaceAll(/^["']|["']$/gu,""),w=(e,n)=>{const t=k(e);if(I.has(t))throw f(n,`table name "${t}" is reserved — it collides with a \`ctx.db\` member (one of ${[...I].map(s=>`"${s}"`).join(", ")}). Rename the table.`);if(Q.has(t))throw f(n,`table name "${t}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${t} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!W.test(t))throw f(n,`table name ${JSON.stringify(t)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`)},g=(e,n)=>{const t=e.getProperty(n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=g(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},m=(e,n)=>{const t=g(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},X=(e,n)=>{const t=g(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},x=(e,n)=>{const t=g(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},T=e=>e&&G.has(e)?e:void 0,H=e=>e&&Z.has(e)?e:void 0,Y=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},ee=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,o]=n.getArguments();if(!r||!i.isStringLiteral(r))throw f(r??n,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",u;return o&&i.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,u=s==="one"?H(d(o,"onDelete")):void 0),{field:l,kind:s,name:e.getName(),onDelete:u,references:c,table:a}},te=e=>{const n=Y(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=ee(s);r&&t.push(r)}return t},b=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ne=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},re=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=e.getProperty("unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},se=e=>{const[n,t,s]=e,r=re(s),o=b(n),a=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw f(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)ne(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},ie=e=>{const[n,t]=e;let s="_unknown_",r,o,a,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"filterFields"),o=d(t,"language"),a=X(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:o,name:b(n),staged:a,strategy:l}},oe=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=m(t,"precision")),{field:s,name:b(n),precision:r}},ae=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=m(t,"after")),{after:r,field:s}},le=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},ce=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>le(l)).filter(l=>l!==void 0))}r=x(t,"partitionBy")}return{name:b(n),partitionBy:r,sortBy:s}},de=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:m(s,"dimensions"),field:r,metadata:x(s,"metadata"),metric:T(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},fe=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},ue=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=e.getProperty("field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},pe=(e,n)=>{const t=x(e,n);return t!==void 0&&t.length>0?t:void 0},ge=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:pe(n,"columns"),hasReconcile:n.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:n.getProperty("softDeleteColumn")!==void 0,hasTenantBy:n.getProperty("tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},me=(e,n,t,s)=>{switch(n){case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(oe(t));break}case"global":{e.shardMode="global",e.globalBackend=fe(t);break}case"index":{e.indexes.push(se(t));break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ce(t));break}case"relations":{const r=t[0];r&&e.relations.push(...te(r));break}case"searchIndex":{e.searchIndexes.push(ie(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:ue(t[0])};break}case"source":{e.externalSource=ge(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=ae(t);break}case"vectorize":{const r=de(t,s);r&&e.vectorIndexes.push(r);break}}},S=["__vocab","_config","_content","_data","_docsize","_idx"],xe=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const o of S){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw f(e,`table "${n}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${S.join(", ")}.`)}},L=(e,n)=>{const t={externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))me(t,o.getName(),a,n),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=$(l);else if(l)throw f(l,`table "${n}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),xe(e,n,t.searchIndexes),{externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},be=e=>{const n=e.getProperty("source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},he=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:m(s,"dimensions"),metric:T(d(s,"metric")),name:o,table:be(s)}},P=e=>{const n=[];for(const t of e.getProperties()){const s=he(t);s&&n.push(s)}return n},v=(e,n)=>`${e}_${n}`,y=(e,n,t)=>t.has(e)?v(n,e):e,ye=(e,n,t)=>{const s=v(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:y(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:y(r.table,n,t)}))}},ve=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ee=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},Ie=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},Se=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ke=(e,n)=>{const t=ve(e);if(t){if(i.isPropertyAccessExpression(n)){const s=Se(t);return s?g(s,n.getName()):void 0}return t}},we=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,Ee(n))return n;const s=Ie(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=ke(a,n)}},Te=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),options:t}},Le=e=>{const n=e.getProperty("tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=r.getName();w(a,r.getNameNode()),s.push(L(o,a))}return s},Pe=e=>{const n=e.getProperty("vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:P(t)},N=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=n.map(a=>ye(a,e,s)),o=t.map(a=>({...a,name:v(e,a.name),table:y(a.table,e,s)}));return{tables:r,vectorIndexes:o}},Ne=(e,n)=>N(e,Le(n),Pe(n)),Oe=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=we(t);if(!s){if(n!==void 0){const o=K(t,n);if(o)return N(o.key,o.bareTables,o.bareVectorIndexes)}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Te(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Ne(r.key,r.options)},Ae=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},O=(e,n,t,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const u=c.getLiteralText();if(!s.has(u))throw f(c,`unknown ${t} ${JSON.stringify(u)} — expected ${r}`);return u}o=l}},_e=new Set(["eu","fedramp","us"]),je=e=>O(e,"jurisdiction","jurisdiction",_e,'"eu", "us", or "fedramp"'),$e=new Set(["required"]),ze=e=>O(e,"rls","rls mode",$e,'"required"'),De=e=>{const n=[],t=new Set;for(const s of e.getProperties()){if(!i.isPropertyAssignment(s))continue;const r=s.getInitializer();if(r){const o=s.getName();w(o,s.getNameNode());const a=k(o);if(t.has(a))throw f(s.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(a),n.push(L(r,o))}}return n},Ce=(e,n,t)=>{const s=new Set(n.map(o=>o.name)),r=[];for(const o of Ae(e)){const a=Oe(o,t);if(a){for(const l of a.tables){if(s.has(l.name))throw f(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...a.vectorIndexes)}}return r},Je=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(j.CallExpression).find(h=>{const E=h.getExpression();return i.isIdentifier(E)&&E.getText()==="defineSchema"});if(!r)throw new _("INTERNAL",`defineSchema() not found in ${n}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw f(r,"defineSchema() expects an object literal");const a=De(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?P(l):[],u=Ce(r,a,t),A=[...a.flatMap(h=>h.vectorIndexes),...c,...u];return{jurisdiction:je(r),rlsMode:ze(r),tables:a,vectorIndexes:A}};export{Je as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as n}from"ts-morph";import{l as f,a as p,b as u}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as g}from"./discoverFunctions-
|
|
1
|
+
import{Node as n}from"ts-morph";import{l as f,a as p,b as u}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as g}from"./discoverFunctions-4eSpCR6m.mjs";const m=new Set(["delete","list","read","write"]),d=o=>{if(!n.isCallExpression(o))return!1;const e=o.getExpression();return n.isIdentifier(e)?e.getText()==="storageRules":n.isPropertyAccessExpression(e)&&e.getName()==="storageRules"},x=o=>{const e=[];let s=o;for(;n.isCallExpression(s);){const t=s.getExpression();if(!n.isPropertyAccessExpression(t))break;if(t.getName()==="use"){const r=s.getArguments()[0];r&&d(r)&&e.push(r)}s=t.getExpression()}return e},h=(o,e,s)=>{const t=o.getArguments()[0];if(!t||!n.isArrayLiteralExpression(t))return[];const r=[];for(const i of t.getElements()){if(!n.isObjectLiteralExpression(i))continue;const a=u(i,"on");if(a===void 0||!m.has(a))continue;const c=u(i,"prefix"),l={bucket:u(i,"bucket")??"",file:e,on:a,procedure:s};c!==void 0&&(l.prefix=c),r.push(l)}return r},E=o=>{const e=[];for(const s of o.getVariableStatements())if(s.isExported())for(const t of s.getDeclarations()){const r=t.getInitializer(),i=r&&n.isCallExpression(r)?g(r):void 0;i?.receiver&&e.push({name:t.getName(),receiver:i.receiver})}return e},R=(o,e)=>{const s=[];for(const t of f(e)){const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),i=p(e,t);for(const{name:a,receiver:c}of E(r))for(const l of x(c))s.push(...h(l,i,a))}return{rules:s}};export{R as default};
|