@lunora/codegen 1.0.0-alpha.406 → 1.0.0-alpha.408
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +24 -1
- package/dist/index.d.ts +24 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-DPxI0EHQ.mjs → ALL_NOTIFY_CHANNELS-D1LVGz6_.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CitMcXVT.mjs +54 -0
- package/dist/packem_shared/{SHAPES_FILENAME-CH0KrAdb.mjs → SHAPES_FILENAME-BYnZ1Xw-.mjs} +1 -1
- package/dist/packem_shared/chain-CONXUmWW.mjs +1 -0
- package/dist/packem_shared/{classify-procedure-call-BZ164dkJ.mjs → classify-procedure-call-n9urVsqb.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-Ggrmu3UL.mjs → context-property-calls-DXzNVV1P.mjs} +1 -1
- package/dist/packem_shared/{context-root-DnvrQxae.mjs → context-root-DP9WbBI_.mjs} +1 -1
- package/dist/packem_shared/{database-calls-BRI5W-Mp.mjs → database-calls-Do0YbPCL.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-CeHY4_ii.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-W96s1VgA.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-DmSa4WKU.mjs → discoverInserts-BtyJbg8A.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-BFm9rkZ7.mjs +1 -0
- package/dist/packem_shared/{discoverNondeterministicCalls-BoF6ob-B.mjs → discoverNondeterministicCalls-DR0S5Xb4.mjs} +1 -1
- package/dist/packem_shared/{discoverQueries-spxu-wHR.mjs → discoverQueries-BLyL2qzX.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-Cb4AmcY8.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-Cc0zA-gZ.mjs → discoverRlsMetadata-Cf4gZvxW.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-mjiA0I4S.mjs → discoverRlsProcedures-_Dh3Xb9Z.mjs} +1 -1
- package/dist/packem_shared/{discoverStorageRulesMetadata-CtE5trUR.mjs → discoverStorageRulesMetadata-ZKW6DInk.mjs} +1 -1
- package/dist/packem_shared/{emitApp-BsXqg0CQ.mjs → emitApp-pPxkJ2Z-.mjs} +74 -66
- package/dist/packem_shared/{emitServer-DsSAaZaT.mjs → emitServer-CbcZN_Ug.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-h8Y7xDjq.mjs → exported-procedure-chains-DomRzs5_.mjs} +1 -1
- package/dist/packem_shared/{index-jtzAVdUp.mjs → index-BH3e-J44.mjs} +1 -1
- package/dist/packem_shared/{index-mFEIaT45.mjs → index-D03C6Kao.mjs} +1 -1
- package/dist/packem_shared/{ip-reads-BPDWkzEu.mjs → ip-reads-ByzaRhd2.mjs} +1 -1
- package/dist/packem_shared/{server-CRFaUMKQ.mjs → server-5ph4hltf.mjs} +63 -55
- package/package.json +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DfLhJQrR.mjs +0 -54
- package/dist/packem_shared/chain-CXiqZFUk.mjs +0 -1
- package/dist/packem_shared/discoverFunctions-mAWlAiuj.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-CyjXtZgc.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs +0 -1
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import{existsSync as z,readFileSync as at,mkdirSync as ns,writeFileSync as Xr,rmSync as he,readdirSync as is}from"node:fs";import{dirname as ct,join as v,basename as Jr,relative as rs}from"node:path";import{performance as Ct}from"node:perf_hooks";import{runAdvisor as Zr}from"@lunora/advisor";import{LunoraError as F}from"@lunora/errors";import{serializeSchemaSnapshot as eo}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as to}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as os,ts as so,VariableDeclarationKind as as}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as P,descendantsOfKind as E,bindingKeyName as ve,collectCallRows as O,findObjectProperty as W,collectSecurityCallRows as no,propertyInitializer as _,listSecurityScanFiles as $e,objectLiteralFromCallbackBody as Qn,limitNameOf as Xn,optionsObjectLiteral as Jn,handlerOf as io,memberAccessOf as cs,chainRootOf as lt,unwrapExpression as h,collectNodeRows as oe,isConstDeclaration as ae,outermostValueWrapper as C,isWriteTarget as be,isSameNode as b,returningFunctionOf as Kt,walkChain as ro,RUN_METHODS as Zn,functionReferenceSegments as oo,isTestPath as ao,isFunctionLike as ge,functionKeyOf as ei,withSourceListMemo as co}from"./isTestPath-DRIdZaij.mjs";import{j as Z,h as Y,d as M,b as ls,c as A,a as ds,w as us,k as lo,l as uo,f as fo,m as go,g as Bt,i as po}from"./attribution-BhGR_h0Z.mjs";import{b as tn,r as Tt,a as H,e as mo,m as ti,c as dt,f as fs,E as si,C as ni,d as ho,g as vo,i as Eo}from"./context-root-DP9WbBI_.mjs";import{a as T,i as ii,c as ce,d as ri,e as oi,f as xo,g as So}from"./classify-procedure-call-n9urVsqb.mjs";import{a as S,s as gs}from"./property-name-7cBlgK_O.mjs";import{b as Ao,a as ai}from"./module-specifiers-BctA0m_p.mjs";import{r as ut,s as yo}from"./parse-validator-BisfC8bR.mjs";import bo from"./discoverAuthApiCalls-ENLGem4M.mjs";import{i as K,r as ci}from"./database-calls-Do0YbPCL.mjs";import{i as Vt,p as li,w as No,d as Po}from"./index-BH3e-J44.mjs";import wo from"./discoverHyperdriveCalls-W96s1VgA.mjs";import{PROJECT_CONFIG_FILENAMES as Io,findProjectConfigFile as di,findCodegenConfigFile as Co}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{contextPropertiesRead as To,createTargetScope as Oo,fileWiresRequestSecretTool as ko,discoverFeatureUsage as Ro}from"./capabilitiesUsedBy-BwhaHK08.mjs";import{diagnosticAt as Ne}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ps,a as et,s as ui,d as Fo}from"./index-D03C6Kao.mjs";import{MUTATORS_FILENAME as Lo,isDefineMutatorCallee as Do,mutatorServerImplOf as _o,discoverMutators as Mo}from"./MUTATORS_FILENAME-C3OImAxC.mjs";import $o from"./discoverNondeterministicCalls-DR0S5Xb4.mjs";import{discoverNotifyConfig as zo,discoverNotifyCalls as Ko}from"./ALL_NOTIFY_CHANNELS-D1LVGz6_.mjs";import Bo from"./discoverR2sqlCalls-Cb4AmcY8.mjs";import Vo from"./discoverRlsProcedures-_Dh3Xb9Z.mjs";import{s as ms,n as Uo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Wo,redact as qo,isHeuristicSecretKind as jo,isSecretishName as Ho}from"./redact-Cy14LEnc.mjs";import{r as fi,p as Go,c as Yo,a as Qo,e as Xo,d as Jo}from"./project-config-file-DR7xrrNB.mjs";import{a as qe,d as Zo,r as ea}from"./modules-Qpm_zqz4.mjs";import{WORKFLOWS_FILENAME as ta,discoverWorkflows as sa}from"./WORKFLOWS_FILENAME-DfVfBum_.mjs";import{r as na}from"./json-data-Chfs2Cz5.mjs";import{a as ia,I as ra,g as oa,G as gi,d as aa,i as ca}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as la}from"./createCodegenProject-Cfr1xHPC.mjs";import{findTsconfig as Vx,refreshCodegenProject as Ux,tsconfigFingerprint as Wx}from"./createCodegenProject-Cfr1xHPC.mjs";import{wranglerString as da,wranglerValue as ua,companionName as fa,COMPANION_FILES as ga}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as pa,usedCapabilities as ma}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as pi,isHyperdriveGlobalTable as mi}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as ha}from"./AGENTS_FILENAME-D0Y0_UgB.mjs";import{discoverContainers as va}from"./CONTAINERS_FILENAME-J-e3Vanb.mjs";import Ea from"./discoverCrons-DWVXmktw.mjs";import{discoverEnv as xa}from"./ENV_FILENAME-COPIfgzp.mjs";import hi from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Sa}from"./QUEUES_FILENAME-Ba-sK5Ek.mjs";import{discoverSandboxUsage as Aa}from"./discoverSandboxUsage-Ccy9n7G1.mjs";import{resolveServiceBindings as ya}from"./companionServiceBinding-BZjm486n.mjs";import ba from"./discoverStorageRulesMetadata-ZKW6DInk.mjs";import{resolveCodegenTarget as je,gatePlatformFeatures as Na,readTargetDiagnostics as Pa,vectorizeDimensionDiagnostics as wa,liveStreamsDeliveryAuthorizationDiagnostic as Ia,socketRoutesDeliveryAuthorizationDiagnostic as Ca,studioPlatformFor as Ta,platformFeatureAvailable as Oa,gateAdminTokenRevocation as ka}from"./DEFAULT_TARGET-CVYzxQ0y.mjs";import{i as Ra}from"./schema-BgM8A3XV.mjs";import{b as vi,e as Fa}from"./shard-Csztu3jG.mjs";import{e as La,a as Da}from"./server-5ph4hltf.mjs";import{emitDataModel as _a}from"./emitDataModel-BvCZS4Yq.mjs";import{i as Ma,b as $a,e as za,d as Ka,f as Ba,c as Va}from"./unwrap-handler-return-DUzluwPj.mjs";import Ua from"./discoverHttpRoutes-CAoEemno.mjs";import Wa from"./discoverInserts-BtyJbg8A.mjs";import{e as Ei}from"./exported-procedure-chains-DomRzs5_.mjs";import qa from"./discoverMigrations-Duh6HVG3.mjs";import sn from"./discoverQueries-BLyL2qzX.mjs";import ja from"./discoverRlsMetadata-Cf4gZvxW.mjs";import Ha from"./discoverSchema-ynieYB0n.mjs";import{discoverShapes as Ga}from"./SHAPES_FILENAME-BYnZ1Xw-.mjs";import{i as Ya}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as Qa,emitApp as Xa}from"./emitApp-pPxkJ2Z-.mjs";import{readJsonSync as Ja}from"@visulima/fs";import{indexReferencesOf as Za,buildSchemaSnapshot as ec}from"./SchemaSnapshotParseError-CV7mmuPi.mjs";import{buildOpenApiDocument as tc,emitOpenApiModule as sc}from"./buildOpenApiDocument-B8KEeeRr.mjs";import{buildOpenRpcDocument as nc,emitOpenRpcModule as ic}from"./OPENRPC_VERSION-UNYmA7Ty.mjs";import{w as rc,u as oc,v as ac,t as cc,x as lc}from"./shard-runtime-D0xuE0pX.mjs";import{emitCollections as dc,emitSeed as uc,emitApi as fc,emitInternalApi as gc}from"./emitApi-lwadq5G7.mjs";import{emitCrons as pc,emitScheduler as mc,emitAdminRevocations as hc,emitShardRegistry as vc,emitDurableObjects as Ec,emitVectors as xc,emitWranglerCronTriggers as Sc}from"./emitCrons-CCRKs482.mjs";import Ac from"./emitDrizzleSchema-BzOChEYW.mjs";import{LAZY_FUNCTION_DIRECTORY as xi,emitFunctions as yc,emitLazyFunctionModules as bc}from"./emitFunctions-ppMX7E3X.mjs";const Nc=(e,t=!1)=>{if(e.length===0)return"";const s=aa(t),n=e.map(c=>{if(ia(c.exportName,"live stream export name"),!ra.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{oa(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const x=u.fields.map(k=>`\${encodeURIComponent(key.${k})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
|
|
2
|
+
__lunoraLive: ${m},
|
|
3
|
+
topic: \`${u.name}:${x}\`,
|
|
4
|
+
}),`});return` ${c.exportName}: {
|
|
5
|
+
${l.join(`
|
|
6
|
+
`)}
|
|
7
|
+
},`}),a=e.some(c=>c.topics.some(l=>l.fields.length>0))?"LiveTopicKey, LiveTopicPayload, LiveTopicRef":"LiveTopicPayload, LiveTopicRef";return`${gi}import type { ${a} } from "${s.server}";
|
|
8
|
+
|
|
9
|
+
${n.join(`
|
|
10
|
+
`)}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A typed reference to each declared live topic, grouped by the stream's export name:
|
|
14
|
+
* \`live.posts.post({ postId })\`. Pass one to \`ctx.live.publish(ref, payload)\` on the server, or to a
|
|
15
|
+
* live-topic hook in the browser. A reference is plain data and carries no server code.
|
|
16
|
+
*/
|
|
17
|
+
export const live = {
|
|
18
|
+
${i.join(`
|
|
19
|
+
`)}
|
|
20
|
+
};
|
|
21
|
+
`},Si=new Set(["delete","get","head","options","patch","post","put"]),Pc=new Set(["handler","stream"]),wc=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,nn=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Ic=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Si.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Cc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||Si.has(n.getName()))break;s=n.getExpression()}return Ic(s)},Tc=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(nn.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&nn.has(s.getText()))return!0}return!1},Oc=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Pc.has(n.getName()))return;const i=Cc(s);if(!i||!wc.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&Tc(o);return{exportName:Y(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},kc=(e,t)=>{const s=[];for(const n of Z(e)){const i=Oc(n,t);i&&s.push(i)}return s},Rc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...kc(i,P(t,n)))}return s},Fc=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Lc=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?ve(t):void 0}},Dc=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&tn(a)}))return!1;const n=M(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&tn(i)},rn=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Fc(e);return n!==void 0&&Lc(n)===t?!0:t==="args"&&Dc(e)},Ai=(e,t)=>r.isIdentifier(e)?rn(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>rn(s,t)),_c=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},on=e=>{const t=r.isIdentifier(e)?M(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!ls(t)?t.getInitializer():void 0},Ut=e=>Ai(e,"args"),J=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of E(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},G=e=>{if(Ut(e))return!0;const t=J(e);return t!==void 0&&Ut(t)},Mc=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=J(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},Ee=e=>{if(Tt(e))return!0;const t=on(e);if(t!==void 0&&Tt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=on(i);return o!==void 0&&Tt(o)})},He=(e,t)=>Ai(e,t),$c=(e,t)=>{if(He(e,t))return!0;const s=J(e);if(s!==void 0&&He(s,t))return!0;const n=_c(e);if(n!==void 0){const i=J(n);return i!==void 0&&He(i,t)}return!1},zc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:H(e.getExpression(),["ai"]),Kc=(e,t)=>{if(!zc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)||Ee(s)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},Bc=(e,t)=>O(e,t,Kc),Vc=new Set(["generateText","streamText"]),Uc=new Set(["messages","prompt","system"]),Wc=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","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"]}],qc=(e,t)=>Wc.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),jc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[mo(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&qc(i,s));return n===void 0?void 0:`${n}.${s}`},Hc=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=jc(t);if(s!==void 0)return s}},Gc=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=ve(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Yc=e=>{if(Ut(e))return!0;const t=Gc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},Qc=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!Uc.has(S(t)))continue;const s=t.getInitializer();if(s!==void 0&&Yc(s))return!0}return!1},Xc=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=T(n.getExpression());if(i===void 0||!Vc.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(T(c.getExpression())==="tool"&&(a=Hc(c),a!==void 0))break;a!==void 0&&s.push({scope:A(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Qc(o)})}return s},Jc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xc(i,P(t,n)))}return s},Zc=e=>H(e,["fetch"]),el=(e,t)=>{if(!Zc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},tl=(e,t)=>O(e,t,el),hs=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=ut(s.getExpression());return n===void 0||hs(n,t)})}finally{t.delete(e)}},sl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=W(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:ut(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:hs(i)}},nl=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?ut(o):void 0;a===void 0?s=!0:(t.push(a),s||=hs(a))}n=i.getExpression()}return{objects:t,opaque:s}},vs=(e,t)=>t?nl(t):sl(e),yi=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=ut(s.getExpression());return n===void 0?[]:yi(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[S(s)]:[]})}finally{t.delete(e)}},il=e=>e.flatMap(t=>yi(t,new Set)),rl=new Set(["check","length","max"]),Wt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(rl.has(s.getName()))return!0;t=n}},qt=e=>Ao(e)||e==="@lunora/values",ol=e=>{const t=new Set(["v"]);for(const s of ii(e,"v",qt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&qt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},al=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},cl=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),ll=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&qt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Es=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return cl(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&ll(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},dl=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},ul=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},fl=e=>r.isReturnStatement(e)?e.getExpression():void 0,gl=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ul(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=fl(t);return s?[s]:[]}),bi=(e,t)=>{if(Es(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return bi(e.getExpression(),t)},pl=(e,t)=>{const s=dl(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Wt(e),i=new Set(gl(s).map(o=>bi(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Es(o,t);return a===void 0?[]:[{bounded:Wt(o)||n&&i.has(o),factory:a}]})},ml=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Es(s,t),i=n===void 0?[]:[{bounded:Wt(s),factory:n}];return r.isCallExpression(s)?[...i,...pl(s,t)]:i}),hl=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=ml(a,t),l=S(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},vl=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ce(n);if(i?.visibility!=="public")return;const{objects:o}=vs(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=hl(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:Y(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},El=(e,t)=>{const s=[],n=ol(e),i={destructured:al(e,n),namespaces:n};for(const o of Z(e)){const a=vl(o,t,i);a&&s.push(a)}return s},xl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...El(i,P(t,n)))}return s},Ot=e=>e?.getKind()===d.TrueKeyword,Sl=e=>e?.getKind()===d.FalseKeyword,Al=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,yl=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),bl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&T(t.getExpression())==="scim"),Nl=e=>e!==void 0&&r.isCallExpression(e)&&yl.has(T(e.getExpression())??""),Pl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),wl=e=>{const t=_(e,"advanced"),s=_(e,"emailAndPassword"),n=_(e,"session");return{analyzable:!0,disableCsrfCheck:Ot(_(t,"disableCSRFCheck")),emailPasswordEnabled:Ot(_(s,"enabled")),requireEmailVerification:Ot(_(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:bl(_(e,"plugins"))&&Nl(_(e,"database")),secureCookiesDisabled:Sl(_(t,"useSecureCookies")),sessionFreshAgeZero:Al(_(n,"freshAge")),trustedOriginsWildcard:Pl(_(e,"trustedOrigins"))}},Il=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Cl=(e,t)=>{if(T(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?wl(s):Il();return{scope:A(e),file:t,line:e.getStartLineNumber(),...i}},Tl=(e,t)=>no(e,t,Cl),Ol=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return ti(e.getExpression(),t.matchReceiver)?s:void 0},kl=(e,t,s)=>{const n=Ol(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!G(i)||Ee(i))&&!(s.requireUnmodifiedReach===!0&&!Mc(i)))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:n}},ft=(e,t,s)=>O(e,t,(n,i)=>kl(n,i,s)),Rl=new Set(["content","pdf","scrape","screenshot"]),Fl=(e,t)=>ft(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Rl}),Ll=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Dl=new Set(["RateLimiter"]),_l=new Set(["extend"]),an="lunora",Ml=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Ni=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=S(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},jt=e=>e&&r.isObjectLiteralExpression(e)?Ni(e):{analyzable:!1,presentKeys:[],trueKeys:[]},$l=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Qn(t.getBody());return s?Ni(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},zl=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=T(n.getExpression());i!==void 0&&(Ll.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...jt(n.getArguments()[0])}):_l.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...$l(n.getArguments()[0])}))}for(const n of E(e,d.NewExpression)){const i=T(n.getExpression());i===void 0||!Dl.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...jt(n.getArguments()[0])})}return s},Kl=e=>{for(const t of Ml){const s=v(e,t);if(!z(s))continue;const n=new os({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,at(s,"utf8")),i=[];for(const o of E(n,d.CallExpression))T(o.getExpression())===an&&i.push({callee:an,file:t,line:o.getStartLineNumber(),...jt(o.getArguments()[0])});return i}return[]},Bl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of $e(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...zl(o,n))}return s.push(...Kl(ct(t))),s},cn="ctx.containers.",Vl=e=>{if(!e.startsWith(cn))return!1;const t=e.slice(cn.length);return t.length>0&&!t.includes(".")},Ul=(e,t)=>ft(e,t,{argIndex:0,matchReceiver:Vl,methods:new Set(["get"])}),Wl=new Set(["allow","deny","setAllowed"]),ql=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=W(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},jl=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!ql(e)))return{detail:"enableInternet: true",scope:A(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Hl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Wl.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:A(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Gl=(e,t)=>jl(e,t)??Hl(e,t),Yl=(e,t)=>O(e,t,Gl),Ql=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&K(s.getExpression())?s.getName():void 0},Xl=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&K(s)?1:0]},Jl=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Zl=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>Jl.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},ed=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return O(e,t,(i,o)=>{const a=Ql(i);if(a===void 0)return;const c=Zl(Xl(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:A(i),table:a}})},td=new Set(["defineExportSink","r2Sink","webhookExportSink"]),sd=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return td.has(s)?s:void 0},nd=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=S(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(S(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},id=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of $e(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of E(o,d.CallExpression)){const c=sd(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?nd(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},rd=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),od=new Set(["dbRateLimit","rateLimit"]),ad=e=>{const t=Jn(e);if(!t)return!1;const s=W(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},cd=(e,t)=>{const s=T(e.getExpression());if(s===void 0)return;const n=rd.get(s);if(n!==void 0)return{callee:s,scope:A(e),failOpen:ad(e.getArguments()[n]),file:t,limitName:od.has(s)?Xn(e):"",line:e.getStartLineNumber()}},ld=(e,t)=>O(e,t,cd),dd=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ce(t);if(s?.kind!=="query")return;const n=io(t,s.receiver);return n?{exportName:Y(e)??e.getName(),handler:n}:void 0},ln=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},ud=e=>{const t=ln(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=ln(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},fd=(e,t)=>{const s=[];for(const n of dt(e.handler,"flags"))s.push({callee:ud(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},gd=(e,t)=>{const s=[];for(const n of Z(e)){const i=dd(n);i&&s.push(...fd(i,t))}return s},pd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...gd(i,P(t,n)))}return s},md=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:H(e.getExpression(),["flags"]),hd=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},vd=(e,t)=>{if(!md(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=hd(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:A(e),file:t,key:i,line:e.getStartLineNumber()}},Ed=(e,t)=>O(e,t,vd),xd=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Sd=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Ad=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of E(i,d.CallExpression))xd(a)&&s.push({file:o,indexName:Sd(a),line:a.getStartLineNumber()})}return s},yd=new Set(["delete","get","head","options","patch","post","put"]),bd=new Set(["handler","stream"]),Nd=new Set(["runAction","runMutation"]),Pd=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Le=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Pi=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(ve(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},dn=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Pi(s,"ctx")},un=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Pi(s,"request")},fn=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Nd.has(a)&&Le(c,t))return a;if(Pd.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Le(c.getExpression(),t))return`db.${a}`}},gn=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Le(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Le(n.getInitializer(),t))){for(const o of i.getElements())if(ve(o)==="auth")return!0}}return!1},wd=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Id=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Le(n.getExpression(),t)},Cd=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],wi=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Cd(s)},Td=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?wi(t,a.getText()):[]}return[]},Od=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=wi(s,t.getText());return n.length>0?n:Td(t,s)},pn=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>Id(i,t)&&Od(i).some(o=>wd.test(o)))},kd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!bd.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(yd.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Rd=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Vt(e.getArguments()[0]),l=c&&dn(c,!0);if(!c||l===void 0||pn(c,un(c,!0)))return;const u=fn(c,l);return u===void 0?void 0:{scope:A(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:gn(c,l),sideEffect:u}}const n=kd(e);if(n===void 0)return;const i=Vt(e.getArguments()[0]),o=i&&dn(i,!1);if(!i||o===void 0||pn(i,un(i,!1)))return;const a=fn(i,o);return a===void 0?void 0:{scope:A(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:gn(i,o),sideEffect:a}},Fd=(e,t)=>O(e,t,Rd),Ld=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Dd=new Set(["append","set"]),Ii=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",mn=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Ld.has(T(n.getExpression())??"")&&He(n,t)),_d=(e,t)=>{if(mn(e,t))return!0;const s=J(e);return s!==void 0&&mn(s,t)},Ht=(e,t)=>$c(e,t)&&!_d(e,t),Md=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=J(e);return t!==void 0&&r.isNewExpression(t)&&T(t.getExpression())==="Headers"},tt=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=J(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},xs=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Ht(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Ii(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Ht(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:S(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=tt(n.getExpression());i!==void 0&&xs(i,t,s)}},Ci=(e,t)=>{const s=tt(e);if(s===void 0)return;const n=W(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=tt(n.getInitializer());i!==void 0&&xs(i,"response-init",t)},$d=(e,t)=>{const s=T(e.getExpression());if(s==="Response")Ci(e.getArguments()[1],t);else if(s==="Headers"){const n=tt(e.getArguments()[0]);n!==void 0&&xs(n,"headers-ctor",t)}},zd=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){Ci(e.getArguments()[1],t);return}if(Dd.has(n)&&Md(i)){const o=e.getArguments()[1];o!==void 0&&Ht(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Ii(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Kd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))$d(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))zd(s,t)},Bd=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Vt(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return Kd(n,{scope:A(e),relativePath:t,requestName:o.getText(),rows:a}),a},Vd=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression))s.push(...Bd(n,t));return s},Ud=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Vd(i,P(t,n)))}return s},Wd=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token","tokenHash"]),qd=new Set(["__proto__","email","exp","expiresAtMs","iat","name","nbf","orgId","role","roles","sub","teamId","userId"]),kt=32,jd=/^[A-Z_]\w{0,63}$/i,Hd={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},Gd=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Yd=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},Qd=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(S(s));if(!r.isPropertyAssignment(s)||!t.has(S(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Xd=new Set(["durable"]),Jd=new Set(["rollback"]),Ti=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Zd="defineApp",Oe="app",hn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>S(s)===Oe&&s.getInitializer()?.getText()===t)||t===Oe&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>S(s)===Oe),eu=e=>{if(e===void 0||!Io.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&S(e)===Oe;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return S(t)===Oe;if(r.isVariableDeclaration(t))return hn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&hn(e.getSourceFile(),s)},tu="AppBuilder",Oi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},ki=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===tu&&s.getDeclarations().some(n=>Oi(n))},su=e=>e.getText()===Zd&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Oi(t)),Ss=(e,t,s=new Set)=>{const n=lt(t);if(n===void 0||!r.isIdentifier(n))return!1;if(su(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return eu(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Ss(e,a.getInitializer(),s)}}return!1},Ri=(e,t)=>{const s=cs(t.getExpression());return s?.member==="deliveryAuthorization"&&(Ss(e,s.object)||ki(s.object))},nu=new Map([["defineContainer",{keys:Gd,signal:"containerEgressPolicy"}],["defineStep",{keys:Jd,signal:"workflowRollback"}],["stream",{keys:Xd,signal:"durableStreams"}]]),iu=(e,t)=>{const s=nu.get(Ti(t));if(s!==void 0)return t.getArguments().some(n=>Qd(Yd(e,n),s.keys))?s.signal:void 0},ru=(e,t)=>Hd[Ti(t)]??(Ri(e,t)?"deliveryAuthorization":void 0),ou=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=To(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=E(o,d.CallExpression);for(const c of a){const l=iu(o,c)??ru(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>ri(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new os({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,at(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Ri(i,o))}return n},De={claims:[],diagnostics:[]},re=e=>({claims:[],diagnostics:[e]}),gt=e=>r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)?gt(e.getExpression()):e,Fi=e=>{if(r.isSpreadAssignment(e))return!0;const t=e.getNameNode();return r.isComputedPropertyName(t)&&gs(t)===void 0},Ae=e=>e.getProperties().some(t=>Fi(t)),Li=(e,t)=>e.getProperties().findLast(s=>!r.isSpreadAssignment(s)&&S(s)===t),Di=(e,t)=>{const s=Li(e,t);return r.isPropertyAssignment(s)?s.getInitializer():void 0},_i=(e,t)=>{const s=Di(e,t);return s!==void 0&>(s).getKind()===d.FalseKeyword},_e="unreadable",As=(e,t)=>{const s=Li(e,t);if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer()??_e:r.isShorthandPropertyAssignment(s)?s.getNameNode():_e},vn=e=>{if(e===void 0||!r.isBlock(e))return e;const t=e.getStatements().filter(s=>r.isReturnStatement(s));return t.length===1?t[0]?.getExpression():void 0},fe=(e,t=0)=>{if(t>4)return;const s=gt(e);if(r.isObjectLiteralExpression(s))return s;if(r.isArrowFunction(s)||r.isFunctionExpression(s)){const c=vn(s.getBody());return c===void 0?void 0:fe(c,t+1)}if(!r.isIdentifier(s))return;const n=s.getParent(),i=r.isShorthandPropertyAssignment(n)?n.getValueSymbol():s.getSymbol(),o=i?.isAlias()?i.getAliasedSymbol():i,[a]=o?.getDeclarations()??[];if(r.isVariableDeclaration(a)){const c=a.getInitializer();return c===void 0?void 0:fe(c,t+1)}if(r.isFunctionDeclaration(a)){const c=vn(a.getBody());return c===void 0?void 0:fe(c,t+1)}},au=e=>{if(e===void 0)return;const t=gt(e);if(r.isArrayLiteralExpression(t))return"string";if(!(!r.isStringLiteral(t)&&!r.isNoSubstitutionTemplateLiteral(t)))switch(t.getLiteralValue()){case"boolean":return"boolean";case"date":case"string":return"string";case"number":return"number";default:return}},cu=e=>_i(e,"returned"),lu=(e,t)=>{if(!jd.test(e))return{reason:`\`${e}\` is not an identifier of at most 64 characters`};if(qd.has(e)||Wd.has(e))return{reason:`\`${e}\` is reserved or secret-bearing, so the session never forwards it`};const s=fe(t);if(s===void 0||Ae(s))return{reason:`\`${e}\` is not a literal field definition`};const n=au(Di(s,"type"));return n===void 0?{reason:`\`${e}\` is not a scalar (string, number, boolean or date) column`}:{claim:{name:e,type:n,writable:!_i(s,"input")}}},du=e=>{if(r.isSpreadAssignment(e))return;if(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e))return{reason:`\`${e.getName()}\` is a method or accessor, not a field definition`};const t=r.isPropertyAssignment(e)?S(e):e.getName(),s=r.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),n=s===void 0?void 0:fe(s);if(!(n!==void 0&&!Ae(n)&&cu(n)))return s===void 0?{reason:`\`${t}\` has no initializer`}:lu(t,s)},uu=e=>{const t=[],s=[];for(const n of e.getProperties()){const i=du(n);i?.claim!==void 0?t.push(i.claim):i!==void 0&&s.push(`${i.reason??"the entry cannot be a claim"}; it is not added to ctx.auth`)}return t.length>kt&&s.push(`${t.length.toString()} claims declared; the first ${kt.toString()} are forwarded, the rest are not`),{claims:t.slice(0,kt),diagnostics:s}},fu=e=>{if(Ae(e))return re("`user` has a spread or a computed key, so the user columns cannot be read");const t=As(e,"additionalFields");if(t===void 0)return De;const s=t===_e?void 0:fe(t);return s===void 0||Ae(s)?re("`user.additionalFields` is not an object literal, so the user columns cannot be read"):uu(s)},gu=e=>{if(Ae(e))return re("the auth options contain a spread or a computed key, so the user columns cannot be read");const t=As(e,"user");if(t===void 0)return De;const s=t===_e?void 0:fe(t);return s===void 0?re("`user` is not an object literal, so the user columns cannot be read"):fu(s)},pu=(e,t)=>{const s=t.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="auth")return!1;const n=s.getExpression();return Ss(e,n)||ki(n)},mu=e=>{const t=e.getProperties(),s=t.findLastIndex(n=>!r.isSpreadAssignment(n)&&S(n)==="options");return t.some((n,i)=>i>s&&Fi(n))},hu=e=>{const[t]=e.getArguments();if(t===void 0)return De;if(!r.isObjectLiteralExpression(t))return re(".auth() is not called with an object literal, so its user columns cannot be read");const s=As(t,"options");if(s===void 0)return Ae(t)?re("the .auth() argument has a spread or a computed key, so its options cannot be read"):De;if(mu(t))return re("a spread or computed key after `options` in .auth() may replace it, so the user columns cannot be read");const n=s===_e?void 0:fe(s);return n===void 0?re("`.auth({ options })` does not resolve to an object literal, so the user columns cannot be read"):gu(n)},Mi=(e,t)=>{const s=[];for(const{filePath:o}of $e(t)){const a=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...E(a,d.CallExpression).filter(c=>pu(a,c)))}const[n,...i]=s;return n===void 0?De:i.length===0?hu(n):re(`the app builder's .auth() is called ${s.length.toString()} times, so which declaration applies cannot be read`)},$i="identity.ts",vu=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return ai(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Eu=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&ai(n.getModuleSpecifierValue())}return!1},xu=e=>{if(r.isIdentifier(e))return vu(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Eu(t)}return!1},Su=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!xu(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Ne(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=ds(s,"member");a!==void 0&&t.push({exportName:a})}return t},Au=(e,t)=>{const s=v(t,$i);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Su(n);if(i.length!==0){if(i.length>1)throw Ne(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},zi=new Set(["auth","context.auth"]),yu="userId",bu=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(S(s))}return t},Nu=(e,t)=>{const s=v(t,$i);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(T(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?bu(o):void 0}},Pu=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return zi.has(t.getText())||H(t,["auth"])?e:void 0},Gt=(e,t=!1)=>r.isAwaitExpression(e)?Gt(e.getExpression(),!0):r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isTypeAssertion(e)||r.isNonNullExpression(e)?Gt(e.getExpression(),t):{awaited:t,value:e},Ki=e=>{if(e===void 0)return;const{awaited:t,value:s}=Gt(e);if(!t||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||n.getName()!=="getIdentity")return;const i=n.getExpression();return zi.has(i.getText())||H(i,["auth"])?s:void 0},Bi=e=>{if(r.isPropertyAccessExpression(e))return e.getName();const t=h(e.getArgumentExpression());return r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0},wu=e=>{if(!r.isPropertyAccessExpression(e)&&!r.isElementAccessExpression(e)||be(e))return;const t=e.getExpression();return Pu(t)!==void 0||Ki(t)!==void 0?Bi(e):void 0},Yt=(e,t,s,n)=>({declared:t===yu||n.has(t),file:s,key:t,line:e.getStartLineNumber(),scope:A(e)}),En=(e,t,s)=>{const n=wu(e);return n===void 0?void 0:Yt(e,n,t,s)},Iu=(e,t,s)=>{if(Ki(e.getInitializer())===void 0)return[];const n=e.getNameNode();return r.isObjectBindingPattern(n)?n.getElements().filter(i=>i.getDotDotDotToken()===void 0).flatMap(i=>{const o=gs(i.getPropertyNameNode()??i.getNameNode());return o===void 0?[]:[Yt(i,o,t,s)]}):!r.isIdentifier(n)||!ae(e)?[]:n.findReferencesAsNodes().filter(i=>i!==n).flatMap(i=>{const o=C(i),a=o.getParent();if(!r.isPropertyAccessExpression(a)&&!r.isElementAccessExpression(a)||be(a))return[];const c=a.getExpression()===o?Bi(a):void 0;return c===void 0?[]:[Yt(a,c,t,s)]})},Cu=(e,t)=>{const s=Nu(e,t);if(s===void 0)return[];const n=Mi(e,t).claims.filter(o=>!o.writable).map(o=>o.name),i=new Set([...s,...n]);return[...oe(e,t,d.PropertyAccessExpression,(o,a)=>En(o,a,i)),...oe(e,t,d.ElementAccessExpression,(o,a)=>En(o,a,i)),...oe(e,t,d.VariableDeclaration,(o,a)=>Iu(o,a,i))]},Tu=(e,t)=>{if(T(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=_(s,"key");if(!(!n||!G(n)||Ee(n)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},Ou=(e,t)=>O(e,t,Tu),ku=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ru=(e,t,s=[])=>{const n=ft(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ku});return us(n,s)},Fu=new Set(["queue","send"]),xn=new Set(["bcc","cc","to"]),Lu=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Fu.has(t))return;const s=e.getExpression();return H(s,["mail"])||H(s,["email"])?t:void 0},Du=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return xn.has(S(t))&&G(n)&&!Ee(n)}if(!r.isPropertyAssignment(t)||!xn.has(S(t)))return!1;const s=t.getInitializer();return s!==void 0&&G(s)&&!Ee(s)}):!1,_u=(e,t)=>{const s=Lu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Du(n)))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s}},Mu=(e,t)=>O(e,t,_u),$u=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=et(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=et(l);if(u===void 0)continue;const f=ui(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},zu=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ce(s):void 0;return n?.receiver?ps(n.receiver).flatMap(i=>$u(i,Y(e)??e.getName(),t)):[]},Ku=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...zu(a,o))}return s},Bu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return K(s)},Vu=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=W(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Uu=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Do(s.getExpression())?s:void 0},Wu=e=>{const t=Uu(e),s=t===void 0?void 0:Vu(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?Y(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Bu(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},qu=e=>e.getVariableDeclarations().flatMap(t=>Wu(t)),ju=(e,t)=>{const s=v(t,Lo);if(!z(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return qu(n)},Hu=new Set(["delete","get","patch"]),Gu=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Yu=new Set(["auth","identity","session","user"]),Qu=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Xu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!K(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Ju=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},Zu=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),ef=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,tf=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Zu(s.getExpression(),t)&&ef(s.getThenStatement())),sf=(e,t)=>{for(const s of E(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Hu.has(i))continue;const o=n.getExpression(),a=K(o);if(!(a||r.isPropertyAccessExpression(o)&&K(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},nf=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>fs(lt(s))!==void 0)),rf=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Qu.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),of=e=>{for(const t of E(e,d.Identifier))if(Gu.has(t.getText()))return!0;return[...Yu].some(t=>dt(e,t).length>0)?!0:nf(e)||rf(e)},af=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ce(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=li(s);if(i===void 0)return[];const o=n.receiver!==void 0&&oi(n.receiver,"use","rls"),a=of(i),c=new Set,l=[];for(const u of E(i,d.CallExpression)){const f=Xu(u);if(f===void 0)continue;const g=Ju(u);if(g===void 0||c.has(g)||!tf(i,g))continue;const m=sf(i,g);m!==void 0&&(c.add(g),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},cf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...af(a,o))}return s},Vi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?M(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},lf=e=>{const t=C(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!be(s)},df=e=>{const t=C(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},uf=e=>{const s=C(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!be(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},st=e=>{const t=M(e);return t===void 0||uo(t.getSourceFile())},Qt=(e,t)=>{const s=C(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&st(o);if(Vi(lt(o),t))return!(r.isPropertyAccessExpression(o)&&si.has(o.getName()))||r.isExpressionStatement(C(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!st(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},Ge={kind:"opaque"},ff={kind:"unreached"},gf=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Xt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?M(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=gf(s);return i===void 0||ls(i)?void 0:i}const n=ae(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Ui=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?Ge:c===void 0?a.some(l=>l.isRestParameter())?Ge:ff:c.isRestParameter()?Ge:{kind:"parameter",parameter:c}},pf=e=>{const t=C(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Xt(s.getExpression());return n===void 0?Ge:Ui(n,s,t)},mf=new Set(["__defineGetter__","__defineSetter__","__proto__"]),hf=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Wi=e=>{const t=C(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=hf(s);if(n!==void 0)return b(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},vf=4,qi=(e,t,s=0)=>{if(lo(e))return!0;if(lf(e)){const i=C(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!mf.has(c)}if(df(e)||uf(e)||Wi(e)||Qt(e,t))return!0;const n=pf(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Ef(n.parameter,s+1)},Sn=new WeakMap,Ef=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Sn.get(e.compilerNode);if(n!==void 0)return n;if(t>vf)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||M(a)?.compilerNode!==e.compilerNode||qi(a,void 0,t));return(o||t===0)&&Sn.set(e.compilerNode,o),o},An=new WeakMap,xf=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=M(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Sf=(e,t,s)=>{const{context:n,impl:i}=e,o=An.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const m=g.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?qi(g,n):!be(g),f=!xf(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const m=g.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(g)||M(g)?.compilerNode!==x?!0:u(g)});return An.set(i.compilerNode,f),f},yn=new WeakMap,Af=e=>{let t=yn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=_o(s);return n===void 0?[]:[[n.compilerNode,s]]})),yn.set(e.compilerNode,t)),t},yf=e=>{const t=Af(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:Y(n)??n.getName()};return a!==void 0&&Sf(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},Rt="args",ke=e=>{const t=cs(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===Rt?t.member:void 0}if(!r.isIdentifier(e))return;const s=M(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=ae(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&ve(i)===Rt||r.isIdentifier(o)&&o.getText()===Rt?ve(s):void 0},bf=new Set(["auth","identity","user"]),Jt=e=>{const t=i=>{const o=fs(i);return o!==void 0&&o.length>0&&bf.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=J(s);return n!==void 0&&t(n)},ji=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=ke(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?J(n):void 0;if(o!==void 0)for(const a of ji(o,t-1))s.add(a)}return s},Ye=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Ye(n),...Ye(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=ke(h(u)??u);return g===void 0?[]:Ye(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=ke(h(n)??n),c=ke(h(i)??i);return a!==void 0&&Jt(i)&&o.push(a),c!==void 0&&Jt(n)&&o.push(c),o},Nf=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&xo(i.getExpression(),"defineIdentityGuard")},Pf=e=>{if(!Nf(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=ke(h(s)??s),o=t.some((a,c)=>c!==n&&Jt(a));return i!==void 0&&o?[i]:[]})},wf=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},If=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),bn=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},Cf=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Tf=(e,t)=>{const s=new Set;for(const n of E(e,d.IfStatement))if(n.getEnd()<=t&&bn(n,e)&&wf(n.getThenStatement()))for(const i of Ye(n.getExpression()))s.add(i);for(const n of E(e,d.CallExpression))if(n.getEnd()<=t&&Cf(n)&&bn(n,e))for(const i of Pf(n))s.add(i);return s},Of=(e,t)=>{const s=ji(t);if(s.size===0)return!1;const n=e.getFirstAncestor(If);if(n===void 0)return!1;const i=Tf(n,e.getStart());return[...s].every(o=>i.has(o))},kf=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Rf=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Zt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Hi=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Ff=e=>{const t=C(e),s=t.getParent();if(r.isVariableDeclaration(s))return b(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Lf=e=>{const t=Ff(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ae(t)?[t]:void 0:Hi(t)},Re=e=>e.isUnion()?e.getUnionTypes().every(t=>Re(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Re(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),nt=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Qe=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Df=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&Rf.get(s.getText())?.has(t.getName())===!0&&st(s)},_f=e=>{const t=Kt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=C(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&nt(n,ni)?n:void 0},Mf=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=C(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:nt(n,kf,t)?n:void 0},$f=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},zf=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&b(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},Nn=e=>{const t=C(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Df(s);return Mf(s,t)??$f(s,t)??zf(s,t)??(n?s:_f(t))},Kf=5e4,Gi=()=>({inProgress:new Set,verdicts:new Map});class Bf{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Kf&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Vf=8,Uf=8;class Wf{budget;scope;taint;verdicts=Gi();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Re(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Hi(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Vf?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(C(l),!0,a,0))&&(t===n||!Re(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=Nn(o);m!==void 0;m=Nn(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=C(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Re(o.getType());if(be(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Lf(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=C(t).getParent();if(n>=Uf)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===C(t)?this.valueCompromises(i,!1,s,n+1):!nt(i,Zt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ae(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=C(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Qe(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=nt(t,Zt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Xt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!Qt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(Qt(s,this.scope.context))return!1;const i=Xt(t.getExpression()),o=i===void 0?void 0:Ui(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||Wi(t)||b(Kt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Kt(t);return b(s,this.scope.impl)?void 0:s}}const qf=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),jf=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=M(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Hf=new Set(["all","allSettled","any","race"]),Pn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,Ft=8;class Gf{budget=new Bf;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Gi();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Wf(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,Ft)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>fo(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=M(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=C(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Zt.has(g.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&ae(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const m=C(g),x=m.getParent();return!r.isCallExpression(x)||x.getExpression()!==m||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&st(i)&&Hf.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Qe(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=M(t),i=Pn(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&si.has(i)?!1:i!==void 0&&ni.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Qe(a)!==void 0)&&(i===void 0||!qf.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=lt(i),c=r.isIdentifier(a)?Pn(M(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Qe(i);if(o===void 0)return!jf(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=ro(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Vi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?M(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=ae(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=ls(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,Ft))return!1;if(this.variableDepth>=Ft)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const wn=new WeakMap,Yf=e=>{const t=wn.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Gf(e);return wn.set(e.impl.compilerNode,s),s},Qf=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Xf=new Set(["insert","insertManyUnsafe","patch","replace"]),Jf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Xf.has(t)&&ho(e.getExpression())?t:void 0},Zf=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},eg=(e,t)=>{const s=cs(e);return s?.member===t?h(s.object):void 0},In=(e,t)=>r.isIdentifier(e)&&M(e)?.compilerNode===t.compilerNode,Yi=(e,t,s,n=1)=>{const i=eg(e,s);if(i!==void 0)return In(i,t);const o=r.isIdentifier(e)?M(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&ve(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ae(l)&&In(h(l.getInitializer()),t))}const a=ae(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Yi(a,t,s,n-1)},es=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...es(t.getWhenTrue()),...es(t.getWhenFalse())]:[t]},tg=(e,t,s)=>{const n=[],i=s===void 0?void 0:Yf(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=S(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=S(o),c=o.getNameNode()),a===void 0||c===void 0||!Qf.has(a))continue;const l=es(c).filter(f=>i===void 0?G(f)&&!vo(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&Yi(c,s.parameter,a),g=l.every(m=>Of(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},sg=(e,t,s)=>{const n=Jf(e.getExpression()),i=n==="patch"||n==="replace"?2:1,o=n===void 0?void 0:e.getArguments()[i];if(n===void 0||o===void 0)return[];const a=Zf(o,n);if(a.length===0)return[];const c=A(e),l=yf(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>tg(f,u,l))},ng=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=O(e,t,(c,l)=>sg(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return us(o,s).map(c=>go(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},ig=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),rg=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,og=e=>{const t=W(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?rg(t.getInitializer()):void 0},ag=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!ig.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?og(n):void 0;return{callee:s,scope:A(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},cg=(e,t)=>O(e,t,ag),lg=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),dg=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},ug=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=W(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Qi=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Xi=(e,t)=>e===t||e.startsWith(`${t}.`),Ji=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},Cn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},Zi=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Cn(s));return r.isIdentifier(e)&&Cn(e)&&t.push(e),t},fg=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},gg=e=>{const t=Qi(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},pg=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:gg(e),i=new Set,o=a=>Ji(a).some(c=>n.some(l=>Xi(c.getText(),l)))?!0:Zi(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of fg(a))i.add(l)}return{names:i,prefixes:n}},mg=(e,t)=>Ji(e).some(s=>t.prefixes.some(n=>Xi(s.getText(),n)))?!0:Zi(e).some(s=>t.names.has(s.getText())),hg=e=>{const t=oo(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},vg=(e,t,s)=>{const n=Qi(e,0);if(n===void 0)return[];const i=pg(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!Zn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!mg(u,i))continue;const f=hg(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:A(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Eg=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=dg(n),o=i===void 0?void 0:lg.get(i);if(o===void 0)continue;const a=ug(n,o);a!==void 0&&s.push(...vg(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},xg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Eg(i,P(t,n)))}return s},Tn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},On=new Set(["account","credential","member","passkey","session","user"]),Sg=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Ag=e=>{const s=Sg(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return On.has(s)||On.has(n)},yg=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},bg=(e,t)=>{const{objects:s,opaque:n}=vs(e,t);return il(s).some(i=>yg(i))?!0:n?void 0:!1},Ng=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!W(t,"captcha"),usesRateLimit:!!W(t,"rateLimit")}},Pg=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Xe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},wg=e=>{const t=Pg(e),s=t?T(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Ng(t);return{...Xe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Tn?{...Xe,[Tn[s]]:!0}:Xe},Ig=e=>{const t={...Xe};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=wg(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Cg=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Tg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Cg.has(t.getName()))return!1;const s=t.getExpression();if(!K(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:Ag(i.getLiteralText())},Og=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),kn=new Set(["queues","scheduler","topics","workflows"]),kg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Og.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&kn.has(s.getName())&&Eo(s.getExpression()))return!0;s=s.getExpression()}const n=fs(s);return n?.length===1&&kn.has(n[0]??"")},Rg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return K(s)},er=new Set(["generateObject","generateText","streamObject","streamText"]),Fg=e=>{const t=T(e.getExpression());return t!==void 0&&er.has(t)},Lg=e=>{const t=T(e.getExpression());if(t===void 0||!er.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!W(s,"maxOutputTokens")},Dg=new Set(["log","span","trace"]),_g=new Set(["ai"]),Mg=new Set(["email","mail"]),$g=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Lt=(e,t)=>[...t].some(s=>dt(e,s).length>0),tr=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),zg=new Set(["every","filter","flatMap","forEach","map","some"]),Kg=new Set(["all","allSettled","race"]),sr=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(zg.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Kg.has(n))return t},Bg=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(tr.has(t.getKind())){const s=sr(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Vg=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(tr.has(t.getKind())){if(t=sr(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Ug=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const x=m.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Wg=e=>{let t=e;for(;;){const s=t.getParent();if(!r.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(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},qg=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},jg=e=>{let t=!1,s=!0;for(const n of[...$g].flatMap(i=>dt(e,i))){const i=qg(n);i&&(t=!0,!Bg(i)&&!Wg(i)&&!Ug(i)&&!Vg(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Hg=e=>E(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),Rn="lunora-advisor-exempt",Gg=/^[\s*/]+/u,Yg=/[\w-]/u,Qg=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
22
|
+
`);for(const n of s.split(`
|
|
23
|
+
`)){const i=n.replace(Gg,"");if(!i.startsWith(Rn))continue;const o=i.slice(Rn.length);if(Yg.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Xg=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=W(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Jg=(e,t)=>{const s=Xg(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},Zg=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of E(e,d.CallExpression))if(Tg(l)&&(o=!0),kg(l)&&(t=!0),Rg(l)&&(i=!0),Fg(l)&&(s=!0),Lg(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=jg(e);return{callsMail:Lt(e,Mg),emitsEvent:Lt(e,Dg),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Lt(e,_g),throwsBareError:Hg(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},ep=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ce(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Ig(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Jg(e,s);return{...o?Zg(o):{},...Qg(e),...i,analyzableBody:o!==void 0,exportName:Y(e)??e.getName(),file:t,hasEmailArg:bg(s,n.receiver),kind:n.kind,visibility:n.visibility}},tp=(e,t)=>{const s=[];for(const n of Z(e)){const i=ep(n,t);i&&s.push(i)}return s},sp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tp(i,P(t,n)))}return s},np=new Set(["dbRateLimit","rateLimit"]),ip=e=>r.isArrowFunction(e)?e.getBody():e,rp=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},nr=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},ir=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},op=(e,t)=>G(e)||t!==void 0&&ir(e,t).some(s=>nr(s)),ap=(e,t)=>t===void 0?Ee(e):ir(e,t).some(s=>!nr(s)),cp=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!np.has(s))return;const n=_(Jn(e.getArguments()[2]),"key");if(!n)return;const i=ip(n),o=rp(n);if(!(!op(i,o)||ap(i,o)))return{callee:s,scope:A(e),file:t,limitName:Xn(e),line:e.getStartLineNumber()}},lp=(e,t)=>O(e,t,cp),dp=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),up=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!dp.has(t.getName()))return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&K(s.getExpression()))return s.getName()},fp=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&K(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},gp=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},rr=(e,t=!1)=>{const s=gp(e);if(r.isIdentifier(s)){if(t)return;const n=J(s);return n===void 0?void 0:rr(n,!0)}if(r.isCallExpression(s))return up(s)??fp(s)},pp=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of E(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},mp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ce(s);if(n?.kind!=="query")return[];const i=li(s);if(i===void 0)return[];const o=n.receiver!==void 0&&So(n.receiver,"output"),a=n.receiver!==void 0&&oi(n.receiver,"use","mask"),c=new Set,l=[];for(const u of pp(i)){const f=rr(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},hp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...mp(a,o))}return s},vp=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(S(s));return t},Ep=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ce(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=ci(o);if(a===void 0)continue;const c=vp(_(a.options,"with"));c.length!==0&&i.push({exportName:Y(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},xp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...Ep(a,o))}return s},j=(e,t)=>`${e}:${t}`,Fn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Sp=(e,t)=>[...oe(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Fn(s,n,s.getName(),s.isExported()):void 0),...oe(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Fn(i,n,s.getName(),i.isExported()):void 0})],Ap=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=P(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(j(c,a))},yp=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,bp=(e,t)=>{const s=new Map(e.map(n=>[j(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(j(i.file,i.name))?.set(yp(n),{fields:n.fields,method:n.method,table:n.table})}return s},Np=(e,t,s)=>E(e.node,d.CallExpression).map(n=>Ap(n,t,s)).filter(n=>n!==void 0),Pp=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(j(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(j(o.file,o.name))?.push(a)}},wp=(e,t,s)=>{const n=new Map(e.map(a=>[j(a.file,a.name),a])),i=new Map(e.map(a=>[`${ms(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[j(a.file,a.name),Np(a,n,t)]));return Pp(s,n,i,o),o},Ip=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Cp=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(j(i.file,i.name))??[])Ip(t.get(j(i.file,i.name)),t.get(j(o.file,o.name)))&&(n=!0)}},Tp=(e,t,s,n)=>{const i=Sp(e,t),o=bp(i,s);return Cp(i,o,wp(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(j(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},it=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=it(e.getLeft()),s=it(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Op=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&it(t)!==void 0},kp=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return S(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Rp=(e,t,s)=>jo(e)?!ao(s)&&Ho(kp(t)):!0,Fp=(e,t)=>{const s=[],n=[...E(e,d.BinaryExpression),...E(e,d.StringLiteral),...E(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(Op(o))continue;const a=it(o);if(a===void 0)continue;const c=Wo(a);if(c===void 0||!Rp(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:qo(a)}))}return s},Lp=(e,t)=>{const s=[],n=new os({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,at(i,"utf8"),{overwrite:!0});s.push(...Fp(o,P(t,i)))}return s},Dp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ce(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=ci(o);if(a===void 0)continue;const c=_(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&G(c);!l&&!u||i.push({exportName:Y(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},_p=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...Dp(a,o))}return s},Mp=new Set(["query","unsafe"]),$p=e=>!r.isPropertyAccessExpression(e)||!Mp.has(e.getName())?!1:H(e.getExpression(),["sql"]),zp=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Kp=(e,t)=>{if(!$p(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!zp(s)))return{file:t,line:s.getStartLineNumber(),scope:A(e)}},Bp=(e,t)=>O(e,t,Kp),Vp=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Up=e=>{for(const[t,s]of Vp)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Wp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Up(a);c!==void 0&&s.push({file:P(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},qp=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),jp=(e,t,s=[])=>{const n=ft(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:qp,requireUnmodifiedReach:!0});return us(n,s)},Hp=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Gp=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Yp=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=S(i);t.push(o),o==="expiresInSeconds"&&(s=Gp(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Qp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Hp.get(t);return s===void 0?void 0:ti(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Xp=(e,t)=>{const s=Qp(e.getExpression());if(s!==void 0)return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s.method,...Yp(e.getArguments()[s.optionsIndex])}},Jp=(e,t)=>O(e,t,Xp),Zp=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),or=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Zp(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>ge(i)||s(i));if(!(n===void 0||ge(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},ys=(e,t)=>b(e.getFirstAncestor(s=>b(s,t)||ge(s)),t),em=(e,t)=>b(e,t)||e.getFirstAncestor(s=>b(s,t))!==void 0,ar=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return b(e,t)||ys(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=or(e);return s!==void 0&&!em(s,t)}return!1},cr=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],tm=e=>cr(e).some(t=>ar(t,e)),sm=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},nm=e=>cr(e).some(t=>ar(t,e)||r.isBreakStatement(t)&&b(or(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>sm(t)&&ys(t,e)),im=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>ys(t,e)),rm=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),om=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Dt=(e,t)=>{const s=rm(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||nm(e)||im(e))return;const i=A(e);if(!(i.kind==="module"&&e.getFirstAncestor(ge)!==void 0))return{file:t,kind:om(e),line:e.getStartLineNumber(),scope:i}},am=(e,t)=>[...oe(e,t,d.WhileStatement,Dt),...oe(e,t,d.ForStatement,Dt),...oe(e,t,d.DoStatement,Dt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),cm=new Set(["when","where"]),_t=new Set(["definePolicy","defineShape"]),lm=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return _t.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return _t.has(i)?i:void 0}const s=t.getText();return _t.has(s)?s:void 0},dm=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,lr=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(dm(e))return"empty-object";if(r.isParenthesizedExpression(e))return lr(e.getExpression())}},bs=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),um=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>bs(t)===e),dr=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>bs(t)===e),fm=e=>{const t=um(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||dr(e).length>0},gm=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>bs(t)===e),ts=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",pm=(e,t)=>ts(e)||ts(t),mm=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Ln=e=>!ts(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),hm=(e,t,s)=>{const n=mm.get(e);if(n!==void 0)return pm(t,s)?n==="positive"?"negative":"positive":Ln(t)||Ln(s)?void 0:n},Fe=e=>{if(r.isParenthesizedExpression(e))return Fe(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=hm(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=Fe(e.getLeft()),i=Fe(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Dn=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},vm=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Em=e=>r.isReturnStatement(e)?e.getExpression()??e:e,xm=e=>{const t=[];for(const s of dr(e)){const n=Fe(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of gm(e)){const n=Fe(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Dn(s.getThenStatement()):Dn(s.getElseStatement())??vm(s);i!==void 0&&t.push(Em(i))}return t},Sm=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},Am=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!cm.has(S(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&fm(a))for(const c of xm(a)){const l=lr(c);l!==void 0&&i.push({exportName:Sm(e),file:s,form:l,key:S(o),line:c.getStartLineNumber(),owner:t})}}return i},ym=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=lm(n);i!==void 0&&s.push(...Am(n,i,t))}return s},bm=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ym(i,P(t,n)))}return s},Nm=new Set(["query","upsert","upsertMany","upsertNow"]),Se=new Set,Pm=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Nm.has(t))return H(e.getExpression(),["vectors"])?t:void 0},Ns=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},ur=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},fr=e=>ur(e)?.getDeclarations()[0],wm=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},gr=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},_n=(e,t,s)=>{const n=ur(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=gr(fr(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return Ps(o,t,s-1)}return G(e)},Ps=(e,t,s)=>{const n=Ns(e);return Ee(n)?!1:r.isIdentifier(n)?_n(n,t,s):G(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>wm(i)&&_n(i,t,s))},pr=e=>{const t=gr(fr(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ie=(e,t)=>{const s=Ns(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ie(s.getWhenTrue(),t),...ie(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ie(s.getLeft(),t),...ie(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=pr(s);return n===void 0?[]:ie(n,!1)}return[]},Im=(e,t)=>{const s=ie(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>rt(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Cm=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Tm=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),rt=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Im(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Cm(n)&&(s=[Tm(n)]);return s},Om=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},km=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return Se;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return Se;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},ss=(e,t=!0,s=Se)=>{const n=Ns(e);if(r.isIdentifier(n)){const o=t?pr(n):void 0;return o===void 0?[{node:n,parameters:s}]:ss(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?ss(o.getExpression(),t,s):ie(o,!0).flatMap(a=>rt(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=Ps(i.getExpression(),Se,1)?km(o):Se;return Om(o).flatMap(c=>ie(c,!0).flatMap(l=>rt(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Rm=(e,t)=>{const s=Pm(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?ss(n):ie(n,!0).flatMap(o=>rt(o,!0).map(a=>({node:a,parameters:Se})))).some(({node:o,parameters:a})=>Ps(o,a,1))))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s}},Fm=(e,t)=>O(e,t,Rm),Lm=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:m,workflows:x}=s;return to({adminRoutes:Rc(e,t),aiRawRuns:Bc(e,t),aiToolSideEffects:Jc(e,t),argumentDerivedFetches:tl(e,t),argumentValidators:xl(e,t),authApiCalls:bo(e,t),authConfigs:Tl(e,t),browserUrlAccesses:Fl(e,t),callEdges:n.callEdges,configCalls:Bl(e,t),containerKeyAccesses:Ul(e,t),containerOverrides:Yl(e,t),containers:i,countReads:ed(e,t,f.tables),crons:o,cronTargets:o.flatMap(k=>k.functionPath===void 0?[]:[k.functionPath]),exportSinks:id(e,t),staleMigrationImports:Wp(e,t),failOpenGuards:ld(e,t),flagReads:pd(e,t),flagSecurityDefaults:Ed(e,t),geoIndexUsages:Ad(e,t),httpActionGuards:Fd(e,t),httpHeaderWrites:Ud(e,t),hyperdriveCalls:wo(e,t),identityClaimReads:Cu(e,t),imageDeliveryUrlAccesses:Ou(e,t),inserts:n.inserts,kvKeyAccesses:Ru(e,t,a),mailRecipientAccesses:Mu(e,t),maskProcedures:Fo(e,t),maskStrategies:Ku(e,t),mutatorWrites:ju(e,t),nondeterministicCalls:$o(e,t),normalizeIdAuthorizations:cf(e,t),notifyCalls:Ko(e,t),notifyConfig:zo(e,t),mutators:l,ownerFieldWrites:ng(e,t,a,l),unrestrictedWhereBranches:bm(e,t),paymentWebhooks:cg(e,t),privilegedDispatches:xg(e,t),procedureProtections:sp(e,t),queries:n.queries,queues:u,r2sqlCalls:Bo(e,t),ratelimitKeySelectors:lp(e,t),rawRowReturns:hp(e,t),relationLoads:xp(e,t),rlsProcedures:Vo(e,t),schema:f,secretLiterals:Lp(e,t),modules:c,shapes:g,softDeleteReads:_p(e,t),sqlInterpolations:Bp(e,t),storageKeyAccesses:jp(e,t,a),storageUploads:Jp(e,t),tableWrites:n.tableWrites,rowEffects:Tp(e,t,n.tableWrites,n.callEdges),unboundedLoops:am(e,t),vectorNamespaceAccesses:Fm(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:m})},Dm=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),_m=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>Dm(i))]},Mm=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),$m=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",Mn={error:"ERROR",info:"INFO",warn:"WARN"},$n={ERROR:2,INFO:0,WARN:1},zm=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),Km=(e,t)=>{const{advisor:s}=fi(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(Mn,n)?Mn[n]:void 0;return i===void 0?[...t,zm(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>$m(o)||$n[o.level]>=$n[i])},Bm=(e,t)=>{const{advisor:s}=fi(e),n=_m(t,s?.accept??[]);return Km(e,s?.acceptUnreadable===!0?[...n,Mm()]:n)},Vm={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Um="crons",Wm=ta.replace(/\.ts$/u,""),xe=(e,t)=>`${ms(e)}:${t}`,Mt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},qm=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Vm[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...Mt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Mt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Mt("workflow",t.workflow,"workflow name")}))],jm=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Hm=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:jm(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Gm=e=>qm(e).flatMap(t=>Hm(t)),Ym=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:Um,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Qm=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),Te=(e,t)=>t===void 0?e:{...e,module:t},Xm=e=>{const t=new Map,s=new Map,n=Qm(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(xe(c.file,c.exportName),l)};for(const c of e.functions){const l=xe(c.filePath,c.exportName),u=[...Uo(c.filePath),c.exportName].join(".");o(Te({detail:c.kind,id:`function:${l}`,kind:"function",name:u},qe(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=xe(c.filePath,c.exportName);o(Te({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},qe(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(Te({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(Te({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},qe(e.modules,c.filePath)),xe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(Te({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},qe(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},xe(Wm,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},Jm=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Zm=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(xe(e.file,e.exportName))??{reason:Jm(e.exportName)},eh=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Zm(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},$t=e=>`${e.from}|${e.kind}|${e.to}`,th=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,sh=e=>{const{nodes:t,sites:s}=Xm(e),n=new Map,i=new Map;for(const o of[...Ym(e),...Gm(e)]){const a=eh(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set($t(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(th(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>$t(o).localeCompare($t(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},nh=e=>`${gi}export const architecture = ${na(e,"Record<string, unknown>")};
|
|
24
|
+
`,zn=(e,t="api")=>{const s=new Map;for(const n of e){const i=ms(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new F("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},ih=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>pi(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>mi(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:pa)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},rh=(e,t,s={})=>{if(t===void 0)return;const n=ih(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
25
|
+
`);throw new F("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
26
|
+
${i}
|
|
27
|
+
|
|
28
|
+
Install them with your package manager, then re-run codegen.`)},oh=(e,t)=>{const s=Oo();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(ko(i,s))return!0}return!1},ah="createWorker",ch="extend",Kn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Bn=e=>{const t=[],s=Kn(_(e,"backupCron"));s!==void 0&&t.push(s);const n=_(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=Kn(i.getNameNode());o!==void 0&&t.push(o)}return t},lh=e=>{const t=T(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===ah)return r.isObjectLiteralExpression(s)?Bn(s):[];if(t!==ch||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Qn(s.getBody());return n===void 0?[]:Bn(n)},dh=(e,t)=>{const s=[];for(const{filePath:n}of $e(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...lh(o))}return[...new Set(s)]},mr=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:mr(e.inner)},uh=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=mr(n);return i!==void 0&&t.has(i)}))},fh=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new F("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new F("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},gh=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Au(s,t),a=Mi(s,t),c=a.claims;for(const D of a.diagnostics)console.warn(`@lunora/codegen: ${D}.`);const l=xa(s,t),u=sa(s,t),{queues:f,topics:g}=Sa(s,t),m=ya(n),x=ha(s,t);fh(u,x);const k=va(s,t),Q=ba(s,t),w=Ea(s,t,u,x),le=dh(s,t),I=ou(s,t,di(n)),N=Aa(s,t),ee=oh(s,t),te=Ro(s,t);te.browser=te.browser||N.usesSandboxBrowser;const se=je(n,e.target),L=Na(te,se,{agents:x.length>0,commitOrderedTables:i.tables.some(D=>D.commitOrdered===!0),cronTriggers:w.length>0,crossShardFanout:i.tables.some(D=>Ra(D)),containerEgressPolicy:I.containerEgressPolicy,containerRuntimeScheduling:k.some(D=>D.schedulingPolicy==="durable_object"),containerSandboxTools:k.some(D=>D.sandbox===!0),deliveryAuthorization:I.deliveryAuthorization,durableStreams:I.durableStreams,globalTables:i.tables.some(D=>D.shardMode==="global"),liveContext:I.liveContext,liveStreams:I.liveStreams,typedWebSockets:I.typedWebSockets,queues:f.length>0,relationGraph:uh(i),secretValues:ee,secrets:I.secrets,services:m.length>0,topics:g.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:N.usesSandboxLoader,workflowRollback:I.workflowRollback,workflowSchedules:u.some(D=>D.schedules!==void 0)}),R=L.usage,ne=ma(R),de=L.signals.vectorStore!==!1,ue=L.signals.services===!1?[]:m,$=hi(n),X=$??new Set,B=X.has("lunorash");rh(i,$,{hasVectors:de,scheduler:R.scheduler||w.length>0,storage:R.storage||Q.rules.length>0||Object.keys(vi(i)).length>0,usage:R});const V=z(v(t,"flags.ts")),U=z(v(t,"notify.ts"));return{agents:x,capabilities:ne,containers:k,crons:w,dataModelContent:_a(i),declaredDependencies:$,dependencies:X,entryCronTriggers:le,env:l,featureUsage:R,hasFlags:V,hasNotify:U,authClaims:c,identity:o,platformGate:{...L,diagnostics:[...Pa(n,e.target),...L.diagnostics,...wa(se,i.vectorIndexes),...I.liveStreams&&I.deliveryAuthorization?[Ia(se)]:[],...I.socketRoutes&&I.deliveryAuthorization?[Ca(se)]:[]]},queues:f,serverContent:La({agents:x,capabilities:ne,containers:k,env:l,hasVectors:de,hasFlags:V,authClaims:c,hasNotify:U,identity:o,queues:f,schema:i,services:ue,storageRuleBuckets:Q.rules.map(D=>D.bucket),topics:g,useUmbrella:B,workflows:u}),services:ue,storageRulesMetadata:Q,topics:g,usesSandbox:N.usesSandboxBrowser||N.usesSandboxContainer||N.usesSandboxFs,useUmbrella:B,workflows:u}},hr=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},ph=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},mh=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),hh=/^[\w$]+:[\w$]+$/u,vh=(e,t)=>{const s=ei(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Vn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Eh=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Vn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===as.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Vn(s):void 0}}},xh=(e,t,s)=>({schedule:{argKeys:Eh(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Sh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Zn.has(s))return vh(s,n);if((s==="runAfter"||s==="runAt")&&ph(t)){const l=ei(i)??(r.isStringLiteral(i)&&hh.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...xh(s,n,o)}}const a=mh.get(s),c=a===void 0?void 0:hr(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Ah=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),vr=e=>so.isOptionalChain(e.compilerNode),yh=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ge(t)?t.getFirstAncestor(ge)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Ah.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&vr(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&tm(s)),bh=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ge);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(ge),i))===!0},Nh=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),Ph=(e,t)=>{if(vr(e)||t==="schedule"&&bh(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(yh(s,i)){if(!Nh(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Un=(e,t,s)=>{if(s===void 0)return;const n=Ph(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:A(e)}},wh=(e,t)=>[...O(e,t,(s,n)=>Un(s,n,Sh(s))),...oe(e,t,d.PropertyAccessExpression,(s,n)=>{const i=hr(s,"services");return Un(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Ih=new Set(["boolean","number","object","string"]),Ch=e=>{const t=e.getName();if(!Ih.has(t))return;const s=e.getExpression();return H(s,["flags"])||H(s,["flags","details"])?t:void 0},Th=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Ch(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},Oh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=Th(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},kh=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||Ma(o))return;const a=e.getSourceFile().getFilePath();if($a(i,e,a)){const c=za(i,e,a,0,new Set);return c===void 0&&Ka(o),c}return o},Rh=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=gs(t.getNameNode());return s===void 0||s==="namespace"}),Fh=(e,t)=>{for(const{filePath:s}of $e(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of E(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Rh(a)))return i}}},Lh="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Dh=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Ne(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Lh}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},_h="room:",Mh="__lunora_socket__:",$h=/^[A-Za-z]\w*$/u,Wn=e=>$h.test(e),zh=e=>`${e}:`.startsWith(_h)||`${e}:`.startsWith(Mh),Er=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),xr=e=>Er(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),qn=e=>S(e),ws=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&S(s)===t),me=(e,t)=>{const s=Ne(e,`defineLiveStream ${t}`);return new F("LIVE_STREAM_NOT_LITERAL",s.message)},Sr=(e,t,s)=>{const n=ws(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw me(n??e,`needs ${s} so codegen can read its topics`);if(xr(i))throw me(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Kh=(e,t)=>{const s=qn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw me(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(xr(n))throw me(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Wn(s)||zh(s))throw new F("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(ws(n,"key")===void 0)return{fields:[],name:s};const a=Sr(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>qn(l)),c=a.find(l=>!Wn(l));if(c!==void 0)throw new F("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},Bh=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw me(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Er(n))throw me(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=ws(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw me(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Sr(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:P(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Kh(a,l))}},Vh=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new F("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},Uh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},Wh=(e,t)=>E(e,d.CallExpression).filter(s=>ri(s,"defineLiveStream")).map(s=>{const n=Uh(s),i=r.isVariableDeclaration(n)?ds(n,"binding"):void 0;if(i===void 0)throw new F("LIVE_STREAM_NOT_EXPORTED",Ne(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return Bh(s,i,t)}),qh=(e,t)=>{const s=y(t).flatMap(n=>Wh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return Vh(s),s},jh=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Hh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?jh(e):!0,Ar=(e,t=!1)=>{for(const s of e.getProperties()){if(Hh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Ar(n,!0))return!0}return!1},Gh=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Ei(n))for(const o of ps(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Ar(a)))return!0}}return!1},Yh=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=et(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=et(a);c!==void 0&&s.push({column:c,strategy:ui(a),table:i})}}return s},Qh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Ei(i))for(const a of ps(o))for(const c of Yh(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Xh=["providerSubscriptionId","state"],Jh=["providerEventId","processedAt"],jn=(e,t)=>t.every(s=>s in e.shape),Zh=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&jn(t,Xh)&&jn(s,Jh)},ev=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],tv=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},sv=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},nv="@lunora/privacy",yr="userId",Hn=new Set(["user","users"]),iv=e=>e.replaceAll("\\","/"),rv="privacy",ov=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),pt=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Me=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Is=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),av=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},mt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},cv=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=av(s,"tables"),i=pt(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Is(n).map(a=>Me(a)))t.datasets.set(o,i)},Cs=8,ye=(e,t=0)=>{if(t>Cs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return ye(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:ye(i,t+1)},lv=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:ye(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?Is(n):[],o=new Set(i.map(a=>Me(a)));for(const a of ev)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?pt(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Me(a)==="user"&&t.userTables.add(c))}},Gn=(e,t,s)=>{t.datasets.set(pt(e.getArguments()[0])??s,s)},dv=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Me(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},br=(e,t=0)=>{const s=ye(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Cs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?br(i.getExpression(),t+1):[dv(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},uv=e=>{const t=e.getArguments()[0];return t===void 0?void 0:br(t)},fv=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:ye(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Is(n):[])t.excluded.set(Me(i),r.isPropertyAssignment(i)?pt(i.getInitializer())??"":"")},gv=(e,t)=>{switch(mt(e)){case"actionCacheDataset":{Gn(e,t,"actionCache");break}case"authDataset":{lv(e,t);break}case"defineDataset":{cv(e,t);break}case"documentHistoryDataset":{Gn(e,t,"documentHistory");break}}},Ts=e=>e!==void 0&&r.isCallExpression(e)&&mt(e)==="defineDataset",Nr=e=>e!==void 0&&r.isCallExpression(e)&&ov.has(mt(e)??""),pv=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(Ts(i)||Nr(i))?n:void 0},Pr=(e,t,s=0)=>{const n=ye(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Cs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Pr(i.getExpression(),t,s+1))return!1}else if(!Ts(i)&&!Nr(i)){const o=r.isIdentifier(i)?pv(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},mv=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Pr(t,s)?s:void 0},hv=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if(gv(i,t),mt(i)==="definePrivacy"){const o=uv(i);fv(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:mv(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>Ts(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},vv=(e,t)=>{const s=v(t,"schema.ts"),n=[...y(t),...z(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>iv(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Ev=(e,t,s)=>{if(s?.has(nv)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Hn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Hn)},i=[],o=[];for(const f of vv(e,t)){const g=hv(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:tv(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},wr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&wr(n,t)),xv=(e,t)=>e.extensionKey!==rv&&(yr in e.shape||Object.values(e.shape).some(s=>wr(s,t))),Sv=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${yr}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Av=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>xv(o,t.userTables)).map(o=>o.name),[n]=sv(s,t.classifications);if(n!==void 0)throw new F("PRIVACY_COVERAGE",Sv(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new F("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},yv=(e,t)=>{const s=Ta(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),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"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),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:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},bv=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Yn=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Nv="",Pv=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},wv=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===as.Const?t.getInitializer():void 0},Je=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Je(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=wv(e);if(n!==void 0)return Je(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},Iv=(e,t)=>{if(bv.has(e))return{method:e,tables:Je(t)??[Nv]}},zt=(e,t,s)=>e===void 0?void 0:{...e,fields:Pv(t,e.method,s)},Cv=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===as.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!K(s.getExpression())))return s.getName()},Tv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Cv(n);if(i!==void 0)return Yn.has(s)?zt({method:s,tables:[i]},e,1):void 0;if(K(n))return zt(Iv(s,e.getArguments()[0]),e,2);if(Yn.has(s)&&r.isPropertyAccessExpression(n)&&K(n.getExpression()))return zt({method:s,tables:[n.getName()]},e,1)},Ov=(e,t)=>O(e,t,(s,n)=>{const i=Tv(s);if(i===void 0)return;const o=A(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),kv=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),Rv=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||W(s,"args")===void 0)return!1}return vs(e,t).opaque},Fv=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ce(a);c!==void 0&&Rv(a,c.receiver)&&s.push(kv(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},Lv=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...Fv(i,P(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Dv=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),ot=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Ir=e=>!e.isAny(),Cr=e=>{const t=e.getType();if(!Ir(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Dv.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},_v=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},Tr={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},Mv=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),$v={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},zv=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Kv={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},Bv=(e,t,s)=>{if(!t.some(i=>po(i)))return $v;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return zv.has(s.typeName)&&!n&&!t.some(i=>Ya(i))?Kv:Tr},Or=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Mv(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},Vv=(e,t,s)=>{const n=[];for(const i of Z(e)){const o=r.isIdentifier(i.getNameNode())?Bt(i):[i.getName()],c=o.some(u=>ot(s,t,u))||!_v(i)?void 0:Cr(i),[l=i.getName()]=o;c!==void 0&&n.push(Or(t,l,c,i.getStartLineNumber(),Bv(i,o,c)))}return n},Uv=(e,t,s)=>{if(ot(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=Cr(i.getExpression());o!==void 0&&n.push(Or(t,"default",o,i.getStartLineNumber(),Tr))}return n},Wv=(e,t,s)=>[...Vv(e,t,s),...Uv(e,t,s)],qv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Bt(n).some(i=>ot(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Bt(n).find(o=>ot(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),jv=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),Hv=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=P(t,a);n.push(...Wv(c,l,s)),i.push(...qv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Ir(a.getType()))&&n.push(jv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Gv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},Yv=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Qv=(e,t)=>O(e,t,(s,n)=>Gv(s)?{file:n,line:s.getStartLineNumber(),scope:A(s),workflow:Yv(s)}:void 0),kr=e=>e==="@lunora/workflow",Xv=e=>new Set(e.getImportDeclarations().filter(t=>kr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),Jv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),Zv=(e,t)=>{const s=ii(e,"defineWorkflowEvent",kr),n=Xv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!Jv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?ds(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new F("WORKFLOW_EVENT_NOT_LITERAL",Ne(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:P(t,e.getFilePath()),type:l.getLiteralValue()})}return i},eE=(e,t)=>{const s=y(t).flatMap(i=>Zv(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new F("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},tE=e=>{const t=da(e,"compatibility_date"),s=ua(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:fa(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
|
|
29
|
+
`},sE=e=>`// Generated by @lunora/codegen. Do not edit.
|
|
30
|
+
// Serves the advisor procedure list to the app's Worker, which forwards it to a hosted Studio after the admin check.
|
|
31
|
+
const PROCEDURES = ${JSON.stringify(e)};
|
|
32
|
+
|
|
33
|
+
const ADVISOR_PROCEDURES_PATH = "/__lunora/advisor-procedures";
|
|
34
|
+
|
|
35
|
+
export default {
|
|
36
|
+
fetch(request: Request): Response {
|
|
37
|
+
if (new URL(request.url).pathname !== ADVISOR_PROCEDURES_PATH) {
|
|
38
|
+
return Response.json({ error: "not found" }, { status: 404 });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (request.method !== "GET") {
|
|
42
|
+
return Response.json({ error: "GET only" }, { status: 405 });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return new Response(PROCEDURES, { headers: { "Content-Type": "application/json" }, status: 200 });
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
`,nE=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":sE(t),"wrangler.jsonc":tE(e)}:{},iE=(e,t)=>{for(const s of new Set([Co(t),di(e)])){const n=s===void 0?[]:Go(s);if(s!==void 0&&n.length>0)throw new F("PROJECT_CONFIG_INVALID",`${Jr(s)} is invalid:
|
|
49
|
+
${n.map(i=>` - ${i}`).join(`
|
|
50
|
+
`)}`)}},rE=(e,t,s)=>{for(const n of s)t[n]===void 0&&he(v(e,n),{force:!0});for(const n of[...new Set(s.map(i=>ct(v(e,i))))].toSorted((i,o)=>o.length-i.length))z(n)&&is(n).length===0&&he(n,{recursive:!0})},oE=(e,t)=>{for(const s of is(e,{recursive:!0,withFileTypes:!0})){const n=v(s.parentPath,s.name);s.isFile()&&t[rs(e,n)]===void 0&&he(n)}},ze=(e,t)=>{z(e)&&at(e,"utf8")===t||Xr(e,t,"utf8")},aE=(e,t)=>{if(t===""){he(e,{force:!0});return}ze(e,t)},cE=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){he(s,{force:!0,recursive:!0});return}if(z(s))for(const n of is(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[rs(e,i)]===void 0&&he(i)}for(const[n,i]of Object.entries(t))ns(ct(v(e,n)),{recursive:!0}),ze(v(e,n),i)},lE=(e,t,s,n)=>{const i=v(e,t);if(n!==void 0)rE(i,s,n);else if(Object.keys(s).length===0){he(i,{force:!0,recursive:!0});return}else z(i)&&oE(i,s);for(const[o,a]of Object.entries(s)){const c=v(i,o);ns(ct(c),{recursive:!0}),ze(c,a)}},dE=e=>{try{const t=Ja(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Ze=(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)},uE=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,fE=(e,t)=>{z(e)||ns(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{ze(v(e,n.name),n.content),s.push(n.name);break}case"directory":{lE(e,n.name,n.files,n.owned),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{cE(e,n.files),s.push(...Object.keys(n.files));break}default:aE(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},gE=e=>{const t=dE(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=tc({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=nc({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
|
|
51
|
+
`,openApiModuleContent:sc(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
|
|
52
|
+
`,openRpcModuleContent:ic(i)}},pE=".lunora-schema.json",mE=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},hE=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new F("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) (${o}), 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 o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new F("MASK_UNSUPPORTED",`defineShape "${o.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 "${o.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(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.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})}},vE=8,EE=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:x}=e,k=()=>Va(()=>{const N=Po(l,a,{lazyFunctions:o}),ee=Mo(l,a);return{functions:N,httpRoutes:Ua(l,a),mutators:ee}});let{erased:Q,value:{functions:w,httpRoutes:le,mutators:I}}=k();No(y(a).map(N=>l.getSourceFileOrThrow(N)),N=>rs(a,N.getFilePath())),zn([...w,...I].map(N=>N.filePath)),zn(le.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const ee=u?w:w.filter($=>$.channel?.kind!=="room"&&$.lifecycle!=="socket"),te=fc({agents:t,functions:ee,httpRoutes:le,mutators:I,useUmbrella:m,workflows:x}),se={agents:t,functions:ee,lazyFunctions:o,migrations:c,mutators:I,shapes:f,useUmbrella:m,usesSandbox:g},L=yc(se),R=bc(se),ne=gc({functions:w,useUmbrella:m}),de=v(a,"_generated",xi),ue=[[s,te],[i,ne],[n,L],...Object.entries(R).map(([$,X])=>[v(de,$),X])];if(N>=vE||ue.every(([$,X])=>uE(l,$,X)))return{apiContent:te,erased:Q,functions:w,functionModulesContent:R,functionsContent:L,httpRoutes:le,internalContent:ne,mutators:I};for(const[$,X]of ue)Ze(l,$,X);({erased:Q,value:{functions:w,httpRoutes:le,mutators:I}}=k())}},xE=e=>{const t=mE(),s=t?Ct.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora");iE(e.projectRoot,n);const i=Yo(n),o=e.lazyFunctions===!0||i,a=Qo(n),c=v(n,"schema.ts");if(!z(c))throw new F("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??la(n);yo(kh);const u=Ha(l,c,e.projectRoot);Av(u.tables,Ev(l,n,hi(e.projectRoot)));const{agents:f,authClaims:g,capabilities:m,containers:x,crons:k,dataModelContent:Q,dependencies:w,entryCronTriggers:le,env:I,featureUsage:N,hasFlags:ee,hasNotify:te,identity:se,platformGate:L,queues:R,serverContent:ne,services:de,storageRulesMetadata:ue,topics:$,usesSandbox:X,useUmbrella:B,workflows:V}=gh({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:u,target:e.target});Dh(u,u.jurisdiction===void 0?void 0:Fh(l,n));const U=v(n,"_generated"),D=v(U,"dataModel.ts"),Rr=v(U,"server.ts"),Fr=v(U,"api.ts"),Lr=v(U,"internal.ts"),Dr=v(U,"functions.ts");Ze(l,D,Q),Ze(l,Rr,ne);const Os=Object.fromEntries(de.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(Da(p,U))));for(const[p,It]of Object.entries(Os))Ze(l,v(U,p),It);const Ke=qa(l,n),pe=Ga(l,n),ht=L.signals.typedWebSockets!==!1,{apiContent:ks,erased:_r,functions:q,functionModulesContent:Rs,functionsContent:Fs,httpRoutes:vt,internalContent:Ls,mutators:Et}=EE({agents:f,apiPath:Fr,generatedFunctionsPath:Dr,internalPath:Lr,lazyFunctions:o,roomsSupported:ht,lunoraDirectory:n,migrations:Ke,project:l,shapes:pe,useUmbrella:B,usesSandbox:X,workflows:V}),Ds=Zo(l,n),xt=ea(Ds,u,[...q,...vt].map(p=>p.filePath)),Be=Ds.length>0,Pe=e.lint===!1&&!Be?void 0:{callEdges:wh(l,n),inserts:Wa(l,n),queries:sn(l,n,q),tableWrites:Ov(l,n),workflowCalls:Qv(l,n)},Mr=Za(Pe?.queries??sn(l,n,q)),we=e.lint===!1||Pe===void 0?void 0:Lm(l,n,{callSites:Pe,containers:x,crons:k,functions:q,modules:xt,mutators:Et,queues:R,schema:u,shapes:pe,workflows:V,wranglerVariables:e.wranglerVariables}),_s=we===void 0?[]:Bm(e.projectRoot,[...Zr(we,{source:"static"}),...Hv(l,n,{byName:new Set([...V,...R,...f,...x].map(p=>p.exportName)),byPath:new Set([...q,...Et,...pe,...Ke].map(p=>`${p.filePath}:${p.exportName}`))}),...Lv(l,n),...Ba(_r,n),...rc(R,e.wranglerQueueProducers)]),$r=ja(l,n),Ms=Qh(l,n);hE(pe,Ms,Gh(l,n));const zr=ee?Oh(l,n):[],St=L.signals.vectorStore!==!1,Kr=Oa(je(e.projectRoot,e.target),"deliveryAuthorization"),Ie=yv(N,{containerCount:x.length,cronCount:k.length,dependencies:w,hasPaymentTables:Zh(u.tables),queueCount:R.length,storageColumnCount:Object.keys(vi(u)).length,storageRuleCount:ue.rules.length,vectorIndexCount:u.vectorIndexes.length,target:je(e.projectRoot,e.target),vectorStoreSupported:St,workflowCount:V.length}),$s=t?Ct.now():0,At=ec(u,Ke.map(p=>p.id)),yt=qh(l,n),zs=Fa({advisories:_s.filter(p=>p.name!=="procedure_type_check_unavailable"),agents:f,capabilities:m,containers:x,env:I,flagKeys:zr,hasFlags:ee,hasNotify:te,hasIpReaders:q.some(p=>p.readsIp===!0)||pe.some(p=>p.readsIp===!0),hasRooms:ht&&q.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:f.length>0||q.some(p=>ca(p)),hasSecretValues:L.signals.secretValues===!0,hasSockets:ht&&q.some(p=>p.lifecycle==="socket"),lazyFunctions:o,hasVectors:St,liveStreamDeclarations:yt,liveStreams:L.signals.liveStreams===!0,maskMetadata:Ms,mutators:Et,queues:R,rlsMetadata:$r,schema:u,schemaSnapshot:At,shapes:pe,services:de,storageRules:ue,studioFeatures:Ie,topics:$,useUmbrella:B,workflowEvents:eE(l,n),workflows:V}),Ks=dc(pe,w.has("@lunora/db"),B),Bs=oc(x,u.jurisdiction),Vs=ac(V,{lazy:o}),Us=cc(f,{lazy:o}),Ws=lc(R,e.wranglerQueueProducers),qs=Nc(yt,B),js=pc(k),Br=mc(Ie.scheduler),Ve=ka(je(e.projectRoot,e.target)),Vr=Ve.supported?hc(B):"",Ur=vc(u.tables,B,u.jurisdiction),Wr=Xo(e.projectRoot)?Ec(B):"",Hs=xc(u.vectorIndexes),Ue=Ac(u,B),Gs=uc(w.has("@lunora/seed")),We=e.apiSpec??"openapi",bt=We==="openapi"||We==="both",qr=we?.procedureProtections??[],jr=we===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...qr]},Nt=`${JSON.stringify(jr,void 0,2)}
|
|
53
|
+
`,Pt=We==="openrpc"||We==="both",Ys=Qa(w.has("@lunora/auth")),Qs=Xa({agentWorkflows:f.map(p=>p.className),authClaims:g.map(p=>p.name),capabilities:m,emailAgents:f.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:w.has("@lunora/cloudflare-access"),hasAuth:w.has("@lunora/auth"),hasFramework:w.has("@lunora/astro")||w.has("@lunora/svelte")||w.has("@lunora/vue")||z(v(e.projectRoot,"src","worker.ts")),hasGlobal:u.tables.some(p=>pi(p)),hasHyperdriveGlobal:u.tables.some(p=>mi(p)),hasKvIntrospector:Ie.kv,hasNotify:te,hasQueue:R.some(p=>p.mode==="push"),liveStreams:L.signals.liveStreams===!0,liveStreamsWithheld:L.liveStreamsWithheld,liveStreamDeclarations:yt,hasAdminRevocations:Ve.supported,hasScheduler:Ie.scheduler,hasSourcedTables:u.tables.some(p=>p.externalSource!==void 0),hasStorage:Ie.storage,hasDeliveryAuthorization:Kr,hasVectors:St,hasWorkflow:V.length>0,identity:se,jurisdiction:u.jurisdiction,jurisdictionPinsAuth:u.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:u.tables.map(p=>({name:p.name,shardMode:p.shardMode})),securityHeaders:Jo(n),spaAssetsBindings:e.spaAssetsBindings,useUmbrella:B,vectorIndexCount:u.vectorIndexes.length,voiceAgents:f.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:Be,wantsOpenApi:bt,wantsOpenRpc:Pt}),{openApiContent:Xs,openApiModuleContent:Js,openRpcContent:Zs,openRpcModuleContent:en}=gE({functions:q,httpRoutes:vt,modules:xt,projectRoot:e.projectRoot,wantsArchitecture:Be}),Ce=Be&&Pe!==void 0?sh({...Pe,crons:k,functions:q,httpRoutes:vt,modules:xt,queues:R,schema:u,services:de,topics:$,workflows:V}):void 0,wt=v(n,pE),Hr=z(wt),Gr=e.dryRun?[]:fE(U,[{content:Qs,kind:"always",name:"app.ts"},{content:Q,kind:"always",name:"dataModel.ts"},{content:ks,kind:"always",name:"api.ts"},{content:Ls,kind:"always",name:"internal.ts"},{content:ne,kind:"always",name:"server.ts"},{content:Fs,kind:"always",name:"functions.ts"},{files:Rs,kind:"directory",name:xi},{content:zs,kind:"always",name:"shard.ts"},{content:js,kind:"always",name:"crons.ts"},{content:Hs,kind:"always",name:"vectors.ts"},{content:Ue.global,kind:"always",name:"drizzle.global.ts"},{content:Ue.shard,kind:"always",name:"drizzle.shard.ts"},{content:Bs,kind:"optional",name:"containers.ts"},{content:Vs,kind:"optional",name:"workflows.ts"},{content:Us,kind:"optional",name:"agents.ts"},{content:Ws,kind:"optional",name:"queues.ts"},{content:qs,kind:"optional",name:"live.ts"},{content:Br,kind:"optional",name:"scheduler.ts"},{content:Ur,kind:"optional",name:"shardRegistry.ts"},{content:Vr,kind:"optional",name:"adminRevocations.ts"},{content:Wr,kind:"optional",name:"durableObjects.ts"},{content:Gs,kind:"optional",name:"seed.ts"},{content:Ys,kind:"optional",name:"authModule.ts"},{content:Ks,kind:"optional",name:"collections.ts"},{files:Os,kind:"services"},{files:nE(e.projectRoot,Nt,a),kind:"directory",name:"companion",owned:ga},{content:bt?Xs:"",kind:"optional",name:"openapi.json"},{content:bt?Js:"",kind:"optional",name:"openapi.ts"},{content:Pt?Zs:"",kind:"optional",name:"openrpc.json"},{content:Pt?en:"",kind:"optional",name:"openrpc.ts"},{content:Nt,kind:"optional",name:"advisor-procedures.json"},{content:Ce===void 0?"":`${JSON.stringify(Ce,void 0,2)}
|
|
54
|
+
`,kind:"optional",name:"architecture.json"},{content:Ce===void 0?"":nh(Ce),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!Hr&&ze(wt,eo(At)),t){const p=Ct.now(),It=Math.round(p-s),Yr=Math.round($s-s),Qr=Math.round(p-$s);console.error(`@lunora/codegen: codegen took ${It.toString()}ms (discovery ${Yr.toString()}ms, emit ${Qr.toString()}ms)`)}return{advisories:_s,advisorContext:we,agents:f,architecture:Ce,containers:x,cronTriggers:[...new Set([...Sc(k),...le])],generated:{advisorProceduresJson:Nt,agents:Us,api:ks,app:Qs,authModule:Ys,collections:Ks,containers:Bs,crons:js,dataModel:Q,drizzleGlobal:Ue.global,drizzleShard:Ue.shard,functionModules:Rs,functions:Fs,internal:Ls,live:qs,openApi:Xs,openApiModule:Js,openRpc:Zs,openRpcModule:en,queues:Ws,seed:Gs,server:ne,shard:zs,vectors:Hs,workflows:Vs},migrations:Ke,outputDirectory:U,platformDiagnostics:Ve.diagnostic===void 0?L.diagnostics:[...L.diagnostics,Ve.diagnostic],queues:R,indexReferences:Mr,schemaSnapshot:At,schemaSnapshotPath:wt,schemaTables:u.tables,workflows:V,writtenFiles:Gr}},zx=e=>co(()=>xE(e));export{pE as SCHEMA_SNAPSHOT_FILENAME,la as createCodegenProject,Vx as findTsconfig,Ux as refreshCodegenProject,zx as runCodegen,Wx as tsconfigFingerprint};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as d}from"node:fs";import{join as g}from"node:path";import{SyntaxKind as m,Node as o}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as u}from"./module-specifiers-BctA0m_p.mjs";import{p as h}from"./parse-validator-BisfC8bR.mjs";import{findObjectProperty as c}from"./isTestPath-DRIdZaij.mjs";import{a as x}from"./attribution-BhGR_h0Z.mjs";import{m as f}from"./ip-reads-
|
|
1
|
+
import{existsSync as d}from"node:fs";import{join as g}from"node:path";import{SyntaxKind as m,Node as o}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as u}from"./module-specifiers-BctA0m_p.mjs";import{p as h}from"./parse-validator-BisfC8bR.mjs";import{findObjectProperty as c}from"./isTestPath-DRIdZaij.mjs";import{a as x}from"./attribution-BhGR_h0Z.mjs";import{m as f}from"./ip-reads-ByzaRhd2.mjs";const S="shapes.ts",b=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return u(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},y=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(m.ImportDeclaration);return i!==void 0&&u(i.getModuleSpecifierValue())}return!1},I=r=>{if(o.isIdentifier(r))return b(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&y(t)}return!1},N=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=c(t,"table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},A=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=c(t,"args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:h(i)},E=r=>{const[t]=r.getArguments(),e=o.isObjectLiteralExpression(t)?c(t,"where"):void 0,i=o.isPropertyAssignment(e)?e.getInitializer():void 0;if(e===void 0)return f(r);if(!o.isArrowFunction(i)&&!o.isFunctionExpression(i))return!0;const n=i.getParameters()[0]?.getNameNode();return o.isIdentifier(n)&&n.getText()!=="ctx"&&n.findReferencesAsNodes().length>0||f(r)},P=r=>{const t=[];for(const e of r.getVariableDeclarations()){const i=e.getInitializer();if(i?.getKind()!==m.CallExpression)continue;const n=i,s=n.getExpression();if(!I(s))continue;const a=e.getNameNode();if(!o.isIdentifier(a)){if(e.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw l(a,"defineShape exports must be plain named exports (no destructuring)")}const p=x(e,"binding");p!==void 0&&t.push({args:A(n),exportName:p,filePath:"shapes",...E(n)?{readsIp:!0}:{},table:N(n)})}return t},V=(r,t)=>{const e=g(t,S);if(!d(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=P(i);return n.sort((s,a)=>s.exportName.localeCompare(a.exportName)),n};export{S as SHAPES_FILENAME,V as discoverShapes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w as a}from"./classify-procedure-call-n9urVsqb.mjs";const l=s=>a(s,"use","rls");export{l as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o,VariableDeclarationKind as b,SyntaxKind as h}from"ts-morph";import{a as y,b as c}from"./module-specifiers-BctA0m_p.mjs";import{unwrapExpression as l}from"./isTestPath-DRIdZaij.mjs";const G=e=>o.isIdentifier(e)?e.getText():o.isPropertyAccessExpression(e)?e.getName():void 0,N=(e,t,r=c)=>{const i=new Set;for(const n of e.getImportDeclarations())if(r(n.getModuleSpecifierValue()))for(const s of n.getNamedImports())s.getNameNode().getText()===t&&i.add(s.getAliasNode()?.getText()??s.getName());return i},M=(e,t)=>{if(o.isPropertyAccessExpression(e))return e.getName()===t;if(!o.isIdentifier(e))return!1;const r=e.getText();return r===t||N(e.getSourceFile(),t).has(r)},x=e=>{for(const t of e.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(t)&&c(t.getImportDeclaration().getModuleSpecifierValue()))return t.getNameNode().getText()},E=e=>e.getSymbol()?x(e):e.getText(),K=(e,t)=>o.isIdentifier(e)&&x(e)===t,J=(e,t)=>{const r=e.getExpression(),i=e.getSourceFile();if(o.isIdentifier(r))return N(i,t,y).has(r.getText());if(!o.isPropertyAccessExpression(r)||r.getName()!==t)return!1;const n=r.getExpression().getText();return i.getImportDeclarations().some(s=>s.getNamespaceImport()?.getText()===n&&y(s.getModuleSpecifierValue()))},u=e=>{const t=[];let r=l(e);for(;r&&o.isCallExpression(r);){const i=l(r.getExpression());if(!i||!o.isPropertyAccessExpression(i))return{root:void 0,steps:t};t.push({call:r,name:i.getName()}),r=l(i.getExpression())}return{root:r,steps:t}},A=e=>u(e).steps,C=(e,t,r)=>A(e).filter(i=>i.name===t).map(i=>i.call.getArguments()[0]).filter(i=>i!==void 0&&o.isCallExpression(i)&&r(i.getExpression())),R=(e,t,r)=>C(e,t,i=>M(i,r)),X=(e,t)=>A(e).some(r=>r.name===t),Z=(e,t,r)=>R(e,t,r).length>0,D=new Set(["action","internalAction","internalMutation","internalQuery","mutation","query","stream"]),T=e=>{if(o.isIdentifier(e)){for(const t of e.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(t)&&c(t.getImportDeclaration().getModuleSpecifierValue()))return t.getName()}if(o.isPropertyAccessExpression(e)){const t=e.getExpression();if(o.isIdentifier(t))return t.getSymbol()?.getDeclarations().some(i=>o.isNamespaceImport(i)&&c(i.getFirstAncestorByKindOrThrow(h.ImportDeclaration).getModuleSpecifierValue()))?e.getName():void 0}},B=e=>{const t=e.getParent(),r=t.getParent(),i=e.getPropertyNameNode()??e.getNameNode();if(!o.isObjectBindingPattern(t)||!o.isVariableDeclaration(r)||r.getVariableStatement()?.getDeclarationKind()!==b.Const||e.getDotDotDotToken()||e.getInitializer()||!o.isIdentifier(i)||!D.has(i.getText())||i.getText()==="stream")return;const n=r.getInitializer();if(!n)return;const{root:s,steps:a}=u(n);return s&&T(s)==="initLunora"&&a.length===2&&a[0]?.name==="create"&&a[1]?.name==="dataModel"?i.getText():void 0},_=e=>{const t=T(e);if(t)return D.has(t)?{factory:t}:{};if(!o.isIdentifier(e))return{};const r=e.getSymbol(),i=(r?.isAlias()?r.getAliasedSymbol():r)?.getValueDeclaration();return i&&o.isBindingElement(i)?{factory:B(i)}:i&&o.isVariableDeclaration(i)&&i.getVariableStatement()?.getDeclarationKind()===b.Const?{initializer:i.getInitializer()}:{}},j=e=>{const t=[],r=new Set;let i=e;for(;i!==void 0&&!r.has(i);){r.add(i);const n=u(i);if(t.push(...n.steps),!n.root)break;const{factory:s,initializer:a}=_(n.root);if(s)return{factory:s,steps:t};i=a}return{steps:t}},g=new Set(["action","mutation","query","stream"]),w={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},p={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init",onWhisper:"whisper",defineWebSocket:"socket"},f={defineRoom:"room"},z=e=>e==="whisper"?"query":"mutation",O=e=>{const{root:t}=u(e);return t&&o.isIdentifier(t)?t:void 0},k=(e,t=!1)=>{const r=O(e);if(!r)return;const i=E(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&o.isVariableDeclaration(n)){const s=n.getInitializer();return s?k(s,!0):void 0}return}return g.has(i)?"public":w[i]?"internal":void 0},V=(e,t=!1)=>{if(C(e,"use",s=>K(s,"platformAdmin")).length>0)return!0;if(t)return!1;const r=O(e)?.getSymbol(),i=(r?.isAlias()?r.getAliasedSymbol():r)?.getValueDeclaration(),n=i&&o.isVariableDeclaration(i)?i.getInitializer():void 0;return n!==void 0&&V(n,!0)},v=e=>V(e)?{adminOnly:!0}:{},L=(e,t)=>{const r=e.getName();if(!g.has(r))return;const i=e.getExpression(),n=l(i)??i,s=i===n?[n]:[i,n];if(s.some(d=>d.getType().getProperty("__lunoraProcedure"))){const d=s.some(F=>F.getType().getProperty("__lunoraVisibility"));return{kind:r,receiver:n,visibility:d?"internal":"public",...v(n)}}const a=t?j(n).factory:void 0,P=a?.startsWith("internal")?"internal":"public",m=a?P:k(n);if(m)return{kind:r,receiver:n,visibility:m,...v(n)}},W=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>o.isNamespaceImport(t)&&c(t.getFirstAncestorByKind(h.ImportDeclaration)?.getModuleSpecifierValue()??"")),q=e=>Object.hasOwn(f,e)||Object.hasOwn(p,e),I=e=>{if(Object.hasOwn(f,e))return{channel:f[e],kind:"mutation",visibility:"internal"};const t=Object.hasOwn(p,e)?p[e]:void 0;return t?{kind:z(t),lifecycle:t,visibility:"internal"}:void 0},Q=(e,t)=>{const r=e.getExpression();if(o.isPropertyAccessExpression(r)){const s=r.getExpression(),a=r.getName();return q(a)&&o.isIdentifier(s)&&W(s)?I(a):L(r,t)}if(!o.isIdentifier(r))return;const i=E(r);if(!i)return;if(g.has(i))return{kind:i,visibility:"public"};const n=w[i];return n?{kind:n,visibility:"internal"}:I(i)},S=new WeakMap,$=(e,t=!1)=>{const r=e.getProject().getTypeChecker().compilerObject;let i=S.get(r);i===void 0&&(i=new WeakMap,S.set(r,i));let n=i.get(e.compilerNode);return n===void 0&&(n=new Map,i.set(e.compilerNode,n)),n.has(t)||n.set(t,Q(e,t)),n.get(t)};export{G as a,A as b,$ as c,
|
|
1
|
+
import{Node as o,VariableDeclarationKind as b,SyntaxKind as h}from"ts-morph";import{a as y,b as c}from"./module-specifiers-BctA0m_p.mjs";import{unwrapExpression as l}from"./isTestPath-DRIdZaij.mjs";const G=e=>o.isIdentifier(e)?e.getText():o.isPropertyAccessExpression(e)?e.getName():void 0,N=(e,t,r=c)=>{const i=new Set;for(const n of e.getImportDeclarations())if(r(n.getModuleSpecifierValue()))for(const s of n.getNamedImports())s.getNameNode().getText()===t&&i.add(s.getAliasNode()?.getText()??s.getName());return i},M=(e,t)=>{if(o.isPropertyAccessExpression(e))return e.getName()===t;if(!o.isIdentifier(e))return!1;const r=e.getText();return r===t||N(e.getSourceFile(),t).has(r)},x=e=>{for(const t of e.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(t)&&c(t.getImportDeclaration().getModuleSpecifierValue()))return t.getNameNode().getText()},E=e=>e.getSymbol()?x(e):e.getText(),K=(e,t)=>o.isIdentifier(e)&&x(e)===t,J=(e,t)=>{const r=e.getExpression(),i=e.getSourceFile();if(o.isIdentifier(r))return N(i,t,y).has(r.getText());if(!o.isPropertyAccessExpression(r)||r.getName()!==t)return!1;const n=r.getExpression().getText();return i.getImportDeclarations().some(s=>s.getNamespaceImport()?.getText()===n&&y(s.getModuleSpecifierValue()))},u=e=>{const t=[];let r=l(e);for(;r&&o.isCallExpression(r);){const i=l(r.getExpression());if(!i||!o.isPropertyAccessExpression(i))return{root:void 0,steps:t};t.push({call:r,name:i.getName()}),r=l(i.getExpression())}return{root:r,steps:t}},A=e=>u(e).steps,C=(e,t,r)=>A(e).filter(i=>i.name===t).map(i=>i.call.getArguments()[0]).filter(i=>i!==void 0&&o.isCallExpression(i)&&r(i.getExpression())),R=(e,t,r)=>C(e,t,i=>M(i,r)),X=(e,t)=>A(e).some(r=>r.name===t),Z=(e,t,r)=>R(e,t,r).length>0,D=new Set(["action","internalAction","internalMutation","internalQuery","mutation","query","stream"]),T=e=>{if(o.isIdentifier(e)){for(const t of e.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(t)&&c(t.getImportDeclaration().getModuleSpecifierValue()))return t.getName()}if(o.isPropertyAccessExpression(e)){const t=e.getExpression();if(o.isIdentifier(t))return t.getSymbol()?.getDeclarations().some(i=>o.isNamespaceImport(i)&&c(i.getFirstAncestorByKindOrThrow(h.ImportDeclaration).getModuleSpecifierValue()))?e.getName():void 0}},B=e=>{const t=e.getParent(),r=t.getParent(),i=e.getPropertyNameNode()??e.getNameNode();if(!o.isObjectBindingPattern(t)||!o.isVariableDeclaration(r)||r.getVariableStatement()?.getDeclarationKind()!==b.Const||e.getDotDotDotToken()||e.getInitializer()||!o.isIdentifier(i)||!D.has(i.getText())||i.getText()==="stream")return;const n=r.getInitializer();if(!n)return;const{root:s,steps:a}=u(n);return s&&T(s)==="initLunora"&&a.length===2&&a[0]?.name==="create"&&a[1]?.name==="dataModel"?i.getText():void 0},_=e=>{const t=T(e);if(t)return D.has(t)?{factory:t}:{};if(!o.isIdentifier(e))return{};const r=e.getSymbol(),i=(r?.isAlias()?r.getAliasedSymbol():r)?.getValueDeclaration();return i&&o.isBindingElement(i)?{factory:B(i)}:i&&o.isVariableDeclaration(i)&&i.getVariableStatement()?.getDeclarationKind()===b.Const?{initializer:i.getInitializer()}:{}},j=e=>{const t=[],r=new Set;let i=e;for(;i!==void 0&&!r.has(i);){r.add(i);const n=u(i);if(t.push(...n.steps),!n.root)break;const{factory:s,initializer:a}=_(n.root);if(s)return{factory:s,steps:t};i=a}return{steps:t}},g=new Set(["action","mutation","query","stream"]),w={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},p={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init",onWhisper:"whisper",defineWebSocket:"socket"},f={defineRoom:"room"},z=e=>e==="whisper"?"query":"mutation",O=e=>{const{root:t}=u(e);return t&&o.isIdentifier(t)?t:void 0},k=(e,t=!1)=>{const r=O(e);if(!r)return;const i=E(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&o.isVariableDeclaration(n)){const s=n.getInitializer();return s?k(s,!0):void 0}return}return g.has(i)?"public":w[i]?"internal":void 0},V=(e,t=!1)=>{if(C(e,"use",s=>K(s,"platformAdmin")).length>0)return!0;if(t)return!1;const r=O(e)?.getSymbol(),i=(r?.isAlias()?r.getAliasedSymbol():r)?.getValueDeclaration(),n=i&&o.isVariableDeclaration(i)?i.getInitializer():void 0;return n!==void 0&&V(n,!0)},v=e=>V(e)?{adminOnly:!0}:{},L=(e,t)=>{const r=e.getName();if(!g.has(r))return;const i=e.getExpression(),n=l(i)??i,s=i===n?[n]:[i,n];if(s.some(d=>d.getType().getProperty("__lunoraProcedure"))){const d=s.some(F=>F.getType().getProperty("__lunoraVisibility"));return{kind:r,receiver:n,visibility:d?"internal":"public",...v(n)}}const a=t?j(n).factory:void 0,P=a?.startsWith("internal")?"internal":"public",m=a?P:k(n);if(m)return{kind:r,receiver:n,visibility:m,...v(n)}},W=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>o.isNamespaceImport(t)&&c(t.getFirstAncestorByKind(h.ImportDeclaration)?.getModuleSpecifierValue()??"")),q=e=>Object.hasOwn(f,e)||Object.hasOwn(p,e),I=e=>{if(Object.hasOwn(f,e))return{channel:f[e],kind:"mutation",visibility:"internal"};const t=Object.hasOwn(p,e)?p[e]:void 0;return t?{kind:z(t),lifecycle:t,visibility:"internal"}:void 0},Q=(e,t)=>{const r=e.getExpression();if(o.isPropertyAccessExpression(r)){const s=r.getExpression(),a=r.getName();return q(a)&&o.isIdentifier(s)&&W(s)?I(a):L(r,t)}if(!o.isIdentifier(r))return;const i=E(r);if(!i)return;if(g.has(i))return{kind:i,visibility:"public"};const n=w[i];return n?{kind:n,visibility:"internal"}:I(i)},S=new WeakMap,$=(e,t=!1)=>{const r=e.getProject().getTypeChecker().compilerObject;let i=S.get(r);i===void 0&&(i=new WeakMap,S.set(r,i));let n=i.get(e.compilerNode);return n===void 0&&(n=new Map,i.set(e.compilerNode,n)),n.has(t)||n.set(t,Q(e,t)),n.get(t)};export{G as a,A as b,$ as c,J as d,Z as e,K as f,X as g,N as i,j as s,R as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as c,handlerOf as l}from"./isTestPath-DRIdZaij.mjs";import{j as d,h as f}from"./attribution-BhGR_h0Z.mjs";import{c as u}from"./context-root-
|
|
1
|
+
import{Node as i}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as c,handlerOf as l}from"./isTestPath-DRIdZaij.mjs";import{j as d,h as f}from"./attribution-BhGR_h0Z.mjs";import{c as u}from"./context-root-DP9WbBI_.mjs";import{c as m}from"./classify-procedure-call-n9urVsqb.mjs";const p=t=>{const r=t.getInitializer();if(!r||!i.isCallExpression(r))return;const e=m(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const o=l(r,e.receiver);return o?{exportName:f(t)??t.getName(),handler:o,kind:e.kind}:void 0},x=(t,r)=>{const e=t.getParent();return e&&i.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.${r}.${e.getName()}`:`ctx.${r}`},h=(t,r,e)=>{const o=[];for(const n of u(t.handler,e))o.push({callee:x(n,e),exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()});return o},N=(t,r,e)=>{const o=[];for(const n of d(t)){const s=p(n);s&&o.push(...h(s,r,e))}return o},F=(t,r,e)=>{const o=[];for(const n of a(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);o.push(...N(s,c(r,n),e))}return o};export{F as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as C,descendantsOfKind as p,bindingKeyName as I,findObjectProperty as E,isConstDeclaration as D,walkChain as M}from"./isTestPath-DRIdZaij.mjs";import{d as v,b as S,f as F}from"./attribution-BhGR_h0Z.mjs";import{c as b}from"./classify-procedure-call-
|
|
1
|
+
import{Node as r,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as C,descendantsOfKind as p,bindingKeyName as I,findObjectProperty as E,isConstDeclaration as D,walkChain as M}from"./isTestPath-DRIdZaij.mjs";import{d as v,b as S,f as F}from"./attribution-BhGR_h0Z.mjs";import{c as b}from"./classify-procedure-call-n9urVsqb.mjs";import{isDefineMutatorCallee as w}from"./MUTATORS_FILENAME-C3OImAxC.mjs";const x=8,N=t=>{if(r.isMethodDeclaration(t))return t;const e=r.isPropertyAssignment(t)?l(t.getInitializer()):void 0,o=r.isShorthandPropertyAssignment(t)?t.getNameNode():e;if(r.isArrowFunction(o)||r.isFunctionExpression(o))return o;const i=r.isIdentifier(o)?v(o):void 0;if(r.isFunctionDeclaration(i))return i;const n=D(i)?l(i.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},T=t=>{const e=l(t.getArguments()[0]),o=r.isObjectLiteralExpression(e)?e:void 0,i=E(o,"server"),n=E(o,"handler"),s=i!==void 0&&w(t.getExpression()),a=n===void 0?void 0:b(t),u=a!==void 0&&a.receiver===void 0;return[s?N(i):void 0,u?N(n):void 0].filter(f=>f!==void 0)},P=new WeakMap,O=t=>{const e=t.getSourceFile(),o=P.get(e.compilerNode);if(o!==void 0)return o;const i=new Set(e.getDescendantsOfKind(d.CallExpression).flatMap(n=>T(n)).map(n=>n.compilerNode));return P.set(e.compilerNode,i),i},A=t=>{const e=t.getParent();return(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e))&&e.getParameters()[0]===t&&O(t).has(e.compilerNode)},Q=t=>{const e=t.getParent();return(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e))&&e.getParameters()[1]===t&&O(t).has(e.compilerNode)},B=t=>t.getNameNode().getDescendantsOfKind(d.BindingElement).some(e=>e.getParent().getParent()===t&&["args","ctx"].includes(I(e))),g=(t,e,o)=>{const i=t.getParent().getParent(),n=I(t);if(t.getDotDotDotToken()!==void 0||e==="trust"&&S(t))return;let s;if(r.isParameterDeclaration(i)){if(!A(i)||B(i))return n==="ctx"?[]:void 0;s=[]}else r.isBindingElement(i)?s=g(i,e,o):r.isVariableDeclaration(i)&&o>0&&(s=c(i.getInitializer(),e,o-1));return s===void 0?void 0:[...s,n]},c=(t,e="discover",o=x)=>{const i=l(t),n=C(i);if(n!==void 0){const s=c(n.object,e,o);return s===void 0?void 0:[...s,n.member]}return r.isIdentifier(i)?H(i,e,o):void 0},H=(t,e,o)=>{const i=t.getText()==="ctx",n=e==="trust"||!i?v(t):void 0;return i&&!r.isVariableDeclaration(n)?r.isBindingElement(n)?g(n,e,o):[]:r.isParameterDeclaration(n)?r.isIdentifier(n.getNameNode())&&A(n)?[]:void 0:r.isBindingElement(n)?g(n,e,o):!(r.isVariableDeclaration(n)&&r.isIdentifier(n.getNameNode())&&o>0)||e==="trust"&&S(n)?void 0:c(n.getInitializer(),e,o-1)},q=t=>c(t,"discover"),K=t=>{const e=c(t);return e===void 0?void 0:["ctx",...e].join(".")},J=(t,e)=>{if(e(t.getText()))return!0;const o=K(t);return o!==void 0&&e(o)},Y=(t,e)=>{const o=l(t),i=C(o);if(i!==void 0&&i.member!==e.at(-1))return!1;const n=o===void 0?void 0:c(o);return n?.length===e.length&&n.every((s,a)=>s===e[a])},Z=(t,e)=>y(t).get(e)??[],U=t=>{const e=new Map;for(const i of p(t,d.BindingElement)){const n=r.isIdentifier(i.getNameNode())?g(i,"discover",x):void 0;n?.length===1&&n[0]!==void 0&&e.set(i.compilerNode,n[0])}const o=new Set([...e.keys()].map(i=>i.name.getText()));return p(t,d.Identifier).flatMap(i=>{const s=o.has(i.getText())&&!r.isBindingElement(i.getParent())?v(i):void 0,a=s===void 0?void 0:e.get(s.compilerNode);return a===void 0?[]:[[a,i]]})},h=new WeakMap,y=t=>{const e=h.get(t.compilerNode);if(e!==void 0)return e;const o=new Map;for(const[n,s]of[...z(t),...U(t)])o.set(n,[...o.get(n)??[],s]);const i=new Map([...o].map(([n,s])=>[n,s.toSorted((a,u)=>a.getPos()-u.getPos())]));return h.set(t.compilerNode,i),i},z=t=>t.getDescendantsOfKind(d.PropertyAccessExpression).flatMap(e=>_(e.getExpression())?[[e.getName(),e]]:[]),_=t=>r.isIdentifier(t)&&c(t)?.length===0,$=t=>{const e=c(t);return e?.length===1&&e[0]==="db"},R=new Set(["asId","createMultipartUpload","fetch","generateUploadUrl","getPresignedUrl","getSignedUrl","getUrl","normalizeId","resumeMultipartUpload","runAction","runMutation","runQuery","store","upload"]),k=new Set(["catch","flatMap","map","reduce","reduceRight","then"]),L=(t,e=x)=>{const o=M(t,u=>{const f=l(u.getExpression()),m=r.isPropertyAccessExpression(f)?f.getName():void 0;return m!==void 0&&(R.has(m)||k.has(m))?!1:void 0}),i=o.root;if(o.verdict!==void 0||!r.isIdentifier(i))return o.verdict??!1;if(c(i,"trust")!==void 0)return!0;const n=v(i),s=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n,a=D(s)&&e>0?s.getInitializer():void 0;return a!==void 0&&L(a,e-1)},ee=t=>(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(o=>F(o)&&c(o,"trust")!==void 0);export{k as C,R as E,Y as a,Q as b,Z as c,$ as d,K as e,q as f,L as g,_ as i,J as m,ee as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SyntaxKind as g,Node as n}from"ts-morph";import{descendantsOfKind as p}from"./isTestPath-DRIdZaij.mjs";import{d as l}from"./context-root-
|
|
1
|
+
import{SyntaxKind as g,Node as n}from"ts-morph";import{descendantsOfKind as p}from"./isTestPath-DRIdZaij.mjs";import{d as l}from"./context-root-DP9WbBI_.mjs";const c=e=>n.isPropertyAccessExpression(e)&&e.getName()==="db"||n.isIdentifier(e)&&e.getText()==="db"||l(e),b=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),E=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t)||!b.has(t.getName()))return;const s=t.getExpression();if(c(s))return{options:e.getArguments()[1],table:d(e)};if(n.isPropertyAccessExpression(s)){const o=s.getExpression();if(c(o))return{options:e.getArguments()[0],table:s.getName()}}},f=(e,t)=>{const s=e.getExpression();return!n.isPropertyAccessExpression(s)||!t.has(s.getName())?!1:c(s.getExpression())},d=e=>{const t=e.getArguments()[0];return t&&n.isStringLiteral(t)?t.getLiteralText():""},A=(e,t,s)=>{const o=new Set,i=new Set;for(const a of p(e,g.CallExpression))if(f(a,t)){const r=d(a);r!==""&&o.add(r)}else if(f(a,s)){const r=d(a);r!==""&&i.add(r)}return{tablesRead:[...o],tablesWritten:[...i]}};export{c as i,E as r,A as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./declared-output-Iaar469J.mjs";import"./isTestPath-DRIdZaij.mjs";import"./attribution-BhGR_h0Z.mjs";import"./unwrap-handler-return-DUzluwPj.mjs";import"./ip-reads-ByzaRhd2.mjs";import"./classify-procedure-call-n9urVsqb.mjs";import{d as f}from"./index-BH3e-J44.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
|