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