@lunora/codegen 1.0.0-alpha.303 → 1.0.0-alpha.304

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 CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as l,errorPlatformDiagnosticNames as c,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as N,discoverAgents as g}from"./packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-B81lOULB.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs";import{default as P}from"./packem_shared/discoverCrons-DBnCama4.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as y,mayReadCapabilityContext as U,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs";import{default as W}from"./packem_shared/discoverFunctions-CbxZGGj0.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-DgfoyNcf.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-CwnXgjFJ.mjs";import{default as w}from"./packem_shared/discoverInserts-mHOX_dJR.mjs";import{d as Y}from"./packem_shared/index-CkS96b8a.mjs";import{default as Z}from"./packem_shared/discoverMigrations-C9mLIhGZ.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-qVDmv8st.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-9ZDpRptb.mjs";import{NOTIFY_FILENAME as ae,discoverNotifyCalls as ie,discoverNotifyChannels as me,discoverNotifyConfig as fe}from"./packem_shared/NOTIFY_FILENAME-CLoeWMb5.mjs";import{default as pe}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-CfxkjP5X.mjs";import{QUEUES_FILENAME as xe,discoverQueues as Se}from"./packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs";import{default as ue}from"./packem_shared/discoverR2sqlCalls-XBhs4XRZ.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-TskedRMh.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Cb8JR1b4.mjs";import{discoverSandboxUsage as Oe}from"./packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs";import{default as Te}from"./packem_shared/discoverSchema-CRBUNY3s.mjs";import{readServiceBindings as Ie,resolveServiceBindings as _e}from"./packem_shared/readServiceBindings-DvqIThzd.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Fe}from"./packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs";import{default as De}from"./packem_shared/discoverStorageRulesMetadata-BPJplDfz.mjs";import{WORKFLOWS_FILENAME as ye,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs";import{emitApp as He}from"./packem_shared/emitApp-CJe2L06A.mjs";import{isD1GlobalTable as Be,isHyperdriveGlobalTable as ke}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-DFv-RYZU.mjs";import{OPENRPC_VERSION as qe,buildOpenRpcDocument as we,emitOpenRpc as Je,emitOpenRpcModule as Ye}from"./packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs";import{DEFAULT_TARGET as Ze,platformMatrixIds as $e,readProjectTarget as er,resolveCodegenTarget as rr}from"./packem_shared/DEFAULT_TARGET-BnQiNNKu.mjs";import{l as tr,r as sr}from"./packem_shared/project-config-file-BV7RR-l6.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ir,runCodegen as mr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Reo6uCpZ.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as pr,evaluateSchemaDrift as nr,parseSchemaSnapshot as lr}from"./packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs";import{default as xr}from"./packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs";import{schemaFromIr as Er}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Ar,validatorIrToJsonSchema as vr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Nr,SDK_TARGETS as gr,generateSdk as Or}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as Tr,secretKindOf as hr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as _r}from"./packem_shared/emitDrizzleSchema-DitcRZ1a.mjs";import{default as Mr}from"./packem_shared/emitFunctions-BeKgL3dl.mjs";import{e as Pr}from"./packem_shared/server-DAvi_bv_.mjs";import{e as br}from"./packem_shared/shard-QKj9rp3r.mjs";import{G as Ur}from"./packem_shared/shared-DnCokNcE.mjs";import{MESSAGE_SOLUTIONS as Hr,findSolutionByMessage as jr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as kr,findProjectConfigFile as Wr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{createCodegenProject as Vr,findTsconfig as zr,refreshCodegenProject as Qr}from"./packem_shared/createCodegenProject-V51_yBw3.mjs";import{s as wr,t as Jr,u as Yr}from"./packem_shared/shard-runtime-BX0xmo0P.mjs";import{emitApi as Zr,emitCollections as $r,emitInternalApi as eo}from"./packem_shared/emitApi-Zx6VPN-7.mjs";import{emitCrons as oo,emitScheduler as to,emitVectors as so,emitWranglerCronTriggers as ao}from"./packem_shared/emitCrons-BQW2lviZ.mjs";import{emitDataModel as mo}from"./packem_shared/emitDataModel-BskFt9Wv.mjs";import{isTypedSchema as po}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{N as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Ze as DEFAULT_TARGET,j as FLAGS_FILENAME,Ur as GENERATED_HEADER,Ar as LUNORA_ERROR_CODES,Hr as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,ae as NOTIFY_FILENAME,qe as OPENRPC_VERSION,kr as PROJECT_CONFIG_FILENAMES,xe as QUEUES_FILENAME,ir as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Nr as SDK_LANGUAGES,gr as SDK_TARGETS,Me as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,ye as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,we as buildOpenRpcDocument,pr as buildSchemaSnapshot,b as capabilitiesUsedBy,Vr as createCodegenProject,n as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,g as discoverAgents,I as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyChannels,fe as discoverNotifyConfig,le as discoverQueries,Se as discoverQueues,ue as discoverR2sqlCalls,Ne as discoverRlsMetadata,ve as discoverRlsProcedures,Oe as discoverSandboxUsage,Te as discoverSchema,Fe as discoverShapes,De as discoverStorageRulesMetadata,Ue as discoverWorkflows,wr as emitAgents,Zr as emitApi,He as emitApp,$r as emitCollections,Jr as emitContainers,oo as emitCrons,mo as emitDataModel,_r as emitDrizzleSchema,Mr as emitFunctions,eo as emitInternalApi,Ve as emitOpenApi,ze as emitOpenApiModule,Je as emitOpenRpc,Ye as emitOpenRpcModule,to as emitScheduler,Pr as emitServer,br as emitShard,so as emitVectors,Yr as emitWorkflows,ao as emitWranglerCronTriggers,l as errorAdvisoryNames,c as errorPlatformDiagnosticNames,nr as evaluateSchemaDrift,jr as findLunoraSolution,Wr as findProjectConfigFile,zr as findTsconfig,xr as fingerprintSchemaSources,y as foldCapabilitySignals,m as formatAdvisories,Or as generateSdk,Be as isD1GlobalTable,ke as isHyperdriveGlobalTable,R as isTestPath,po as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,tr as loadProjectConfig,U as mayReadCapabilityContext,lr as parseSchemaSnapshot,$e as platformMatrixIds,pe as readPackageDependencies,sr as readProjectConfigLiterals,er as readProjectTarget,Ie as readServiceBindings,Tr as redact,Qr as refreshCodegenProject,rr as resolveCodegenTarget,_e as resolveServiceBindings,mr as runCodegen,Er as schemaFromIr,hr as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,d as toAdvisorContext,vr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as l,errorPlatformDiagnosticNames as c,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as N,discoverAgents as g}from"./packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-B81lOULB.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs";import{default as P}from"./packem_shared/discoverCrons-DBnCama4.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as y,mayReadCapabilityContext as U,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs";import{default as W}from"./packem_shared/discoverFunctions-CbxZGGj0.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-DgfoyNcf.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-CwnXgjFJ.mjs";import{default as w}from"./packem_shared/discoverInserts-mHOX_dJR.mjs";import{d as Y}from"./packem_shared/index-CkS96b8a.mjs";import{default as Z}from"./packem_shared/discoverMigrations-C9mLIhGZ.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-qVDmv8st.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-9ZDpRptb.mjs";import{NOTIFY_FILENAME as ae,discoverNotifyCalls as ie,discoverNotifyChannels as me,discoverNotifyConfig as fe}from"./packem_shared/NOTIFY_FILENAME-CLoeWMb5.mjs";import{default as pe}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-CfxkjP5X.mjs";import{QUEUES_FILENAME as xe,discoverQueues as Se}from"./packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs";import{default as ue}from"./packem_shared/discoverR2sqlCalls-XBhs4XRZ.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-TskedRMh.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Cb8JR1b4.mjs";import{discoverSandboxUsage as Oe}from"./packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs";import{default as Te}from"./packem_shared/discoverSchema-CqVS3R3n.mjs";import{readServiceBindings as Ie,resolveServiceBindings as _e}from"./packem_shared/readServiceBindings-DvqIThzd.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Fe}from"./packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs";import{default as De}from"./packem_shared/discoverStorageRulesMetadata-BPJplDfz.mjs";import{WORKFLOWS_FILENAME as ye,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs";import{emitApp as He}from"./packem_shared/emitApp-CJe2L06A.mjs";import{isD1GlobalTable as Be,isHyperdriveGlobalTable as ke}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-DFv-RYZU.mjs";import{OPENRPC_VERSION as qe,buildOpenRpcDocument as we,emitOpenRpc as Je,emitOpenRpcModule as Ye}from"./packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs";import{DEFAULT_TARGET as Ze,platformMatrixIds as $e,readProjectTarget as er,resolveCodegenTarget as rr}from"./packem_shared/DEFAULT_TARGET-BnQiNNKu.mjs";import{l as tr,r as sr}from"./packem_shared/project-config-file-BV7RR-l6.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ir,runCodegen as mr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-B8fjAt1q.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as pr,evaluateSchemaDrift as nr,parseSchemaSnapshot as lr}from"./packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs";import{default as xr}from"./packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs";import{schemaFromIr as Er}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Ar,validatorIrToJsonSchema as vr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Nr,SDK_TARGETS as gr,generateSdk as Or}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as Tr,secretKindOf as hr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as _r}from"./packem_shared/emitDrizzleSchema-DitcRZ1a.mjs";import{default as Mr}from"./packem_shared/emitFunctions-BeKgL3dl.mjs";import{e as Pr}from"./packem_shared/server-DAvi_bv_.mjs";import{e as br}from"./packem_shared/shard-QKj9rp3r.mjs";import{G as Ur}from"./packem_shared/shared-DnCokNcE.mjs";import{MESSAGE_SOLUTIONS as Hr,findSolutionByMessage as jr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as kr,findProjectConfigFile as Wr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{createCodegenProject as Vr,findTsconfig as zr,refreshCodegenProject as Qr}from"./packem_shared/createCodegenProject-V51_yBw3.mjs";import{s as wr,t as Jr,u as Yr}from"./packem_shared/shard-runtime-BX0xmo0P.mjs";import{emitApi as Zr,emitCollections as $r,emitInternalApi as eo}from"./packem_shared/emitApi-Zx6VPN-7.mjs";import{emitCrons as oo,emitScheduler as to,emitVectors as so,emitWranglerCronTriggers as ao}from"./packem_shared/emitCrons-BQW2lviZ.mjs";import{emitDataModel as mo}from"./packem_shared/emitDataModel-BskFt9Wv.mjs";import{isTypedSchema as po}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{N as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Ze as DEFAULT_TARGET,j as FLAGS_FILENAME,Ur as GENERATED_HEADER,Ar as LUNORA_ERROR_CODES,Hr as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,ae as NOTIFY_FILENAME,qe as OPENRPC_VERSION,kr as PROJECT_CONFIG_FILENAMES,xe as QUEUES_FILENAME,ir as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Nr as SDK_LANGUAGES,gr as SDK_TARGETS,Me as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,ye as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,we as buildOpenRpcDocument,pr as buildSchemaSnapshot,b as capabilitiesUsedBy,Vr as createCodegenProject,n as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,g as discoverAgents,I as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyChannels,fe as discoverNotifyConfig,le as discoverQueries,Se as discoverQueues,ue as discoverR2sqlCalls,Ne as discoverRlsMetadata,ve as discoverRlsProcedures,Oe as discoverSandboxUsage,Te as discoverSchema,Fe as discoverShapes,De as discoverStorageRulesMetadata,Ue as discoverWorkflows,wr as emitAgents,Zr as emitApi,He as emitApp,$r as emitCollections,Jr as emitContainers,oo as emitCrons,mo as emitDataModel,_r as emitDrizzleSchema,Mr as emitFunctions,eo as emitInternalApi,Ve as emitOpenApi,ze as emitOpenApiModule,Je as emitOpenRpc,Ye as emitOpenRpcModule,to as emitScheduler,Pr as emitServer,br as emitShard,so as emitVectors,Yr as emitWorkflows,ao as emitWranglerCronTriggers,l as errorAdvisoryNames,c as errorPlatformDiagnosticNames,nr as evaluateSchemaDrift,jr as findLunoraSolution,Wr as findProjectConfigFile,zr as findTsconfig,xr as fingerprintSchemaSources,y as foldCapabilitySignals,m as formatAdvisories,Or as generateSdk,Be as isD1GlobalTable,ke as isHyperdriveGlobalTable,R as isTestPath,po as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,tr as loadProjectConfig,U as mayReadCapabilityContext,lr as parseSchemaSnapshot,$e as platformMatrixIds,pe as readPackageDependencies,sr as readProjectConfigLiterals,er as readProjectTarget,Ie as readServiceBindings,Tr as redact,Qr as refreshCodegenProject,rr as resolveCodegenTarget,_e as resolveServiceBindings,mr as runCodegen,Er as schemaFromIr,hr as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,d as toAdvisorContext,vr as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as F,mkdirSync as nn,readFileSync as ki,writeFileSync as Ri,rmSync as ht,readdirSync as Fi}from"node:fs";import{dirname as rn,join as E,relative as Li}from"node:path";import{performance as rt}from"node:perf_hooks";import{runAdvisor as Di}from"@lunora/advisor";import{LunoraError as U}from"@lunora/errors";import{serializeSchemaSnapshot as Mi}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as _i}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,ts as Ki,VariableDeclarationKind as Bi}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as I,bindingKeyName as te,collectCallRows as C,findObjectProperty as M,collectSecurityCallRows as zi,propertyInitializer as T,listSecurityScanFiles as ze,objectLiteralFromCallbackBody as on,limitNameOf as an,optionsObjectLiteral as cn,handlerOf as $i,collectNodeRows as J,chainRootOf as Ot,outermostValueWrapper as w,isWriteTarget as $e,isSameNode as S,unwrapExpression as h,isConstDeclaration as Z,memberAccessOf as ln,returningFunctionOf as vt,walkChain as Vi,RUN_METHODS as dn,functionReferenceSegments as Ui,isTestPath as qi,isFunctionLike as ee,functionKeyOf as un}from"./isTestPath-B81lOULB.mjs";import{b as j,d as $,f as O,g as kt,c as v,a as fn,w as Rt,k as Wi,l as Hi,h as ji,m as Gi,j as Et,i as Yi}from"./attribution-hVBriwzy.mjs";import{a as gs,r as ot,i as q,b as Qi,m as gn,c as Ve,e as Ft,E as pn,C as mn,d as Xi,f as Ji,g as Zi}from"./context-root-LyOsqj_o.mjs";import{a as b,i as er,c as Q,d as hn,e as tr,f as sr}from"./classify-procedure-call-BAj0D1u2.mjs";import{a as y,r as vn,s as nr,b as ir}from"./project-config-file-BV7RR-l6.mjs";import{a as rr,b as Ue}from"./module-specifiers-WF8iAydP.mjs";import{r as qe,s as or}from"./parse-validator-IDBKIT7M.mjs";import ar from"./discoverAuthApiCalls-xs0ONfI-.mjs";import{i as L,r as En}from"./database-calls-BPpefKqO.mjs";import cr from"./discoverHyperdriveCalls-CwnXgjFJ.mjs";import{diagnosticAt as Se}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Lt,a as Le,s as xn,d as lr}from"./index-CkS96b8a.mjs";import{MUTATORS_FILENAME as dr,isDefineMutatorCallee as ur,mutatorServerImplOf as fr,discoverMutators as gr}from"./MUTATORS_FILENAME-qVDmv8st.mjs";import pr from"./discoverNondeterministicCalls-9ZDpRptb.mjs";import{discoverNotifyConfig as mr,discoverNotifyCalls as hr}from"./NOTIFY_FILENAME-CLoeWMb5.mjs";import vr from"./discoverR2sqlCalls-XBhs4XRZ.mjs";import Er from"./discoverRlsProcedures-TskedRMh.mjs";import{s as Dt,n as xr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Sr,redact as Ar,isHeuristicSecretKind as yr,isSecretishName as br}from"./redact-Cy14LEnc.mjs";import{a as Ce,d as Nr,r as Pr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as wr,discoverWorkflows as Ir}from"./WORKFLOWS_FILENAME-CdeS224T.mjs";import{r as Cr}from"./json-data-Chfs2Cz5.mjs";import{G as Tr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Or}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as av,refreshCodegenProject as cv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as kr,usedCapabilities as Rr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Sn,isHyperdriveGlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Fr}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as Lr}from"./CONTAINERS_FILENAME-dFRtAyIe.mjs";import Dr from"./discoverCrons-DBnCama4.mjs";import{contextPropertiesRead as Mr,discoverFeatureUsage as _r}from"./capabilitiesUsedBy-QgSZyE0T.mjs";import yn from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Kr}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as Br}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as zr}from"./readServiceBindings-DvqIThzd.mjs";import $r from"./discoverStorageRulesMetadata-BPJplDfz.mjs";import{resolveCodegenTarget as bn,gatePlatformFeatures as Vr,readTargetDiagnostics as Ur,vectorizeDimensionDiagnostics as qr,studioPlatformFor as Wr}from"./DEFAULT_TARGET-BnQiNNKu.mjs";import{i as Hr}from"./schema-BgM8A3XV.mjs";import{b as Nn,e as jr}from"./shard-QKj9rp3r.mjs";import{e as Gr,a as Yr}from"./server-DAvi_bv_.mjs";import{emitDataModel as Qr}from"./emitDataModel-BskFt9Wv.mjs";import{i as Xr,a as Jr,e as Zr,b as eo,d as to,c as so}from"./unwrap-handler-return-CJrkfrSH.mjs";import no from"./discoverFunctions-CbxZGGj0.mjs";import io from"./discoverHttpRoutes-DgfoyNcf.mjs";import ro from"./discoverInserts-mHOX_dJR.mjs";import{e as Pn}from"./exported-procedure-chains-DKK5HoK3.mjs";import oo from"./discoverMigrations-C9mLIhGZ.mjs";import ao from"./discoverQueries-CfxkjP5X.mjs";import co from"./discoverRlsMetadata-Cb8JR1b4.mjs";import lo from"./discoverSchema-CRBUNY3s.mjs";import{discoverShapes as uo}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as fo}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as go}from"./emitApp-CJe2L06A.mjs";import{readJsonSync as po}from"@visulima/fs";import{buildSchemaSnapshot as mo}from"./SchemaSnapshotParseError-BRJT7c2k.mjs";import{buildOpenApiDocument as ho,emitOpenApiModule as vo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as Eo,emitOpenRpcModule as xo}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as So,t as Ao,u as yo,s as bo,w as No}from"./shard-runtime-BX0xmo0P.mjs";import{emitCollections as Po,emitSeed as wo,emitApi as Io,emitInternalApi as Co}from"./emitApi-Zx6VPN-7.mjs";import{emitCrons as To,emitScheduler as Oo,emitShardRegistry as ko,emitDurableObjects as Ro,emitVectors as Fo,emitWranglerCronTriggers as Lo}from"./emitCrons-BQW2lviZ.mjs";import Do from"./emitDrizzleSchema-DitcRZ1a.mjs";import Mo from"./emitFunctions-BeKgL3dl.mjs";const wn=new Set(["delete","get","head","options","patch","post","put"]),_o=new Set(["handler","stream"]),Ko=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ps=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Bo=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!wn.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()}},zo=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)||wn.has(n.getName()))break;s=n.getExpression()}return Bo(s)},$o=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(ps.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&ps.has(s.getText()))return!0}return!1},Vo=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!_o.has(n.getName()))return;const i=zo(s);if(!i||!Ko.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&$o(o);return{exportName:$(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Uo=(e,t)=>{const s=[];for(const n of j(e)){const i=Vo(n,t);i&&s.push(i)}return s},qo=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Uo(i,I(t,n)))}return s},Wo=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}},Ho=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)?te(t):void 0}},jo=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))&&gs(a)}))return!1;const n=O(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&gs(i)},ms=(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=Wo(e);return n!==void 0&&Ho(n)===t?!0:t==="args"&&jo(e)},In=(e,t)=>r.isIdentifier(e)?ms(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>ms(s,t)),Go=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},hs=e=>{const t=r.isIdentifier(e)?O(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!kt(t)?t.getInitializer():void 0},xt=e=>In(e,"args"),W=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 s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},H=e=>{if(xt(e))return!0;const t=W(e);return t!==void 0&&xt(t)},Yo=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=W(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},se=e=>{if(ot(e))return!0;const t=hs(e);if(t!==void 0&&ot(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=hs(i);return o!==void 0&&ot(o)})},Te=(e,t)=>In(e,t),Qo=(e,t)=>{if(Te(e,t))return!0;const s=W(e);if(s!==void 0&&Te(s,t))return!0;const n=Go(e);if(n!==void 0){const i=W(n);return i!==void 0&&Te(i,t)}return!1},Xo=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:q(e.getExpression(),["ai"]),Jo=(e,t)=>{if(!Xo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)||se(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},Zo=(e,t)=>C(e,t,Jo),ea=new Set(["generateText","streamText"]),ta=new Set(["messages","prompt","system"]),sa=[{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"]}],na=(e,t)=>sa.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ia=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Qi(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&na(i,s));return n===void 0?void 0:`${n}.${s}`},ra=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ia(t);if(s!==void 0)return s}},oa=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=te(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},aa=e=>{if(xt(e))return!0;const t=oa(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},ca=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!ta.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&aa(s))return!0}return!1},la=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());if(i===void 0||!ea.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(b(c.getExpression())==="tool"&&(a=ra(c),a!==void 0))break;a!==void 0&&s.push({scope:v(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:ca(o)})}return s},da=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...la(i,I(t,n)))}return s},ua=e=>q(e,["fetch"]),fa=(e,t)=>{if(!ua(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},ga=(e,t)=>C(e,t,fa),Mt=(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=qe(s.getExpression());return n===void 0||Mt(n,t)})}finally{t.delete(e)}},pa=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=M(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:qe(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Mt(i)}},ma=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)?qe(o):void 0;a===void 0?s=!0:(t.push(a),s||=Mt(a))}n=i.getExpression()}return{objects:t,opaque:s}},_t=(e,t)=>t?ma(t):pa(e),Cn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=qe(s.getExpression());return n===void 0?[]:Cn(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},ha=e=>e.flatMap(t=>Cn(t,new Set)),va=new Set(["check","length","max"]),St=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(va.has(s.getName()))return!0;t=n}},At=e=>rr(e)||e==="@lunora/values",Ea=e=>{const t=new Set(["v"]);for(const s of er(e,"v",At))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&At(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},xa=(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},Sa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Aa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&At(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Kt=(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 Sa(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Aa(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},ya=(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)},ba=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Na=e=>r.isReturnStatement(e)?e.getExpression():void 0,Pa=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ba(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Na(t);return s?[s]:[]}),Tn=(e,t)=>{if(Kt(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Tn(e.getExpression(),t)},wa=(e,t)=>{const s=ya(e.getExpression(),e.getSourceFile());if(!s)return[];const n=St(e),i=new Set(Pa(s).map(o=>Tn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Kt(o,t);return a===void 0?[]:[{bounded:St(o)||n&&i.has(o),factory:a}]})},Ia=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Kt(s,t),i=n===void 0?[]:[{bounded:St(s),factory:n}];return r.isCallExpression(s)?[...i,...wa(s,t)]:i}),Ca=(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=Ia(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}},Ta=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=Q(n);if(i?.visibility!=="public")return;const{objects:o}=_t(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Ca(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:$(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Oa=(e,t)=>{const s=[],n=Ea(e),i={destructured:xa(e,n),namespaces:n};for(const o of j(e)){const a=Ta(o,t,i);a&&s.push(a)}return s},ka=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Oa(i,I(t,n)))}return s},at=e=>e?.getKind()===d.TrueKeyword,Ra=e=>e?.getKind()===d.FalseKeyword,Fa=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,La=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Da=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&b(t.getExpression())==="scim"),Ma=e=>e!==void 0&&r.isCallExpression(e)&&La.has(b(e.getExpression())??""),_a=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),Ka=e=>{const t=T(e,"advanced"),s=T(e,"emailAndPassword"),n=T(e,"session");return{analyzable:!0,disableCsrfCheck:at(T(t,"disableCSRFCheck")),emailPasswordEnabled:at(T(s,"enabled")),requireEmailVerification:at(T(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Da(T(e,"plugins"))&&Ma(T(e,"database")),secureCookiesDisabled:Ra(T(t,"useSecureCookies")),sessionFreshAgeZero:Fa(T(n,"freshAge")),trustedOriginsWildcard:_a(T(e,"trustedOrigins"))}},Ba=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),za=(e,t)=>{if(b(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?Ka(s):Ba();return{scope:v(e),file:t,line:e.getStartLineNumber(),...i}},$a=(e,t)=>zi(e,t,za),Va=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return gn(e.getExpression(),t.matchReceiver)?s:void 0},Ua=(e,t,s)=>{const n=Va(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!H(i)||se(i))&&!(s.requireUnmodifiedReach===!0&&!Yo(i)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:n}},We=(e,t,s)=>C(e,t,(n,i)=>Ua(n,i,s)),qa=new Set(["content","pdf","scrape","screenshot"]),Wa=(e,t)=>We(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:qa}),Ha=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),ja=new Set(["RateLimiter"]),Ga=new Set(["extend"]),vs="lunora",Ya=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],On=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}},yt=e=>e&&r.isObjectLiteralExpression(e)?On(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Qa=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&on(t.getBody());return s?On(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Xa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());i!==void 0&&(Ha.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...yt(n.getArguments()[0])}):Ga.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Qa(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=b(n.getExpression());i===void 0||!ja.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...yt(n.getArguments()[0])})}return s},Ja=(e,t)=>{for(const s of Ya){const n=E(t,s);if(!F(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))b(a.getExpression())===vs&&o.push({callee:vs,file:s,line:a.getStartLineNumber(),...yt(a.getArguments()[0])});return o}return[]},Za=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Xa(o,n))}return s.push(...Ja(e,rn(t))),s},Es="ctx.containers.",ec=e=>{if(!e.startsWith(Es))return!1;const t=e.slice(Es.length);return t.length>0&&!t.includes(".")},tc=(e,t)=>We(e,t,{argIndex:0,matchReceiver:ec,methods:new Set(["get"])}),sc=new Set(["allow","deny","setAllowed"]),nc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=M(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},ic=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!nc(e)))return{detail:"enableInternet: true",scope:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},rc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!sc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},oc=(e,t)=>ic(e,t)??rc(e,t),ac=(e,t)=>C(e,t,oc),cc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(L(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&L(s.getExpression())?s.getName():void 0},lc=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&L(s)?1:0]},dc=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),uc=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=>dc.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},fc=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return C(e,t,(i,o)=>{const a=cc(i);if(a===void 0)return;const c=uc(lc(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:v(i),table:a}})},gc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),pc=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return gc.has(s)?s:void 0},mc=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}},hc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=pc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?mc(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},vc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Ec=new Set(["dbRateLimit","rateLimit"]),xc=e=>{const t=cn(e);if(!t)return!1;const s=M(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Sc=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=vc.get(s);if(n!==void 0)return{callee:s,scope:v(e),failOpen:xc(e.getArguments()[n]),file:t,limitName:Ec.has(s)?an(e):"",line:e.getStartLineNumber()}},Ac=(e,t)=>C(e,t,Sc),yc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=Q(t);if(s?.kind!=="query")return;const n=$i(t,s.receiver);return n?{exportName:$(e)??e.getName(),handler:n}:void 0},xs=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},bc=e=>{const t=xs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=xs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Nc=(e,t)=>{const s=[];for(const n of Ve(e.handler,"flags"))s.push({callee:bc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Pc=(e,t)=>{const s=[];for(const n of j(e)){const i=yc(n);i&&s.push(...Nc(i,t))}return s},wc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Pc(i,I(t,n)))}return s},Ic=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:q(e.getExpression(),["flags"]),Cc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Tc=(e,t)=>{if(!Ic(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Cc(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:v(e),file:t,key:i,line:e.getStartLineNumber()}},Oc=(e,t)=>C(e,t,Tc),kc=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Rc=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Fc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of i.getDescendantsOfKind(d.CallExpression))kc(a)&&s.push({file:o,indexName:Rc(a),line:a.getStartLineNumber()})}return s},ve=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,kn=e=>{const t=e.getArguments()[0],s=ve(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=M(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?ve(n.getInitializer()):void 0},Lc=new Set(["delete","get","head","options","patch","post","put"]),Dc=new Set(["handler","stream"]),Mc=new Set(["runAction","runMutation"]),_c=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Ee=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Rn=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(te(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Ss=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Rn(s,"ctx")},As=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Rn(s,"request")},ys=(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(Mc.has(a)&&Ee(c,t))return a;if(_c.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Ee(c.getExpression(),t))return`db.${a}`}},bs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Ee(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Ee(n.getInitializer(),t))){for(const o of i.getElements())if(te(o)==="auth")return!0}}return!1},Kc=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Bc=(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"&&Ee(n.getExpression(),t)},zc=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],Fn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:zc(s)},$c=(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)?Fn(t,a.getText()):[]}return[]},Vc=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=Fn(s,t.getText());return n.length>0?n:$c(t,s)},Ns=(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=>Bc(i,t)&&Vc(i).some(o=>Kc.test(o)))},Uc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Dc.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(Lc.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},qc=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=ve(e.getArguments()[0]),l=c&&Ss(c,!0);if(!c||l===void 0||Ns(c,As(c,!0)))return;const u=ys(c,l);return u===void 0?void 0:{scope:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:bs(c,l),sideEffect:u}}const n=Uc(e);if(n===void 0)return;const i=ve(e.getArguments()[0]),o=i&&Ss(i,!1);if(!i||o===void 0||Ns(i,As(i,!1)))return;const a=ys(i,o);return a===void 0?void 0:{scope:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:bs(i,o),sideEffect:a}},Wc=(e,t)=>C(e,t,qc),Hc=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),jc=new Set(["append","set"]),Ln=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Ps=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Hc.has(b(n.getExpression())??"")&&Te(n,t)),Gc=(e,t)=>{if(Ps(e,t))return!0;const s=W(e);return s!==void 0&&Ps(s,t)},bt=(e,t)=>Qo(e,t)&&!Gc(e,t),Yc=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=W(e);return t!==void 0&&r.isNewExpression(t)&&b(t.getExpression())==="Headers"},De=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=W(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Bt=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&bt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Ln(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();bt(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=De(n.getExpression());i!==void 0&&Bt(i,t,s)}},Dn=(e,t)=>{const s=De(e);if(s===void 0)return;const n=M(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=De(n.getInitializer());i!==void 0&&Bt(i,"response-init",t)},Qc=(e,t)=>{const s=b(e.getExpression());if(s==="Response")Dn(e.getArguments()[1],t);else if(s==="Headers"){const n=De(e.getArguments()[0]);n!==void 0&&Bt(n,"headers-ctor",t)}},Xc=(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"){Dn(e.getArguments()[1],t);return}if(jc.has(n)&&Yc(i)){const o=e.getArguments()[1];o!==void 0&&bt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Ln(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Jc=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Qc(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Xc(s,t)},Zc=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=ve(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 Jc(n,{scope:v(e),relativePath:t,requestName:o.getText(),rows:a}),a},el=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...Zc(n,t));return s},tl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...el(i,I(t,n)))}return s},Mn="identity.ts",sl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ue(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},nl=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&&Ue(n.getModuleSpecifierValue())}return!1},il=e=>{if(r.isIdentifier(e))return sl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&nl(t)}return!1},rl=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!il(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Se(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=fn(s,"member");a!==void 0&&t.push({exportName:a})}return t},ol=(e,t)=>{const s=E(t,Mn);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=rl(n);if(i.length!==0){if(i.length>1)throw Se(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},al=new Set(["auth","context.auth"]),cl="userId",ll=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},dl=(e,t)=>{const s=E(t,Mn);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(b(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?ll(o):void 0}},ws=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return al.has(t.getText())||q(t,["auth"])?e:void 0},ul=e=>{if(r.isPropertyAccessExpression(e)&&ws(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&ws(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},Is=(e,t,s)=>{const n=ul(e);return n===void 0?void 0:{declared:n===cl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:v(e)}},fl=(e,t)=>{const s=dl(e,t);return s===void 0?[]:[...J(e,t,d.PropertyAccessExpression,(n,i)=>Is(n,i,s)),...J(e,t,d.ElementAccessExpression,(n,i)=>Is(n,i,s))]},gl=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=T(s,"key");if(!(!n||!H(n)||se(n)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},pl=(e,t)=>C(e,t,gl),ml=new Set(["delete","get","getRaw","getWithMetadata","put"]),hl=(e,t,s=[])=>{const n=We(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ml});return Rt(n,s)},vl=new Set(["queue","send"]),Cs=new Set(["bcc","cc","to"]),El=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!vl.has(t))return;const s=e.getExpression();return q(s,["mail"])||q(s,["email"])?t:void 0},xl=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Cs.has(y(t))&&H(n)&&!se(n)}if(!r.isPropertyAssignment(t)||!Cs.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&H(s)&&!se(s)}):!1,Sl=(e,t)=>{const s=El(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!xl(n)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},Al=(e,t)=>C(e,t,Sl),yl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Le(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=Le(l);if(u===void 0)continue;const f=xn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},bl=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Q(s):void 0;return n?.receiver?Lt(n.receiver).flatMap(i=>yl(i,$(e)??e.getName(),t)):[]},Nl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...bl(a,o))}return s},Pl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return L(s)},wl=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=M(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Il=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ur(s.getExpression())?s:void 0},Cl=e=>{const t=Il(e),s=t===void 0?void 0:wl(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?$(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Pl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Tl=e=>e.getVariableDeclarations().flatMap(t=>Cl(t)),Ol=(e,t)=>{const s=E(t,dr);if(!F(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Tl(n)},kl=new Set(["delete","get","patch"]),Rl=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Fl=new Set(["auth","identity","session","user"]),Ll=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Dl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!L(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Ml=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},_l=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Kl=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Bl=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>_l(s.getExpression(),t)&&Kl(s.getThenStatement())),zl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!kl.has(i))continue;const o=n.getExpression();if(!(L(o)||r.isPropertyAccessExpression(o)&&L(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},$l=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Ft(Ot(s))!==void 0)),Vl=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Ll.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Ul=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Rl.has(t.getText()))return!0;return[...Fl].some(t=>Ve(e,t).length>0)?!0:$l(e)||Vl(e)},ql=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Q(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=kn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&hn(n.receiver,"use","rls"),a=Ul(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=Dl(u);if(f===void 0)continue;const g=Ml(u);if(g===void 0||c.has(g)||!Bl(i,g))continue;const p=zl(i,g);p!==void 0&&(c.add(g),l.push({exportName:$(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:f,usesRls:o,visibility:n.visibility}))}return l},Wl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...ql(a,o))}return s},_n=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?O(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},Hl=e=>{const t=w(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!$e(s)},jl=e=>{const t=w(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Gl=e=>{const s=w(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!$e(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},Me=e=>{const t=O(e);return t===void 0||Hi(t.getSourceFile())},Nt=(e,t)=>{const s=w(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&Me(o);if(_n(Ot(o),t))return!(r.isPropertyAccessExpression(o)&&pn.has(o.getName()))||r.isExpressionStatement(w(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!Me(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}},Oe={kind:"opaque"},Yl={kind:"unreached"},Ql=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},Pt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?O(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=Ql(s);return i===void 0||kt(i)?void 0:i}const n=Z(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Kn=(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?Oe:c===void 0?a.some(l=>l.isRestParameter())?Oe:Yl:c.isRestParameter()?Oe:{kind:"parameter",parameter:c}},Xl=e=>{const t=w(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Pt(s.getExpression());return n===void 0?Oe:Kn(n,s,t)},Jl=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Zl=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Bn=e=>{const t=w(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=Zl(s);if(n!==void 0)return S(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},ed=4,zn=(e,t,s=0)=>{if(Wi(e))return!0;if(Hl(e)){const i=w(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||!Jl.has(c)}if(jl(e)||Gl(e)||Bn(e)||Nt(e,t))return!0;const n=Xl(e);return n?.kind==="unreached"||n?.kind==="parameter"&&td(n.parameter,s+1)},Ts=new WeakMap,td=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Ts.get(e.compilerNode);if(n!==void 0)return n;if(t>ed)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||O(a)?.compilerNode!==e.compilerNode||zn(a,void 0,t));return(o||t===0)&&Ts.set(e.compilerNode,o),o},Os=new WeakMap,sd=(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=O(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},nd=(e,t,s)=>{const{context:n,impl:i}=e,o=Os.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const p=g.getNameNode();return r.isIdentifier(p)?[p]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?zn(g,n):!$e(g),f=!sd(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const p=g.getText();if(p==="arguments")return!1;const x=l.get(p);return x===void 0||c.includes(g)||O(g)?.compilerNode!==x?!0:u(g)});return Os.set(i.compilerNode,f),f},ks=new WeakMap,id=e=>{let t=ks.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=fr(s);return n===void 0?[]:[[n.compilerNode,s]]})),ks.set(e.compilerNode,t)),t},rd=e=>{const t=id(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:$(n)??n.getName()};return a!==void 0&&nd(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},ct="args",pe=e=>{const t=ln(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===ct?t.member:void 0}if(!r.isIdentifier(e))return;const s=O(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=Z(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&te(i)===ct||r.isIdentifier(o)&&o.getText()===ct?te(s):void 0},od=new Set(["auth","identity","user"]),wt=e=>{const t=i=>{const o=Ft(i);return o!==void 0&&o.length>0&&od.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=W(s);return n!==void 0&&t(n)},$n=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=pe(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?W(n):void 0;if(o!==void 0)for(const a of $n(o,t-1))s.add(a)}return s},ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...ke(n),...ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=pe(h(u)??u);return g===void 0?[]:ke(f).filter(p=>p===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=pe(h(n)??n),c=pe(h(i)??i);return a!==void 0&&wt(i)&&o.push(a),c!==void 0&&wt(n)&&o.push(c),o},ad=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&tr(i.getExpression(),"defineIdentityGuard")},cd=e=>{if(!ad(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=pe(h(s)??s),o=t.some((a,c)=>c!==n&&wt(a));return i!==void 0&&o?[i]:[]})},ld=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)},dd=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Rs=(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},ud=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),fd=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&Rs(n,e)&&ld(n.getThenStatement()))for(const i of ke(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&ud(n)&&Rs(n,e))for(const i of cd(n))s.add(i);return s},gd=(e,t)=>{const s=$n(t);if(s.size===0)return!1;const n=e.getFirstAncestor(dd);if(n===void 0)return!1;const i=fd(n,e.getStart());return[...s].every(o=>i.has(o))},pd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),md=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),It=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Vn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),hd=e=>{const t=w(e),s=t.getParent();if(r.isVariableDeclaration(s))return S(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},vd=e=>{const t=hd(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||Z(t)?[t]:void 0:Vn(t)},me=e=>e.isUnion()?e.getUnionTypes().every(t=>me(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>me(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),_e=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Re=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Ed=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&md.get(s.getText())?.has(t.getName())===!0&&Me(s)},xd=e=>{const t=vt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=w(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&_e(n,mn)?n:void 0},Sd=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=w(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:_e(n,pd,t)?n:void 0},Ad=(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},yd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&S(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},Fs=e=>{const t=w(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Ed(s);return Sd(s,t)??Ad(s,t)??yd(s,t)??(n?s:xd(t))},bd=5e4,Un=()=>({inProgress:new Set,verdicts:new Map});class Nd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>bd&&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 Pd=8,wd=8;class Id{budget;scope;taint;verdicts=Un();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!me(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)?Vn(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Pd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(w(l),!0,a,0))&&(t===n||!me(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let p=Fs(o);p!==void 0;p=Fs(o)){if(r.isCallExpression(p)&&this.callbackCompromises(p,n))return!0;o=w(p)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&me(o.getType());if($e(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=vd(o);if(u!==void 0)return u.some(p=>n(p,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=w(t).getParent();if(n>=wd)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===w(t)?this.valueCompromises(i,!1,s,n+1):!_e(i,It);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||Z(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=w(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=>Re(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=_e(t,It)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Pt(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!Nt(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(Nt(s,this.scope.context))return!1;const i=Pt(t.getExpression()),o=i===void 0?void 0:Kn(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)||Bn(t)||S(vt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=vt(t);return S(s,this.scope.impl)?void 0:s}}const Cd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Td=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=O(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Od=new Set(["all","allSettled","any","race"]),Ls=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,lt=8;class kd{budget=new Nd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Un();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Id(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,lt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>ji(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=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(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=w(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!It.has(g.getName()))return!0;const p=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(g.getExpression(),!0)||p.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&Z(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const p=w(g),x=p.getParent();return!r.isCallExpression(x)||x.getExpression()!==p||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&Me(i)&&Od.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Re(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=O(t),i=Ls(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&pn.has(i)?!1:i!==void 0&&mn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Re(a)!==void 0)&&(i===void 0||!Cd.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Ot(i),c=r.isIdentifier(a)?Ls(O(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=Re(i);if(o===void 0)return!Td(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Vi(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(_n(i,this.scope.context))return!0;const o=r.isIdentifier(i)?O(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=Z(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=kt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,lt))return!1;if(this.variableDepth>=lt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Ds=new WeakMap,Rd=e=>{const t=Ds.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new kd(e);return Ds.set(e.impl.compilerNode,s),s},Fd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Ld=new Set(["insert","insertManyUnsafe","patch","replace"]),Dd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Ld.has(t)&&Xi(e.getExpression())?t:void 0},Md=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},_d=(e,t)=>{const s=ln(e);return s?.member===t?h(s.object):void 0},Ms=(e,t)=>r.isIdentifier(e)&&O(e)?.compilerNode===t.compilerNode,qn=(e,t,s,n=1)=>{const i=_d(e,s);if(i!==void 0)return Ms(i,t);const o=r.isIdentifier(e)?O(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&te(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||Z(l)&&Ms(h(l.getInitializer()),t))}const a=Z(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&qn(a,t,s,n-1)},Ct=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Ct(t.getWhenTrue()),...Ct(t.getWhenFalse())]:[t]},Kd=(e,t,s)=>{const n=[],i=s===void 0?void 0:Rd(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||!Fd.has(a))continue;const l=Ct(c).filter(f=>i===void 0?H(f)&&!Ji(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&qn(c,s.parameter,a),g=l.every(p=>gd(t.call,p));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Bd=(e,t,s)=>{const n=Dd(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=Md(i,n);if(o.length===0)return[];const a=v(e),c=rd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Kd(u,l,c))},zd=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=C(e,t,(c,l)=>Bd(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Rt(o,s).map(c=>Gi(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},$d=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Vd=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Ud=e=>{const t=M(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?Vd(t.getInitializer()):void 0},qd=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!$d.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Ud(n):void 0;return{callee:s,scope:v(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Wd=(e,t)=>C(e,t,qd),Hd=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),jd=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Gd=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=M(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Wn=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Hn=(e,t)=>e===t||e.startsWith(`${t}.`),jn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},_s=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)},Gn=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>_s(s));return r.isIdentifier(e)&&_s(e)&&t.push(e),t},Yd=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Qd=e=>{const t=Wn(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Xd=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Qd(e),i=new Set,o=a=>jn(a).some(c=>n.some(l=>Hn(c.getText(),l)))?!0:Gn(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Yd(a))i.add(l)}return{names:i,prefixes:n}},Jd=(e,t)=>jn(e).some(s=>t.prefixes.some(n=>Hn(s.getText(),n)))?!0:Gn(e).some(s=>t.names.has(s.getText())),Zd=e=>{const t=Ui(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},eu=(e,t,s)=>{const n=Wn(e,0);if(n===void 0)return[];const i=Xd(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!dn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Jd(u,i))continue;const f=Zd(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:v(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},tu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=jd(n),o=i===void 0?void 0:Hd.get(i);if(o===void 0)continue;const a=Gd(n,o);a!==void 0&&s.push(...eu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},su=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tu(i,I(t,n)))}return s},Ks={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Bs=new Set(["account","credential","member","passkey","session","user"]),nu=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),iu=e=>{const s=nu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Bs.has(s)||Bs.has(n)},ru=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ou=(e,t)=>{const{objects:s,opaque:n}=_t(e,t);return ha(s).some(i=>ru(i))?!0:n?void 0:!1},au=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!M(t,"captcha"),usesRateLimit:!!M(t,"rateLimit")}},cu=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Fe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},lu=e=>{const t=cu(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=au(t);return{...Fe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ks?{...Fe,[Ks[s]]:!0}:Fe},du=e=>{const t={...Fe};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=lu(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},uu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),fu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!uu.has(t.getName()))return!1;const s=t.getExpression();if(!L(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:iu(i.getLiteralText())},gu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),zs=new Set(["queues","scheduler","topics","workflows"]),pu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!gu.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&zs.has(s.getName())&&Zi(s.getExpression()))return!0;s=s.getExpression()}const n=Ft(s);return n?.length===1&&zs.has(n[0]??"")},mu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return L(s)},Yn=new Set(["generateObject","generateText","streamObject","streamText"]),hu=e=>{const t=b(e.getExpression());return t!==void 0&&Yn.has(t)},vu=e=>{const t=b(e.getExpression());if(t===void 0||!Yn.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!M(s,"maxOutputTokens")},Eu=new Set(["log","span","trace"]),xu=new Set(["ai"]),Su=new Set(["email","mail"]),Au=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),dt=(e,t)=>[...t].some(s=>Ve(e,s).length>0),Qn=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),yu=new Set(["every","filter","flatMap","forEach","map","some"]),bu=new Set(["all","allSettled","race"]),Xn=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(yu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&bu.has(n))return t},Nu=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(Qn.has(t.getKind())){const s=Xn(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Pu=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Qn.has(t.getKind())){if(t=Xn(t),t===void 0)return!1;continue}t=t.getParent()}return!1},wu=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(p=>{const x=p.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(p.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Iu=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}},Cu=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}},Tu=e=>{let t=!1,s=!0;for(const n of[...Au].flatMap(i=>Ve(e,i))){const i=Cu(n);i&&(t=!0,!Nu(i)&&!Iu(i)&&!wu(i)&&!Pu(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ou=e=>e.getDescendantsOfKind(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"}),$s="lunora-advisor-exempt",ku=/^[\s*/]+/u,Ru=/[\w-]/u,Fu=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
1
+ import{existsSync as F,mkdirSync as nn,readFileSync as ki,writeFileSync as Ri,rmSync as ht,readdirSync as Fi}from"node:fs";import{dirname as rn,join as E,relative as Li}from"node:path";import{performance as rt}from"node:perf_hooks";import{runAdvisor as Di}from"@lunora/advisor";import{LunoraError as U}from"@lunora/errors";import{serializeSchemaSnapshot as Mi}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as _i}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,ts as Ki,VariableDeclarationKind as Bi}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as I,bindingKeyName as te,collectCallRows as C,findObjectProperty as M,collectSecurityCallRows as zi,propertyInitializer as T,listSecurityScanFiles as ze,objectLiteralFromCallbackBody as on,limitNameOf as an,optionsObjectLiteral as cn,handlerOf as $i,collectNodeRows as J,chainRootOf as Ot,outermostValueWrapper as w,isWriteTarget as $e,isSameNode as S,unwrapExpression as h,isConstDeclaration as Z,memberAccessOf as ln,returningFunctionOf as vt,walkChain as Vi,RUN_METHODS as dn,functionReferenceSegments as Ui,isTestPath as qi,isFunctionLike as ee,functionKeyOf as un}from"./isTestPath-B81lOULB.mjs";import{b as j,d as $,f as O,g as kt,c as v,a as fn,w as Rt,k as Wi,l as Hi,h as ji,m as Gi,j as Et,i as Yi}from"./attribution-hVBriwzy.mjs";import{a as gs,r as ot,i as q,b as Qi,m as gn,c as Ve,e as Ft,E as pn,C as mn,d as Xi,f as Ji,g as Zi}from"./context-root-LyOsqj_o.mjs";import{a as b,i as er,c as Q,d as hn,e as tr,f as sr}from"./classify-procedure-call-BAj0D1u2.mjs";import{a as y,r as vn,s as nr,b as ir}from"./project-config-file-BV7RR-l6.mjs";import{a as rr,b as Ue}from"./module-specifiers-WF8iAydP.mjs";import{r as qe,s as or}from"./parse-validator-IDBKIT7M.mjs";import ar from"./discoverAuthApiCalls-xs0ONfI-.mjs";import{i as L,r as En}from"./database-calls-BPpefKqO.mjs";import cr from"./discoverHyperdriveCalls-CwnXgjFJ.mjs";import{diagnosticAt as Se}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Lt,a as Le,s as xn,d as lr}from"./index-CkS96b8a.mjs";import{MUTATORS_FILENAME as dr,isDefineMutatorCallee as ur,mutatorServerImplOf as fr,discoverMutators as gr}from"./MUTATORS_FILENAME-qVDmv8st.mjs";import pr from"./discoverNondeterministicCalls-9ZDpRptb.mjs";import{discoverNotifyConfig as mr,discoverNotifyCalls as hr}from"./NOTIFY_FILENAME-CLoeWMb5.mjs";import vr from"./discoverR2sqlCalls-XBhs4XRZ.mjs";import Er from"./discoverRlsProcedures-TskedRMh.mjs";import{s as Dt,n as xr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Sr,redact as Ar,isHeuristicSecretKind as yr,isSecretishName as br}from"./redact-Cy14LEnc.mjs";import{a as Ce,d as Nr,r as Pr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as wr,discoverWorkflows as Ir}from"./WORKFLOWS_FILENAME-CdeS224T.mjs";import{r as Cr}from"./json-data-Chfs2Cz5.mjs";import{G as Tr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Or}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as av,refreshCodegenProject as cv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as kr,usedCapabilities as Rr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Sn,isHyperdriveGlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Fr}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as Lr}from"./CONTAINERS_FILENAME-dFRtAyIe.mjs";import Dr from"./discoverCrons-DBnCama4.mjs";import{contextPropertiesRead as Mr,discoverFeatureUsage as _r}from"./capabilitiesUsedBy-QgSZyE0T.mjs";import yn from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Kr}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as Br}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as zr}from"./readServiceBindings-DvqIThzd.mjs";import $r from"./discoverStorageRulesMetadata-BPJplDfz.mjs";import{resolveCodegenTarget as bn,gatePlatformFeatures as Vr,readTargetDiagnostics as Ur,vectorizeDimensionDiagnostics as qr,studioPlatformFor as Wr}from"./DEFAULT_TARGET-BnQiNNKu.mjs";import{i as Hr}from"./schema-BgM8A3XV.mjs";import{b as Nn,e as jr}from"./shard-QKj9rp3r.mjs";import{e as Gr,a as Yr}from"./server-DAvi_bv_.mjs";import{emitDataModel as Qr}from"./emitDataModel-BskFt9Wv.mjs";import{i as Xr,a as Jr,e as Zr,b as eo,d as to,c as so}from"./unwrap-handler-return-CJrkfrSH.mjs";import no from"./discoverFunctions-CbxZGGj0.mjs";import io from"./discoverHttpRoutes-DgfoyNcf.mjs";import ro from"./discoverInserts-mHOX_dJR.mjs";import{e as Pn}from"./exported-procedure-chains-DKK5HoK3.mjs";import oo from"./discoverMigrations-C9mLIhGZ.mjs";import ao from"./discoverQueries-CfxkjP5X.mjs";import co from"./discoverRlsMetadata-Cb8JR1b4.mjs";import lo from"./discoverSchema-CqVS3R3n.mjs";import{discoverShapes as uo}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as fo}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as go}from"./emitApp-CJe2L06A.mjs";import{readJsonSync as po}from"@visulima/fs";import{buildSchemaSnapshot as mo}from"./SchemaSnapshotParseError-BRJT7c2k.mjs";import{buildOpenApiDocument as ho,emitOpenApiModule as vo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as Eo,emitOpenRpcModule as xo}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as So,t as Ao,u as yo,s as bo,w as No}from"./shard-runtime-BX0xmo0P.mjs";import{emitCollections as Po,emitSeed as wo,emitApi as Io,emitInternalApi as Co}from"./emitApi-Zx6VPN-7.mjs";import{emitCrons as To,emitScheduler as Oo,emitShardRegistry as ko,emitDurableObjects as Ro,emitVectors as Fo,emitWranglerCronTriggers as Lo}from"./emitCrons-BQW2lviZ.mjs";import Do from"./emitDrizzleSchema-DitcRZ1a.mjs";import Mo from"./emitFunctions-BeKgL3dl.mjs";const wn=new Set(["delete","get","head","options","patch","post","put"]),_o=new Set(["handler","stream"]),Ko=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ps=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Bo=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!wn.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()}},zo=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)||wn.has(n.getName()))break;s=n.getExpression()}return Bo(s)},$o=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(ps.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&ps.has(s.getText()))return!0}return!1},Vo=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!_o.has(n.getName()))return;const i=zo(s);if(!i||!Ko.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&$o(o);return{exportName:$(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Uo=(e,t)=>{const s=[];for(const n of j(e)){const i=Vo(n,t);i&&s.push(i)}return s},qo=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Uo(i,I(t,n)))}return s},Wo=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}},Ho=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)?te(t):void 0}},jo=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))&&gs(a)}))return!1;const n=O(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&gs(i)},ms=(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=Wo(e);return n!==void 0&&Ho(n)===t?!0:t==="args"&&jo(e)},In=(e,t)=>r.isIdentifier(e)?ms(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>ms(s,t)),Go=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},hs=e=>{const t=r.isIdentifier(e)?O(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!kt(t)?t.getInitializer():void 0},xt=e=>In(e,"args"),W=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 s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},H=e=>{if(xt(e))return!0;const t=W(e);return t!==void 0&&xt(t)},Yo=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=W(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},se=e=>{if(ot(e))return!0;const t=hs(e);if(t!==void 0&&ot(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=hs(i);return o!==void 0&&ot(o)})},Te=(e,t)=>In(e,t),Qo=(e,t)=>{if(Te(e,t))return!0;const s=W(e);if(s!==void 0&&Te(s,t))return!0;const n=Go(e);if(n!==void 0){const i=W(n);return i!==void 0&&Te(i,t)}return!1},Xo=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:q(e.getExpression(),["ai"]),Jo=(e,t)=>{if(!Xo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)||se(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},Zo=(e,t)=>C(e,t,Jo),ea=new Set(["generateText","streamText"]),ta=new Set(["messages","prompt","system"]),sa=[{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"]}],na=(e,t)=>sa.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ia=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Qi(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&na(i,s));return n===void 0?void 0:`${n}.${s}`},ra=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ia(t);if(s!==void 0)return s}},oa=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=te(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},aa=e=>{if(xt(e))return!0;const t=oa(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},ca=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!ta.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&aa(s))return!0}return!1},la=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());if(i===void 0||!ea.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(b(c.getExpression())==="tool"&&(a=ra(c),a!==void 0))break;a!==void 0&&s.push({scope:v(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:ca(o)})}return s},da=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...la(i,I(t,n)))}return s},ua=e=>q(e,["fetch"]),fa=(e,t)=>{if(!ua(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},ga=(e,t)=>C(e,t,fa),Mt=(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=qe(s.getExpression());return n===void 0||Mt(n,t)})}finally{t.delete(e)}},pa=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=M(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:qe(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Mt(i)}},ma=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)?qe(o):void 0;a===void 0?s=!0:(t.push(a),s||=Mt(a))}n=i.getExpression()}return{objects:t,opaque:s}},_t=(e,t)=>t?ma(t):pa(e),Cn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=qe(s.getExpression());return n===void 0?[]:Cn(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},ha=e=>e.flatMap(t=>Cn(t,new Set)),va=new Set(["check","length","max"]),St=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(va.has(s.getName()))return!0;t=n}},At=e=>rr(e)||e==="@lunora/values",Ea=e=>{const t=new Set(["v"]);for(const s of er(e,"v",At))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&At(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},xa=(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},Sa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Aa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&At(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Kt=(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 Sa(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Aa(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},ya=(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)},ba=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Na=e=>r.isReturnStatement(e)?e.getExpression():void 0,Pa=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ba(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Na(t);return s?[s]:[]}),Tn=(e,t)=>{if(Kt(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Tn(e.getExpression(),t)},wa=(e,t)=>{const s=ya(e.getExpression(),e.getSourceFile());if(!s)return[];const n=St(e),i=new Set(Pa(s).map(o=>Tn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Kt(o,t);return a===void 0?[]:[{bounded:St(o)||n&&i.has(o),factory:a}]})},Ia=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Kt(s,t),i=n===void 0?[]:[{bounded:St(s),factory:n}];return r.isCallExpression(s)?[...i,...wa(s,t)]:i}),Ca=(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=Ia(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}},Ta=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=Q(n);if(i?.visibility!=="public")return;const{objects:o}=_t(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Ca(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:$(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Oa=(e,t)=>{const s=[],n=Ea(e),i={destructured:xa(e,n),namespaces:n};for(const o of j(e)){const a=Ta(o,t,i);a&&s.push(a)}return s},ka=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Oa(i,I(t,n)))}return s},at=e=>e?.getKind()===d.TrueKeyword,Ra=e=>e?.getKind()===d.FalseKeyword,Fa=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,La=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Da=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&b(t.getExpression())==="scim"),Ma=e=>e!==void 0&&r.isCallExpression(e)&&La.has(b(e.getExpression())??""),_a=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),Ka=e=>{const t=T(e,"advanced"),s=T(e,"emailAndPassword"),n=T(e,"session");return{analyzable:!0,disableCsrfCheck:at(T(t,"disableCSRFCheck")),emailPasswordEnabled:at(T(s,"enabled")),requireEmailVerification:at(T(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Da(T(e,"plugins"))&&Ma(T(e,"database")),secureCookiesDisabled:Ra(T(t,"useSecureCookies")),sessionFreshAgeZero:Fa(T(n,"freshAge")),trustedOriginsWildcard:_a(T(e,"trustedOrigins"))}},Ba=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),za=(e,t)=>{if(b(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?Ka(s):Ba();return{scope:v(e),file:t,line:e.getStartLineNumber(),...i}},$a=(e,t)=>zi(e,t,za),Va=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return gn(e.getExpression(),t.matchReceiver)?s:void 0},Ua=(e,t,s)=>{const n=Va(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!H(i)||se(i))&&!(s.requireUnmodifiedReach===!0&&!Yo(i)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:n}},We=(e,t,s)=>C(e,t,(n,i)=>Ua(n,i,s)),qa=new Set(["content","pdf","scrape","screenshot"]),Wa=(e,t)=>We(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:qa}),Ha=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),ja=new Set(["RateLimiter"]),Ga=new Set(["extend"]),vs="lunora",Ya=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],On=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}},yt=e=>e&&r.isObjectLiteralExpression(e)?On(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Qa=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&on(t.getBody());return s?On(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Xa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());i!==void 0&&(Ha.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...yt(n.getArguments()[0])}):Ga.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Qa(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=b(n.getExpression());i===void 0||!ja.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...yt(n.getArguments()[0])})}return s},Ja=(e,t)=>{for(const s of Ya){const n=E(t,s);if(!F(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))b(a.getExpression())===vs&&o.push({callee:vs,file:s,line:a.getStartLineNumber(),...yt(a.getArguments()[0])});return o}return[]},Za=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Xa(o,n))}return s.push(...Ja(e,rn(t))),s},Es="ctx.containers.",ec=e=>{if(!e.startsWith(Es))return!1;const t=e.slice(Es.length);return t.length>0&&!t.includes(".")},tc=(e,t)=>We(e,t,{argIndex:0,matchReceiver:ec,methods:new Set(["get"])}),sc=new Set(["allow","deny","setAllowed"]),nc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=M(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},ic=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!nc(e)))return{detail:"enableInternet: true",scope:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},rc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!sc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},oc=(e,t)=>ic(e,t)??rc(e,t),ac=(e,t)=>C(e,t,oc),cc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(L(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&L(s.getExpression())?s.getName():void 0},lc=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&L(s)?1:0]},dc=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),uc=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=>dc.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},fc=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return C(e,t,(i,o)=>{const a=cc(i);if(a===void 0)return;const c=uc(lc(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:v(i),table:a}})},gc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),pc=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return gc.has(s)?s:void 0},mc=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}},hc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=pc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?mc(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},vc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Ec=new Set(["dbRateLimit","rateLimit"]),xc=e=>{const t=cn(e);if(!t)return!1;const s=M(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Sc=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=vc.get(s);if(n!==void 0)return{callee:s,scope:v(e),failOpen:xc(e.getArguments()[n]),file:t,limitName:Ec.has(s)?an(e):"",line:e.getStartLineNumber()}},Ac=(e,t)=>C(e,t,Sc),yc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=Q(t);if(s?.kind!=="query")return;const n=$i(t,s.receiver);return n?{exportName:$(e)??e.getName(),handler:n}:void 0},xs=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},bc=e=>{const t=xs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=xs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Nc=(e,t)=>{const s=[];for(const n of Ve(e.handler,"flags"))s.push({callee:bc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Pc=(e,t)=>{const s=[];for(const n of j(e)){const i=yc(n);i&&s.push(...Nc(i,t))}return s},wc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Pc(i,I(t,n)))}return s},Ic=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:q(e.getExpression(),["flags"]),Cc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Tc=(e,t)=>{if(!Ic(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Cc(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:v(e),file:t,key:i,line:e.getStartLineNumber()}},Oc=(e,t)=>C(e,t,Tc),kc=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Rc=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Fc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of i.getDescendantsOfKind(d.CallExpression))kc(a)&&s.push({file:o,indexName:Rc(a),line:a.getStartLineNumber()})}return s},ve=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,kn=e=>{const t=e.getArguments()[0],s=ve(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=M(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?ve(n.getInitializer()):void 0},Lc=new Set(["delete","get","head","options","patch","post","put"]),Dc=new Set(["handler","stream"]),Mc=new Set(["runAction","runMutation"]),_c=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Ee=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Rn=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(te(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Ss=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Rn(s,"ctx")},As=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Rn(s,"request")},ys=(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(Mc.has(a)&&Ee(c,t))return a;if(_c.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Ee(c.getExpression(),t))return`db.${a}`}},bs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Ee(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Ee(n.getInitializer(),t))){for(const o of i.getElements())if(te(o)==="auth")return!0}}return!1},Kc=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Bc=(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"&&Ee(n.getExpression(),t)},zc=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],Fn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:zc(s)},$c=(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)?Fn(t,a.getText()):[]}return[]},Vc=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=Fn(s,t.getText());return n.length>0?n:$c(t,s)},Ns=(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=>Bc(i,t)&&Vc(i).some(o=>Kc.test(o)))},Uc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Dc.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(Lc.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},qc=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=ve(e.getArguments()[0]),l=c&&Ss(c,!0);if(!c||l===void 0||Ns(c,As(c,!0)))return;const u=ys(c,l);return u===void 0?void 0:{scope:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:bs(c,l),sideEffect:u}}const n=Uc(e);if(n===void 0)return;const i=ve(e.getArguments()[0]),o=i&&Ss(i,!1);if(!i||o===void 0||Ns(i,As(i,!1)))return;const a=ys(i,o);return a===void 0?void 0:{scope:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:bs(i,o),sideEffect:a}},Wc=(e,t)=>C(e,t,qc),Hc=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),jc=new Set(["append","set"]),Ln=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Ps=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Hc.has(b(n.getExpression())??"")&&Te(n,t)),Gc=(e,t)=>{if(Ps(e,t))return!0;const s=W(e);return s!==void 0&&Ps(s,t)},bt=(e,t)=>Qo(e,t)&&!Gc(e,t),Yc=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=W(e);return t!==void 0&&r.isNewExpression(t)&&b(t.getExpression())==="Headers"},De=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=W(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Bt=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&bt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Ln(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();bt(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=De(n.getExpression());i!==void 0&&Bt(i,t,s)}},Dn=(e,t)=>{const s=De(e);if(s===void 0)return;const n=M(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=De(n.getInitializer());i!==void 0&&Bt(i,"response-init",t)},Qc=(e,t)=>{const s=b(e.getExpression());if(s==="Response")Dn(e.getArguments()[1],t);else if(s==="Headers"){const n=De(e.getArguments()[0]);n!==void 0&&Bt(n,"headers-ctor",t)}},Xc=(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"){Dn(e.getArguments()[1],t);return}if(jc.has(n)&&Yc(i)){const o=e.getArguments()[1];o!==void 0&&bt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Ln(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Jc=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Qc(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Xc(s,t)},Zc=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=ve(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 Jc(n,{scope:v(e),relativePath:t,requestName:o.getText(),rows:a}),a},el=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...Zc(n,t));return s},tl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...el(i,I(t,n)))}return s},Mn="identity.ts",sl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ue(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},nl=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&&Ue(n.getModuleSpecifierValue())}return!1},il=e=>{if(r.isIdentifier(e))return sl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&nl(t)}return!1},rl=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!il(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Se(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=fn(s,"member");a!==void 0&&t.push({exportName:a})}return t},ol=(e,t)=>{const s=E(t,Mn);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=rl(n);if(i.length!==0){if(i.length>1)throw Se(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},al=new Set(["auth","context.auth"]),cl="userId",ll=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},dl=(e,t)=>{const s=E(t,Mn);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(b(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?ll(o):void 0}},ws=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return al.has(t.getText())||q(t,["auth"])?e:void 0},ul=e=>{if(r.isPropertyAccessExpression(e)&&ws(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&ws(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},Is=(e,t,s)=>{const n=ul(e);return n===void 0?void 0:{declared:n===cl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:v(e)}},fl=(e,t)=>{const s=dl(e,t);return s===void 0?[]:[...J(e,t,d.PropertyAccessExpression,(n,i)=>Is(n,i,s)),...J(e,t,d.ElementAccessExpression,(n,i)=>Is(n,i,s))]},gl=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=T(s,"key");if(!(!n||!H(n)||se(n)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},pl=(e,t)=>C(e,t,gl),ml=new Set(["delete","get","getRaw","getWithMetadata","put"]),hl=(e,t,s=[])=>{const n=We(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ml});return Rt(n,s)},vl=new Set(["queue","send"]),Cs=new Set(["bcc","cc","to"]),El=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!vl.has(t))return;const s=e.getExpression();return q(s,["mail"])||q(s,["email"])?t:void 0},xl=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Cs.has(y(t))&&H(n)&&!se(n)}if(!r.isPropertyAssignment(t)||!Cs.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&H(s)&&!se(s)}):!1,Sl=(e,t)=>{const s=El(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!xl(n)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},Al=(e,t)=>C(e,t,Sl),yl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Le(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=Le(l);if(u===void 0)continue;const f=xn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},bl=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Q(s):void 0;return n?.receiver?Lt(n.receiver).flatMap(i=>yl(i,$(e)??e.getName(),t)):[]},Nl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...bl(a,o))}return s},Pl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return L(s)},wl=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=M(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Il=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ur(s.getExpression())?s:void 0},Cl=e=>{const t=Il(e),s=t===void 0?void 0:wl(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?$(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Pl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Tl=e=>e.getVariableDeclarations().flatMap(t=>Cl(t)),Ol=(e,t)=>{const s=E(t,dr);if(!F(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Tl(n)},kl=new Set(["delete","get","patch"]),Rl=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Fl=new Set(["auth","identity","session","user"]),Ll=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Dl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!L(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Ml=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},_l=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Kl=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Bl=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>_l(s.getExpression(),t)&&Kl(s.getThenStatement())),zl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!kl.has(i))continue;const o=n.getExpression();if(!(L(o)||r.isPropertyAccessExpression(o)&&L(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},$l=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Ft(Ot(s))!==void 0)),Vl=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Ll.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Ul=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Rl.has(t.getText()))return!0;return[...Fl].some(t=>Ve(e,t).length>0)?!0:$l(e)||Vl(e)},ql=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Q(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=kn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&hn(n.receiver,"use","rls"),a=Ul(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=Dl(u);if(f===void 0)continue;const g=Ml(u);if(g===void 0||c.has(g)||!Bl(i,g))continue;const p=zl(i,g);p!==void 0&&(c.add(g),l.push({exportName:$(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:f,usesRls:o,visibility:n.visibility}))}return l},Wl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...ql(a,o))}return s},_n=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?O(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},Hl=e=>{const t=w(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!$e(s)},jl=e=>{const t=w(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Gl=e=>{const s=w(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!$e(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},Me=e=>{const t=O(e);return t===void 0||Hi(t.getSourceFile())},Nt=(e,t)=>{const s=w(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&Me(o);if(_n(Ot(o),t))return!(r.isPropertyAccessExpression(o)&&pn.has(o.getName()))||r.isExpressionStatement(w(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!Me(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}},Oe={kind:"opaque"},Yl={kind:"unreached"},Ql=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},Pt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?O(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=Ql(s);return i===void 0||kt(i)?void 0:i}const n=Z(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Kn=(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?Oe:c===void 0?a.some(l=>l.isRestParameter())?Oe:Yl:c.isRestParameter()?Oe:{kind:"parameter",parameter:c}},Xl=e=>{const t=w(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Pt(s.getExpression());return n===void 0?Oe:Kn(n,s,t)},Jl=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Zl=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Bn=e=>{const t=w(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=Zl(s);if(n!==void 0)return S(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},ed=4,zn=(e,t,s=0)=>{if(Wi(e))return!0;if(Hl(e)){const i=w(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||!Jl.has(c)}if(jl(e)||Gl(e)||Bn(e)||Nt(e,t))return!0;const n=Xl(e);return n?.kind==="unreached"||n?.kind==="parameter"&&td(n.parameter,s+1)},Ts=new WeakMap,td=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Ts.get(e.compilerNode);if(n!==void 0)return n;if(t>ed)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||O(a)?.compilerNode!==e.compilerNode||zn(a,void 0,t));return(o||t===0)&&Ts.set(e.compilerNode,o),o},Os=new WeakMap,sd=(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=O(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},nd=(e,t,s)=>{const{context:n,impl:i}=e,o=Os.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const p=g.getNameNode();return r.isIdentifier(p)?[p]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?zn(g,n):!$e(g),f=!sd(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const p=g.getText();if(p==="arguments")return!1;const x=l.get(p);return x===void 0||c.includes(g)||O(g)?.compilerNode!==x?!0:u(g)});return Os.set(i.compilerNode,f),f},ks=new WeakMap,id=e=>{let t=ks.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=fr(s);return n===void 0?[]:[[n.compilerNode,s]]})),ks.set(e.compilerNode,t)),t},rd=e=>{const t=id(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:$(n)??n.getName()};return a!==void 0&&nd(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},ct="args",pe=e=>{const t=ln(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===ct?t.member:void 0}if(!r.isIdentifier(e))return;const s=O(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=Z(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&te(i)===ct||r.isIdentifier(o)&&o.getText()===ct?te(s):void 0},od=new Set(["auth","identity","user"]),wt=e=>{const t=i=>{const o=Ft(i);return o!==void 0&&o.length>0&&od.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=W(s);return n!==void 0&&t(n)},$n=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=pe(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?W(n):void 0;if(o!==void 0)for(const a of $n(o,t-1))s.add(a)}return s},ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...ke(n),...ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=pe(h(u)??u);return g===void 0?[]:ke(f).filter(p=>p===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=pe(h(n)??n),c=pe(h(i)??i);return a!==void 0&&wt(i)&&o.push(a),c!==void 0&&wt(n)&&o.push(c),o},ad=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&tr(i.getExpression(),"defineIdentityGuard")},cd=e=>{if(!ad(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=pe(h(s)??s),o=t.some((a,c)=>c!==n&&wt(a));return i!==void 0&&o?[i]:[]})},ld=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)},dd=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Rs=(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},ud=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),fd=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&Rs(n,e)&&ld(n.getThenStatement()))for(const i of ke(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&ud(n)&&Rs(n,e))for(const i of cd(n))s.add(i);return s},gd=(e,t)=>{const s=$n(t);if(s.size===0)return!1;const n=e.getFirstAncestor(dd);if(n===void 0)return!1;const i=fd(n,e.getStart());return[...s].every(o=>i.has(o))},pd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),md=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),It=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Vn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),hd=e=>{const t=w(e),s=t.getParent();if(r.isVariableDeclaration(s))return S(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},vd=e=>{const t=hd(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||Z(t)?[t]:void 0:Vn(t)},me=e=>e.isUnion()?e.getUnionTypes().every(t=>me(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>me(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),_e=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Re=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Ed=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&md.get(s.getText())?.has(t.getName())===!0&&Me(s)},xd=e=>{const t=vt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=w(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&_e(n,mn)?n:void 0},Sd=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=w(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:_e(n,pd,t)?n:void 0},Ad=(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},yd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&S(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},Fs=e=>{const t=w(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Ed(s);return Sd(s,t)??Ad(s,t)??yd(s,t)??(n?s:xd(t))},bd=5e4,Un=()=>({inProgress:new Set,verdicts:new Map});class Nd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>bd&&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 Pd=8,wd=8;class Id{budget;scope;taint;verdicts=Un();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!me(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)?Vn(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Pd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(w(l),!0,a,0))&&(t===n||!me(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let p=Fs(o);p!==void 0;p=Fs(o)){if(r.isCallExpression(p)&&this.callbackCompromises(p,n))return!0;o=w(p)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&me(o.getType());if($e(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=vd(o);if(u!==void 0)return u.some(p=>n(p,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=w(t).getParent();if(n>=wd)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===w(t)?this.valueCompromises(i,!1,s,n+1):!_e(i,It);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||Z(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=w(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=>Re(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=_e(t,It)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Pt(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!Nt(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(Nt(s,this.scope.context))return!1;const i=Pt(t.getExpression()),o=i===void 0?void 0:Kn(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)||Bn(t)||S(vt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=vt(t);return S(s,this.scope.impl)?void 0:s}}const Cd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Td=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=O(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Od=new Set(["all","allSettled","any","race"]),Ls=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,lt=8;class kd{budget=new Nd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Un();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Id(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,lt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>ji(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=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(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=w(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!It.has(g.getName()))return!0;const p=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(g.getExpression(),!0)||p.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&Z(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const p=w(g),x=p.getParent();return!r.isCallExpression(x)||x.getExpression()!==p||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&Me(i)&&Od.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Re(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=O(t),i=Ls(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&pn.has(i)?!1:i!==void 0&&mn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Re(a)!==void 0)&&(i===void 0||!Cd.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Ot(i),c=r.isIdentifier(a)?Ls(O(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=Re(i);if(o===void 0)return!Td(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Vi(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(_n(i,this.scope.context))return!0;const o=r.isIdentifier(i)?O(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=Z(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=kt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,lt))return!1;if(this.variableDepth>=lt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Ds=new WeakMap,Rd=e=>{const t=Ds.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new kd(e);return Ds.set(e.impl.compilerNode,s),s},Fd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Ld=new Set(["insert","insertManyUnsafe","patch","replace"]),Dd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Ld.has(t)&&Xi(e.getExpression())?t:void 0},Md=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},_d=(e,t)=>{const s=ln(e);return s?.member===t?h(s.object):void 0},Ms=(e,t)=>r.isIdentifier(e)&&O(e)?.compilerNode===t.compilerNode,qn=(e,t,s,n=1)=>{const i=_d(e,s);if(i!==void 0)return Ms(i,t);const o=r.isIdentifier(e)?O(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&te(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||Z(l)&&Ms(h(l.getInitializer()),t))}const a=Z(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&qn(a,t,s,n-1)},Ct=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Ct(t.getWhenTrue()),...Ct(t.getWhenFalse())]:[t]},Kd=(e,t,s)=>{const n=[],i=s===void 0?void 0:Rd(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||!Fd.has(a))continue;const l=Ct(c).filter(f=>i===void 0?H(f)&&!Ji(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&qn(c,s.parameter,a),g=l.every(p=>gd(t.call,p));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Bd=(e,t,s)=>{const n=Dd(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=Md(i,n);if(o.length===0)return[];const a=v(e),c=rd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Kd(u,l,c))},zd=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=C(e,t,(c,l)=>Bd(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Rt(o,s).map(c=>Gi(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},$d=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Vd=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Ud=e=>{const t=M(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?Vd(t.getInitializer()):void 0},qd=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!$d.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Ud(n):void 0;return{callee:s,scope:v(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Wd=(e,t)=>C(e,t,qd),Hd=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),jd=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Gd=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=M(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Wn=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Hn=(e,t)=>e===t||e.startsWith(`${t}.`),jn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},_s=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)},Gn=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>_s(s));return r.isIdentifier(e)&&_s(e)&&t.push(e),t},Yd=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Qd=e=>{const t=Wn(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Xd=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Qd(e),i=new Set,o=a=>jn(a).some(c=>n.some(l=>Hn(c.getText(),l)))?!0:Gn(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Yd(a))i.add(l)}return{names:i,prefixes:n}},Jd=(e,t)=>jn(e).some(s=>t.prefixes.some(n=>Hn(s.getText(),n)))?!0:Gn(e).some(s=>t.names.has(s.getText())),Zd=e=>{const t=Ui(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},eu=(e,t,s)=>{const n=Wn(e,0);if(n===void 0)return[];const i=Xd(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!dn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Jd(u,i))continue;const f=Zd(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:v(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},tu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=jd(n),o=i===void 0?void 0:Hd.get(i);if(o===void 0)continue;const a=Gd(n,o);a!==void 0&&s.push(...eu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},su=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tu(i,I(t,n)))}return s},Ks={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Bs=new Set(["account","credential","member","passkey","session","user"]),nu=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),iu=e=>{const s=nu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Bs.has(s)||Bs.has(n)},ru=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ou=(e,t)=>{const{objects:s,opaque:n}=_t(e,t);return ha(s).some(i=>ru(i))?!0:n?void 0:!1},au=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!M(t,"captcha"),usesRateLimit:!!M(t,"rateLimit")}},cu=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Fe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},lu=e=>{const t=cu(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=au(t);return{...Fe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ks?{...Fe,[Ks[s]]:!0}:Fe},du=e=>{const t={...Fe};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=lu(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},uu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),fu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!uu.has(t.getName()))return!1;const s=t.getExpression();if(!L(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:iu(i.getLiteralText())},gu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),zs=new Set(["queues","scheduler","topics","workflows"]),pu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!gu.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&zs.has(s.getName())&&Zi(s.getExpression()))return!0;s=s.getExpression()}const n=Ft(s);return n?.length===1&&zs.has(n[0]??"")},mu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return L(s)},Yn=new Set(["generateObject","generateText","streamObject","streamText"]),hu=e=>{const t=b(e.getExpression());return t!==void 0&&Yn.has(t)},vu=e=>{const t=b(e.getExpression());if(t===void 0||!Yn.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!M(s,"maxOutputTokens")},Eu=new Set(["log","span","trace"]),xu=new Set(["ai"]),Su=new Set(["email","mail"]),Au=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),dt=(e,t)=>[...t].some(s=>Ve(e,s).length>0),Qn=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),yu=new Set(["every","filter","flatMap","forEach","map","some"]),bu=new Set(["all","allSettled","race"]),Xn=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(yu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&bu.has(n))return t},Nu=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(Qn.has(t.getKind())){const s=Xn(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Pu=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Qn.has(t.getKind())){if(t=Xn(t),t===void 0)return!1;continue}t=t.getParent()}return!1},wu=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(p=>{const x=p.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(p.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Iu=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}},Cu=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}},Tu=e=>{let t=!1,s=!0;for(const n of[...Au].flatMap(i=>Ve(e,i))){const i=Cu(n);i&&(t=!0,!Nu(i)&&!Iu(i)&&!wu(i)&&!Pu(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ou=e=>e.getDescendantsOfKind(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"}),$s="lunora-advisor-exempt",ku=/^[\s*/]+/u,Ru=/[\w-]/u,Fu=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
2
2
  `);for(const n of s.split(`
3
3
  `)){const i=n.replace(ku,"");if(!i.startsWith($s))continue;const o=i.slice($s.length);if(Ru.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Lu=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=M(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Du=(e,t)=>{const s=Lu(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)},Mu=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(fu(l)&&(o=!0),pu(l)&&(t=!0),mu(l)&&(i=!0),hu(l)&&(s=!0),vu(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Tu(e);return{callsMail:dt(e,Su),emitsEvent:dt(e,Eu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||dt(e,xu),throwsBareError:Ou(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},_u=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=Q(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?du(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Du(e,s);return{...o?Mu(o):{},...Fu(e),...i,analyzableBody:o!==void 0,exportName:$(e)??e.getName(),file:t,hasEmailArg:ou(s,n.receiver),kind:n.kind,visibility:n.visibility}},Ku=(e,t)=>{const s=[];for(const n of j(e)){const i=_u(n,t);i&&s.push(i)}return s},Bu=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ku(i,I(t,n)))}return s},zu=new Set(["dbRateLimit","rateLimit"]),$u=e=>r.isArrowFunction(e)?e.getBody():e,Vu=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Jn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Zn=(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)})},Uu=(e,t)=>H(e)||t!==void 0&&Zn(e,t).some(s=>Jn(s)),qu=(e,t)=>t===void 0?se(e):Zn(e,t).some(s=>!Jn(s)),Wu=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!zu.has(s))return;const n=T(cn(e.getArguments()[2]),"key");if(!n)return;const i=$u(n),o=Vu(n);if(!(!Uu(i,o)||qu(i,o)))return{callee:s,scope:v(e),file:t,limitName:an(e),line:e.getStartLineNumber()}},Hu=(e,t)=>C(e,t,Wu),ju=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Gu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ju.has(t.getName()))return;const s=t.getExpression();if(L(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&L(s.getExpression()))return s.getName()},Yu=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&L(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Qu=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},ei=(e,t=!1)=>{const s=Qu(e);if(r.isIdentifier(s)){if(t)return;const n=W(s);return n===void 0?void 0:ei(n,!0)}if(r.isCallExpression(s))return Gu(s)??Yu(s)},Xu=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(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},Ju=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Q(s);if(n?.kind!=="query")return[];const i=kn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&sr(n.receiver,"output"),a=n.receiver!==void 0&&hn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Xu(i)){const f=ei(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:$(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Zu=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...Ju(a,o))}return s},ef=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},tf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Q(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=En(o);if(a===void 0)continue;const c=ef(T(a.options,"with"));c.length!==0&&i.push({exportName:$(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},sf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...tf(a,o))}return s},z=(e,t)=>`${e}:${t}`,Vs=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},nf=(e,t)=>[...J(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Vs(s,n,s.getName(),s.isExported()):void 0),...J(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Vs(i,n,s.getName(),i.isExported()):void 0})],rf=(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=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(z(c,a))},of=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,af=(e,t)=>{const s=new Map(e.map(n=>[z(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(z(i.file,i.name))?.set(of(n),{fields:n.fields,method:n.method,table:n.table})}return s},cf=(e,t,s)=>e.node.getDescendantsOfKind(d.CallExpression).map(n=>rf(n,t,s)).filter(n=>n!==void 0),lf=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(z(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(z(o.file,o.name))?.push(a)}},df=(e,t,s)=>{const n=new Map(e.map(a=>[z(a.file,a.name),a])),i=new Map(e.map(a=>[`${Dt(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[z(a.file,a.name),cf(a,n,t)]));return lf(s,n,i,o),o},uf=(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},ff=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(z(i.file,i.name))??[])uf(t.get(z(i.file,i.name)),t.get(z(o.file,o.name)))&&(n=!0)}},gf=(e,t,s,n)=>{const i=nf(e,t),o=af(i,s);return ff(i,o,df(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(z(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ke=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ke(e.getLeft()),s=Ke(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},pf=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&&Ke(t)!==void 0},mf=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()}},hf=(e,t,s)=>yr(e)?!qi(s)&&br(mf(t)):!0,vf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(pf(o))continue;const a=Ke(o);if(a===void 0)continue;const c=Sr(a);if(c===void 0||!hf(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:Ar(a)}))}return s},Ef=(e,t)=>{const s=[];for(const n of A(t,{includeSkipped:!0})){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vf(i,I(t,n)))}return s},xf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Q(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=En(o);if(a===void 0)continue;const c=T(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&H(c);!l&&!u||i.push({exportName:$(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Sf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...xf(a,o))}return s},Af=new Set(["query","unsafe"]),yf=e=>!r.isPropertyAccessExpression(e)||!Af.has(e.getName())?!1:q(e.getExpression(),["sql"]),bf=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Nf=(e,t)=>{if(!yf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!bf(s)))return{file:t,line:s.getStartLineNumber(),scope:v(e)}},Pf=(e,t)=>C(e,t,Nf),wf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],If=e=>{for(const[t,s]of wf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Cf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=If(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Tf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Of=(e,t,s=[])=>{const n=We(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Tf,requireUnmodifiedReach:!0});return Rt(n,s)},kf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Rf=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Ff=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=Rf(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Lf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=kf.get(t);return s===void 0?void 0:gn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Df=(e,t)=>{const s=Lf(e.getExpression());if(s!==void 0)return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...Ff(e.getArguments()[s.optionsIndex])}},Mf=(e,t)=>C(e,t,Df),_f=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),ti=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:_f(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>ee(i)||s(i));if(!(n===void 0||ee(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},zt=(e,t)=>S(e.getFirstAncestor(s=>S(s,t)||ee(s)),t),Kf=(e,t)=>S(e,t)||e.getFirstAncestor(s=>S(s,t))!==void 0,si=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return S(e,t)||zt(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=ti(e);return s!==void 0&&!Kf(s,t)}return!1},ni=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)],Bf=e=>ni(e).some(t=>si(t,e)),zf=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},$f=e=>ni(e).some(t=>si(t,e)||r.isBreakStatement(t)&&S(ti(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>zf(t)&&zt(t,e)),Vf=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>zt(t,e)),Uf=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),qf=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",ut=(e,t)=>{const s=Uf(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||$f(e)||Vf(e))return;const i=v(e);if(!(i.kind==="module"&&e.getFirstAncestor(ee)!==void 0))return{file:t,kind:qf(e),line:e.getStartLineNumber(),scope:i}},Wf=(e,t)=>[...J(e,t,d.WhileStatement,ut),...J(e,t,d.ForStatement,ut),...J(e,t,d.DoStatement,ut)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),Hf=new Set(["when","where"]),ft=new Set(["definePolicy","defineShape"]),jf=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return ft.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 ft.has(i)?i:void 0}const s=t.getText();return ft.has(s)?s:void 0},Gf=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,ii=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Gf(e))return"empty-object";if(r.isParenthesizedExpression(e))return ii(e.getExpression())}},$t=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),Yf=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>$t(t)===e),ri=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>$t(t)===e),Qf=e=>{const t=Yf(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||ri(e).length>0},Xf=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>$t(t)===e),Tt=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()==="",Jf=(e,t)=>Tt(e)||Tt(t),Zf=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Us=e=>!Tt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),eg=(e,t,s)=>{const n=Zf.get(e);if(n!==void 0)return Jf(t,s)?n==="positive"?"negative":"positive":Us(t)||Us(s)?void 0:n},he=e=>{if(r.isParenthesizedExpression(e))return he(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=eg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=he(e.getLeft()),i=he(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},qs=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}}},tg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},sg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,ng=e=>{const t=[];for(const s of ri(e)){const n=he(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Xf(e)){const n=he(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?qs(s.getThenStatement()):qs(s.getElseStatement())??tg(s);i!==void 0&&t.push(sg(i))}return t},ig=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},rg=(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)||!Hf.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&Qf(a))for(const c of ng(a)){const l=ii(c);l!==void 0&&i.push({exportName:ig(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},og=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=jf(n);i!==void 0&&s.push(...rg(n,i,t))}return s},ag=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...og(i,I(t,n)))}return s},cg=new Set(["query","upsert","upsertNow"]),lg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(cg.has(t))return q(e.getExpression(),["vectors"])?t:void 0},dg=(e,t)=>{const s=lg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=T(n,"namespace");if(!(!i||!H(i)||se(i)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},ug=(e,t)=>C(e,t,dg),fg=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:p,workflows:x}=s;return _i({adminRoutes:qo(e,t),aiRawRuns:Zo(e,t),aiToolSideEffects:da(e,t),argumentDerivedFetches:ga(e,t),argumentValidators:ka(e,t),authApiCalls:ar(e,t),authConfigs:$a(e,t),browserUrlAccesses:Wa(e,t),callEdges:n.callEdges,configCalls:Za(e,t),containerKeyAccesses:tc(e,t),containerOverrides:ac(e,t),containers:i,countReads:fc(e,t,f.tables),cronTargets:o.flatMap(k=>k.functionPath===void 0?[]:[k.functionPath]),exportSinks:hc(e,t),staleMigrationImports:Cf(e,t),failOpenGuards:Ac(e,t),flagReads:wc(e,t),flagSecurityDefaults:Oc(e,t),geoIndexUsages:Fc(e,t),httpActionGuards:Wc(e,t),httpHeaderWrites:tl(e,t),hyperdriveCalls:cr(e,t),identityClaimReads:fl(e,t),imageDeliveryUrlAccesses:pl(e,t),inserts:n.inserts,kvKeyAccesses:hl(e,t,a),mailRecipientAccesses:Al(e,t),maskProcedures:lr(e,t),maskStrategies:Nl(e,t),mutatorWrites:Ol(e,t),nondeterministicCalls:pr(e,t),normalizeIdAuthorizations:Wl(e,t),notifyCalls:hr(e,t),notifyConfig:mr(e,t),mutators:l,ownerFieldWrites:zd(e,t,a,l),unrestrictedWhereBranches:ag(e,t),paymentWebhooks:Wd(e,t),privilegedDispatches:su(e,t),procedureProtections:Bu(e,t),queries:n.queries,queues:u,r2sqlCalls:vr(e,t),ratelimitKeySelectors:Hu(e,t),rawRowReturns:Zu(e,t),relationLoads:sf(e,t),rlsProcedures:Er(e,t),schema:f,secretLiterals:Ef(e,t),modules:c,shapes:g,softDeleteReads:Sf(e,t),sqlInterpolations:Pf(e,t),storageKeyAccesses:Of(e,t,a),storageUploads:Mf(e,t),tableWrites:n.tableWrites,rowEffects:gf(e,t,n.tableWrites,n.callEdges),unboundedLoops:Wf(e,t),vectorNamespaceAccesses:ug(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:p})},gg=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"}),pg=(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=>gg(i))]},mg=()=>({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"}),hg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",Ws={error:"ERROR",info:"INFO",warn:"WARN"},Hs={ERROR:2,INFO:0,WARN:1},vg=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"}),Eg=(e,t)=>{const{advisor:s}=vn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(Ws,n)?Ws[n]:void 0;return i===void 0?[...t,vg(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=>hg(o)||Hs[o.level]>=Hs[i])},xg=(e,t)=>{const{advisor:s}=vn(e),n=pg(t,s?.accept??[]);return Eg(e,s?.acceptUnreadable===!0?[...n,mg()]:n)},Sg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Ag="crons",yg=wr.replace(/\.ts$/u,""),oe=(e,t)=>`${Dt(e)}:${t}`,gt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},bg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Sg[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,...gt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...gt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...gt("workflow",t.workflow,"workflow name")}))],Ng=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Pg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Ng(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},wg=e=>bg(e).flatMap(t=>Pg(t)),Ig=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:Ag,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Cg=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),ge=(e,t)=>t===void 0?e:{...e,module:t},Tg=e=>{const t=new Map,s=new Map,n=Cg(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(oe(c.file,c.exportName),l)};for(const c of e.functions){const l=oe(c.filePath,c.exportName),u=[...xr(c.filePath),c.exportName].join(".");o(ge({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Ce(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=oe(c.filePath,c.exportName);o(ge({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Ce(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(ge({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(ge({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Ce(e.modules,c.filePath)),oe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(ge({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Ce(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},oe(yg,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}},Og=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,kg=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(oe(e.file,e.exportName))??{reason:Og(e.exportName)},Rg=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=kg(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`}},pt=e=>`${e.from}|${e.kind}|${e.to}`,Fg=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Lg=e=>{const{nodes:t,sites:s}=Tg(e),n=new Map,i=new Map;for(const o of[...Ig(e),...wg(e)]){const a=Rg(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(pt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Fg(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>pt(o).localeCompare(pt(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}},Dg=e=>`${Tr}export const architecture = ${Cr(e,"Record<string, unknown>")};
4
4
  `,js=(e,t="api")=>{const s=new Map;for(const n of e){const i=Dt(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 U("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})}}},Mg=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Sn(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=>An(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?[]:kr)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)},_g=(e,t,s={})=>{if(t===void 0)return;const n=Mg(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
@@ -0,0 +1 @@
1
+ import{LunoraError as C}from"@lunora/errors";import{Node as i,SyntaxKind as B}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as V}from"node:module";import{join as _}from"node:path";import{fileURLToPath as q}from"node:url";import{createJiti as J}from"jiti";import{findObjectProperty as u}from"./isTestPath-B81lOULB.mjs";import{r as U,p as K}from"./parse-validator-IDBKIT7M.mjs";import{R as W}from"./reserved-words-CW1QFbTd.mjs";import{a as w}from"./project-config-file-BV7RR-l6.mjs";const Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,G=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},X=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:X(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=G(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},H=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Q=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},Y=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Q(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:H(e.shardMode),vectorIndexes:[]}},ee=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>Y(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},te=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},ne=e=>{const t=te(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},re=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},se=(e,t)=>{const n=ne(e);if(n)try{const s=J(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=V(_(t,"noop.cjs"))(s.startsWith("file:")?q(s):s),o=re(r,n);return typeof o!="object"||o===null?void 0:ee(o)}catch{return}},ie=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},y=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},N=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},v=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},P=e=>e&&ie.has(e)?e:void 0,E=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",oe=(e,t)=>{const n=v(e,t);return n!==void 0&&n.length>0?n:void 0},j=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const d=l.getArguments()[0];if(!d||!i.isStringLiteral(d))throw c(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=d.getLiteralText();if(!s.has(m))throw c(d,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},ae=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,le=/^(?:sqlite_|_cf_|__)/u,ce=/__(?:agg|rank|geo|fts)_/u,de=e=>le.test(e)||ce.test(e),fe=new Set(["cascade","restrict","set null"]),ue=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,k=(e,t)=>{if(ue.has(e))throw c(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(W.has(e))throw c(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw c(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(de(e))throw c(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},pe=e=>e&&fe.has(e)?e:void 0,ge=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},me=(e,t,n)=>{const s=i.isPropertyAssignment(e)?e.getInitializer():void 0;if(!s||!i.isObjectLiteralExpression(s))throw c(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[r,o,a]=["table","from","to"].map(l=>f(s,l));if(r===void 0||o===void 0||a===void 0)throw c(s,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(o===a)throw c(s,`relation \`through\` has \`from\` and \`to\` both set to "${o}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:o,table:r,to:a}}},he=(e,t,n,s)=>{const r=s&&i.isObjectLiteralExpression(s)?s:void 0,o=e==="many"?r?.getProperty("through"):void 0;return o?me(o,t,n):{field:(r&&f(r,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&r?pe(f(r,"onDelete")):void 0,references:(r&&f(r,"references"))??"_id",table:n}},be=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw c(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();return he(s,w(e),a,o)},xe=e=>{const t=ge(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=be(s);r&&n.push(r)}return n},ye=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw c(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ve=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw c(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},Ee=e=>{const[t,n,s]=e,r=ve(s),o=E(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const d of a)if(!i.isStringLiteral(d))throw c(d,`index "${o}" lists a non-literal field (${JSON.stringify(d.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(d=>i.isStringLiteral(d));for(const d of l)ye(d,d.getLiteralText(),o);return{fields:l.map(d=>d.getLiteralText()),name:o,unique:r}},Ie=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=v(n,"filterFields"),o=f(n,"language"),a=N(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:E(t),staged:a,strategy:l}},we=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=y(n,"precision")),{field:s,name:E(t),precision:r}},ke=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=y(n,"after")),{after:r,field:s}},Se=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Te=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Se(l)).filter(l=>l!==void 0))}r=v(n,"partitionBy")}return{name:E(t),partitionBy:r,sortBy:s}},Oe=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:y(s,"dimensions"),field:r,metadata:v(s,"metadata"),metric:P(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},_e=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},A=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw c(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw c(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Ae=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:oe(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Le=(e,t,n,s)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(we(n));break}case"global":{e.shardMode="global",e.globalBackend=_e(n);break}case"index":{e.indexes.push(Ee(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Te(n));break}case"relations":{const r=n[0];r&&e.relations.push(...xe(r));break}case"searchIndex":{e.searchIndexes.push(Ie(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:A(n[0],"deletedAt")};break}case"source":{e.externalSource=Ae(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(A(n[0],"updatedAt"));break}case"ttl":{e.ttl=ke(n);break}case"vectorize":{const r=Oe(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Ne=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw c(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Pe=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw c(e,ae(t))},je=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw c(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw c(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw c(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},D=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))Le(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=K(l);else if(l)throw c(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=je(e,s,n),Ne(e,t,n.searchIndexes),Pe(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},z=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=U(r.getExpression());a!==void 0&&!s.has(a)&&z(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=w(r);if(k(a,r.getNameNode()),n.has(a))throw c(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(D(o,a))}}return t},$e=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},De=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:y(s,"dimensions"),metric:P(f(s,"metric")),name:o,table:$e(s)}},F=e=>{const t=[];for(const n of e.getProperties()){const s=De(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,ze=(e,t)=>{if(!$.test(e))throw c(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},h=(e,t,n)=>n.has(e)?S(t,e):e,x=(e,t)=>{const n=s=>s===void 0?void 0:x(s,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(s=>x(s,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([s,r])=>[s,x(r,t)]))}}},Fe=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,shape:Object.fromEntries(Object.entries(e.shape).map(([o,a])=>[o,x(a,l=>h(l,t,n))])),relations:e.relations.map(o=>{const a=h(o.table,t,n);return o.through===void 0?{...o,table:a}:{...o,table:a,through:{...o.through,table:h(o.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:h(o.table,t,n)}))}},Me=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Re=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Ce=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Be=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Ve=(e,t)=>{const n=Me(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Be(n);return s?b(s,t.getName()):void 0}return n}},qe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,Re(t))return t;const s=Ce(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Ve(a,t)}},Je=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ue=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=w(r);k(a,r.getNameNode()),s.push(D(o,a))}return s},Ke=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:F(n)},M=(e,t,n,s,r)=>{ze(e,s);const o=new Set(t.map(d=>d.name)),a=t.map(d=>Fe(d,e,o,r)),l=n.map(d=>({...d,name:S(e,d.name),table:h(d.table,e,o)}));return{tables:a,vectorIndexes:l}},We=(e,t,n)=>M(e,Ue(n),Ke(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ze=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=qe(n);if(!s){if(t!==void 0){const o=se(n,t);if(o){for(const a of o.bareTables)k(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Je(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return We(r.key,r.keyNode,r.options)},Ge=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Xe=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ge(e)){const a=Ze(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw c(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},He=new Set(["eu","fedramp","us"]),Qe=e=>j(e,"jurisdiction","jurisdiction",He,'"eu", "us", or "fedramp"'),Ye=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&N(r,"pinAuth")===!0}t=s}},et=new Set(["required"]),tt=e=>j(e,"rls","rls mode",et,'"required"'),nt=e=>{if(!i.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(!s||!i.isCallExpression(s))return;const r=s.getExpression(),o=s.getArguments()[1],a=o&&i.isObjectLiteralExpression(o)?f(o,"on"):void 0;if(!i.isIdentifier(r)||r.getText()!=="defineAggregateIndex"||a===void 0)return;t.add(a)}return t},rt=(e,t)=>{if(t===void 0)return;const n=nt(t);for(const s of e)(n===void 0||n.has(s.name))&&(s.aggregateIndexed=!0)},mt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(B.CallExpression).find(p=>{const O=p.getExpression();return i.isIdentifier(O)&&O.getText()==="defineSchema"});if(!r)throw new C("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw c(r,"defineSchema() expects an object literal");const a=z(o),l=r.getArguments()[1],d=l&&i.isObjectLiteralExpression(l)?F(l):[],m=Xe(r,a,n);rt(a,r.getArguments()[2]);const T=[...a.flatMap(p=>p.vectorIndexes),...d,...m],R=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),I=T.find(p=>R.has(p.table));if(I)throw c(r,Z(I.table,I.name));return{jurisdiction:Qe(r),...Ye(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:tt(r),tables:a,vectorIndexes:T}};export{mt as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.303",
3
+ "version": "1.0.0-alpha.304",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,8 +46,8 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.216",
50
- "@lunora/agent": "1.0.0-alpha.206",
49
+ "@lunora/advisor": "1.0.0-alpha.217",
50
+ "@lunora/agent": "1.0.0-alpha.207",
51
51
  "@lunora/container": "1.0.0-alpha.75",
52
52
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
53
53
  "@lunora/platform": "1.0.0-alpha.64",
@@ -1 +0,0 @@
1
- import{LunoraError as C}from"@lunora/errors";import{Node as i,SyntaxKind as B}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as V}from"node:module";import{join as _}from"node:path";import{fileURLToPath as q}from"node:url";import{createJiti as J}from"jiti";import{findObjectProperty as u}from"./isTestPath-B81lOULB.mjs";import{r as U,p as K}from"./parse-validator-IDBKIT7M.mjs";import{R as W}from"./reserved-words-CW1QFbTd.mjs";import{a as w}from"./project-config-file-BV7RR-l6.mjs";const Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,G=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},X=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:X(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=G(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},H=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Q=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},Y=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Q(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:H(e.shardMode),vectorIndexes:[]}},ee=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>Y(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},te=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},ne=e=>{const t=te(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},re=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},se=(e,t)=>{const n=ne(e);if(n)try{const s=J(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=V(_(t,"noop.cjs"))(s.startsWith("file:")?q(s):s),o=re(r,n);return typeof o!="object"||o===null?void 0:ee(o)}catch{return}},ie=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},y=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},N=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},v=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},P=e=>e&&ie.has(e)?e:void 0,E=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",oe=(e,t)=>{const n=v(e,t);return n!==void 0&&n.length>0?n:void 0},j=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const d=l.getArguments()[0];if(!d||!i.isStringLiteral(d))throw c(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=d.getLiteralText();if(!s.has(m))throw c(d,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},ae=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,le=/^(?:sqlite_|_cf_|__)/u,ce=/__(?:agg|rank|geo|fts)_/u,de=e=>le.test(e)||ce.test(e),fe=new Set(["cascade","restrict","set null"]),ue=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,k=(e,t)=>{if(ue.has(e))throw c(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(W.has(e))throw c(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw c(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(de(e))throw c(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},pe=e=>e&&fe.has(e)?e:void 0,ge=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},me=(e,t,n)=>{const s=i.isPropertyAssignment(e)?e.getInitializer():void 0;if(!s||!i.isObjectLiteralExpression(s))throw c(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[r,o,a]=["table","from","to"].map(l=>f(s,l));if(r===void 0||o===void 0||a===void 0)throw c(s,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(o===a)throw c(s,`relation \`through\` has \`from\` and \`to\` both set to "${o}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:o,table:r,to:a}}},he=(e,t,n,s)=>{const r=s&&i.isObjectLiteralExpression(s)?s:void 0,o=e==="many"?r?.getProperty("through"):void 0;return o?me(o,t,n):{field:(r&&f(r,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&r?pe(f(r,"onDelete")):void 0,references:(r&&f(r,"references"))??"_id",table:n}},be=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw c(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();return he(s,w(e),a,o)},xe=e=>{const t=ge(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=be(s);r&&n.push(r)}return n},ye=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw c(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ve=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw c(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},Ee=e=>{const[t,n,s]=e,r=ve(s),o=E(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const d of a)if(!i.isStringLiteral(d))throw c(d,`index "${o}" lists a non-literal field (${JSON.stringify(d.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(d=>i.isStringLiteral(d));for(const d of l)ye(d,d.getLiteralText(),o);return{fields:l.map(d=>d.getLiteralText()),name:o,unique:r}},Ie=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=v(n,"filterFields"),o=f(n,"language"),a=N(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:E(t),staged:a,strategy:l}},we=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=y(n,"precision")),{field:s,name:E(t),precision:r}},ke=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=y(n,"after")),{after:r,field:s}},Se=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Te=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Se(l)).filter(l=>l!==void 0))}r=v(n,"partitionBy")}return{name:E(t),partitionBy:r,sortBy:s}},Oe=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:y(s,"dimensions"),field:r,metadata:v(s,"metadata"),metric:P(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},_e=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},A=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw c(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw c(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Ae=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:oe(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Le=(e,t,n,s)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(we(n));break}case"global":{e.shardMode="global",e.globalBackend=_e(n);break}case"index":{e.indexes.push(Ee(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Te(n));break}case"relations":{const r=n[0];r&&e.relations.push(...xe(r));break}case"searchIndex":{e.searchIndexes.push(Ie(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:A(n[0],"deletedAt")};break}case"source":{e.externalSource=Ae(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(A(n[0],"updatedAt"));break}case"ttl":{e.ttl=ke(n);break}case"vectorize":{const r=Oe(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Ne=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw c(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Pe=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw c(e,ae(t))},je=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw c(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw c(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw c(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},D=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))Le(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=K(l);else if(l)throw c(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=je(e,s,n),Ne(e,t,n.searchIndexes),Pe(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},z=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=U(r.getExpression());a!==void 0&&!s.has(a)&&z(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=w(r);if(k(a,r.getNameNode()),n.has(a))throw c(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(D(o,a))}}return t},$e=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},De=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:y(s,"dimensions"),metric:P(f(s,"metric")),name:o,table:$e(s)}},F=e=>{const t=[];for(const n of e.getProperties()){const s=De(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,ze=(e,t)=>{if(!$.test(e))throw c(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},h=(e,t,n)=>n.has(e)?S(t,e):e,x=(e,t)=>{const n=s=>s===void 0?void 0:x(s,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(s=>x(s,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([s,r])=>[s,x(r,t)]))}}},Fe=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,shape:Object.fromEntries(Object.entries(e.shape).map(([o,a])=>[o,x(a,l=>h(l,t,n))])),relations:e.relations.map(o=>{const a=h(o.table,t,n);return o.through===void 0?{...o,table:a}:{...o,table:a,through:{...o.through,table:h(o.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:h(o.table,t,n)}))}},Me=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Re=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Ce=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Be=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Ve=(e,t)=>{const n=Me(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Be(n);return s?b(s,t.getName()):void 0}return n}},qe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,Re(t))return t;const s=Ce(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Ve(a,t)}},Je=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ue=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=w(r);k(a,r.getNameNode()),s.push(D(o,a))}return s},Ke=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:F(n)},M=(e,t,n,s,r)=>{ze(e,s);const o=new Set(t.map(d=>d.name)),a=t.map(d=>Fe(d,e,o,r)),l=n.map(d=>({...d,name:S(e,d.name),table:h(d.table,e,o)}));return{tables:a,vectorIndexes:l}},We=(e,t,n)=>M(e,Ue(n),Ke(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ze=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=qe(n);if(!s){if(t!==void 0){const o=se(n,t);if(o){for(const a of o.bareTables)k(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Je(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return We(r.key,r.keyNode,r.options)},Ge=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Xe=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ge(e)){const a=Ze(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw c(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},He=new Set(["eu","fedramp","us"]),Qe=e=>j(e,"jurisdiction","jurisdiction",He,'"eu", "us", or "fedramp"'),Ye=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&N(r,"pinAuth")===!0}t=s}},et=new Set(["required"]),tt=e=>j(e,"rls","rls mode",et,'"required"'),nt=e=>{if(!i.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(!s||!i.isCallExpression(s))return;const r=s.getExpression(),o=s.getArguments()[1],a=o&&i.isObjectLiteralExpression(o)?f(o,"on"):void 0;if(!i.isIdentifier(r)||r.getText()!=="defineAggregateIndex"||a===void 0)return;t.add(a)}return t},rt=(e,t)=>{if(t===void 0)return;const n=nt(t);for(const s of e)(n===void 0||n.has(s.name))&&(s.aggregateIndexed=!0)},mt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(B.CallExpression).find(p=>{const O=p.getExpression();return i.isIdentifier(O)&&O.getText()==="defineSchema"});if(!r)throw new C("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw c(r,"defineSchema() expects an object literal");const a=z(o),l=r.getArguments()[1],d=l&&i.isObjectLiteralExpression(l)?F(l):[],m=Xe(r,a,n);rt(a,r.getArguments()[2]);const T=[...a.flatMap(p=>p.vectorIndexes),...d,...m],R=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),I=T.find(p=>R.has(p.table));if(I)throw c(r,Z(I.table,I.name));return{jurisdiction:Qe(r),...Ye(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:tt(r),tables:a,vectorIndexes:T}};export{mt as default};