@lunora/codegen 1.0.0-alpha.422 → 1.0.0-alpha.423

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 i,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as d,lintSchema as f,toAdvisorContext as m}from"./packem_shared/formatAdvisories-Bue5tbp6.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as S}from"./packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs";import{COMPANION_BINDING as u,COMPANION_SERVICE_NAME as N}from"./packem_shared/COMPANION_BINDING-Da_v9XpC.mjs";import{CodegenDiagnosticError as g,diagnosticAt as C}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as I,discoverAgents as _}from"./packem_shared/AGENTS_FILENAME-C4tHmiZZ.mjs";import{isTestPath as L,listLunoraSourceFiles as M}from"./packem_shared/isTestPath-Uwb5a6Kq.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-CuqaLRa0.mjs";import{CONTAINERS_FILENAME as P,discoverContainers as D}from"./packem_shared/CONTAINERS_FILENAME-d3XTFcqV.mjs";import{default as b}from"./packem_shared/discoverCrons-bT8F5GyL.mjs";import{ENV_FILENAME as U}from"./packem_shared/ENV_FILENAME-DJ11PXN5.mjs";import{capabilitiesUsedBy as H,createTargetScope as j,foldCapabilitySignals as V,mayReadCapabilityContext as k,sourceCapabilitySignals as W}from"./packem_shared/capabilitiesUsedBy-BNvoiCu1.mjs";import{FLAGS_FILENAME as K,discoverFlags as Q}from"./packem_shared/FLAGS_FILENAME-DeSjFBWq.mjs";import{d as q}from"./packem_shared/index-M4HwQ4Jr.mjs";import{default as J}from"./packem_shared/discoverHttpRoutes-CesuhqW1.mjs";import{default as Z}from"./packem_shared/discoverHyperdriveCalls-BmAoOGGq.mjs";import{default as ee}from"./packem_shared/discoverInserts-DIarYU2P.mjs";import{d as oe}from"./packem_shared/index-CfSmiylg.mjs";import{default as ie}from"./packem_shared/discoverMigrations-C9AlZYFi.mjs";import{MUTATORS_FILENAME as se,discoverMutators as de}from"./packem_shared/MUTATORS_FILENAME-C0ZV0hh6.mjs";import{default as me}from"./packem_shared/discoverNondeterministicCalls-ZeZDQJAI.mjs";import{ALL_NOTIFY_CHANNELS as ne,NOTIFY_FILENAME as ce,discoverNotifyCalls as le,discoverNotifyChannels as Se,discoverNotifyConfig as xe}from"./packem_shared/ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs";import{default as Ae}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as Ne}from"./packem_shared/discoverQueries-DLZHcDzB.mjs";import{QUEUES_FILENAME as ge,discoverQueues as Ce}from"./packem_shared/QUEUES_FILENAME-DbuJZnrY.mjs";import{default as Ie}from"./packem_shared/discoverR2sqlCalls-D_HWbbky.mjs";import{default as Re}from"./packem_shared/discoverRlsProcedures-BbSdCvmA.mjs";import{default as Me}from"./packem_shared/discoverRlsMetadata-C0UkQkWd.mjs";import{discoverSandboxUsage as Fe}from"./packem_shared/discoverSandboxUsage-Dgvv6F_7.mjs";import{default as Pe}from"./packem_shared/discoverSchema-BLTROO8Z.mjs";import{companionServiceBinding as ye,readBoundServiceBindings as be,readDevServiceBindings as Ge,readServiceBindings as Ue,resolveServiceBindings as Be}from"./packem_shared/companionServiceBinding-BZjm486n.mjs";import{SHAPES_FILENAME as je,discoverShapes as Ve}from"./packem_shared/SHAPES_FILENAME-DTJKanSz.mjs";import{default as We}from"./packem_shared/discoverStorageRulesMetadata-DeBgC7po.mjs";import{WORKFLOWS_FILENAME as Ke,discoverWorkflows as Qe}from"./packem_shared/WORKFLOWS_FILENAME-7FysJsMZ.mjs";import{emitApp as qe}from"./packem_shared/emitApp-LFKtDRYu.mjs";import{isD1GlobalTable as Je,isHyperdriveGlobalTable as Xe}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as $e,emitOpenApi as er,emitOpenApiModule as rr}from"./packem_shared/buildOpenApiDocument-DmV_PBFv.mjs";import{OPENRPC_VERSION as tr,buildOpenRpcDocument as ir,emitOpenRpc as ar,emitOpenRpcModule as sr}from"./packem_shared/OPENRPC_VERSION-BOBo0zdQ.mjs";import{DEFAULT_TARGET as fr,platformMatrixIds as mr,readProjectTarget as pr,resolveCodegenTarget as nr}from"./packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs";import{b as lr,r as Sr,c as xr,d as Er}from"./packem_shared/project-config-file-DR7xrrNB.mjs";import{PROJECT_CONFIG_FILENAMES as ur,findCodegenConfigFile as Nr,findProjectConfigFile as vr,projectConfigCandidatePaths as gr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Or,runCodegen as Ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Ce8xsmI9.mjs";import{SchemaSnapshotParseError as Rr,buildSchemaSnapshot as Lr,evaluateSchemaDrift as Mr,indexReferencesOf as Tr,parseSchemaSnapshot as Fr}from"./packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs";import{default as Pr}from"./packem_shared/fingerprintSchemaSources-TN-rU6Of.mjs";import{schemaFromIr as yr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Gr,validatorIrToJsonSchema as Ur}from"./packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs";import{SDK_LANGUAGES as Hr,SDK_TARGETS as jr,generateSdk as Vr}from"./sdk/index.mjs";import{redact as Wr,secretKindOf as zr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Qr}from"./packem_shared/emitDrizzleSchema-BzOChEYW.mjs";import{e as qr}from"./packem_shared/server-Dfxmm5Zw.mjs";import{e as Jr}from"./packem_shared/shard-CWAD5mYy.mjs";import{G as Zr}from"./packem_shared/shared-Cn7dMQ_u.mjs";import{MESSAGE_SOLUTIONS as eo,findSolutionByMessage as ro}from"@lunora/errors";import{createCodegenProject as to,findTsconfig as io,refreshCodegenProject as ao,tsconfigFingerprint as so}from"./packem_shared/createCodegenProject-dC6oJh5H.mjs";import{t as mo,u as po,v as no}from"./packem_shared/shard-runtime-G5mZQjY0.mjs";import{emitApi as lo,emitCollections as So,emitInternalApi as xo}from"./packem_shared/emitApi-lwadq5G7.mjs";import{emitCrons as Ao,emitScheduler as uo,emitVectors as No,emitWranglerCronTriggers as vo}from"./packem_shared/emitCrons-CCRKs482.mjs";import{emitDataModel as Co}from"./packem_shared/emitDataModel-BvCZS4Yq.mjs";import{emitFunctions as Io}from"./packem_shared/emitFunctions-ppMX7E3X.mjs";import{isTypedSchema as Ro}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{I as AGENTS_FILENAME,ne as ALL_NOTIFY_CHANNELS,E as CAPABILITY_PROBES,u as COMPANION_BINDING,N as COMPANION_SERVICE_NAME,P as CONTAINERS_FILENAME,g as CodegenDiagnosticError,fr as DEFAULT_TARGET,U as ENV_FILENAME,K as FLAGS_FILENAME,Zr as GENERATED_HEADER,Gr as LUNORA_ERROR_CODES,eo as LUNORA_SOLUTION_RULES,se as MUTATORS_FILENAME,ce as NOTIFY_FILENAME,tr as OPENRPC_VERSION,ur as PROJECT_CONFIG_FILENAMES,ge as QUEUES_FILENAME,Or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Hr as SDK_LANGUAGES,jr as SDK_TARGETS,je as SHAPES_FILENAME,Rr as SchemaSnapshotParseError,e as VERSION,Ke as WORKFLOWS_FILENAME,$e as buildOpenApiDocument,ir as buildOpenRpcDocument,Lr as buildSchemaSnapshot,H as capabilitiesUsedBy,ye as companionServiceBinding,to as createCodegenProject,j as createTargetScope,n as describeErrorLevelFindings,C as diagnosticAt,i as diffSchemaSnapshots,_ as discoverAgents,F as discoverAuthApiCalls,D as discoverContainers,b as discoverCrons,Q as discoverFlags,q as discoverFunctions,J as discoverHttpRoutes,Z as discoverHyperdriveCalls,ee as discoverInserts,oe as discoverMaskProcedures,ie as discoverMigrations,de as discoverMutators,me as discoverNondeterministicCalls,le as discoverNotifyCalls,Se as discoverNotifyChannels,xe as discoverNotifyConfig,Ne as discoverQueries,Ce as discoverQueues,Ie as discoverR2sqlCalls,Me as discoverRlsMetadata,Re as discoverRlsProcedures,Fe as discoverSandboxUsage,Pe as discoverSchema,Ve as discoverShapes,We as discoverStorageRulesMetadata,Qe as discoverWorkflows,mo as emitAgents,lo as emitApi,qe as emitApp,So as emitCollections,po as emitContainers,Ao as emitCrons,Co as emitDataModel,Qr as emitDrizzleSchema,Io as emitFunctions,xo as emitInternalApi,er as emitOpenApi,rr as emitOpenApiModule,ar as emitOpenRpc,sr as emitOpenRpcModule,uo as emitScheduler,qr as emitServer,Jr as emitShard,No as emitVectors,no as emitWorkflows,vo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Mr as evaluateSchemaDrift,Nr as findCodegenConfigFile,ro as findLunoraSolution,vr as findProjectConfigFile,io as findTsconfig,Pr as fingerprintSchemaSources,V as foldCapabilitySignals,d as formatAdvisories,Vr as generateSdk,Tr as indexReferencesOf,Je as isD1GlobalTable,Xe as isHyperdriveGlobalTable,L as isTestPath,Ro as isTypedSchema,f as lintSchema,M as listLunoraSourceFiles,lr as loadProjectConfig,k as mayReadCapabilityContext,Fr as parseSchemaSnapshot,mr as platformMatrixIds,gr as projectConfigCandidatePaths,be as readBoundServiceBindings,Ge as readDevServiceBindings,Ae as readPackageDependencies,Sr as readProjectConfigLiterals,xr as readProjectLazyFunctions,Er as readProjectSecurityHeaders,pr as readProjectTarget,Ue as readServiceBindings,Wr as redact,ao as refreshCodegenProject,nr as resolveCodegenTarget,Be as resolveServiceBindings,Ir as runCodegen,yr as schemaFromIr,zr as secretKindOf,a as serializeSchemaSnapshot,S as sortedUniqueNames,W as sourceCapabilitySignals,m as toAdvisorContext,so as tsconfigFingerprint,Ur as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as i,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as d,lintSchema as f,toAdvisorContext as m}from"./packem_shared/formatAdvisories-Bue5tbp6.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as S}from"./packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs";import{COMPANION_BINDING as u,COMPANION_SERVICE_NAME as N}from"./packem_shared/COMPANION_BINDING-Da_v9XpC.mjs";import{CodegenDiagnosticError as g,diagnosticAt as C}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as I,discoverAgents as _}from"./packem_shared/AGENTS_FILENAME-C4tHmiZZ.mjs";import{isTestPath as L,listLunoraSourceFiles as M}from"./packem_shared/isTestPath-Uwb5a6Kq.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-CuqaLRa0.mjs";import{CONTAINERS_FILENAME as P,discoverContainers as D}from"./packem_shared/CONTAINERS_FILENAME-d3XTFcqV.mjs";import{default as b}from"./packem_shared/discoverCrons-BlL_VbIv.mjs";import{ENV_FILENAME as U}from"./packem_shared/ENV_FILENAME-DJ11PXN5.mjs";import{capabilitiesUsedBy as H,createTargetScope as j,foldCapabilitySignals as V,mayReadCapabilityContext as k,sourceCapabilitySignals as W}from"./packem_shared/capabilitiesUsedBy-BNvoiCu1.mjs";import{FLAGS_FILENAME as K,discoverFlags as Q}from"./packem_shared/FLAGS_FILENAME-DeSjFBWq.mjs";import{d as q}from"./packem_shared/index-M4HwQ4Jr.mjs";import{default as J}from"./packem_shared/discoverHttpRoutes-CesuhqW1.mjs";import{default as Z}from"./packem_shared/discoverHyperdriveCalls-BmAoOGGq.mjs";import{default as ee}from"./packem_shared/discoverInserts-DIarYU2P.mjs";import{d as oe}from"./packem_shared/index-CfSmiylg.mjs";import{default as ie}from"./packem_shared/discoverMigrations-C9AlZYFi.mjs";import{MUTATORS_FILENAME as se,discoverMutators as de}from"./packem_shared/MUTATORS_FILENAME-C0ZV0hh6.mjs";import{default as me}from"./packem_shared/discoverNondeterministicCalls-ZeZDQJAI.mjs";import{ALL_NOTIFY_CHANNELS as ne,NOTIFY_FILENAME as ce,discoverNotifyCalls as le,discoverNotifyChannels as Se,discoverNotifyConfig as xe}from"./packem_shared/ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs";import{default as Ae}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as Ne}from"./packem_shared/discoverQueries-DLZHcDzB.mjs";import{QUEUES_FILENAME as ge,discoverQueues as Ce}from"./packem_shared/QUEUES_FILENAME-DbuJZnrY.mjs";import{default as Ie}from"./packem_shared/discoverR2sqlCalls-D_HWbbky.mjs";import{default as Re}from"./packem_shared/discoverRlsProcedures-BbSdCvmA.mjs";import{default as Me}from"./packem_shared/discoverRlsMetadata-C0UkQkWd.mjs";import{discoverSandboxUsage as Fe}from"./packem_shared/discoverSandboxUsage-Dgvv6F_7.mjs";import{default as Pe}from"./packem_shared/discoverSchema-BLTROO8Z.mjs";import{companionServiceBinding as ye,readBoundServiceBindings as be,readDevServiceBindings as Ge,readServiceBindings as Ue,resolveServiceBindings as Be}from"./packem_shared/companionServiceBinding-BZjm486n.mjs";import{SHAPES_FILENAME as je,discoverShapes as Ve}from"./packem_shared/SHAPES_FILENAME-DTJKanSz.mjs";import{default as We}from"./packem_shared/discoverStorageRulesMetadata-DeBgC7po.mjs";import{WORKFLOWS_FILENAME as Ke,discoverWorkflows as Qe}from"./packem_shared/WORKFLOWS_FILENAME-7FysJsMZ.mjs";import{emitApp as qe}from"./packem_shared/emitApp-LFKtDRYu.mjs";import{isD1GlobalTable as Je,isHyperdriveGlobalTable as Xe}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as $e,emitOpenApi as er,emitOpenApiModule as rr}from"./packem_shared/buildOpenApiDocument-DmV_PBFv.mjs";import{OPENRPC_VERSION as tr,buildOpenRpcDocument as ir,emitOpenRpc as ar,emitOpenRpcModule as sr}from"./packem_shared/OPENRPC_VERSION-BOBo0zdQ.mjs";import{DEFAULT_TARGET as fr,platformMatrixIds as mr,readProjectTarget as pr,resolveCodegenTarget as nr}from"./packem_shared/DEFAULT_TARGET-5-_edM-R.mjs";import{b as lr,r as Sr,c as xr,d as Er}from"./packem_shared/project-config-file-DR7xrrNB.mjs";import{PROJECT_CONFIG_FILENAMES as ur,findCodegenConfigFile as Nr,findProjectConfigFile as vr,projectConfigCandidatePaths as gr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Or,runCodegen as Ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CdN_q7ja.mjs";import{SchemaSnapshotParseError as Rr,buildSchemaSnapshot as Lr,evaluateSchemaDrift as Mr,indexReferencesOf as Tr,parseSchemaSnapshot as Fr}from"./packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs";import{default as Pr}from"./packem_shared/fingerprintSchemaSources-TN-rU6Of.mjs";import{schemaFromIr as yr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Gr,validatorIrToJsonSchema as Ur}from"./packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs";import{SDK_LANGUAGES as Hr,SDK_TARGETS as jr,generateSdk as Vr}from"./sdk/index.mjs";import{redact as Wr,secretKindOf as zr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Qr}from"./packem_shared/emitDrizzleSchema-BzOChEYW.mjs";import{e as qr}from"./packem_shared/server-Dfxmm5Zw.mjs";import{e as Jr}from"./packem_shared/shard-CWAD5mYy.mjs";import{G as Zr}from"./packem_shared/shared-Cn7dMQ_u.mjs";import{MESSAGE_SOLUTIONS as eo,findSolutionByMessage as ro}from"@lunora/errors";import{createCodegenProject as to,findTsconfig as io,refreshCodegenProject as ao,tsconfigFingerprint as so}from"./packem_shared/createCodegenProject-dC6oJh5H.mjs";import{t as mo,u as po,v as no}from"./packem_shared/shard-runtime-G5mZQjY0.mjs";import{emitApi as lo,emitCollections as So,emitInternalApi as xo}from"./packem_shared/emitApi-lwadq5G7.mjs";import{emitCrons as Ao,emitScheduler as uo,emitVectors as No,emitWranglerCronTriggers as vo}from"./packem_shared/emitCrons-CCRKs482.mjs";import{emitDataModel as Co}from"./packem_shared/emitDataModel-BvCZS4Yq.mjs";import{emitFunctions as Io}from"./packem_shared/emitFunctions-ppMX7E3X.mjs";import{isTypedSchema as Ro}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{I as AGENTS_FILENAME,ne as ALL_NOTIFY_CHANNELS,E as CAPABILITY_PROBES,u as COMPANION_BINDING,N as COMPANION_SERVICE_NAME,P as CONTAINERS_FILENAME,g as CodegenDiagnosticError,fr as DEFAULT_TARGET,U as ENV_FILENAME,K as FLAGS_FILENAME,Zr as GENERATED_HEADER,Gr as LUNORA_ERROR_CODES,eo as LUNORA_SOLUTION_RULES,se as MUTATORS_FILENAME,ce as NOTIFY_FILENAME,tr as OPENRPC_VERSION,ur as PROJECT_CONFIG_FILENAMES,ge as QUEUES_FILENAME,Or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Hr as SDK_LANGUAGES,jr as SDK_TARGETS,je as SHAPES_FILENAME,Rr as SchemaSnapshotParseError,e as VERSION,Ke as WORKFLOWS_FILENAME,$e as buildOpenApiDocument,ir as buildOpenRpcDocument,Lr as buildSchemaSnapshot,H as capabilitiesUsedBy,ye as companionServiceBinding,to as createCodegenProject,j as createTargetScope,n as describeErrorLevelFindings,C as diagnosticAt,i as diffSchemaSnapshots,_ as discoverAgents,F as discoverAuthApiCalls,D as discoverContainers,b as discoverCrons,Q as discoverFlags,q as discoverFunctions,J as discoverHttpRoutes,Z as discoverHyperdriveCalls,ee as discoverInserts,oe as discoverMaskProcedures,ie as discoverMigrations,de as discoverMutators,me as discoverNondeterministicCalls,le as discoverNotifyCalls,Se as discoverNotifyChannels,xe as discoverNotifyConfig,Ne as discoverQueries,Ce as discoverQueues,Ie as discoverR2sqlCalls,Me as discoverRlsMetadata,Re as discoverRlsProcedures,Fe as discoverSandboxUsage,Pe as discoverSchema,Ve as discoverShapes,We as discoverStorageRulesMetadata,Qe as discoverWorkflows,mo as emitAgents,lo as emitApi,qe as emitApp,So as emitCollections,po as emitContainers,Ao as emitCrons,Co as emitDataModel,Qr as emitDrizzleSchema,Io as emitFunctions,xo as emitInternalApi,er as emitOpenApi,rr as emitOpenApiModule,ar as emitOpenRpc,sr as emitOpenRpcModule,uo as emitScheduler,qr as emitServer,Jr as emitShard,No as emitVectors,no as emitWorkflows,vo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Mr as evaluateSchemaDrift,Nr as findCodegenConfigFile,ro as findLunoraSolution,vr as findProjectConfigFile,io as findTsconfig,Pr as fingerprintSchemaSources,V as foldCapabilitySignals,d as formatAdvisories,Vr as generateSdk,Tr as indexReferencesOf,Je as isD1GlobalTable,Xe as isHyperdriveGlobalTable,L as isTestPath,Ro as isTypedSchema,f as lintSchema,M as listLunoraSourceFiles,lr as loadProjectConfig,k as mayReadCapabilityContext,Fr as parseSchemaSnapshot,mr as platformMatrixIds,gr as projectConfigCandidatePaths,be as readBoundServiceBindings,Ge as readDevServiceBindings,Ae as readPackageDependencies,Sr as readProjectConfigLiterals,xr as readProjectLazyFunctions,Er as readProjectSecurityHeaders,pr as readProjectTarget,Ue as readServiceBindings,Wr as redact,ao as refreshCodegenProject,nr as resolveCodegenTarget,Be as resolveServiceBindings,Ir as runCodegen,yr as schemaFromIr,zr as secretKindOf,a as serializeSchemaSnapshot,S as sortedUniqueNames,W as sourceCapabilitySignals,m as toAdvisorContext,so as tsconfigFingerprint,Ur as validatorIrToJsonSchema};
@@ -0,0 +1 @@
1
+ import{NODE_CAPABILITIES as g,CLOUDFLARE_CAPABILITIES as b,CELLD_CAPABILITIES as y}from"@lunora/platform";import{r as f}from"./project-config-file-DR7xrrNB.mjs";const m="cloudflare",S=t=>{const{target:e}=f(t);return e!==void 0&&e.length>0?e:void 0},I=(t,e)=>e??S(t)??m,z=(t,e)=>{if(e!==void 0)return[];const{target:r,unreadable:o}=f(t);return o!==!0||r!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${m}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${m}" }\`), or pass \`--target\`.`,target:m}]},k={max:1536,min:32},E=(t,e)=>{if(t!=="cloudflare")return[];const{max:r,min:o}=k,n=`${String(o)}-${String(r)}`;return e.filter(({dimensions:a})=>a!==void 0&&(!Number.isInteger(a)||a<o||a>r)).map(({dimensions:a,name:s})=>({level:"warn",message:`Vector index "${s}" declares ${String(a)} dimensions; Cloudflare Vectorize accepts ${n}, so creating a Vectorize index for it fails at deploy.`,name:"platform_vector_dimensions_out_of_range",remediation:`If a Vectorize index backs "${s}", use ${n} dimensions (many embedding models can truncate output to fit). Ignore this if another store, such as pgvector, backs it.`,target:t}))},u={celld:y,cloudflare:b,node:g},O=(t,e)=>{const r=u[t];if(r===void 0)return!0;const o=r.features[e]?.level;return o==="native"||o==="emulated"},W=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),w={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:"secrets"},_=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","cronWorkflowTriggers","crossShardFanout","deliveryAuthorization","durableStreams","globalTables","liveStreams","queues","relationGraph","secrets","secretValues","services","topics","typedWebSockets","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],h={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",deliveryAuthorization:"delivery authorization (`.deliveryAuthorization(...)` on the app builder)",cronTriggers:"declared cron triggers (`cronJobs()`)",cronWorkflowTriggers:"declared cron jobs that start a workflow (`cronJobs()` with a workflow target)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",liveContext:"the live publisher (`ctx.live`)",liveStreams:"live topic streams (`defineLiveStream`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",secretValues:"human-supplied secret values (`requestSecretTool`, held for one agent step)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",typedWebSockets:"typed WebSocket routes and rooms (`defineWebSocket` / `defineRoom`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},T=(t,e,r)=>({level:"error",message:`${e.name} does not support ${h[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:r}),x=(t,e)=>({level:"error",message:`${t.name} withholds live streams, so ctx.live is not available on the "${e}" target, but this app reads ctx.live.`,name:"platform_unsupported_feature",remediation:'Remove the ctx.live usage, or deploy to a target whose capability matrix marks "liveStreams" as native or emulated.',target:e}),D=t=>({level:"error",message:"This app declares defineLiveStream topics and enables delivery authorization. With delivery authorization on, the shard answers every /_lunora/live/* request with 501, so the live streams cannot be served.",name:"platform_live_stream_delivery_authorization",remediation:"Remove the defineLiveStream declarations, or remove the .deliveryAuthorization(...) call. Live streams and delivery authorization cannot be combined.",target:t}),P=t=>({level:"error",message:"This app declares defineWebSocket routes and enables delivery authorization. With delivery authorization on, the shard answers every route upgrade with 501, so the routes cannot be served.",name:"platform_socket_delivery_authorization",remediation:"Remove the defineWebSocket declarations, or remove the .deliveryAuthorization(...) call. Socket routes and delivery authorization cannot be combined.",target:t}),A=(t,e,r)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${h[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:r}),$=t=>{const{diagnostics:e,gatedSignals:r,matrix:o,reported:n,signals:a,target:s}=t;for(const i of _){if(a[i]!==!0)continue;const d=o.features[i]?.level;d!=="unsupported"&&d!==void 0||(r[i]=!1,!n.has(i)&&e.push(d==="unsupported"?T(i,o,s):A(i,o,s)))}},R=(t,e,r,o={})=>{const n={...t},a={...o},s=[],i=new Set;for(const[l,c]of Object.entries(w)){if(c===null||!t[l])continue;const v=e.features[c]?.level;v==="unsupported"?(n[l]=!1,i.add(c),s.push({feature:l,level:"error",message:`${e.name} does not support "${l}" (ctx.${l}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${l} usage, or deploy to a target whose capability matrix marks "${c}" as native or emulated.`,target:r})):v===void 0&&(n[l]=!1,i.add(c),s.push({feature:l,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${l}" (ctx.${l}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${c}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:r}))}$({diagnostics:s,gatedSignals:a,matrix:e,reported:i,signals:o,target:r});const d=e.features.liveStreams?.level,p=d===void 0||d==="unsupported";return o.liveContext===!0&&p&&s.push(x(e,r)),{diagnostics:s,liveStreamsWithheld:p,signals:a,usage:n}},j=(t,e,r={})=>{const o=u[e];return o===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],liveStreamsWithheld:!1,signals:{...r},usage:{...t}}:R(t,o,e,r)},F=t=>{const e=u[t];if(e===void 0)return{supported:!0};const r=e.features.adminTokenRevocation?.level;return r!==void 0&&r!=="unsupported"?{supported:!0}:{diagnostic:{level:"warn",message:`${e.name} ${r===void 0?"does not declare a support level for":"does not support"} named admin tokens, so codegen omits the admin revocation store (\`_generated/adminRevocations.ts\` and the builder's \`.adminRevocations()\`). The root LUNORA_ADMIN_TOKEN is the only admin credential here.`,name:r===void 0?"platform_undeclared_feature":"platform_unsupported_feature",remediation:'Use the root admin token, or deploy to a target whose capability matrix marks "adminTokenRevocation" as native or emulated.',target:t},supported:!1}},N=t=>{const e=u[t];if(e===void 0)return;const r=Object.entries(e.features).filter(([,o])=>o.level==="unsupported").map(([o])=>o).toSorted((o,n)=>o.localeCompare(n));return{id:e.id,name:e.name,unsupported:r}};export{w as CAPABILITY_TO_FEATURE,m as DEFAULT_TARGET,F as gateAdminTokenRevocation,R as gateAgainstMatrix,j as gatePlatformFeatures,D as liveStreamsDeliveryAuthorizationDiagnostic,O as platformFeatureAvailable,W as platformMatrixIds,S as readProjectTarget,z as readTargetDiagnostics,I as resolveCodegenTarget,P as socketRoutesDeliveryAuthorizationDiagnostic,N as studioPlatformFor,E as vectorizeDimensionDiagnostics};
@@ -1,4 +1,4 @@
1
- import{existsSync as z,readFileSync as ze,mkdirSync as pt,writeFileSync as ho,rmSync as ve,readdirSync as ds}from"node:fs";import{dirname as gt,join as E,relative as Be,sep as si,basename as vo}from"node:path";import{performance as _t}from"node:perf_hooks";import{RUNTIME_LINTS as Eo,STATIC_LINTS as xo,runAdvisor as So}from"@lunora/advisor";import{LunoraError as F}from"@lunora/errors";import{serializeSchemaSnapshot as yo}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Ao}from"./formatAdvisories-Bue5tbp6.mjs";import{Node as r,SyntaxKind as d,Project as us,VariableDeclarationKind as fs,ts as C}from"ts-morph";import{listLunoraSourceFiles as b,lunoraRelativePath as I,declarationLineOf as ni,collectCallRows as R,descendantsOfKind as S,bindingKeyName as Ee,findObjectProperty as U,collectSecurityCallRows as bo,propertyInitializer as $,listSecurityScanFiles as Ve,objectLiteralFromCallbackBody as ii,limitNameOf as ri,optionsObjectLiteral as oi,handlerOf as No,memberAccessOf as ps,chainRootOf as mt,unwrapExpression as v,collectNodeRows as ce,isConstDeclaration as X,outermostValueWrapper as O,isWriteTarget as we,isSameNode as w,returningFunctionOf as Ht,walkChain as wo,staticNumberValue as ai,RUN_METHODS as gs,functionReferenceSegments as Po,isTestPath as Io,isFunctionLike as pe,functionKeyOf as ci,withSourceListMemo as To}from"./isTestPath-Uwb5a6Kq.mjs";import{j as te,h as Z,c as A,a as ms,w as hs,k as Co,d as V,l as Oo,b as li,f as ko,m as Ro,g as Gt,i as Lo}from"./attribution-Cwt30DDJ.mjs";import{i as H,a as Ae,r as Fo,b as Do,c as di,d as _o,s as Ue,e as Mo,f as $o,g as Ko}from"./ip-reads-By7tJdyu.mjs";import{e as J,f as zo,m as ui,b as ht,g as vs,E as fi,C as pi,d as gi,h as Bo,j as Vo,a as Uo}from"./context-root-BpDEhvNE.mjs";import{a as k,i as mi,c as le,d as hi,e as vi,f as Wo,b as jo,g as qo,h as Ho}from"./classify-procedure-call-BmEirzc_.mjs";import{a as y,s as Es}from"./property-name-7cBlgK_O.mjs";import{b as Go,a as Ei}from"./module-specifiers-BctA0m_p.mjs";import{r as vt,s as Yo}from"./parse-validator-BisfC8bR.mjs";import Qo from"./discoverAuthApiCalls-CuqaLRa0.mjs";import{i as B,r as xi}from"./database-calls-d-Sssc-3.mjs";import{i as Yt,p as Si,w as Xo,d as Jo}from"./index-M4HwQ4Jr.mjs";import Zo from"./discoverHyperdriveCalls-BmAoOGGq.mjs";import{PROJECT_CONFIG_FILENAMES as ea,findProjectConfigFile as yi,findCodegenConfigFile as ta}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{contextPropertiesRead as sa,createTargetScope as na,fileWiresRequestSecretTool as ia,discoverFeatureUsage as ra}from"./capabilitiesUsedBy-BNvoiCu1.mjs";import{diagnosticAt as Pe}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as xs,a as ot,s as Ai,d as oa}from"./index-CfSmiylg.mjs";import{MUTATORS_FILENAME as aa,isDefineMutatorCallee as ca,mutatorServerImplOf as la,discoverMutators as da}from"./MUTATORS_FILENAME-C0ZV0hh6.mjs";import ua from"./discoverNondeterministicCalls-ZeZDQJAI.mjs";import{discoverNotifyConfig as fa,discoverNotifyCalls as pa}from"./ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs";import ga from"./discoverR2sqlCalls-D_HWbbky.mjs";import ma from"./discoverRlsProcedures-BbSdCvmA.mjs";import{s as Ss,n as ha}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as va,redact as Ea,isHeuristicSecretKind as xa,isSecretishName as Sa}from"./redact-Cy14LEnc.mjs";import{r as bi,p as ya,c as Aa,a as ba,e as Na,d as wa}from"./project-config-file-DR7xrrNB.mjs";import{a as Je,d as Pa,r as Ia}from"./modules-DdOd-7Wp.mjs";import{WORKFLOWS_FILENAME as Ta,discoverWorkflows as Ca}from"./WORKFLOWS_FILENAME-7FysJsMZ.mjs";import{r as Oa}from"./json-data-Chfs2Cz5.mjs";import{a as ka,I as Ra,g as La,G as Ni,d as Fa,i as Da}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as _a}from"./createCodegenProject-dC6oJh5H.mjs";import{findTsconfig as MS,refreshCodegenProject as $S,tsconfigFingerprint as KS}from"./createCodegenProject-dC6oJh5H.mjs";import{wranglerString as Ma,wranglerValue as $a,companionName as Ka,COMPANION_FILES as za}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as Ba,usedCapabilities as Va}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{isD1GlobalTable as wi,isHyperdriveGlobalTable as Pi}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Ua}from"./AGENTS_FILENAME-C4tHmiZZ.mjs";import{discoverContainers as Wa}from"./CONTAINERS_FILENAME-d3XTFcqV.mjs";import ja from"./discoverCrons-bT8F5GyL.mjs";import{discoverEnv as qa}from"./ENV_FILENAME-DJ11PXN5.mjs";import Ii from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Ha}from"./QUEUES_FILENAME-DbuJZnrY.mjs";import{discoverSandboxUsage as Ga}from"./discoverSandboxUsage-Dgvv6F_7.mjs";import{resolveServiceBindings as Ya}from"./companionServiceBinding-BZjm486n.mjs";import Qa from"./discoverStorageRulesMetadata-DeBgC7po.mjs";import{resolveCodegenTarget as ke,gatePlatformFeatures as Xa,readTargetDiagnostics as Ja,vectorizeDimensionDiagnostics as Za,liveStreamsDeliveryAuthorizationDiagnostic as ec,socketRoutesDeliveryAuthorizationDiagnostic as tc,studioPlatformFor as sc,platformFeatureAvailable as nc,gateAdminTokenRevocation as ic}from"./DEFAULT_TARGET-CVYzxQ0y.mjs";import{i as rc}from"./schema-BgM8A3XV.mjs";import{b as Ti,e as oc}from"./shard-CWAD5mYy.mjs";import{e as ac,a as cc}from"./server-Dfxmm5Zw.mjs";import{emitDataModel as lc}from"./emitDataModel-BvCZS4Yq.mjs";import{i as dc,b as uc,e as fc,d as pc,f as gc,c as mc}from"./unwrap-handler-return-DvbyiLjc.mjs";import hc from"./discoverHttpRoutes-CesuhqW1.mjs";import vc from"./discoverInserts-DIarYU2P.mjs";import{e as Ci}from"./exported-procedure-chains-CfH5jrzD.mjs";import Ec from"./discoverMigrations-C9AlZYFi.mjs";import on from"./discoverQueries-DLZHcDzB.mjs";import xc from"./discoverRlsMetadata-C0UkQkWd.mjs";import Sc from"./discoverSchema-BLTROO8Z.mjs";import{discoverShapes as yc}from"./SHAPES_FILENAME-DTJKanSz.mjs";import{i as Ac}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as bc,emitApp as Nc}from"./emitApp-LFKtDRYu.mjs";import{readJsonSync as wc}from"@visulima/fs";import{indexReferencesOf as Pc,buildSchemaSnapshot as Ic}from"./SchemaSnapshotParseError-CV7mmuPi.mjs";import{buildOpenApiDocument as Tc,emitOpenApiModule as Cc}from"./buildOpenApiDocument-DmV_PBFv.mjs";import{buildOpenRpcDocument as Oc,emitOpenRpcModule as kc}from"./OPENRPC_VERSION-BOBo0zdQ.mjs";import{w as Rc,u as Lc,v as Fc,t as Dc,x as _c}from"./shard-runtime-G5mZQjY0.mjs";import{emitCollections as Mc,emitSeed as $c,emitApi as Kc,emitInternalApi as zc}from"./emitApi-lwadq5G7.mjs";import{emitCrons as Bc,emitScheduler as Vc,emitAdminRevocations as Uc,emitShardRegistry as Wc,emitDurableObjects as jc,emitVectors as qc,emitWranglerCronTriggers as Hc}from"./emitCrons-CCRKs482.mjs";import Gc from"./emitDrizzleSchema-BzOChEYW.mjs";import{LAZY_FUNCTION_DIRECTORY as Oi,emitFunctions as Yc,emitLazyFunctionModules as Qc}from"./emitFunctions-ppMX7E3X.mjs";const Xc=(e,t=!1)=>{if(e.length===0)return"";const s=Fa(t),n=e.map(c=>{if(ka(c.exportName,"live stream export name"),!Ra.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{La(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,p=`LiveTopicRef<LiveTopicPayload<${f}>>`,g=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${p} => ({ __lunoraLive: ${g}, topic: ${JSON.stringify(u.name)} }),`;const h=u.fields.map(x=>`\${encodeURIComponent(key.${x})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${p} => ({
1
+ import{existsSync as z,readFileSync as ze,mkdirSync as pt,writeFileSync as ho,rmSync as ve,readdirSync as ds}from"node:fs";import{dirname as gt,join as E,relative as Be,sep as si,basename as vo}from"node:path";import{performance as _t}from"node:perf_hooks";import{RUNTIME_LINTS as Eo,STATIC_LINTS as xo,runAdvisor as So}from"@lunora/advisor";import{LunoraError as D}from"@lunora/errors";import{serializeSchemaSnapshot as yo}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Ao}from"./formatAdvisories-Bue5tbp6.mjs";import{Node as r,SyntaxKind as d,Project as us,VariableDeclarationKind as fs,ts as C}from"ts-morph";import{listLunoraSourceFiles as b,lunoraRelativePath as I,declarationLineOf as ni,collectCallRows as L,descendantsOfKind as S,bindingKeyName as Ee,findObjectProperty as U,collectSecurityCallRows as bo,propertyInitializer as $,listSecurityScanFiles as Ve,objectLiteralFromCallbackBody as ii,limitNameOf as ri,optionsObjectLiteral as oi,handlerOf as No,memberAccessOf as ps,chainRootOf as mt,unwrapExpression as v,collectNodeRows as ce,isConstDeclaration as X,outermostValueWrapper as O,isWriteTarget as we,isSameNode as w,returningFunctionOf as Ht,walkChain as wo,staticNumberValue as ai,RUN_METHODS as gs,functionReferenceSegments as Po,isTestPath as Io,isFunctionLike as pe,functionKeyOf as ci,withSourceListMemo as To}from"./isTestPath-Uwb5a6Kq.mjs";import{j as te,h as Z,c as A,a as ms,w as hs,k as Co,d as V,l as Oo,b as li,f as ko,m as Ro,g as Gt,i as Lo}from"./attribution-Cwt30DDJ.mjs";import{i as H,a as Ae,r as Fo,b as Do,c as di,d as _o,s as Ue,e as Mo,f as $o,g as Ko}from"./ip-reads-By7tJdyu.mjs";import{e as J,f as zo,m as ui,b as ht,g as vs,E as fi,C as pi,d as gi,h as Bo,j as Vo,a as Uo}from"./context-root-BpDEhvNE.mjs";import{a as k,i as mi,c as le,d as hi,e as vi,f as Wo,b as jo,g as qo,h as Ho}from"./classify-procedure-call-BmEirzc_.mjs";import{a as y,s as Es}from"./property-name-7cBlgK_O.mjs";import{b as Go,a as Ei}from"./module-specifiers-BctA0m_p.mjs";import{r as vt,s as Yo}from"./parse-validator-BisfC8bR.mjs";import Qo from"./discoverAuthApiCalls-CuqaLRa0.mjs";import{i as B,r as xi}from"./database-calls-d-Sssc-3.mjs";import{i as Yt,p as Si,w as Xo,d as Jo}from"./index-M4HwQ4Jr.mjs";import Zo from"./discoverHyperdriveCalls-BmAoOGGq.mjs";import{PROJECT_CONFIG_FILENAMES as ea,findProjectConfigFile as yi,findCodegenConfigFile as ta}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{contextPropertiesRead as sa,createTargetScope as na,fileWiresRequestSecretTool as ia,discoverFeatureUsage as ra}from"./capabilitiesUsedBy-BNvoiCu1.mjs";import{diagnosticAt as Pe}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as xs,a as ot,s as Ai,d as oa}from"./index-CfSmiylg.mjs";import{MUTATORS_FILENAME as aa,isDefineMutatorCallee as ca,mutatorServerImplOf as la,discoverMutators as da}from"./MUTATORS_FILENAME-C0ZV0hh6.mjs";import ua from"./discoverNondeterministicCalls-ZeZDQJAI.mjs";import{discoverNotifyConfig as fa,discoverNotifyCalls as pa}from"./ALL_NOTIFY_CHANNELS-BgkkvuUe.mjs";import ga from"./discoverR2sqlCalls-D_HWbbky.mjs";import ma from"./discoverRlsProcedures-BbSdCvmA.mjs";import{s as Ss,n as ha}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as va,redact as Ea,isHeuristicSecretKind as xa,isSecretishName as Sa}from"./redact-Cy14LEnc.mjs";import{r as bi,p as ya,c as Aa,a as ba,e as Na,d as wa}from"./project-config-file-DR7xrrNB.mjs";import{a as Je,d as Pa,r as Ia}from"./modules-DdOd-7Wp.mjs";import{WORKFLOWS_FILENAME as Ta,discoverWorkflows as Ca}from"./WORKFLOWS_FILENAME-7FysJsMZ.mjs";import{r as Oa}from"./json-data-Chfs2Cz5.mjs";import{a as ka,I as Ra,g as La,G as Ni,d as Fa,i as Da}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as _a}from"./createCodegenProject-dC6oJh5H.mjs";import{findTsconfig as MS,refreshCodegenProject as $S,tsconfigFingerprint as KS}from"./createCodegenProject-dC6oJh5H.mjs";import{wranglerString as Ma,wranglerValue as $a,companionName as Ka,COMPANION_FILES as za}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as Ba,usedCapabilities as Va}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{isD1GlobalTable as wi,isHyperdriveGlobalTable as Pi}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Ua}from"./AGENTS_FILENAME-C4tHmiZZ.mjs";import{discoverContainers as Wa}from"./CONTAINERS_FILENAME-d3XTFcqV.mjs";import ja from"./discoverCrons-BlL_VbIv.mjs";import{discoverEnv as qa}from"./ENV_FILENAME-DJ11PXN5.mjs";import Ii from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Ha}from"./QUEUES_FILENAME-DbuJZnrY.mjs";import{discoverSandboxUsage as Ga}from"./discoverSandboxUsage-Dgvv6F_7.mjs";import{resolveServiceBindings as Ya}from"./companionServiceBinding-BZjm486n.mjs";import Qa from"./discoverStorageRulesMetadata-DeBgC7po.mjs";import{resolveCodegenTarget as ke,gatePlatformFeatures as Xa,readTargetDiagnostics as Ja,vectorizeDimensionDiagnostics as Za,liveStreamsDeliveryAuthorizationDiagnostic as ec,socketRoutesDeliveryAuthorizationDiagnostic as tc,studioPlatformFor as sc,platformFeatureAvailable as nc,gateAdminTokenRevocation as ic}from"./DEFAULT_TARGET-5-_edM-R.mjs";import{i as rc}from"./schema-BgM8A3XV.mjs";import{b as Ti,e as oc}from"./shard-CWAD5mYy.mjs";import{e as ac,a as cc}from"./server-Dfxmm5Zw.mjs";import{emitDataModel as lc}from"./emitDataModel-BvCZS4Yq.mjs";import{i as dc,b as uc,e as fc,d as pc,f as gc,c as mc}from"./unwrap-handler-return-DvbyiLjc.mjs";import hc from"./discoverHttpRoutes-CesuhqW1.mjs";import vc from"./discoverInserts-DIarYU2P.mjs";import{e as Ci}from"./exported-procedure-chains-CfH5jrzD.mjs";import Ec from"./discoverMigrations-C9AlZYFi.mjs";import on from"./discoverQueries-DLZHcDzB.mjs";import xc from"./discoverRlsMetadata-C0UkQkWd.mjs";import Sc from"./discoverSchema-BLTROO8Z.mjs";import{discoverShapes as yc}from"./SHAPES_FILENAME-DTJKanSz.mjs";import{i as Ac}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as bc,emitApp as Nc}from"./emitApp-LFKtDRYu.mjs";import{readJsonSync as wc}from"@visulima/fs";import{indexReferencesOf as Pc,buildSchemaSnapshot as Ic}from"./SchemaSnapshotParseError-CV7mmuPi.mjs";import{buildOpenApiDocument as Tc,emitOpenApiModule as Cc}from"./buildOpenApiDocument-DmV_PBFv.mjs";import{buildOpenRpcDocument as Oc,emitOpenRpcModule as kc}from"./OPENRPC_VERSION-BOBo0zdQ.mjs";import{w as Rc,u as Lc,v as Fc,t as Dc,x as _c}from"./shard-runtime-G5mZQjY0.mjs";import{emitCollections as Mc,emitSeed as $c,emitApi as Kc,emitInternalApi as zc}from"./emitApi-lwadq5G7.mjs";import{emitCrons as Bc,emitScheduler as Vc,emitAdminRevocations as Uc,emitShardRegistry as Wc,emitDurableObjects as jc,emitVectors as qc,emitWranglerCronTriggers as Hc}from"./emitCrons-CCRKs482.mjs";import Gc from"./emitDrizzleSchema-BzOChEYW.mjs";import{LAZY_FUNCTION_DIRECTORY as Oi,emitFunctions as Yc,emitLazyFunctionModules as Qc}from"./emitFunctions-ppMX7E3X.mjs";const Xc=(e,t=!1)=>{if(e.length===0)return"";const s=Fa(t),n=e.map(c=>{if(ka(c.exportName,"live stream export name"),!Ra.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{La(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,p=`LiveTopicRef<LiveTopicPayload<${f}>>`,g=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${p} => ({ __lunoraLive: ${g}, topic: ${JSON.stringify(u.name)} }),`;const h=u.fields.map(x=>`\${encodeURIComponent(key.${x})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${p} => ({
2
2
  __lunoraLive: ${g},
3
3
  topic: \`${u.name}:${h}\`,
4
4
  }),`});return` ${c.exportName}: {
@@ -18,17 +18,17 @@ export const live = {
18
18
  ${i.join(`
19
19
  `)}
20
20
  };
21
- `},ki=new Set(["delete","get","head","options","patch","post","put"]),Jc=new Set(["handler","stream"]),Zc=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,an=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),el=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ki.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()}},tl=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)||ki.has(n.getName()))break;s=n.getExpression()}return el(s)},sl=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(an.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&an.has(s.getText()))return!0}return!1},nl=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Jc.has(n.getName()))return;const i=tl(s);if(!i||!Zc.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&sl(o);return{exportName:Z(e)??e.getName(),file:t,line:ni(e),method:i.method,path:i.path,usesGuard:a}},il=(e,t)=>{const s=[];for(const n of te(e)){const i=nl(n,t);i&&s.push(i)}return s},rl=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...il(i,I(t,n)))}return s},ol=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:J(e.getExpression(),["ai"]),al=(e,t)=>{if(!ol(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)||Ae(s)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},cl=(e,t)=>R(e,t,al),ll=new Set(["generateText","streamText"]),dl=new Set(["messages","prompt","system"]),ul=[{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"]}],fl=(e,t)=>ul.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),pl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[zo(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&fl(i,s));return n===void 0?void 0:`${n}.${s}`},gl=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=pl(t);if(s!==void 0)return s}},ml=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=Ee(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},hl=e=>{if(Fo(e))return!0;const t=ml(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},vl=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!dl.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&hl(s))return!0}return!1},El=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression)){const i=k(n.getExpression());if(i===void 0||!ll.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(k(c.getExpression())==="tool"&&(a=gl(c),a!==void 0))break;a!==void 0&&s.push({scope:A(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:vl(o)})}return s},xl=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...El(i,I(t,n)))}return s},Sl=e=>J(e,["fetch"]),yl=(e,t)=>{if(!Sl(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},Al=(e,t)=>R(e,t,yl),ys=(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=vt(s.getExpression());return n===void 0||ys(n,t)})}finally{t.delete(e)}},bl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=U(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:vt(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:ys(i)}},Nl=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?vt(o):void 0;a===void 0?s=!0:(t.push(a),s||=ys(a))}n=i.getExpression()}return{objects:t,opaque:s}},As=(e,t)=>t?Nl(t):bl(e),Ri=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=vt(s.getExpression());return n===void 0?[]:Ri(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},wl=e=>e.flatMap(t=>Ri(t,new Set)),Pl=new Set(["check","length","max"]),Qt=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(Pl.has(s.getName()))return!0;t=n}},Xt=e=>Go(e)||e==="@lunora/values",Il=e=>{const t=new Set(["v"]);for(const s of mi(e,"v",Xt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Xt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Tl=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},Cl=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Ol=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Xt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),bs=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return Cl(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Ol(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},kl=(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)},Rl=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Ll=e=>r.isReturnStatement(e)?e.getExpression():void 0,Fl=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Rl(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Ll(t);return s?[s]:[]}),Li=(e,t)=>{if(bs(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Li(e.getExpression(),t)},Dl=(e,t)=>{const s=kl(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Qt(e),i=new Set(Fl(s).map(o=>Li(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=bs(o,t);return a===void 0?[]:[{bounded:Qt(o)||n&&i.has(o),factory:a}]})},_l=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=bs(s,t),i=n===void 0?[]:[{bounded:Qt(s),factory:n}];return r.isCallExpression(s)?[...i,...Dl(s,t)]:i}),Ml=(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=_l(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}},$l=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=le(n);if(i?.visibility!=="public")return;const{objects:o}=As(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Ml(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:Z(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Kl=(e,t)=>{const s=[],n=Il(e),i={destructured:Tl(e,n),namespaces:n};for(const o of te(e)){const a=$l(o,t,i);a&&s.push(a)}return s},zl=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Kl(i,I(t,n)))}return s},Mt=e=>e?.getKind()===d.TrueKeyword,Bl=e=>e?.getKind()===d.FalseKeyword,Vl=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Ul=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Wl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&k(t.getExpression())==="scim"),jl=e=>e!==void 0&&r.isCallExpression(e)&&Ul.has(k(e.getExpression())??""),ql=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),Hl=e=>{const t=$(e,"advanced"),s=$(e,"emailAndPassword"),n=$(e,"session");return{analyzable:!0,disableCsrfCheck:Mt($(t,"disableCSRFCheck")),emailPasswordEnabled:Mt($(s,"enabled")),requireEmailVerification:Mt($(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Wl($(e,"plugins"))&&jl($(e,"database")),secureCookiesDisabled:Bl($(t,"useSecureCookies")),sessionFreshAgeZero:Vl($(n,"freshAge")),trustedOriginsWildcard:ql($(e,"trustedOrigins"))}},Gl=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Yl=(e,t)=>{if(k(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?Hl(s):Gl();return{scope:A(e),file:t,line:e.getStartLineNumber(),...i}},Ql=(e,t)=>bo(e,t,Yl),Xl=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return ui(e.getExpression(),t.matchReceiver)?s:void 0},Jl=(e,t,s)=>{const n=Xl(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex],o=a=>s.scope==="identity"?di(a)||_o(e,a):Ae(a);if(!(!i||!H(i)||o(i))&&!(s.requireUnmodifiedReach===!0&&!Do(i)))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:n}},Et=(e,t,s)=>R(e,t,(n,i)=>Jl(n,i,s)),Zl=new Set(["content","pdf","scrape","screenshot"]),ed=(e,t)=>Et(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Zl}),td=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),sd=new Set(["RateLimiter"]),nd=new Set(["extend"]),cn="lunora",id=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Fi=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}},Jt=e=>e&&r.isObjectLiteralExpression(e)?Fi(e):{analyzable:!1,presentKeys:[],trueKeys:[]},rd=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&ii(t.getBody());return s?Fi(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},od=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression)){const i=k(n.getExpression());i!==void 0&&(td.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Jt(n.getArguments()[0])}):nd.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...rd(n.getArguments()[0])}))}for(const n of S(e,d.NewExpression)){const i=k(n.getExpression());i===void 0||!sd.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Jt(n.getArguments()[0])})}return s},ad=e=>{for(const t of id){const s=E(e,t);if(!z(s))continue;const n=new us({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,ze(s,"utf8")),i=[];for(const o of S(n,d.CallExpression))k(o.getExpression())===cn&&i.push({callee:cn,file:t,line:o.getStartLineNumber(),...Jt(o.getArguments()[0])});return i}return[]},cd=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ve(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...od(o,n))}return s.push(...ad(gt(t))),s},ln="ctx.containers.",ld=e=>{if(!e.startsWith(ln))return!1;const t=e.slice(ln.length);return t.length>0&&!t.includes(".")},dd=(e,t)=>Et(e,t,{argIndex:0,scope:"identity",matchReceiver:ld,methods:new Set(["get"])}),ud=new Set(["allow","deny","setAllowed"]),fd=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=U(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},pd=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!fd(e)))return{detail:"enableInternet: true",scope:A(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},gd=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!ud.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:A(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},md=(e,t)=>pd(e,t)??gd(e,t),hd=(e,t)=>R(e,t,md),vd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(B(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&B(s.getExpression())?s.getName():void 0},Ed=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&B(s)?1:0]},xd=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Sd=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=>xd.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},yd=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return R(e,t,(i,o)=>{const a=vd(i);if(a===void 0)return;const c=Sd(Ed(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:A(i),table:a}})},Ad=new Set(["defineExportSink","r2Sink","webhookExportSink"]),bd=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Ad.has(s)?s:void 0},Nd=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=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}},wd=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ve(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of S(o,d.CallExpression)){const c=bd(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Nd(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},Pd=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Id=new Set(["dbRateLimit","rateLimit"]),Td=e=>{const t=oi(e);if(!t)return!1;const s=U(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Cd=(e,t)=>{const s=k(e.getExpression());if(s===void 0)return;const n=Pd.get(s);if(n!==void 0)return{callee:s,scope:A(e),failOpen:Td(e.getArguments()[n]),file:t,limitName:Id.has(s)?ri(e):"",line:e.getStartLineNumber()}},Od=(e,t)=>R(e,t,Cd),kd=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=le(t);if(s?.kind!=="query")return;const n=No(t,s.receiver);return n?{exportName:Z(e)??e.getName(),handler:n}:void 0},dn=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Rd=e=>{const t=dn(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=dn(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Ld=(e,t)=>{const s=[];for(const n of ht(e.handler,"flags"))s.push({callee:Rd(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Fd=(e,t)=>{const s=[];for(const n of te(e)){const i=kd(n);i&&s.push(...Ld(i,t))}return s},Dd=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Fd(i,I(t,n)))}return s},_d=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:J(e.getExpression(),["flags"]),Md=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},$d=(e,t)=>{if(!_d(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Md(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:A(e),file:t,key:i,line:e.getStartLineNumber()}},Kd=(e,t)=>R(e,t,$d),zd=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Bd=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Vd=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of S(i,d.CallExpression))zd(a)&&s.push({file:o,indexName:Bd(a),line:a.getStartLineNumber()})}return s},Ud=new Set(["delete","get","head","options","patch","post","put"]),Wd=new Set(["handler","stream"]),jd=new Set(["runAction","runMutation"]),qd=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),_e=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Di=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(Ee(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},un=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Di(s,"ctx")},fn=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Di(s,"request")},pn=(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(jd.has(a)&&_e(c,t))return a;if(qd.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&_e(c.getExpression(),t))return`db.${a}`}},gn=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&_e(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!_e(n.getInitializer(),t))){for(const o of i.getElements())if(Ee(o)==="auth")return!0}}return!1},Hd=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Gd=(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"&&_e(n.getExpression(),t)},Yd=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],_i=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Yd(s)},Qd=(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)?_i(t,a.getText()):[]}return[]},Xd=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=_i(s,t.getText());return n.length>0?n:Qd(t,s)},mn=(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=>Gd(i,t)&&Xd(i).some(o=>Hd.test(o)))},Jd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Wd.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(Ud.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Zd=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Yt(e.getArguments()[0]),l=c&&un(c,!0);if(!c||l===void 0||mn(c,fn(c,!0)))return;const u=pn(c,l);return u===void 0?void 0:{scope:A(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:gn(c,l),sideEffect:u}}const n=Jd(e);if(n===void 0)return;const i=Yt(e.getArguments()[0]),o=i&&un(i,!1);if(!i||o===void 0||mn(i,fn(i,!1)))return;const a=pn(i,o);return a===void 0?void 0:{scope:A(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:gn(i,o),sideEffect:a}},eu=(e,t)=>R(e,t,Zd),tu=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),su=new Set(["append","set"]),Mi=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",hn=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>tu.has(k(n.getExpression())??"")&&$o(n,t)),nu=(e,t)=>{if(hn(e,t))return!0;const s=Ue(e);return s!==void 0&&hn(s,t)},Zt=(e,t)=>Mo(e,t)&&!nu(e,t),iu=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Ue(e);return t!==void 0&&r.isNewExpression(t)&&k(t.getExpression())==="Headers"},at=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=Ue(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Ns=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Mi(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Zt(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=at(n.getExpression());i!==void 0&&Ns(i,t,s)}},$i=(e,t)=>{const s=at(e);if(s===void 0)return;const n=U(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=at(n.getInitializer());i!==void 0&&Ns(i,"response-init",t)},ru=(e,t)=>{const s=k(e.getExpression());if(s==="Response")$i(e.getArguments()[1],t);else if(s==="Headers"){const n=at(e.getArguments()[0]);n!==void 0&&Ns(n,"headers-ctor",t)}},ou=(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"){$i(e.getArguments()[1],t);return}if(su.has(n)&&iu(i)){const o=e.getArguments()[1];o!==void 0&&Zt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Mi(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},au=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))ru(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))ou(s,t)},cu=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Yt(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 au(n,{scope:A(e),relativePath:t,requestName:o.getText(),rows:a}),a},lu=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression))s.push(...cu(n,t));return s},du=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lu(i,I(t,n)))}return s},uu=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token","tokenHash"]),fu=new Set(["__proto__","email","exp","expiresAtMs","iat","name","nbf","orgId","role","roles","sub","teamId","userId"]),$t=32,pu=/^[A-Z_]\w{0,63}$/i,gu={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},mu=new Set(["allowedHosts","deniedHosts","interceptHttps"]),hu=(e,t)=>{const s=v(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return v(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},vu=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(y(s));if(!r.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=v(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Eu=new Set(["durable"]),xu=new Set(["rollback"]),Ki=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Su="defineApp",Re="app",vn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>y(s)===Re&&s.getInitializer()?.getText()===t)||t===Re&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>y(s)===Re),yu=e=>{if(e===void 0||!ea.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&y(e)===Re;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return y(t)===Re;if(r.isVariableDeclaration(t))return vn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&vn(e.getSourceFile(),s)},Au="AppBuilder",zi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},Bi=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Au&&s.getDeclarations().some(n=>zi(n))},bu=e=>e.getText()===Su&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||zi(t)),ws=(e,t,s=new Set)=>{const n=mt(t);if(n===void 0||!r.isIdentifier(n))return!1;if(bu(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return yu(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return ws(e,a.getInitializer(),s)}}return!1},Vi=(e,t)=>{const s=ps(t.getExpression());return s?.member==="deliveryAuthorization"&&(ws(e,s.object)||Bi(s.object))},Nu=new Map([["defineContainer",{keys:mu,signal:"containerEgressPolicy"}],["defineStep",{keys:xu,signal:"workflowRollback"}],["stream",{keys:Eu,signal:"durableStreams"}]]),wu=(e,t)=>{const s=Nu.get(Ki(t));if(s!==void 0)return t.getArguments().some(n=>vu(hu(e,n),s.keys))?s.signal:void 0},Pu=(e,t)=>gu[Ki(t)]??(Vi(e,t)?"deliveryAuthorization":void 0),Iu=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of b(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=sa(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=S(o,d.CallExpression);for(const c of a){const l=wu(o,c)??Pu(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>hi(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new us({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,ze(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Vi(i,o))}return n},Me={claims:[],diagnostics:[]},ae=e=>({claims:[],diagnostics:[e]}),xt=e=>r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)?xt(e.getExpression()):e,Ui=e=>{if(r.isSpreadAssignment(e))return!0;const t=e.getNameNode();return r.isComputedPropertyName(t)&&Es(t)===void 0},be=e=>e.getProperties().some(t=>Ui(t)),Wi=(e,t)=>e.getProperties().findLast(s=>!r.isSpreadAssignment(s)&&y(s)===t),ji=(e,t)=>{const s=Wi(e,t);return r.isPropertyAssignment(s)?s.getInitializer():void 0},qi=(e,t)=>{const s=ji(e,t);return s!==void 0&&xt(s).getKind()===d.FalseKeyword},$e="unreadable",Ps=(e,t)=>{const s=Wi(e,t);if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer()??$e:r.isShorthandPropertyAssignment(s)?s.getNameNode():$e},En=e=>{if(e===void 0||!r.isBlock(e))return e;const t=e.getStatements().filter(s=>r.isReturnStatement(s));return t.length===1?t[0]?.getExpression():void 0},fe=(e,t=0)=>{if(t>4)return;const s=xt(e);if(r.isObjectLiteralExpression(s))return s;if(r.isArrowFunction(s)||r.isFunctionExpression(s)){const c=En(s.getBody());return c===void 0?void 0:fe(c,t+1)}if(!r.isIdentifier(s))return;const n=s.getParent(),i=r.isShorthandPropertyAssignment(n)?n.getValueSymbol():s.getSymbol(),o=i?.isAlias()?i.getAliasedSymbol():i,[a]=o?.getDeclarations()??[];if(r.isVariableDeclaration(a)){const c=a.getInitializer();return c===void 0?void 0:fe(c,t+1)}if(r.isFunctionDeclaration(a)){const c=En(a.getBody());return c===void 0?void 0:fe(c,t+1)}},Tu=e=>{if(e===void 0)return;const t=xt(e);if(r.isArrayLiteralExpression(t))return"string";if(!(!r.isStringLiteral(t)&&!r.isNoSubstitutionTemplateLiteral(t)))switch(t.getLiteralValue()){case"boolean":return"boolean";case"date":case"string":return"string";case"number":return"number";default:return}},Cu=e=>qi(e,"returned"),Ou=(e,t)=>{if(!pu.test(e))return{reason:`\`${e}\` is not an identifier of at most 64 characters`};if(fu.has(e)||uu.has(e))return{reason:`\`${e}\` is reserved or secret-bearing, so the session never forwards it`};const s=fe(t);if(s===void 0||be(s))return{reason:`\`${e}\` is not a literal field definition`};const n=Tu(ji(s,"type"));return n===void 0?{reason:`\`${e}\` is not a scalar (string, number, boolean or date) column`}:{claim:{name:e,type:n,writable:!qi(s,"input")}}},ku=e=>{if(r.isSpreadAssignment(e))return;if(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e))return{reason:`\`${e.getName()}\` is a method or accessor, not a field definition`};const t=r.isPropertyAssignment(e)?y(e):e.getName(),s=r.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),n=s===void 0?void 0:fe(s);if(!(n!==void 0&&!be(n)&&Cu(n)))return s===void 0?{reason:`\`${t}\` has no initializer`}:Ou(t,s)},Ru=e=>{const t=[],s=[];for(const n of e.getProperties()){const i=ku(n);i?.claim!==void 0?t.push(i.claim):i!==void 0&&s.push(`${i.reason??"the entry cannot be a claim"}; it is not added to ctx.auth`)}return t.length>$t&&s.push(`${t.length.toString()} claims declared; the first ${$t.toString()} are forwarded, the rest are not`),{claims:t.slice(0,$t),diagnostics:s}},Lu=e=>{if(be(e))return ae("`user` has a spread or a computed key, so the user columns cannot be read");const t=Ps(e,"additionalFields");if(t===void 0)return Me;const s=t===$e?void 0:fe(t);return s===void 0||be(s)?ae("`user.additionalFields` is not an object literal, so the user columns cannot be read"):Ru(s)},Fu=e=>{if(be(e))return ae("the auth options contain a spread or a computed key, so the user columns cannot be read");const t=Ps(e,"user");if(t===void 0)return Me;const s=t===$e?void 0:fe(t);return s===void 0?ae("`user` is not an object literal, so the user columns cannot be read"):Lu(s)},Du=(e,t)=>{const s=t.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="auth")return!1;const n=s.getExpression();return ws(e,n)||Bi(n)},_u=e=>{const t=e.getProperties(),s=t.findLastIndex(n=>!r.isSpreadAssignment(n)&&y(n)==="options");return t.some((n,i)=>i>s&&Ui(n))},Mu=e=>{const[t]=e.getArguments();if(t===void 0)return Me;if(!r.isObjectLiteralExpression(t))return ae(".auth() is not called with an object literal, so its user columns cannot be read");const s=Ps(t,"options");if(s===void 0)return be(t)?ae("the .auth() argument has a spread or a computed key, so its options cannot be read"):Me;if(_u(t))return ae("a spread or computed key after `options` in .auth() may replace it, so the user columns cannot be read");const n=s===$e?void 0:fe(s);return n===void 0?ae("`.auth({ options })` does not resolve to an object literal, so the user columns cannot be read"):Fu(n)},Hi=(e,t)=>{const s=[];for(const{filePath:o}of Ve(t)){const a=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...S(a,d.CallExpression).filter(c=>Du(a,c)))}const[n,...i]=s;return n===void 0?Me:i.length===0?Mu(n):ae(`the app builder's .auth() is called ${s.length.toString()} times, so which declaration applies cannot be read`)},Gi="identity.ts",$u=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ei(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Ku=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&&Ei(n.getModuleSpecifierValue())}return!1},zu=e=>{if(r.isIdentifier(e))return $u(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Ku(t)}return!1},Bu=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!zu(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Pe(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=ms(s,"member");a!==void 0&&t.push({exportName:a})}return t},Vu=(e,t)=>{const s=E(t,Gi);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Bu(n);if(i.length!==0){if(i.length>1)throw Pe(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Yi=new Set(["auth","context.auth"]),Uu="userId",Wu=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},ju=(e,t)=>{const s=E(t,Gi);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(k(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Wu(o):void 0}},qu=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Yi.has(t.getText())||J(t,["auth"])?e:void 0},es=(e,t=!1)=>r.isAwaitExpression(e)?es(e.getExpression(),!0):r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isTypeAssertion(e)||r.isNonNullExpression(e)?es(e.getExpression(),t):{awaited:t,value:e},Qi=e=>{if(e===void 0)return;const{awaited:t,value:s}=es(e);if(!t||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||n.getName()!=="getIdentity")return;const i=n.getExpression();return Yi.has(i.getText())||J(i,["auth"])?s:void 0},Xi=e=>{if(r.isPropertyAccessExpression(e))return e.getName();const t=v(e.getArgumentExpression());return r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0},Hu=e=>{if(!r.isPropertyAccessExpression(e)&&!r.isElementAccessExpression(e)||we(e))return;const t=e.getExpression();return qu(t)!==void 0||Qi(t)!==void 0?Xi(e):void 0},ts=(e,t,s,n)=>({declared:t===Uu||n.has(t),file:s,key:t,line:e.getStartLineNumber(),scope:A(e)}),xn=(e,t,s)=>{const n=Hu(e);return n===void 0?void 0:ts(e,n,t,s)},Gu=(e,t,s)=>{if(Qi(e.getInitializer())===void 0)return[];const n=e.getNameNode();return r.isObjectBindingPattern(n)?n.getElements().filter(i=>i.getDotDotDotToken()===void 0).flatMap(i=>{const o=Es(i.getPropertyNameNode()??i.getNameNode());return o===void 0?[]:[ts(i,o,t,s)]}):!r.isIdentifier(n)||!X(e)?[]:n.findReferencesAsNodes().filter(i=>i!==n).flatMap(i=>{const o=O(i),a=o.getParent();if(!r.isPropertyAccessExpression(a)&&!r.isElementAccessExpression(a)||we(a))return[];const c=a.getExpression()===o?Xi(a):void 0;return c===void 0?[]:[ts(a,c,t,s)]})},Yu=(e,t)=>{const s=ju(e,t);if(s===void 0)return[];const n=Hi(e,t).claims.filter(o=>!o.writable).map(o=>o.name),i=new Set([...s,...n]);return[...ce(e,t,d.PropertyAccessExpression,(o,a)=>xn(o,a,i)),...ce(e,t,d.ElementAccessExpression,(o,a)=>xn(o,a,i)),...ce(e,t,d.VariableDeclaration,(o,a)=>Gu(o,a,i))]},Qu=(e,t)=>{if(k(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=$(s,"key");if(!(!n||!H(n)||Ae(n)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},Xu=(e,t)=>R(e,t,Qu),Ju=new Set(["delete","get","getRaw","getWithMetadata","put"]),Zu=(e,t,s=[])=>{const n=Et(e,t,{argIndex:0,scope:"identity",matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Ju});return hs(n,s)},ef=new Set(["queue","send"]),Sn=new Set(["bcc","cc","to"]),tf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!ef.has(t))return;const s=e.getExpression();return J(s,["mail"])||J(s,["email"])?t:void 0},sf=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Sn.has(y(t))&&H(n)&&!Ae(n)}if(!r.isPropertyAssignment(t)||!Sn.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&H(s)&&!Ae(s)}):!1,nf=(e,t)=>{const s=tf(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!sf(n)))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s}},rf=(e,t)=>R(e,t,nf),of=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=ot(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=ot(l);if(u===void 0)continue;const f=Ai(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},af=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;return n?.receiver?xs(n.receiver).flatMap(i=>of(i,Z(e)??e.getName(),t)):[]},cf=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...af(a,o))}return s},lf=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Ji=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===fs.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!B(s.getExpression())))return{database:s.getExpression(),table:s.getName()}},St=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!t.has(s.getName()))return;const n=s.getName(),i=s.getExpression(),o=Ji(i);if(o!==void 0)return{database:o.database,method:n,table:o.table};if(r.isPropertyAccessExpression(i)&&B(i.getExpression()))return{database:i.getExpression(),method:n,table:i.getName()}},df=new Set(["replace"]),uf=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="replace"&&B(t.getExpression())?!0:St(e,df)!==void 0},ff=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=U(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},pf=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ca(s.getExpression())?s:void 0},gf=e=>{const t=pf(e),s=t===void 0?void 0:ff(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?Z(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>uf(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},mf=e=>e.getVariableDeclarations().flatMap(t=>gf(t)),hf=(e,t)=>{const s=E(t,aa);if(!z(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return mf(n)},vf=new Set(["delete","get","patch"]),Ef=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),xf=new Set(["auth","identity","session","user"]),Sf=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),yf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!B(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Af=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},bf=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Nf=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,wf=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>bf(s.getExpression(),t)&&Nf(s.getThenStatement())),Pf=(e,t)=>{for(const s of S(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!vf.has(i))continue;const o=n.getExpression(),a=B(o);if(!(a||r.isPropertyAccessExpression(o)&&B(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},If=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>vs(mt(s))!==void 0)),Tf=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Sf.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Cf=e=>{for(const t of S(e,d.Identifier))if(Ef.has(t.getText()))return!0;return[...xf].some(t=>ht(e,t).length>0)?!0:If(e)||Tf(e)},Of=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=le(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Si(s);if(i===void 0)return[];const o=n.receiver!==void 0&&vi(n.receiver,"use","rls"),a=Cf(i),c=new Set,l=[];for(const u of S(i,d.CallExpression)){const f=yf(u);if(f===void 0)continue;const p=Af(u);if(p===void 0||c.has(p)||!wf(i,p))continue;const g=Pf(i,p);g!==void 0&&(c.add(p),l.push({exportName:Z(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:g,table:f,usesRls:o,visibility:n.visibility}))}return l},kf=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...Of(a,o))}return s},Zi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?V(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},Rf=e=>{const t=O(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!we(s)},Lf=e=>{const t=O(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Ff=e=>{const s=O(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!we(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},ct=e=>{const t=V(e);return t===void 0||Oo(t.getSourceFile())},ss=(e,t)=>{const s=O(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=v(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&ct(o);if(Zi(mt(o),t))return!(r.isPropertyAccessExpression(o)&&fi.has(o.getName()))||r.isExpressionStatement(O(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!ct(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}},et={kind:"opaque"},Df={kind:"unreached"},_f=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},ns=e=>{const t=v(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?V(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=_f(s);return i===void 0||li(i)?void 0:i}const n=X(s)?v(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},er=(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?et:c===void 0?a.some(l=>l.isRestParameter())?et:Df:c.isRestParameter()?et:{kind:"parameter",parameter:c}},Mf=e=>{const t=O(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=ns(s.getExpression());return n===void 0?et:er(n,s,t)},$f=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Kf=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,tr=e=>{const t=O(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=Kf(s);if(n!==void 0)return w(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},zf=4,sr=(e,t,s=0)=>{if(Co(e))return!0;if(Rf(e)){const i=O(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!$f.has(c)}if(Lf(e)||Ff(e)||tr(e)||ss(e,t))return!0;const n=Mf(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Bf(n.parameter,s+1)},yn=new WeakMap,Bf=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=yn.get(e.compilerNode);if(n!==void 0)return n;if(t>zf)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||V(a)?.compilerNode!==e.compilerNode||sr(a,void 0,t));return(o||t===0)&&yn.set(e.compilerNode,o),o},An=new WeakMap,Vf=(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=V(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Uf=(e,t,s)=>{const{context:n,impl:i}=e,o=An.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(p=>{const g=p.getNameNode();return r.isIdentifier(g)?[g]:[]}),l=new Map(c.map(p=>[p.getText(),p.getParentOrThrow().compilerNode])),u=p=>r.isIdentifier(a)?sr(p,n):!we(p),f=!Vf(i,s)&&c.every(p=>(p.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(p=>{const g=p.getText();if(g==="arguments")return!1;const h=l.get(g);return h===void 0||c.includes(p)||V(p)?.compilerNode!==h?!0:u(p)});return An.set(i.compilerNode,f),f},bn=new WeakMap,Wf=e=>{let t=bn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=la(s);return n===void 0?[]:[[n.compilerNode,s]]})),bn.set(e.compilerNode,t)),t},jf=e=>{const t=Wf(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:Z(n)??n.getName()};return a!==void 0&&Uf(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},Kt="args",Le=e=>{const t=ps(e);if(t!==void 0){const c=v(t.object);return r.isIdentifier(c)&&c.getText()===Kt?t.member:void 0}if(!r.isIdentifier(e))return;const s=V(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=X(i)?v(i.getInitializer()):void 0;return r.isBindingElement(i)&&Ee(i)===Kt||r.isIdentifier(o)&&o.getText()===Kt?Ee(s):void 0},qf=new Set(["auth","identity","user"]),Hf=new Set(["activeOrganization.id","activeOrganizationId","id","organizationId","orgId","subject","userId"]),is=(e,t=!1)=>{const s=o=>{const a=vs(o);return a===void 0||!qf.has(a[0]??"")?!1:a.length===1?t:Hf.has(a.slice(1).join("."))},n=v(e)??e;if(s(n))return!0;const i=Ue(n);return i!==void 0&&s(i)},nr=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Le(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?Ue(n):void 0;if(o!==void 0)for(const a of nr(o,t-1))s.add(a)}return s},tt=e=>{const t=v(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...tt(n),...tt(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const p=Le(v(u)??u);return p===void 0?[]:tt(f).filter(g=>g===p)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Le(v(n)??n),c=Le(v(i)??i);return a!==void 0&&is(i)&&o.push(a),c!==void 0&&is(n)&&o.push(c),o},Gf=e=>{const t=v(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=v(n.getInitializer());return r.isCallExpression(i)&&Wo(i.getExpression(),"defineIdentityGuard")},Yf=e=>{if(!Gf(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Le(v(s)??s),o=t.some((a,c)=>c!==n&&is(a,!0));return i!==void 0&&o?[i]:[]})},Qf=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)},Xf=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Nn=(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},Jf=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Zf=(e,t)=>{const s=new Set;for(const n of S(e,d.IfStatement))if(n.getEnd()<=t&&Nn(n,e)&&Qf(n.getThenStatement()))for(const i of tt(n.getExpression()))s.add(i);for(const n of S(e,d.CallExpression))if(n.getEnd()<=t&&Jf(n)&&Nn(n,e))for(const i of Yf(n))s.add(i);return s},ep=(e,t)=>{const s=nr(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Xf);if(n===void 0)return!1;const i=Zf(n,e.getStart());return[...s].every(o=>i.has(o))},tp=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),sp=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),rs=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),ir=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),np=e=>{const t=O(e),s=t.getParent();if(r.isVariableDeclaration(s))return w(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},ip=e=>{const t=np(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||X(t)?[t]:void 0:ir(t)},Fe=e=>e.isUnion()?e.getUnionTypes().every(t=>Fe(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Fe(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),lt=(e,t,s)=>{const n=r.isCallExpression(e)?v(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},st=e=>{const t=v(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},rp=e=>{const t=r.isCallExpression(e)?v(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&sp.get(s.getText())?.has(t.getName())===!0&&ct(s)},op=e=>{const t=Ht(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=O(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&lt(n,pi)?n:void 0},ap=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=O(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:lt(n,tp,t)?n:void 0},cp=(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},lp=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&w(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},wn=e=>{const t=O(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&rp(s);return ap(s,t)??cp(s,t)??lp(s,t)??(n?s:op(t))},dp=5e4,rr=()=>({inProgress:new Set,verdicts:new Map});class up{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>dp&&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 fp=8,pp=8;class gp{budget;scope;taint;verdicts=rr();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Fe(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)?ir(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=fp?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(O(l),!0,a,0))&&(t===n||!Fe(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let g=wn(o);g!==void 0;g=wn(o)){if(r.isCallExpression(g)&&this.callbackCompromises(g,n))return!0;o=O(g)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Fe(o.getType());if(we(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=ip(o);if(u!==void 0)return u.some(g=>n(g,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const p=this.nestedReturningFunctionOf(o);return p!==void 0?this.resultCompromises(p,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=O(t).getParent();if(n>=pp)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===O(t)?this.valueCompromises(i,!1,s,n+1):!lt(i,rs);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||X(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=O(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>st(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=lt(t,rs)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=ns(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!ss(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(ss(s,this.scope.context))return!1;const i=ns(t.getExpression()),o=i===void 0?void 0:er(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)||tr(t)||w(Ht(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(v(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Ht(t);return w(s,this.scope.impl)?void 0:s}}const mp=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),hp=e=>{const t=v(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=V(t),n=r.isVariableDeclaration(s)?v(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},vp=new Set(["all","allSettled","any","race"]),Pn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,zt=8;class Ep{budget=new up;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=rr();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new gp(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,zt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>ko(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=V(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(p=>p.getInitializer())].some(p=>p!==void 0&&this.isTaintedValue(p,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(p=>p.compilerNode===t.compilerNode):-1,o=O(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const p=v(a.getExpression());if(!r.isPropertyAccessExpression(p)||!rs.has(p.getName()))return!0;const g=a.getArguments().filter(h=>h!==o);return this.isTaintedValue(p.getExpression(),!0)||g.some(h=>this.isTaintedValue(h,!1))}const c=r.isVariableDeclaration(a)&&X(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(p=>{const g=O(p),h=g.getParent();return!r.isCallExpression(h)||h.getExpression()!==g||this.isCallSiteTainted(h,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=v(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&ct(i)&&vp.has(n.getName())?v(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(p=>!r.isSpreadElement(p)&&this.isRootedInContext(p,s))}const c=r.isCallExpression(a)?v(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?v(a.getArguments()[0]):void 0,u=l===void 0?void 0:st(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=V(t),i=Pn(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=v(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&fi.has(i)?!1:i!==void 0&&pi.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>st(a)!==void 0)&&(i===void 0||!mp.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=mt(i),c=r.isIdentifier(a)?Pn(V(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=st(i);if(o===void 0)return!hp(i)&&n(i);const a=v(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=wo(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Zi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?V(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=X(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=li(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,zt))return!1;if(this.variableDepth>=zt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const In=new WeakMap,xp=e=>{const t=In.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Ep(e);return In.set(e.impl.compilerNode,s),s},Sp=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),yp=new Set(["insert","insertMany","insertManyUnsafe","patch","replace"]),Ap=new Set(["insert","insertMany","patch","patchMany","replace","upsert","upsertMany"]),Ze=(e,t)=>e===void 0||!r.isObjectLiteralExpression(e)?[]:t.flatMap(s=>{const n=U(e,s),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;return i===void 0?[]:[i]}),Tn=e=>e!==void 0&&r.isArrayLiteralExpression(e)?e.getElements():[],bp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return yp.has(t)&&gi(e.getExpression())?t:void 0},Np=(e,t)=>{const[s]=t.getArguments();if(e==="upsert")return Ze(s,["create","update"]);if(e==="upsertMany")return Ze(s,["rows"]).flatMap(i=>Tn(i).flatMap(o=>Ze(o,["create","update"])));if(e==="patchMany")return(s!==void 0&&r.isArrayLiteralExpression(s)?Tn(s):[s]).flatMap(o=>Ze(o,["values"]));const n=e==="patch"||e==="replace"?t.getArguments()[1]:s;return n===void 0?[]:[n]},wp=e=>{const t=e.getExpression(),s=bp(t);if(s!==void 0){const i=s==="patch"||s==="replace"?2:1,o=e.getArguments()[i];return o===void 0?void 0:{documentArguments:[o],method:s}}const n=St(e,Ap);if(!(n===void 0||!gi(n.database)))return{documentArguments:Np(n.method,e),method:n.method}},Pp=(e,t)=>{if(t!=="insertManyUnsafe"&&t!=="insertMany")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},Ip=(e,t)=>{const s=ps(e);return s?.member===t?v(s.object):void 0},Cn=(e,t)=>r.isIdentifier(e)&&V(e)?.compilerNode===t.compilerNode,or=(e,t,s,n=1)=>{const i=Ip(e,s);if(i!==void 0)return Cn(i,t);const o=r.isIdentifier(e)?V(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&Ee(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||X(l)&&Cn(v(l.getInitializer()),t))}const a=X(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&or(a,t,s,n-1)},os=e=>{const t=v(e)??e;return r.isConditionalExpression(t)?[...os(t.getWhenTrue()),...os(t.getWhenFalse())]:[t]},Tp=(e,t,s)=>{const n=[],i=s===void 0?void 0:xp(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||!Sp.has(a))continue;const l=os(c).filter(f=>i===void 0?H(f)&&!Bo(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&or(c,s.parameter,a),p=l.every(g=>ep(t.call,g));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...p&&{guarded:!0}})}}return n},Cp=e=>{const t=new Map;for(const s of e){const n=t.get(s.field);if(n===void 0)t.set(s.field,s);else{const i={...n};s.ownerScoped!==!0&&delete i.ownerScoped,s.guarded!==!0&&delete i.guarded,t.set(s.field,i)}}return[...t.values()]},Op=(e,t,s)=>{const n=wp(e);if(n===void 0)return[];const{method:i}=n,o=n.documentArguments.flatMap(f=>Pp(f,i));if(o.length===0)return[];const a=A(e),c=jf(e),l={call:e,method:i,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a},u=o.flatMap(f=>Tp(f,l,c));return i==="upsert"?Cp(u):u},kp=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=R(e,t,(c,l)=>Op(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return hs(o,s).map(c=>Ro(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},Rp=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Lp=e=>{const t=U(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?ai(t.getInitializer()):void 0},Fp=(e,t)=>{const s=k(e.getExpression());if(s===void 0||!Rp.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Lp(n):void 0;return{callee:s,scope:A(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Dp=(e,t)=>R(e,t,Fp),_p=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Mp=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},$p=(e,t)=>{const s=e.getArguments()[t];if(!(!s||!r.isObjectLiteralExpression(s)))return Vo(U(s,"handler"))},ar=(e,t)=>e.getParameters()[t]?.getNameNode(),cr=e=>{const t=new Map;for(const s of e){const n=s.getNameNode();r.isIdentifier(n)&&t.set(s.getPropertyNameNode()?.getText()??n.getText(),n.getText())}return t},lr=(e,t)=>e===t||e.startsWith(`${t}.`),dr=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},On=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)},ur=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>On(s));return r.isIdentifier(e)&&On(e)&&t.push(e),t},Kp=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},zp=new Set(["every","filter","flatMap","forEach","map","some"]),Bp=e=>{const t=ar(e,1);return t&&r.isIdentifier(t)?`${t.getText()}.messages`:t&&r.isObjectBindingPattern(t)?cr(t.getElements()).get("messages"):void 0},Vp=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!zp.has(s.getName())||s.getExpression().getText()!==t)return;const n=e.getArguments()[0];if(!n||!(r.isArrowFunction(n)||r.isFunctionExpression(n)))return;const i=n.getParameters()[0]?.getNameNode();return i&&r.isIdentifier(i)?i.getText():void 0},Up=e=>{const t=Bp(e);if(t===void 0)return[];const s=[t];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==t)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=Vp(n,t);i!==void 0&&s.push(`${i}.body`)}return s},Wp=e=>{const t=ar(e,0);if(t&&r.isIdentifier(t))return{params:void 0,receiver:t.getText(),runCallees:[]};if(!t||!r.isObjectBindingPattern(t))return{params:void 0,receiver:void 0,runCallees:[]};const s=cr(t.getElements());return{params:s.get("params"),receiver:void 0,runCallees:[...s].filter(([n])=>gs.has(n)).map(([,n])=>n)}},jp=(e,t,s)=>{const n=s.receiver===void 0?[]:[`${s.receiver}.params`],i=t==="workflow"?n:Up(e),o=new Set(t==="workflow"&&s.params!==void 0?[s.params]:[]),a=c=>dr(c).some(l=>i.some(u=>lr(l.getText(),u)))?!0:ur(c).some(l=>o.has(l.getText()));for(const c of e.getDescendantsOfKind(d.VariableDeclaration)){const l=c.getInitializer();if(l&&a(l))for(const u of Kp(c))o.add(u)}return{names:o,prefixes:i}},qp=(e,t)=>dr(e).some(s=>t.prefixes.some(n=>lr(s.getText(),n)))?!0:ur(e).some(s=>t.names.has(s.getText())),Hp=e=>{const t=Po(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Gp=(e,t,s)=>{const n=Wp(e),i=jp(e,t,n),o=new Set([...n.receiver===void 0?[]:[n.receiver],...i.prefixes.filter(l=>l.endsWith(".body")).map(l=>l.slice(0,-5))]),a=new Set(n.runCallees),c=[];for(const l of e.getDescendantsOfKind(d.CallExpression)){const u=l.getExpression(),f=r.isPropertyAccessExpression(u)&&gs.has(u.getName())&&o.has(u.getExpression().getText()),p=r.isIdentifier(u)&&a.has(u.getText());if(!f&&!p)continue;const g=l.getArguments()[1];if(!g||!qp(g,i))continue;const h=Hp(l.getArguments()[0]);h!==void 0&&c.push({dispatchKind:t,file:s,scope:A(l),line:l.getStartLineNumber(),targetExport:h.exportName,targetFile:h.file})}return c},Yp=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression)){const i=Mp(n),o=i===void 0?void 0:_p.get(i);if(o===void 0)continue;const a=$p(n,o);a!==void 0&&s.push(...Gp(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Qp=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Yp(i,I(t,n)))}return s},fr=/^\s*\/\/\s*lunora-advisor-exempt(?![\w-])(.*)$/u,Xp=/^([a-z][\w-]*)(?=\s|--|$)/iu,Is=e=>{const t=e.trimStart();if(!(t.startsWith("--")||t===""))return Xp.exec(t)?.[1]},Jp=new Set(["notify_missing_push_config"]),Zp=new Set(xo.map(e=>e.name)),eg=new Set(Eo.map(e=>e.name)),tg=/^lunora\//u,sg=/\.(?:ts|tsx|js|mts)$/u,Bt=e=>e.replace(tg,"").replace(sg,""),pr=["wrangler.jsonc","wrangler.json"],ng=e=>{if(e.getKind()===C.SyntaxKind.EndOfFileToken)return;const t=e.getStart();let s=e;for(;;){const n=s.getParent();if(n===void 0||r.isSourceFile(n)||r.isSyntaxList(n)||n.getStart()!==t)break;s=n}return{first:e.getStartLineNumber(),last:s.getEndLineNumber()}},kn=e=>e.getKind()===C.SyntaxKind.SingleLineCommentTrivia||e.getKind()===C.SyntaxKind.MultiLineCommentTrivia,ig=(e,t)=>{const s=e.getDescendantAtPos(t)??e.getLastToken();let n=s;if(kn(s)){if(s.getKind()!==C.SyntaxKind.SingleLineCommentTrivia||s.getStart()!==t)return;for(;kn(n);)n=e.getDescendantAtPos(n.getEnd())??e.getLastToken();return n}return s.getStart()<=t?void 0:(C.getLeadingCommentRanges(e.getFullText(),s.getPos())??[]).some(o=>o.pos===t&&o.kind===C.SyntaxKind.SingleLineCommentTrivia)?s:void 0},Rn=(e,t,s)=>{const n=e.getFullText().split(`
21
+ `},ki=new Set(["delete","get","head","options","patch","post","put"]),Jc=new Set(["handler","stream"]),Zc=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,an=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),el=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ki.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()}},tl=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)||ki.has(n.getName()))break;s=n.getExpression()}return el(s)},sl=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(an.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&an.has(s.getText()))return!0}return!1},nl=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Jc.has(n.getName()))return;const i=tl(s);if(!i||!Zc.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&sl(o);return{exportName:Z(e)??e.getName(),file:t,line:ni(e),method:i.method,path:i.path,usesGuard:a}},il=(e,t)=>{const s=[];for(const n of te(e)){const i=nl(n,t);i&&s.push(i)}return s},rl=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...il(i,I(t,n)))}return s},ol=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:J(e.getExpression(),["ai"]),al=(e,t)=>{if(!ol(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)||Ae(s)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},cl=(e,t)=>L(e,t,al),ll=new Set(["generateText","streamText"]),dl=new Set(["messages","prompt","system"]),ul=[{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"]}],fl=(e,t)=>ul.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),pl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[zo(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&fl(i,s));return n===void 0?void 0:`${n}.${s}`},gl=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=pl(t);if(s!==void 0)return s}},ml=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=Ee(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},hl=e=>{if(Fo(e))return!0;const t=ml(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},vl=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!dl.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&hl(s))return!0}return!1},El=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression)){const i=k(n.getExpression());if(i===void 0||!ll.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(k(c.getExpression())==="tool"&&(a=gl(c),a!==void 0))break;a!==void 0&&s.push({scope:A(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:vl(o)})}return s},xl=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...El(i,I(t,n)))}return s},Sl=e=>J(e,["fetch"]),yl=(e,t)=>{if(!Sl(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},Al=(e,t)=>L(e,t,yl),ys=(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=vt(s.getExpression());return n===void 0||ys(n,t)})}finally{t.delete(e)}},bl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=U(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:vt(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:ys(i)}},Nl=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?vt(o):void 0;a===void 0?s=!0:(t.push(a),s||=ys(a))}n=i.getExpression()}return{objects:t,opaque:s}},As=(e,t)=>t?Nl(t):bl(e),Ri=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=vt(s.getExpression());return n===void 0?[]:Ri(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},wl=e=>e.flatMap(t=>Ri(t,new Set)),Pl=new Set(["check","length","max"]),Qt=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(Pl.has(s.getName()))return!0;t=n}},Xt=e=>Go(e)||e==="@lunora/values",Il=e=>{const t=new Set(["v"]);for(const s of mi(e,"v",Xt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Xt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Tl=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},Cl=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Ol=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Xt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),bs=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return Cl(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Ol(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},kl=(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)},Rl=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Ll=e=>r.isReturnStatement(e)?e.getExpression():void 0,Fl=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Rl(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Ll(t);return s?[s]:[]}),Li=(e,t)=>{if(bs(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Li(e.getExpression(),t)},Dl=(e,t)=>{const s=kl(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Qt(e),i=new Set(Fl(s).map(o=>Li(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=bs(o,t);return a===void 0?[]:[{bounded:Qt(o)||n&&i.has(o),factory:a}]})},_l=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=bs(s,t),i=n===void 0?[]:[{bounded:Qt(s),factory:n}];return r.isCallExpression(s)?[...i,...Dl(s,t)]:i}),Ml=(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=_l(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}},$l=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=le(n);if(i?.visibility!=="public")return;const{objects:o}=As(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Ml(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:Z(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Kl=(e,t)=>{const s=[],n=Il(e),i={destructured:Tl(e,n),namespaces:n};for(const o of te(e)){const a=$l(o,t,i);a&&s.push(a)}return s},zl=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Kl(i,I(t,n)))}return s},Mt=e=>e?.getKind()===d.TrueKeyword,Bl=e=>e?.getKind()===d.FalseKeyword,Vl=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Ul=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Wl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&k(t.getExpression())==="scim"),jl=e=>e!==void 0&&r.isCallExpression(e)&&Ul.has(k(e.getExpression())??""),ql=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),Hl=e=>{const t=$(e,"advanced"),s=$(e,"emailAndPassword"),n=$(e,"session");return{analyzable:!0,disableCsrfCheck:Mt($(t,"disableCSRFCheck")),emailPasswordEnabled:Mt($(s,"enabled")),requireEmailVerification:Mt($(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Wl($(e,"plugins"))&&jl($(e,"database")),secureCookiesDisabled:Bl($(t,"useSecureCookies")),sessionFreshAgeZero:Vl($(n,"freshAge")),trustedOriginsWildcard:ql($(e,"trustedOrigins"))}},Gl=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Yl=(e,t)=>{if(k(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?Hl(s):Gl();return{scope:A(e),file:t,line:e.getStartLineNumber(),...i}},Ql=(e,t)=>bo(e,t,Yl),Xl=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return ui(e.getExpression(),t.matchReceiver)?s:void 0},Jl=(e,t,s)=>{const n=Xl(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex],o=a=>s.scope==="identity"?di(a)||_o(e,a):Ae(a);if(!(!i||!H(i)||o(i))&&!(s.requireUnmodifiedReach===!0&&!Do(i)))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:n}},Et=(e,t,s)=>L(e,t,(n,i)=>Jl(n,i,s)),Zl=new Set(["content","pdf","scrape","screenshot"]),ed=(e,t)=>Et(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Zl}),td=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),sd=new Set(["RateLimiter"]),nd=new Set(["extend"]),cn="lunora",id=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Fi=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}},Jt=e=>e&&r.isObjectLiteralExpression(e)?Fi(e):{analyzable:!1,presentKeys:[],trueKeys:[]},rd=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&ii(t.getBody());return s?Fi(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},od=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression)){const i=k(n.getExpression());i!==void 0&&(td.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Jt(n.getArguments()[0])}):nd.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...rd(n.getArguments()[0])}))}for(const n of S(e,d.NewExpression)){const i=k(n.getExpression());i===void 0||!sd.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Jt(n.getArguments()[0])})}return s},ad=e=>{for(const t of id){const s=E(e,t);if(!z(s))continue;const n=new us({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,ze(s,"utf8")),i=[];for(const o of S(n,d.CallExpression))k(o.getExpression())===cn&&i.push({callee:cn,file:t,line:o.getStartLineNumber(),...Jt(o.getArguments()[0])});return i}return[]},cd=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ve(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...od(o,n))}return s.push(...ad(gt(t))),s},ln="ctx.containers.",ld=e=>{if(!e.startsWith(ln))return!1;const t=e.slice(ln.length);return t.length>0&&!t.includes(".")},dd=(e,t)=>Et(e,t,{argIndex:0,scope:"identity",matchReceiver:ld,methods:new Set(["get"])}),ud=new Set(["allow","deny","setAllowed"]),fd=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=U(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},pd=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!fd(e)))return{detail:"enableInternet: true",scope:A(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},gd=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!ud.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:A(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},md=(e,t)=>pd(e,t)??gd(e,t),hd=(e,t)=>L(e,t,md),vd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(B(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&B(s.getExpression())?s.getName():void 0},Ed=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&B(s)?1:0]},xd=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Sd=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=>xd.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},yd=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return L(e,t,(i,o)=>{const a=vd(i);if(a===void 0)return;const c=Sd(Ed(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:A(i),table:a}})},Ad=new Set(["defineExportSink","r2Sink","webhookExportSink"]),bd=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Ad.has(s)?s:void 0},Nd=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=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}},wd=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ve(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of S(o,d.CallExpression)){const c=bd(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Nd(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},Pd=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Id=new Set(["dbRateLimit","rateLimit"]),Td=e=>{const t=oi(e);if(!t)return!1;const s=U(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Cd=(e,t)=>{const s=k(e.getExpression());if(s===void 0)return;const n=Pd.get(s);if(n!==void 0)return{callee:s,scope:A(e),failOpen:Td(e.getArguments()[n]),file:t,limitName:Id.has(s)?ri(e):"",line:e.getStartLineNumber()}},Od=(e,t)=>L(e,t,Cd),kd=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=le(t);if(s?.kind!=="query")return;const n=No(t,s.receiver);return n?{exportName:Z(e)??e.getName(),handler:n}:void 0},dn=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Rd=e=>{const t=dn(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=dn(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Ld=(e,t)=>{const s=[];for(const n of ht(e.handler,"flags"))s.push({callee:Rd(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Fd=(e,t)=>{const s=[];for(const n of te(e)){const i=kd(n);i&&s.push(...Ld(i,t))}return s},Dd=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Fd(i,I(t,n)))}return s},_d=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:J(e.getExpression(),["flags"]),Md=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},$d=(e,t)=>{if(!_d(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Md(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:A(e),file:t,key:i,line:e.getStartLineNumber()}},Kd=(e,t)=>L(e,t,$d),zd=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Bd=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Vd=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of S(i,d.CallExpression))zd(a)&&s.push({file:o,indexName:Bd(a),line:a.getStartLineNumber()})}return s},Ud=new Set(["delete","get","head","options","patch","post","put"]),Wd=new Set(["handler","stream"]),jd=new Set(["runAction","runMutation"]),qd=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),_e=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Di=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(Ee(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},un=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Di(s,"ctx")},fn=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Di(s,"request")},pn=(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(jd.has(a)&&_e(c,t))return a;if(qd.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&_e(c.getExpression(),t))return`db.${a}`}},gn=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&_e(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!_e(n.getInitializer(),t))){for(const o of i.getElements())if(Ee(o)==="auth")return!0}}return!1},Hd=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Gd=(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"&&_e(n.getExpression(),t)},Yd=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],_i=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Yd(s)},Qd=(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)?_i(t,a.getText()):[]}return[]},Xd=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=_i(s,t.getText());return n.length>0?n:Qd(t,s)},mn=(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=>Gd(i,t)&&Xd(i).some(o=>Hd.test(o)))},Jd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Wd.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(Ud.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Zd=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Yt(e.getArguments()[0]),l=c&&un(c,!0);if(!c||l===void 0||mn(c,fn(c,!0)))return;const u=pn(c,l);return u===void 0?void 0:{scope:A(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:gn(c,l),sideEffect:u}}const n=Jd(e);if(n===void 0)return;const i=Yt(e.getArguments()[0]),o=i&&un(i,!1);if(!i||o===void 0||mn(i,fn(i,!1)))return;const a=pn(i,o);return a===void 0?void 0:{scope:A(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:gn(i,o),sideEffect:a}},eu=(e,t)=>L(e,t,Zd),tu=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),su=new Set(["append","set"]),Mi=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",hn=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>tu.has(k(n.getExpression())??"")&&$o(n,t)),nu=(e,t)=>{if(hn(e,t))return!0;const s=Ue(e);return s!==void 0&&hn(s,t)},Zt=(e,t)=>Mo(e,t)&&!nu(e,t),iu=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Ue(e);return t!==void 0&&r.isNewExpression(t)&&k(t.getExpression())==="Headers"},at=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=Ue(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Ns=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Mi(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Zt(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=at(n.getExpression());i!==void 0&&Ns(i,t,s)}},$i=(e,t)=>{const s=at(e);if(s===void 0)return;const n=U(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=at(n.getInitializer());i!==void 0&&Ns(i,"response-init",t)},ru=(e,t)=>{const s=k(e.getExpression());if(s==="Response")$i(e.getArguments()[1],t);else if(s==="Headers"){const n=at(e.getArguments()[0]);n!==void 0&&Ns(n,"headers-ctor",t)}},ou=(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"){$i(e.getArguments()[1],t);return}if(su.has(n)&&iu(i)){const o=e.getArguments()[1];o!==void 0&&Zt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Mi(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},au=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))ru(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))ou(s,t)},cu=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Yt(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 au(n,{scope:A(e),relativePath:t,requestName:o.getText(),rows:a}),a},lu=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression))s.push(...cu(n,t));return s},du=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lu(i,I(t,n)))}return s},uu=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token","tokenHash"]),fu=new Set(["__proto__","email","exp","expiresAtMs","iat","name","nbf","orgId","role","roles","sub","teamId","userId"]),$t=32,pu=/^[A-Z_]\w{0,63}$/i,gu={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},mu=new Set(["allowedHosts","deniedHosts","interceptHttps"]),hu=(e,t)=>{const s=v(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return v(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},vu=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(y(s));if(!r.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=v(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Eu=new Set(["durable"]),xu=new Set(["rollback"]),Ki=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Su="defineApp",Re="app",vn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>y(s)===Re&&s.getInitializer()?.getText()===t)||t===Re&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>y(s)===Re),yu=e=>{if(e===void 0||!ea.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&y(e)===Re;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return y(t)===Re;if(r.isVariableDeclaration(t))return vn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&vn(e.getSourceFile(),s)},Au="AppBuilder",zi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},Bi=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Au&&s.getDeclarations().some(n=>zi(n))},bu=e=>e.getText()===Su&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||zi(t)),ws=(e,t,s=new Set)=>{const n=mt(t);if(n===void 0||!r.isIdentifier(n))return!1;if(bu(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return yu(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return ws(e,a.getInitializer(),s)}}return!1},Vi=(e,t)=>{const s=ps(t.getExpression());return s?.member==="deliveryAuthorization"&&(ws(e,s.object)||Bi(s.object))},Nu=new Map([["defineContainer",{keys:mu,signal:"containerEgressPolicy"}],["defineStep",{keys:xu,signal:"workflowRollback"}],["stream",{keys:Eu,signal:"durableStreams"}]]),wu=(e,t)=>{const s=Nu.get(Ki(t));if(s!==void 0)return t.getArguments().some(n=>vu(hu(e,n),s.keys))?s.signal:void 0},Pu=(e,t)=>gu[Ki(t)]??(Vi(e,t)?"deliveryAuthorization":void 0),Iu=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of b(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=sa(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=S(o,d.CallExpression);for(const c of a){const l=wu(o,c)??Pu(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>hi(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new us({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,ze(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Vi(i,o))}return n},Me={claims:[],diagnostics:[]},ae=e=>({claims:[],diagnostics:[e]}),xt=e=>r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)?xt(e.getExpression()):e,Ui=e=>{if(r.isSpreadAssignment(e))return!0;const t=e.getNameNode();return r.isComputedPropertyName(t)&&Es(t)===void 0},be=e=>e.getProperties().some(t=>Ui(t)),Wi=(e,t)=>e.getProperties().findLast(s=>!r.isSpreadAssignment(s)&&y(s)===t),ji=(e,t)=>{const s=Wi(e,t);return r.isPropertyAssignment(s)?s.getInitializer():void 0},qi=(e,t)=>{const s=ji(e,t);return s!==void 0&&xt(s).getKind()===d.FalseKeyword},$e="unreadable",Ps=(e,t)=>{const s=Wi(e,t);if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer()??$e:r.isShorthandPropertyAssignment(s)?s.getNameNode():$e},En=e=>{if(e===void 0||!r.isBlock(e))return e;const t=e.getStatements().filter(s=>r.isReturnStatement(s));return t.length===1?t[0]?.getExpression():void 0},fe=(e,t=0)=>{if(t>4)return;const s=xt(e);if(r.isObjectLiteralExpression(s))return s;if(r.isArrowFunction(s)||r.isFunctionExpression(s)){const c=En(s.getBody());return c===void 0?void 0:fe(c,t+1)}if(!r.isIdentifier(s))return;const n=s.getParent(),i=r.isShorthandPropertyAssignment(n)?n.getValueSymbol():s.getSymbol(),o=i?.isAlias()?i.getAliasedSymbol():i,[a]=o?.getDeclarations()??[];if(r.isVariableDeclaration(a)){const c=a.getInitializer();return c===void 0?void 0:fe(c,t+1)}if(r.isFunctionDeclaration(a)){const c=En(a.getBody());return c===void 0?void 0:fe(c,t+1)}},Tu=e=>{if(e===void 0)return;const t=xt(e);if(r.isArrayLiteralExpression(t))return"string";if(!(!r.isStringLiteral(t)&&!r.isNoSubstitutionTemplateLiteral(t)))switch(t.getLiteralValue()){case"boolean":return"boolean";case"date":case"string":return"string";case"number":return"number";default:return}},Cu=e=>qi(e,"returned"),Ou=(e,t)=>{if(!pu.test(e))return{reason:`\`${e}\` is not an identifier of at most 64 characters`};if(fu.has(e)||uu.has(e))return{reason:`\`${e}\` is reserved or secret-bearing, so the session never forwards it`};const s=fe(t);if(s===void 0||be(s))return{reason:`\`${e}\` is not a literal field definition`};const n=Tu(ji(s,"type"));return n===void 0?{reason:`\`${e}\` is not a scalar (string, number, boolean or date) column`}:{claim:{name:e,type:n,writable:!qi(s,"input")}}},ku=e=>{if(r.isSpreadAssignment(e))return;if(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e))return{reason:`\`${e.getName()}\` is a method or accessor, not a field definition`};const t=r.isPropertyAssignment(e)?y(e):e.getName(),s=r.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),n=s===void 0?void 0:fe(s);if(!(n!==void 0&&!be(n)&&Cu(n)))return s===void 0?{reason:`\`${t}\` has no initializer`}:Ou(t,s)},Ru=e=>{const t=[],s=[];for(const n of e.getProperties()){const i=ku(n);i?.claim!==void 0?t.push(i.claim):i!==void 0&&s.push(`${i.reason??"the entry cannot be a claim"}; it is not added to ctx.auth`)}return t.length>$t&&s.push(`${t.length.toString()} claims declared; the first ${$t.toString()} are forwarded, the rest are not`),{claims:t.slice(0,$t),diagnostics:s}},Lu=e=>{if(be(e))return ae("`user` has a spread or a computed key, so the user columns cannot be read");const t=Ps(e,"additionalFields");if(t===void 0)return Me;const s=t===$e?void 0:fe(t);return s===void 0||be(s)?ae("`user.additionalFields` is not an object literal, so the user columns cannot be read"):Ru(s)},Fu=e=>{if(be(e))return ae("the auth options contain a spread or a computed key, so the user columns cannot be read");const t=Ps(e,"user");if(t===void 0)return Me;const s=t===$e?void 0:fe(t);return s===void 0?ae("`user` is not an object literal, so the user columns cannot be read"):Lu(s)},Du=(e,t)=>{const s=t.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="auth")return!1;const n=s.getExpression();return ws(e,n)||Bi(n)},_u=e=>{const t=e.getProperties(),s=t.findLastIndex(n=>!r.isSpreadAssignment(n)&&y(n)==="options");return t.some((n,i)=>i>s&&Ui(n))},Mu=e=>{const[t]=e.getArguments();if(t===void 0)return Me;if(!r.isObjectLiteralExpression(t))return ae(".auth() is not called with an object literal, so its user columns cannot be read");const s=Ps(t,"options");if(s===void 0)return be(t)?ae("the .auth() argument has a spread or a computed key, so its options cannot be read"):Me;if(_u(t))return ae("a spread or computed key after `options` in .auth() may replace it, so the user columns cannot be read");const n=s===$e?void 0:fe(s);return n===void 0?ae("`.auth({ options })` does not resolve to an object literal, so the user columns cannot be read"):Fu(n)},Hi=(e,t)=>{const s=[];for(const{filePath:o}of Ve(t)){const a=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...S(a,d.CallExpression).filter(c=>Du(a,c)))}const[n,...i]=s;return n===void 0?Me:i.length===0?Mu(n):ae(`the app builder's .auth() is called ${s.length.toString()} times, so which declaration applies cannot be read`)},Gi="identity.ts",$u=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ei(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Ku=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&&Ei(n.getModuleSpecifierValue())}return!1},zu=e=>{if(r.isIdentifier(e))return $u(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Ku(t)}return!1},Bu=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!zu(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Pe(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=ms(s,"member");a!==void 0&&t.push({exportName:a})}return t},Vu=(e,t)=>{const s=E(t,Gi);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Bu(n);if(i.length!==0){if(i.length>1)throw Pe(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Yi=new Set(["auth","context.auth"]),Uu="userId",Wu=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},ju=(e,t)=>{const s=E(t,Gi);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(k(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Wu(o):void 0}},qu=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Yi.has(t.getText())||J(t,["auth"])?e:void 0},es=(e,t=!1)=>r.isAwaitExpression(e)?es(e.getExpression(),!0):r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isTypeAssertion(e)||r.isNonNullExpression(e)?es(e.getExpression(),t):{awaited:t,value:e},Qi=e=>{if(e===void 0)return;const{awaited:t,value:s}=es(e);if(!t||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||n.getName()!=="getIdentity")return;const i=n.getExpression();return Yi.has(i.getText())||J(i,["auth"])?s:void 0},Xi=e=>{if(r.isPropertyAccessExpression(e))return e.getName();const t=v(e.getArgumentExpression());return r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0},Hu=e=>{if(!r.isPropertyAccessExpression(e)&&!r.isElementAccessExpression(e)||we(e))return;const t=e.getExpression();return qu(t)!==void 0||Qi(t)!==void 0?Xi(e):void 0},ts=(e,t,s,n)=>({declared:t===Uu||n.has(t),file:s,key:t,line:e.getStartLineNumber(),scope:A(e)}),xn=(e,t,s)=>{const n=Hu(e);return n===void 0?void 0:ts(e,n,t,s)},Gu=(e,t,s)=>{if(Qi(e.getInitializer())===void 0)return[];const n=e.getNameNode();return r.isObjectBindingPattern(n)?n.getElements().filter(i=>i.getDotDotDotToken()===void 0).flatMap(i=>{const o=Es(i.getPropertyNameNode()??i.getNameNode());return o===void 0?[]:[ts(i,o,t,s)]}):!r.isIdentifier(n)||!X(e)?[]:n.findReferencesAsNodes().filter(i=>i!==n).flatMap(i=>{const o=O(i),a=o.getParent();if(!r.isPropertyAccessExpression(a)&&!r.isElementAccessExpression(a)||we(a))return[];const c=a.getExpression()===o?Xi(a):void 0;return c===void 0?[]:[ts(a,c,t,s)]})},Yu=(e,t)=>{const s=ju(e,t);if(s===void 0)return[];const n=Hi(e,t).claims.filter(o=>!o.writable).map(o=>o.name),i=new Set([...s,...n]);return[...ce(e,t,d.PropertyAccessExpression,(o,a)=>xn(o,a,i)),...ce(e,t,d.ElementAccessExpression,(o,a)=>xn(o,a,i)),...ce(e,t,d.VariableDeclaration,(o,a)=>Gu(o,a,i))]},Qu=(e,t)=>{if(k(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=$(s,"key");if(!(!n||!H(n)||Ae(n)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},Xu=(e,t)=>L(e,t,Qu),Ju=new Set(["delete","get","getRaw","getWithMetadata","put"]),Zu=(e,t,s=[])=>{const n=Et(e,t,{argIndex:0,scope:"identity",matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Ju});return hs(n,s)},ef=new Set(["queue","send"]),Sn=new Set(["bcc","cc","to"]),tf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!ef.has(t))return;const s=e.getExpression();return J(s,["mail"])||J(s,["email"])?t:void 0},sf=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Sn.has(y(t))&&H(n)&&!Ae(n)}if(!r.isPropertyAssignment(t)||!Sn.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&H(s)&&!Ae(s)}):!1,nf=(e,t)=>{const s=tf(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!sf(n)))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s}},rf=(e,t)=>L(e,t,nf),of=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=ot(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=ot(l);if(u===void 0)continue;const f=Ai(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},af=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;return n?.receiver?xs(n.receiver).flatMap(i=>of(i,Z(e)??e.getName(),t)):[]},cf=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...af(a,o))}return s},lf=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Ji=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===fs.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!B(s.getExpression())))return{database:s.getExpression(),table:s.getName()}},St=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!t.has(s.getName()))return;const n=s.getName(),i=s.getExpression(),o=Ji(i);if(o!==void 0)return{database:o.database,method:n,table:o.table};if(r.isPropertyAccessExpression(i)&&B(i.getExpression()))return{database:i.getExpression(),method:n,table:i.getName()}},df=new Set(["replace"]),uf=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="replace"&&B(t.getExpression())?!0:St(e,df)!==void 0},ff=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=U(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},pf=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ca(s.getExpression())?s:void 0},gf=e=>{const t=pf(e),s=t===void 0?void 0:ff(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?Z(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>uf(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},mf=e=>e.getVariableDeclarations().flatMap(t=>gf(t)),hf=(e,t)=>{const s=E(t,aa);if(!z(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return mf(n)},vf=new Set(["delete","get","patch"]),Ef=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),xf=new Set(["auth","identity","session","user"]),Sf=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),yf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!B(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Af=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},bf=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Nf=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,wf=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>bf(s.getExpression(),t)&&Nf(s.getThenStatement())),Pf=(e,t)=>{for(const s of S(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!vf.has(i))continue;const o=n.getExpression(),a=B(o);if(!(a||r.isPropertyAccessExpression(o)&&B(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},If=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>vs(mt(s))!==void 0)),Tf=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Sf.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Cf=e=>{for(const t of S(e,d.Identifier))if(Ef.has(t.getText()))return!0;return[...xf].some(t=>ht(e,t).length>0)?!0:If(e)||Tf(e)},Of=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=le(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Si(s);if(i===void 0)return[];const o=n.receiver!==void 0&&vi(n.receiver,"use","rls"),a=Cf(i),c=new Set,l=[];for(const u of S(i,d.CallExpression)){const f=yf(u);if(f===void 0)continue;const p=Af(u);if(p===void 0||c.has(p)||!wf(i,p))continue;const g=Pf(i,p);g!==void 0&&(c.add(p),l.push({exportName:Z(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:g,table:f,usesRls:o,visibility:n.visibility}))}return l},kf=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...Of(a,o))}return s},Zi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?V(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},Rf=e=>{const t=O(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!we(s)},Lf=e=>{const t=O(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Ff=e=>{const s=O(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!we(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},ct=e=>{const t=V(e);return t===void 0||Oo(t.getSourceFile())},ss=(e,t)=>{const s=O(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=v(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&ct(o);if(Zi(mt(o),t))return!(r.isPropertyAccessExpression(o)&&fi.has(o.getName()))||r.isExpressionStatement(O(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!ct(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}},et={kind:"opaque"},Df={kind:"unreached"},_f=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},ns=e=>{const t=v(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?V(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=_f(s);return i===void 0||li(i)?void 0:i}const n=X(s)?v(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},er=(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?et:c===void 0?a.some(l=>l.isRestParameter())?et:Df:c.isRestParameter()?et:{kind:"parameter",parameter:c}},Mf=e=>{const t=O(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=ns(s.getExpression());return n===void 0?et:er(n,s,t)},$f=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Kf=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,tr=e=>{const t=O(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=Kf(s);if(n!==void 0)return w(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},zf=4,sr=(e,t,s=0)=>{if(Co(e))return!0;if(Rf(e)){const i=O(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!$f.has(c)}if(Lf(e)||Ff(e)||tr(e)||ss(e,t))return!0;const n=Mf(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Bf(n.parameter,s+1)},yn=new WeakMap,Bf=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=yn.get(e.compilerNode);if(n!==void 0)return n;if(t>zf)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||V(a)?.compilerNode!==e.compilerNode||sr(a,void 0,t));return(o||t===0)&&yn.set(e.compilerNode,o),o},An=new WeakMap,Vf=(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=V(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Uf=(e,t,s)=>{const{context:n,impl:i}=e,o=An.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(p=>{const g=p.getNameNode();return r.isIdentifier(g)?[g]:[]}),l=new Map(c.map(p=>[p.getText(),p.getParentOrThrow().compilerNode])),u=p=>r.isIdentifier(a)?sr(p,n):!we(p),f=!Vf(i,s)&&c.every(p=>(p.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(p=>{const g=p.getText();if(g==="arguments")return!1;const h=l.get(g);return h===void 0||c.includes(p)||V(p)?.compilerNode!==h?!0:u(p)});return An.set(i.compilerNode,f),f},bn=new WeakMap,Wf=e=>{let t=bn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=la(s);return n===void 0?[]:[[n.compilerNode,s]]})),bn.set(e.compilerNode,t)),t},jf=e=>{const t=Wf(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:Z(n)??n.getName()};return a!==void 0&&Uf(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},Kt="args",Le=e=>{const t=ps(e);if(t!==void 0){const c=v(t.object);return r.isIdentifier(c)&&c.getText()===Kt?t.member:void 0}if(!r.isIdentifier(e))return;const s=V(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=X(i)?v(i.getInitializer()):void 0;return r.isBindingElement(i)&&Ee(i)===Kt||r.isIdentifier(o)&&o.getText()===Kt?Ee(s):void 0},qf=new Set(["auth","identity","user"]),Hf=new Set(["activeOrganization.id","activeOrganizationId","id","organizationId","orgId","subject","userId"]),is=(e,t=!1)=>{const s=o=>{const a=vs(o);return a===void 0||!qf.has(a[0]??"")?!1:a.length===1?t:Hf.has(a.slice(1).join("."))},n=v(e)??e;if(s(n))return!0;const i=Ue(n);return i!==void 0&&s(i)},nr=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Le(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?Ue(n):void 0;if(o!==void 0)for(const a of nr(o,t-1))s.add(a)}return s},tt=e=>{const t=v(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...tt(n),...tt(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const p=Le(v(u)??u);return p===void 0?[]:tt(f).filter(g=>g===p)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Le(v(n)??n),c=Le(v(i)??i);return a!==void 0&&is(i)&&o.push(a),c!==void 0&&is(n)&&o.push(c),o},Gf=e=>{const t=v(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=v(n.getInitializer());return r.isCallExpression(i)&&Wo(i.getExpression(),"defineIdentityGuard")},Yf=e=>{if(!Gf(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Le(v(s)??s),o=t.some((a,c)=>c!==n&&is(a,!0));return i!==void 0&&o?[i]:[]})},Qf=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)},Xf=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Nn=(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},Jf=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Zf=(e,t)=>{const s=new Set;for(const n of S(e,d.IfStatement))if(n.getEnd()<=t&&Nn(n,e)&&Qf(n.getThenStatement()))for(const i of tt(n.getExpression()))s.add(i);for(const n of S(e,d.CallExpression))if(n.getEnd()<=t&&Jf(n)&&Nn(n,e))for(const i of Yf(n))s.add(i);return s},ep=(e,t)=>{const s=nr(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Xf);if(n===void 0)return!1;const i=Zf(n,e.getStart());return[...s].every(o=>i.has(o))},tp=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),sp=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),rs=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),ir=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),np=e=>{const t=O(e),s=t.getParent();if(r.isVariableDeclaration(s))return w(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},ip=e=>{const t=np(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||X(t)?[t]:void 0:ir(t)},Fe=e=>e.isUnion()?e.getUnionTypes().every(t=>Fe(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Fe(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),lt=(e,t,s)=>{const n=r.isCallExpression(e)?v(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},st=e=>{const t=v(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},rp=e=>{const t=r.isCallExpression(e)?v(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&sp.get(s.getText())?.has(t.getName())===!0&&ct(s)},op=e=>{const t=Ht(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=O(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&lt(n,pi)?n:void 0},ap=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=O(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:lt(n,tp,t)?n:void 0},cp=(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},lp=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&w(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},wn=e=>{const t=O(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&rp(s);return ap(s,t)??cp(s,t)??lp(s,t)??(n?s:op(t))},dp=5e4,rr=()=>({inProgress:new Set,verdicts:new Map});class up{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>dp&&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 fp=8,pp=8;class gp{budget;scope;taint;verdicts=rr();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Fe(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)?ir(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=fp?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(O(l),!0,a,0))&&(t===n||!Fe(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let g=wn(o);g!==void 0;g=wn(o)){if(r.isCallExpression(g)&&this.callbackCompromises(g,n))return!0;o=O(g)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Fe(o.getType());if(we(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=ip(o);if(u!==void 0)return u.some(g=>n(g,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const p=this.nestedReturningFunctionOf(o);return p!==void 0?this.resultCompromises(p,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=O(t).getParent();if(n>=pp)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===O(t)?this.valueCompromises(i,!1,s,n+1):!lt(i,rs);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||X(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=O(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>st(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=lt(t,rs)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=ns(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!ss(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(ss(s,this.scope.context))return!1;const i=ns(t.getExpression()),o=i===void 0?void 0:er(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)||tr(t)||w(Ht(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(v(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Ht(t);return w(s,this.scope.impl)?void 0:s}}const mp=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),hp=e=>{const t=v(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=V(t),n=r.isVariableDeclaration(s)?v(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},vp=new Set(["all","allSettled","any","race"]),Pn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,zt=8;class Ep{budget=new up;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=rr();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new gp(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,zt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>ko(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=V(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(p=>p.getInitializer())].some(p=>p!==void 0&&this.isTaintedValue(p,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(p=>p.compilerNode===t.compilerNode):-1,o=O(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const p=v(a.getExpression());if(!r.isPropertyAccessExpression(p)||!rs.has(p.getName()))return!0;const g=a.getArguments().filter(h=>h!==o);return this.isTaintedValue(p.getExpression(),!0)||g.some(h=>this.isTaintedValue(h,!1))}const c=r.isVariableDeclaration(a)&&X(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(p=>{const g=O(p),h=g.getParent();return!r.isCallExpression(h)||h.getExpression()!==g||this.isCallSiteTainted(h,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=v(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&ct(i)&&vp.has(n.getName())?v(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(p=>!r.isSpreadElement(p)&&this.isRootedInContext(p,s))}const c=r.isCallExpression(a)?v(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?v(a.getArguments()[0]):void 0,u=l===void 0?void 0:st(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=V(t),i=Pn(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=v(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&fi.has(i)?!1:i!==void 0&&pi.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>st(a)!==void 0)&&(i===void 0||!mp.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=mt(i),c=r.isIdentifier(a)?Pn(V(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=st(i);if(o===void 0)return!hp(i)&&n(i);const a=v(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=wo(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Zi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?V(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=X(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=li(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,zt))return!1;if(this.variableDepth>=zt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const In=new WeakMap,xp=e=>{const t=In.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Ep(e);return In.set(e.impl.compilerNode,s),s},Sp=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),yp=new Set(["insert","insertMany","insertManyUnsafe","patch","replace"]),Ap=new Set(["insert","insertMany","patch","patchMany","replace","upsert","upsertMany"]),Ze=(e,t)=>e===void 0||!r.isObjectLiteralExpression(e)?[]:t.flatMap(s=>{const n=U(e,s),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;return i===void 0?[]:[i]}),Tn=e=>e!==void 0&&r.isArrayLiteralExpression(e)?e.getElements():[],bp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return yp.has(t)&&gi(e.getExpression())?t:void 0},Np=(e,t)=>{const[s]=t.getArguments();if(e==="upsert")return Ze(s,["create","update"]);if(e==="upsertMany")return Ze(s,["rows"]).flatMap(i=>Tn(i).flatMap(o=>Ze(o,["create","update"])));if(e==="patchMany")return(s!==void 0&&r.isArrayLiteralExpression(s)?Tn(s):[s]).flatMap(o=>Ze(o,["values"]));const n=e==="patch"||e==="replace"?t.getArguments()[1]:s;return n===void 0?[]:[n]},wp=e=>{const t=e.getExpression(),s=bp(t);if(s!==void 0){const i=s==="patch"||s==="replace"?2:1,o=e.getArguments()[i];return o===void 0?void 0:{documentArguments:[o],method:s}}const n=St(e,Ap);if(!(n===void 0||!gi(n.database)))return{documentArguments:Np(n.method,e),method:n.method}},Pp=(e,t)=>{if(t!=="insertManyUnsafe"&&t!=="insertMany")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},Ip=(e,t)=>{const s=ps(e);return s?.member===t?v(s.object):void 0},Cn=(e,t)=>r.isIdentifier(e)&&V(e)?.compilerNode===t.compilerNode,or=(e,t,s,n=1)=>{const i=Ip(e,s);if(i!==void 0)return Cn(i,t);const o=r.isIdentifier(e)?V(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&Ee(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||X(l)&&Cn(v(l.getInitializer()),t))}const a=X(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&or(a,t,s,n-1)},os=e=>{const t=v(e)??e;return r.isConditionalExpression(t)?[...os(t.getWhenTrue()),...os(t.getWhenFalse())]:[t]},Tp=(e,t,s)=>{const n=[],i=s===void 0?void 0:xp(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||!Sp.has(a))continue;const l=os(c).filter(f=>i===void 0?H(f)&&!Bo(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&or(c,s.parameter,a),p=l.every(g=>ep(t.call,g));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...p&&{guarded:!0}})}}return n},Cp=e=>{const t=new Map;for(const s of e){const n=t.get(s.field);if(n===void 0)t.set(s.field,s);else{const i={...n};s.ownerScoped!==!0&&delete i.ownerScoped,s.guarded!==!0&&delete i.guarded,t.set(s.field,i)}}return[...t.values()]},Op=(e,t,s)=>{const n=wp(e);if(n===void 0)return[];const{method:i}=n,o=n.documentArguments.flatMap(f=>Pp(f,i));if(o.length===0)return[];const a=A(e),c=jf(e),l={call:e,method:i,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a},u=o.flatMap(f=>Tp(f,l,c));return i==="upsert"?Cp(u):u},kp=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=L(e,t,(c,l)=>Op(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return hs(o,s).map(c=>Ro(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},Rp=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Lp=e=>{const t=U(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?ai(t.getInitializer()):void 0},Fp=(e,t)=>{const s=k(e.getExpression());if(s===void 0||!Rp.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Lp(n):void 0;return{callee:s,scope:A(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Dp=(e,t)=>L(e,t,Fp),_p=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Mp=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},$p=(e,t)=>{const s=e.getArguments()[t];if(!(!s||!r.isObjectLiteralExpression(s)))return Vo(U(s,"handler"))},ar=(e,t)=>e.getParameters()[t]?.getNameNode(),cr=e=>{const t=new Map;for(const s of e){const n=s.getNameNode();r.isIdentifier(n)&&t.set(s.getPropertyNameNode()?.getText()??n.getText(),n.getText())}return t},lr=(e,t)=>e===t||e.startsWith(`${t}.`),dr=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},On=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)},ur=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>On(s));return r.isIdentifier(e)&&On(e)&&t.push(e),t},Kp=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},zp=new Set(["every","filter","flatMap","forEach","map","some"]),Bp=e=>{const t=ar(e,1);return t&&r.isIdentifier(t)?`${t.getText()}.messages`:t&&r.isObjectBindingPattern(t)?cr(t.getElements()).get("messages"):void 0},Vp=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!zp.has(s.getName())||s.getExpression().getText()!==t)return;const n=e.getArguments()[0];if(!n||!(r.isArrowFunction(n)||r.isFunctionExpression(n)))return;const i=n.getParameters()[0]?.getNameNode();return i&&r.isIdentifier(i)?i.getText():void 0},Up=e=>{const t=Bp(e);if(t===void 0)return[];const s=[t];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==t)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=Vp(n,t);i!==void 0&&s.push(`${i}.body`)}return s},Wp=e=>{const t=ar(e,0);if(t&&r.isIdentifier(t))return{params:void 0,receiver:t.getText(),runCallees:[]};if(!t||!r.isObjectBindingPattern(t))return{params:void 0,receiver:void 0,runCallees:[]};const s=cr(t.getElements());return{params:s.get("params"),receiver:void 0,runCallees:[...s].filter(([n])=>gs.has(n)).map(([,n])=>n)}},jp=(e,t,s)=>{const n=s.receiver===void 0?[]:[`${s.receiver}.params`],i=t==="workflow"?n:Up(e),o=new Set(t==="workflow"&&s.params!==void 0?[s.params]:[]),a=c=>dr(c).some(l=>i.some(u=>lr(l.getText(),u)))?!0:ur(c).some(l=>o.has(l.getText()));for(const c of e.getDescendantsOfKind(d.VariableDeclaration)){const l=c.getInitializer();if(l&&a(l))for(const u of Kp(c))o.add(u)}return{names:o,prefixes:i}},qp=(e,t)=>dr(e).some(s=>t.prefixes.some(n=>lr(s.getText(),n)))?!0:ur(e).some(s=>t.names.has(s.getText())),Hp=e=>{const t=Po(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Gp=(e,t,s)=>{const n=Wp(e),i=jp(e,t,n),o=new Set([...n.receiver===void 0?[]:[n.receiver],...i.prefixes.filter(l=>l.endsWith(".body")).map(l=>l.slice(0,-5))]),a=new Set(n.runCallees),c=[];for(const l of e.getDescendantsOfKind(d.CallExpression)){const u=l.getExpression(),f=r.isPropertyAccessExpression(u)&&gs.has(u.getName())&&o.has(u.getExpression().getText()),p=r.isIdentifier(u)&&a.has(u.getText());if(!f&&!p)continue;const g=l.getArguments()[1];if(!g||!qp(g,i))continue;const h=Hp(l.getArguments()[0]);h!==void 0&&c.push({dispatchKind:t,file:s,scope:A(l),line:l.getStartLineNumber(),targetExport:h.exportName,targetFile:h.file})}return c},Yp=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression)){const i=Mp(n),o=i===void 0?void 0:_p.get(i);if(o===void 0)continue;const a=$p(n,o);a!==void 0&&s.push(...Gp(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Qp=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Yp(i,I(t,n)))}return s},fr=/^\s*\/\/\s*lunora-advisor-exempt(?![\w-])(.*)$/u,Xp=/^([a-z][\w-]*)(?=\s|--|$)/iu,Is=e=>{const t=e.trimStart();if(!(t.startsWith("--")||t===""))return Xp.exec(t)?.[1]},Jp=new Set(["notify_missing_push_config"]),Zp=new Set(xo.map(e=>e.name)),eg=new Set(Eo.map(e=>e.name)),tg=/^lunora\//u,sg=/\.(?:ts|tsx|js|mts)$/u,Bt=e=>e.replace(tg,"").replace(sg,""),pr=["wrangler.jsonc","wrangler.json"],ng=e=>{if(e.getKind()===C.SyntaxKind.EndOfFileToken)return;const t=e.getStart();let s=e;for(;;){const n=s.getParent();if(n===void 0||r.isSourceFile(n)||r.isSyntaxList(n)||n.getStart()!==t)break;s=n}return{first:e.getStartLineNumber(),last:s.getEndLineNumber()}},kn=e=>e.getKind()===C.SyntaxKind.SingleLineCommentTrivia||e.getKind()===C.SyntaxKind.MultiLineCommentTrivia,ig=(e,t)=>{const s=e.getDescendantAtPos(t)??e.getLastToken();let n=s;if(kn(s)){if(s.getKind()!==C.SyntaxKind.SingleLineCommentTrivia||s.getStart()!==t)return;for(;kn(n);)n=e.getDescendantAtPos(n.getEnd())??e.getLastToken();return n}return s.getStart()<=t?void 0:(C.getLeadingCommentRanges(e.getFullText(),s.getPos())??[]).some(o=>o.pos===t&&o.kind===C.SyntaxKind.SingleLineCommentTrivia)?s:void 0},Rn=(e,t,s)=>{const n=e.getFullText().split(`
22
22
  `),i=[];let o=0;return n.forEach((a,c)=>{const l=o;o+=a.length+1;const f=fr.exec(a.trimEnd())?.[1];if(f===void 0)return;const p=Is(f),g=p===void 0?void 0:ig(e,l+a.indexOf("//"));if(p===void 0||g===void 0)return;const h=f.indexOf("--"),x=h===-1?"":f.slice(h+2).trim();i.push({display:t,key:s,line:c+1,reason:x,rule:p,span:ng(g)})}),i},rg=new Set([C.SyntaxKind.ConflictMarkerTrivia,C.SyntaxKind.MultiLineCommentTrivia,C.SyntaxKind.NewLineTrivia,C.SyntaxKind.ShebangTrivia,C.SyntaxKind.SingleLineCommentTrivia,C.SyntaxKind.WhitespaceTrivia]),og=e=>{const t=C.createScanner(C.ScriptTarget.Latest,!1,C.LanguageVariant.Standard,e),s=new Set,n=[];for(let i=t.scan();i!==C.SyntaxKind.EndOfFileToken;i=t.scan())i===C.SyntaxKind.SingleLineCommentTrivia?s.add(t.getTokenStart()):rg.has(i)||n.push({kind:i,start:t.getTokenStart(),value:t.getTokenValue()});return{lineComments:s,tokens:n}},ag=(e,t,s)=>{const n=e.findIndex(a=>a.start>=s),i=e[n];return i===void 0?void 0:{key:i.kind===C.SyntaxKind.StringLiteral&&e[n+1]?.kind===C.SyntaxKind.ColonToken?i.value:void 0,line:t.slice(0,i.start).split(`
23
23
  `).length}},cg=e=>{const t=pr.find(l=>z(E(e,l)));if(t===void 0)return[];const s=ze(E(e,t),"utf8"),n=s.split(`
24
- `),i=[],{lineComments:o,tokens:a}=og(s);let c=0;return n.forEach((l,u)=>{const f=c;c+=l.length+1;const g=fr.exec(l.trimEnd())?.[1];if(g===void 0||!o.has(f+l.indexOf("//")))return;const h=Is(g);if(h===void 0)return;const x=g.indexOf("--"),D=x===-1?"":g.slice(x+2).trim(),N=ag(a,s,c),G=N?.key;i.push({display:t,key:t,line:u+1,reason:D,rule:h,span:N===void 0?void 0:{first:N.line,last:N.line},...G===void 0?{}:{variable:G}})}),i},lg=(e,t)=>Be(e,t).split(si).join("/"),Ln=(e,t,s)=>{const{display:n,line:i,rule:o}=t;return{cacheKey:`${e}:${n}:${i.toString()}`,categories:["SCHEMA"],description:"An inline `// lunora-advisor-exempt <rule> -- <reason>` directive accepts one advisor finding at the site it sits above. Each directive needs a rule id that can be suppressed and a non-empty reason, and must match a finding, or it does nothing.",detail:s,facing:"INTERNAL",level:"WARN",metadata:{file:n,line:i,rule:o},name:e,remediation:"Fix the directive so it names a suppressible rule with a reason after `--` and sits directly above the code it accepts, or delete it.",title:"Advisor suppression directive does not apply"}},Fn=e=>e.span===void 0?Number.POSITIVE_INFINITY:e.span.last-e.span.first,dg=e=>{if(eg.has(e.rule))return`\`${e.rule}\` is a runtime lint, which has no source site to suppress.`;if(Jp.has(e.rule))return`\`${e.rule}\` reports no source location, so a directive cannot match it.`;if(!Zp.has(e.rule))return`\`${e.rule}\` is not a known advisor rule.`;if(e.reason==="")return`The \`${e.rule}\` directive gives no reason after \`--\`, so it suppresses nothing.`},ug=(e,t,s,n)=>{const i=[...cg(t)];for(const u of e.getSourceFiles()){const f=u.getFilePath(),p=Be(s,f),g=lg(t,f);p!==""&&!p.startsWith("..")?i.push(...Rn(u,g,Bt(p.split(si).join("/")))):!g.startsWith("..")&&!g.split("/").includes("node_modules")&&!u.isDeclarationFile()&&i.push(...Rn(u,g,Bt(g)))}const o=[],a=[];for(const u of i){const f=dg(u);f===void 0?o.push(u):a.push(Ln("advisor_suppression_invalid",u,f))}const c=new Set,l=n.map(u=>{if(u.suppressed!==void 0)return u;const{file:f,key:p,line:g}=u.metadata;if(typeof f!="string"||typeof g!="number")return u;const[h]=o.filter(x=>x.rule===u.name&&x.key===Bt(f)&&x.span!==void 0&&(!pr.includes(x.key)||x.variable===p)&&x.span.first<=g&&g<=x.span.last).toSorted((x,D)=>Fn(x)-Fn(D));return h===void 0?u:(c.add(h),{...u,suppressed:{file:h.display,line:h.line,reason:h.reason}})});for(const u of o)c.has(u)||a.push(Ln("advisor_suppression_unused",u,`The \`${u.rule}\` directive suppresses no finding: nothing of that rule is reported on the code below it.`));return[...l,...a]},Dn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},_n=new Set(["account","credential","member","passkey","session","user"]),fg=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),gr=e=>{const s=fg(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return _n.has(s)||_n.has(n)},pg=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},gg=(e,t)=>{const{objects:s,opaque:n}=As(e,t);return wl(s).some(i=>pg(i))?!0:n?void 0:!1},mg=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!U(t,"captcha"),usesRateLimit:!!U(t,"rateLimit")}},nt={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},hg=e=>{const t=qo(e),s=t?k(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=mg(t);return{...nt,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Dn?{...nt,[Dn[s]]:!0}:nt},vg=e=>{const t={...nt};for(const s of jo(e)){const n=s.name==="use"?s.call.getArguments()[0]:void 0;if(!n)continue;const i=hg(n);t.usesCaptcha||=i.usesCaptcha,t.usesEmailGate||=i.usesEmailGate,t.usesMask||=i.usesMask,t.usesRateLimit||=i.usesRateLimit,t.usesRls||=i.usesRls}return t},Eg=new Set(["insert","insertMany","insertManyUnsafe","replace"]),xg=new Set(["insert","insertMany","replace","upsert","upsertMany"]),Sg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Eg.has(t.getName()))return!1;const s=t.getExpression();if(!B(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:gr(i.getLiteralText())},yg=e=>{if(Sg(e))return!0;const t=St(e,xg);return t!==void 0&&gr(t.table)},Ag=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Mn=new Set(["queues","scheduler","topics","workflows"]),bg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ag.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&Mn.has(s.getName())&&Uo(s.getExpression()))return!0;s=s.getExpression()}const n=vs(s);return n?.length===1&&Mn.has(n[0]??"")},Ng=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return B(s)},mr=new Set(["generateObject","generateText","streamObject","streamText"]),wg=e=>{const t=k(e.getExpression());return t!==void 0&&mr.has(t)},Pg=e=>{const t=k(e.getExpression());if(t===void 0||!mr.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!U(s,"maxOutputTokens")},Ig=new Set(["log","span","trace"]),Tg=new Set(["ai"]),Cg=new Set(["email","mail"]),Og=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Vt=(e,t)=>[...t].some(s=>ht(e,s).length>0),hr=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),kg=new Set(["every","filter","flatMap","forEach","map","some"]),Rg=new Set(["all","allSettled","race"]),vr=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(kg.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Rg.has(n))return t},Lg=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(hr.has(t.getKind())){const s=vr(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Fg=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(hr.has(t.getKind())){if(t=vr(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Dg=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(g=>{const h=g.getExpression();return r.isIdentifier(h)&&h.getText()===l&&r.isAwaitExpression(g.getParent())}),p=u.getCatchClause();return f&&p!==void 0&&p.getDescendantsOfKind(d.ThrowStatement).length>0})},_g=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}},Mg=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}},$g=e=>{let t=!1,s=!0;for(const n of[...Og].flatMap(i=>ht(e,i))){const i=Mg(n);i&&(t=!0,!Lg(i)&&!_g(i)&&!Dg(i)&&!Fg(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Kg=e=>S(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),$n="lunora-advisor-exempt",zg=/^[\s*/]+/u,Bg=/[\w-]/u,Vg=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
24
+ `),i=[],{lineComments:o,tokens:a}=og(s);let c=0;return n.forEach((l,u)=>{const f=c;c+=l.length+1;const g=fr.exec(l.trimEnd())?.[1];if(g===void 0||!o.has(f+l.indexOf("//")))return;const h=Is(g);if(h===void 0)return;const x=g.indexOf("--"),_=x===-1?"":g.slice(x+2).trim(),N=ag(a,s,c),G=N?.key;i.push({display:t,key:t,line:u+1,reason:_,rule:h,span:N===void 0?void 0:{first:N.line,last:N.line},...G===void 0?{}:{variable:G}})}),i},lg=(e,t)=>Be(e,t).split(si).join("/"),Ln=(e,t,s)=>{const{display:n,line:i,rule:o}=t;return{cacheKey:`${e}:${n}:${i.toString()}`,categories:["SCHEMA"],description:"An inline `// lunora-advisor-exempt <rule> -- <reason>` directive accepts one advisor finding at the site it sits above. Each directive needs a rule id that can be suppressed and a non-empty reason, and must match a finding, or it does nothing.",detail:s,facing:"INTERNAL",level:"WARN",metadata:{file:n,line:i,rule:o},name:e,remediation:"Fix the directive so it names a suppressible rule with a reason after `--` and sits directly above the code it accepts, or delete it.",title:"Advisor suppression directive does not apply"}},Fn=e=>e.span===void 0?Number.POSITIVE_INFINITY:e.span.last-e.span.first,dg=e=>{if(eg.has(e.rule))return`\`${e.rule}\` is a runtime lint, which has no source site to suppress.`;if(Jp.has(e.rule))return`\`${e.rule}\` reports no source location, so a directive cannot match it.`;if(!Zp.has(e.rule))return`\`${e.rule}\` is not a known advisor rule.`;if(e.reason==="")return`The \`${e.rule}\` directive gives no reason after \`--\`, so it suppresses nothing.`},ug=(e,t,s,n)=>{const i=[...cg(t)];for(const u of e.getSourceFiles()){const f=u.getFilePath(),p=Be(s,f),g=lg(t,f);p!==""&&!p.startsWith("..")?i.push(...Rn(u,g,Bt(p.split(si).join("/")))):!g.startsWith("..")&&!g.split("/").includes("node_modules")&&!u.isDeclarationFile()&&i.push(...Rn(u,g,Bt(g)))}const o=[],a=[];for(const u of i){const f=dg(u);f===void 0?o.push(u):a.push(Ln("advisor_suppression_invalid",u,f))}const c=new Set,l=n.map(u=>{if(u.suppressed!==void 0)return u;const{file:f,key:p,line:g}=u.metadata;if(typeof f!="string"||typeof g!="number")return u;const[h]=o.filter(x=>x.rule===u.name&&x.key===Bt(f)&&x.span!==void 0&&(!pr.includes(x.key)||x.variable===p)&&x.span.first<=g&&g<=x.span.last).toSorted((x,_)=>Fn(x)-Fn(_));return h===void 0?u:(c.add(h),{...u,suppressed:{file:h.display,line:h.line,reason:h.reason}})});for(const u of o)c.has(u)||a.push(Ln("advisor_suppression_unused",u,`The \`${u.rule}\` directive suppresses no finding: nothing of that rule is reported on the code below it.`));return[...l,...a]},Dn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},_n=new Set(["account","credential","member","passkey","session","user"]),fg=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),gr=e=>{const s=fg(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return _n.has(s)||_n.has(n)},pg=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},gg=(e,t)=>{const{objects:s,opaque:n}=As(e,t);return wl(s).some(i=>pg(i))?!0:n?void 0:!1},mg=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!U(t,"captcha"),usesRateLimit:!!U(t,"rateLimit")}},nt={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},hg=e=>{const t=qo(e),s=t?k(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=mg(t);return{...nt,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Dn?{...nt,[Dn[s]]:!0}:nt},vg=e=>{const t={...nt};for(const s of jo(e)){const n=s.name==="use"?s.call.getArguments()[0]:void 0;if(!n)continue;const i=hg(n);t.usesCaptcha||=i.usesCaptcha,t.usesEmailGate||=i.usesEmailGate,t.usesMask||=i.usesMask,t.usesRateLimit||=i.usesRateLimit,t.usesRls||=i.usesRls}return t},Eg=new Set(["insert","insertMany","insertManyUnsafe","replace"]),xg=new Set(["insert","insertMany","replace","upsert","upsertMany"]),Sg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Eg.has(t.getName()))return!1;const s=t.getExpression();if(!B(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:gr(i.getLiteralText())},yg=e=>{if(Sg(e))return!0;const t=St(e,xg);return t!==void 0&&gr(t.table)},Ag=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Mn=new Set(["queues","scheduler","topics","workflows"]),bg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ag.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&Mn.has(s.getName())&&Uo(s.getExpression()))return!0;s=s.getExpression()}const n=vs(s);return n?.length===1&&Mn.has(n[0]??"")},Ng=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return B(s)},mr=new Set(["generateObject","generateText","streamObject","streamText"]),wg=e=>{const t=k(e.getExpression());return t!==void 0&&mr.has(t)},Pg=e=>{const t=k(e.getExpression());if(t===void 0||!mr.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!U(s,"maxOutputTokens")},Ig=new Set(["log","span","trace"]),Tg=new Set(["ai"]),Cg=new Set(["email","mail"]),Og=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Vt=(e,t)=>[...t].some(s=>ht(e,s).length>0),hr=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),kg=new Set(["every","filter","flatMap","forEach","map","some"]),Rg=new Set(["all","allSettled","race"]),vr=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(kg.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Rg.has(n))return t},Lg=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(hr.has(t.getKind())){const s=vr(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Fg=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(hr.has(t.getKind())){if(t=vr(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Dg=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(g=>{const h=g.getExpression();return r.isIdentifier(h)&&h.getText()===l&&r.isAwaitExpression(g.getParent())}),p=u.getCatchClause();return f&&p!==void 0&&p.getDescendantsOfKind(d.ThrowStatement).length>0})},_g=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}},Mg=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}},$g=e=>{let t=!1,s=!0;for(const n of[...Og].flatMap(i=>ht(e,i))){const i=Mg(n);i&&(t=!0,!Lg(i)&&!_g(i)&&!Dg(i)&&!Fg(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Kg=e=>S(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),$n="lunora-advisor-exempt",zg=/^[\s*/]+/u,Bg=/[\w-]/u,Vg=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
25
25
  `);for(const n of s.split(`
26
- `)){const i=n.replace(zg,"");if(!i.startsWith($n))continue;const o=i.slice($n.length);if(Bg.test(o.charAt(0))||n.trimStart().startsWith("//")&&Is(o)!==void 0)continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Ug=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=U(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Wg=(e,t)=>{const s=Ug(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)},jg=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of S(e,d.CallExpression))if(yg(l)&&(o=!0),bg(l)&&(t=!0),Ng(l)&&(i=!0),wg(l)&&(s=!0),Pg(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=$g(e);return{callsMail:Vt(e,Cg),emitsEvent:Vt(e,Ig),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Vt(e,Tg),throwsBareError:Kg(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},qg=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=le(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?vg(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Wg(e,s);return{...o?jg(o):{},...Vg(e),...i,analyzableBody:o!==void 0,exportName:Z(e)??e.getName(),file:t,hasEmailArg:gg(s,n.receiver),kind:n.kind,line:ni(e),visibility:n.visibility}},Hg=(e,t)=>{const s=[];for(const n of te(e)){const i=qg(n,t);i&&s.push(i)}return s},Gg=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hg(i,I(t,n)))}return s},Yg=new Set(["dbRateLimit","rateLimit"]),Qg=e=>r.isArrowFunction(e)?e.getBody():e,Xg=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Er=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},xr=(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)})},Jg=(e,t)=>H(e)||t!==void 0&&xr(e,t).some(s=>Er(s)),Zg=(e,t)=>t===void 0?Ae(e):xr(e,t).some(s=>!Er(s)),em=(e,t)=>{const s=k(e.getExpression());if(s===void 0||!Yg.has(s))return;const n=$(oi(e.getArguments()[2]),"key");if(!n)return;const i=Qg(n),o=Xg(n);if(!(!Jg(i,o)||Zg(i,o)))return{callee:s,scope:A(e),file:t,limitName:ri(e),line:e.getStartLineNumber()}},tm=(e,t)=>R(e,t,em),sm=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),nm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!sm.has(t.getName()))return;const s=t.getExpression();if(B(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&B(s.getExpression()))return s.getName()},im=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&B(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},rm=e=>{let t=v(e)??e;for(;r.isAwaitExpression(t);)t=v(t.getExpression())??t.getExpression();return t},Sr=(e,t=!1)=>{const s=rm(e);if(r.isIdentifier(s)){if(t)return;const n=Ko(s),i=n!==void 0&&r.isIdentifier(n.getNameNode())?n.getInitializer():void 0;return i===void 0||!r.isIdentifier(n?.getNameNode())?void 0:Sr(i,!0)}if(r.isCallExpression(s))return nm(s)??im(s)},om=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of S(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},am=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=le(s);if(n?.kind!=="query")return[];const i=Si(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Ho(n.receiver,"output"),a=n.receiver!==void 0&&vi(n.receiver,"use","mask"),c=new Set,l=[];for(const u of om(i)){const f=Sr(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:Z(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},cm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...am(a,o))}return s},lm=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},dm=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;if(!n)return[];const i=[];for(const o of S(e,d.CallExpression)){const a=xi(o);if(a===void 0)continue;const c=lm($(a.options,"with"));c.length!==0&&i.push({exportName:Z(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},um=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...dm(a,o))}return s},Q=(e,t)=>`${e}:${t}`,Kn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},fm=(e,t)=>[...ce(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Kn(s,n,s.getName(),s.isExported()):void 0),...ce(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Kn(i,n,s.getName(),i.isExported()):void 0})],pm=(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(Q(c,a))},gm=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,mm=(e,t)=>{const s=new Map(e.map(n=>[Q(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(Q(i.file,i.name))?.set(gm(n),{fields:n.fields,method:n.method,table:n.table})}return s},hm=(e,t,s)=>S(e.node,d.CallExpression).map(n=>pm(n,t,s)).filter(n=>n!==void 0),vm=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(Q(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(Q(o.file,o.name))?.push(a)}},Em=(e,t,s)=>{const n=new Map(e.map(a=>[Q(a.file,a.name),a])),i=new Map(e.map(a=>[`${Ss(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[Q(a.file,a.name),hm(a,n,t)]));return vm(s,n,i,o),o},xm=(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},Sm=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(Q(i.file,i.name))??[])xm(t.get(Q(i.file,i.name)),t.get(Q(o.file,o.name)))&&(n=!0)}},ym=(e,t,s,n)=>{const i=fm(e,t),o=mm(i,s);return Sm(i,o,Em(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(Q(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},dt=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=dt(e.getLeft()),s=dt(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Am=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&&dt(t)!==void 0},bm=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()}},Nm=(e,t,s)=>xa(e)?!Io(s)&&Sa(bm(t)):!0,wm=(e,t)=>{const s=[],n=[...S(e,d.BinaryExpression),...S(e,d.StringLiteral),...S(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(Am(o))continue;const a=dt(o);if(a===void 0)continue;const c=va(a);if(c===void 0||!Nm(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:Ea(a)}))}return s},Pm=(e,t)=>{const s=[],n=new us({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of b(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,ze(i,"utf8"),{overwrite:!0});s.push(...wm(o,I(t,i)))}return s},Im=e=>{const t=$(e,"includeDeleted");if(t!==void 0||!r.isObjectLiteralExpression(e))return t;const s=U(e,"includeDeleted");return r.isShorthandPropertyAssignment(s)?s.getNameNode():void 0},Tm=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;if(!n)return[];const i=[];for(const o of S(e,d.CallExpression)){const a=xi(o);if(a===void 0)continue;const c=Im(a.options);if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&H(c);!l&&!u||i.push({exportName:Z(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Cm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...Tm(a,o))}return s},Om=new Set(["query","unsafe"]),yr=3,km=e=>!r.isPropertyAccessExpression(e)||!Om.has(e.getName())?!1:J(e.getExpression(),["sql"]),as=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(!(!X(t)||!r.isIdentifier(t.getNameNode())))return t.getInitializer()},Rm=e=>{const t=as(e);if(t!==void 0||!r.isIdentifier(e))return t;const s=e.getSymbol()?.getDeclarations()[0],n=r.isBindingElement(s)?s.getParent().getParent():void 0;if(!r.isBindingElement(s)||!X(n))return;const i=n.getInitializer(),o=v(i),a=v(o!==void 0&&r.isIdentifier(o)?as(o):o),c=u=>r.isSpreadAssignment(u)||r.isPropertyAssignment(u)&&r.isComputedPropertyName(u.getNameNode()),l=r.isObjectLiteralExpression(a)&&!a.getProperties().some(u=>c(u))?a.getProperty(Ee(s)):void 0;return r.isShorthandPropertyAssignment(l)?l.getNameNode():r.isPropertyAssignment(l)?l.getInitializer():i},Lm=e=>{const t=v(e);if(!t)return!1;if(r.isTemplateExpression(t))return!0;if(r.isBinaryExpression(t))return t.getOperatorToken().getKind()===d.PlusToken;if(!r.isCallExpression(t))return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)&&["concat","join"].includes(s.getName())},Fm=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return!1;const n=e.getArguments().every(o=>t(o));if(s.getName()==="concat")return n&&t(s.getExpression());const i=v(s.getExpression());return s.getName()==="join"&&n&&r.isArrayLiteralExpression(i)&&i.getElements().every(o=>t(o))},xe=(e,t=yr)=>{const s=v(e);return s?r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)||r.isNumericLiteral(s)?!0:r.isTemplateExpression(s)?s.getTemplateSpans().every(n=>xe(n.getExpression(),t)):r.isBinaryExpression(s)?s.getOperatorToken().getKind()===d.PlusToken&&xe(s.getLeft(),t)&&xe(s.getRight(),t):r.isIdentifier(s)?t>0&&xe(as(s),t-1):r.isCallExpression(s)?Fm(s,n=>xe(n,t)):!1:!1},Dm=e=>{const t=v(e);if(!t||xe(t))return!1;let s=t;for(let n=0;s!==void 0&&n<=yr;n+=1){if(Lm(s)||H(s))return!0;const i=Rm(s);s=i===void 0?void 0:v(i)}return!1},_m=(e,t)=>{if(!km(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Dm(s)))return{file:t,line:s.getStartLineNumber(),scope:A(e)}},Mm=(e,t)=>R(e,t,_m),$m=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Km=e=>{for(const[t,s]of $m)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},zm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Km(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Bm=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Vm=(e,t,s=[])=>{const n=Et(e,t,{argIndex:0,scope:"identity",matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Bm,requireUnmodifiedReach:!0});return hs(n,s)},Um=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Wm=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=ai(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},jm=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Um.get(t);return s===void 0?void 0:ui(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},qm=(e,t)=>{const s=jm(e.getExpression());if(s!==void 0)return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s.method,...Wm(e.getArguments()[s.optionsIndex])}},Hm=(e,t)=>R(e,t,qm),Gm=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Ar=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Gm(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>pe(i)||s(i));if(!(n===void 0||pe(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},Ts=(e,t)=>w(e.getFirstAncestor(s=>w(s,t)||pe(s)),t),Ym=(e,t)=>w(e,t)||e.getFirstAncestor(s=>w(s,t))!==void 0,br=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return w(e,t)||Ts(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Ar(e);return s!==void 0&&!Ym(s,t)}return!1},Nr=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)],Qm=e=>Nr(e).some(t=>br(t,e)),Xm=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},Jm=e=>Nr(e).some(t=>br(t,e)||r.isBreakStatement(t)&&w(Ar(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Xm(t)&&Ts(t,e)),Zm=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>Ts(t,e)),eh=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),th=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Ut=(e,t)=>{const s=eh(e);if(!(s===void 0||r.isTrueLiteral(v(s)))||Jm(e)||Zm(e))return;const i=A(e);if(!(i.kind==="module"&&e.getFirstAncestor(pe)!==void 0))return{file:t,kind:th(e),line:e.getStartLineNumber(),scope:i}},sh=(e,t)=>[...ce(e,t,d.WhileStatement,Ut),...ce(e,t,d.ForStatement,Ut),...ce(e,t,d.DoStatement,Ut)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),nh=new Set(["when","where"]),Wt=new Set(["definePolicy","defineShape"]),ih=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Wt.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 Wt.has(i)?i:void 0}const s=t.getText();return Wt.has(s)?s:void 0},rh=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,wr=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(rh(e))return"empty-object";if(r.isParenthesizedExpression(e))return wr(e.getExpression())}},Cs=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),oh=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Cs(t)===e),Pr=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>Cs(t)===e),ah=e=>{const t=oh(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Pr(e).length>0},ch=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>Cs(t)===e),cs=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()==="",lh=(e,t)=>cs(e)||cs(t),dh=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),zn=e=>!cs(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),uh=(e,t,s)=>{const n=dh.get(e);if(n!==void 0)return lh(t,s)?n==="positive"?"negative":"positive":zn(t)||zn(s)?void 0:n},De=e=>{if(r.isParenthesizedExpression(e))return De(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=uh(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=De(e.getLeft()),i=De(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Bn=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}}},fh=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},ph=e=>r.isReturnStatement(e)?e.getExpression()??e:e,gh=e=>{const t=[];for(const s of Pr(e)){const n=De(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of ch(e)){const n=De(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Bn(s.getThenStatement()):Bn(s.getElseStatement())??fh(s);i!==void 0&&t.push(ph(i))}return t},mh=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},hh=(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)||!nh.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&ah(a))for(const c of gh(a)){const l=wr(c);l!==void 0&&i.push({exportName:mh(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},vh=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression)){const i=ih(n);i!==void 0&&s.push(...hh(n,i,t))}return s},Eh=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vh(i,I(t,n)))}return s},xh=new Set(["query","upsert","upsertMany","upsertNow"]),ye=new Set,Sh=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(xh.has(t))return J(e.getExpression(),["vectors"])?t:void 0},Os=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},Ir=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Tr=e=>Ir(e)?.getDeclarations()[0],yh=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Cr=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},Vn=(e,t,s)=>{const n=Ir(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Cr(Tr(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return ks(o,t,s-1)}return H(e)},ks=(e,t,s)=>{const n=Os(e);return di(n)?!1:r.isIdentifier(n)?Vn(n,t,s):H(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>yh(i)&&Vn(i,t,s))},Or=e=>{const t=Cr(Tr(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},oe=(e,t)=>{const s=Os(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...oe(s.getWhenTrue(),t),...oe(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...oe(s.getLeft(),t),...oe(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Or(s);return n===void 0?[]:oe(n,!1)}return[]},Ah=(e,t)=>{const s=oe(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>ut(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},bh=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Nh=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),ut=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Ah(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else bh(n)&&(s=[Nh(n)]);return s},wh=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},Ph=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return ye;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return ye;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},ls=(e,t=!0,s=ye)=>{const n=Os(e);if(r.isIdentifier(n)){const o=t?Or(n):void 0;return o===void 0?[{node:n,parameters:s}]:ls(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?ls(o.getExpression(),t,s):oe(o,!0).flatMap(a=>ut(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=ks(i.getExpression(),ye,1)?Ph(o):ye;return wh(o).flatMap(c=>oe(c,!0).flatMap(l=>ut(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Ih=(e,t)=>{const s=Sh(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?ls(n):oe(n,!0).flatMap(o=>ut(o,!0).map(a=>({node:a,parameters:ye})))).some(({node:o,parameters:a})=>ks(o,a,1))))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s}},Th=(e,t)=>R(e,t,Ih),Ch=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:p,topics:g,wranglerVariables:h,workflows:x}=s;return Ao({adminRoutes:rl(e,t),aiRawRuns:cl(e,t),aiToolSideEffects:xl(e,t),argumentDerivedFetches:Al(e,t),argumentValidators:zl(e,t),authApiCalls:Qo(e,t),authConfigs:Ql(e,t),browserUrlAccesses:ed(e,t),callEdges:n.callEdges,configCalls:cd(e,t),containerKeyAccesses:dd(e,t),containerOverrides:hd(e,t),containers:i,countReads:yd(e,t,f.tables),crons:o,cronTargets:o.flatMap(D=>D.functionPath===void 0?[]:[D.functionPath]),exportSinks:wd(e,t),staleMigrationImports:zm(e,t),failOpenGuards:Od(e,t),flagReads:Dd(e,t),flagSecurityDefaults:Kd(e,t),geoIndexUsages:Vd(e,t),httpActionGuards:eu(e,t),httpHeaderWrites:du(e,t),hyperdriveCalls:Zo(e,t),identityClaimReads:Yu(e,t),imageDeliveryUrlAccesses:Xu(e,t),inserts:n.inserts,kvKeyAccesses:Zu(e,t,a),mailRecipientAccesses:rf(e,t),maskProcedures:oa(e,t),maskStrategies:cf(e,t),mutatorWrites:hf(e,t),nondeterministicCalls:ua(e,t),normalizeIdAuthorizations:kf(e,t),notifyCalls:pa(e,t),notifyConfig:fa(e,t),mutators:l,ownerFieldWrites:kp(e,t,a,l),unrestrictedWhereBranches:Eh(e,t),paymentWebhooks:Dp(e,t),privilegedDispatches:Qp(e,t),procedureProtections:Gg(e,t),queries:n.queries,queues:u,r2sqlCalls:ga(e,t),ratelimitKeySelectors:tm(e,t),rawRowReturns:cm(e,t),relationLoads:um(e,t),rlsProcedures:ma(e,t),schema:f,secretLiterals:Pm(e,t),modules:c,shapes:p,topics:g,softDeleteReads:Cm(e,t),sqlInterpolations:Mm(e,t),storageKeyAccesses:Vm(e,t,a),storageUploads:Hm(e,t),tableWrites:n.tableWrites,rowEffects:ym(e,t,n.tableWrites,n.callEdges),unboundedLoops:sh(e,t),vectorNamespaceAccesses:Th(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:h})},Oh=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"}),kh=(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=>Oh(i))]},Rh=()=>({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"}),Lh=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",Un={error:"ERROR",info:"INFO",warn:"WARN"},Wn={ERROR:2,INFO:0,WARN:1},Fh=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"}),Dh=(e,t)=>{const{advisor:s}=bi(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(Un,n)?Un[n]:void 0;return i===void 0?[...t,Fh(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=>Lh(o)||Wn[o.level]>=Wn[i])},_h=(e,t)=>{const{advisor:s}=bi(e),n=kh(t,s?.accept??[]);return Dh(e,s?.acceptUnreadable===!0?[...n,Rh()]:n)},Mh={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},$h="crons",Kh=Ta.replace(/\.ts$/u,""),Se=(e,t)=>`${Ss(e)}:${t}`,jt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},zh=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Mh[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,...jt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...jt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...jt("workflow",t.workflow,"workflow name")}))],Bh=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Vh=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Bh(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Uh=e=>zh(e).flatMap(t=>Vh(t)),Wh=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:$h,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],jh=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),Oe=(e,t)=>t===void 0?e:{...e,module:t},qh=e=>{const t=new Map,s=new Map,n=jh(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(Se(c.file,c.exportName),l)};for(const c of e.functions){const l=Se(c.filePath,c.exportName),u=[...ha(c.filePath),c.exportName].join(".");o(Oe({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Je(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=Se(c.filePath,c.exportName);o(Oe({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Je(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(Oe({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(Oe({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Je(e.modules,c.filePath)),Se(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(Oe({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Je(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},Se(Kh,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}},Hh=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Gh=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(Se(e.file,e.exportName))??{reason:Hh(e.exportName)},Yh=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Gh(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`}},qt=e=>`${e.from}|${e.kind}|${e.to}`,Qh=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Xh=e=>{const{nodes:t,sites:s}=qh(e),n=new Map,i=new Map;for(const o of[...Wh(e),...Uh(e)]){const a=Yh(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(qt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Qh(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>qt(o).localeCompare(qt(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}},Jh=e=>`${Ni}export const architecture = ${Oa(e,"Record<string, unknown>")};
27
- `,jn=(e,t="api")=>{const s=new Map;for(const n of e){const i=Ss(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new F("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Zh=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>wi(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=>Pi(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?[]:Ba)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)},ev=(e,t,s={})=>{if(t===void 0)return;const n=Zh(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
28
- `);throw new F("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
26
+ `)){const i=n.replace(zg,"");if(!i.startsWith($n))continue;const o=i.slice($n.length);if(Bg.test(o.charAt(0))||n.trimStart().startsWith("//")&&Is(o)!==void 0)continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Ug=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=U(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Wg=(e,t)=>{const s=Ug(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)},jg=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of S(e,d.CallExpression))if(yg(l)&&(o=!0),bg(l)&&(t=!0),Ng(l)&&(i=!0),wg(l)&&(s=!0),Pg(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=$g(e);return{callsMail:Vt(e,Cg),emitsEvent:Vt(e,Ig),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Vt(e,Tg),throwsBareError:Kg(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},qg=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=le(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?vg(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Wg(e,s);return{...o?jg(o):{},...Vg(e),...i,analyzableBody:o!==void 0,exportName:Z(e)??e.getName(),file:t,hasEmailArg:gg(s,n.receiver),kind:n.kind,line:ni(e),visibility:n.visibility}},Hg=(e,t)=>{const s=[];for(const n of te(e)){const i=qg(n,t);i&&s.push(i)}return s},Gg=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hg(i,I(t,n)))}return s},Yg=new Set(["dbRateLimit","rateLimit"]),Qg=e=>r.isArrowFunction(e)?e.getBody():e,Xg=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Er=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},xr=(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)})},Jg=(e,t)=>H(e)||t!==void 0&&xr(e,t).some(s=>Er(s)),Zg=(e,t)=>t===void 0?Ae(e):xr(e,t).some(s=>!Er(s)),em=(e,t)=>{const s=k(e.getExpression());if(s===void 0||!Yg.has(s))return;const n=$(oi(e.getArguments()[2]),"key");if(!n)return;const i=Qg(n),o=Xg(n);if(!(!Jg(i,o)||Zg(i,o)))return{callee:s,scope:A(e),file:t,limitName:ri(e),line:e.getStartLineNumber()}},tm=(e,t)=>L(e,t,em),sm=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),nm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!sm.has(t.getName()))return;const s=t.getExpression();if(B(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&B(s.getExpression()))return s.getName()},im=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&B(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},rm=e=>{let t=v(e)??e;for(;r.isAwaitExpression(t);)t=v(t.getExpression())??t.getExpression();return t},Sr=(e,t=!1)=>{const s=rm(e);if(r.isIdentifier(s)){if(t)return;const n=Ko(s),i=n!==void 0&&r.isIdentifier(n.getNameNode())?n.getInitializer():void 0;return i===void 0||!r.isIdentifier(n?.getNameNode())?void 0:Sr(i,!0)}if(r.isCallExpression(s))return nm(s)??im(s)},om=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of S(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},am=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=le(s);if(n?.kind!=="query")return[];const i=Si(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Ho(n.receiver,"output"),a=n.receiver!==void 0&&vi(n.receiver,"use","mask"),c=new Set,l=[];for(const u of om(i)){const f=Sr(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:Z(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},cm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...am(a,o))}return s},lm=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},dm=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;if(!n)return[];const i=[];for(const o of S(e,d.CallExpression)){const a=xi(o);if(a===void 0)continue;const c=lm($(a.options,"with"));c.length!==0&&i.push({exportName:Z(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},um=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...dm(a,o))}return s},Q=(e,t)=>`${e}:${t}`,Kn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},fm=(e,t)=>[...ce(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Kn(s,n,s.getName(),s.isExported()):void 0),...ce(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Kn(i,n,s.getName(),i.isExported()):void 0})],pm=(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(Q(c,a))},gm=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,mm=(e,t)=>{const s=new Map(e.map(n=>[Q(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(Q(i.file,i.name))?.set(gm(n),{fields:n.fields,method:n.method,table:n.table})}return s},hm=(e,t,s)=>S(e.node,d.CallExpression).map(n=>pm(n,t,s)).filter(n=>n!==void 0),vm=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(Q(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(Q(o.file,o.name))?.push(a)}},Em=(e,t,s)=>{const n=new Map(e.map(a=>[Q(a.file,a.name),a])),i=new Map(e.map(a=>[`${Ss(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[Q(a.file,a.name),hm(a,n,t)]));return vm(s,n,i,o),o},xm=(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},Sm=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(Q(i.file,i.name))??[])xm(t.get(Q(i.file,i.name)),t.get(Q(o.file,o.name)))&&(n=!0)}},ym=(e,t,s,n)=>{const i=fm(e,t),o=mm(i,s);return Sm(i,o,Em(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(Q(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},dt=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=dt(e.getLeft()),s=dt(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Am=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&&dt(t)!==void 0},bm=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()}},Nm=(e,t,s)=>xa(e)?!Io(s)&&Sa(bm(t)):!0,wm=(e,t)=>{const s=[],n=[...S(e,d.BinaryExpression),...S(e,d.StringLiteral),...S(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(Am(o))continue;const a=dt(o);if(a===void 0)continue;const c=va(a);if(c===void 0||!Nm(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:Ea(a)}))}return s},Pm=(e,t)=>{const s=[],n=new us({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of b(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,ze(i,"utf8"),{overwrite:!0});s.push(...wm(o,I(t,i)))}return s},Im=e=>{const t=$(e,"includeDeleted");if(t!==void 0||!r.isObjectLiteralExpression(e))return t;const s=U(e,"includeDeleted");return r.isShorthandPropertyAssignment(s)?s.getNameNode():void 0},Tm=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;if(!n)return[];const i=[];for(const o of S(e,d.CallExpression)){const a=xi(o);if(a===void 0)continue;const c=Im(a.options);if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&H(c);!l&&!u||i.push({exportName:Z(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Cm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of te(i))s.push(...Tm(a,o))}return s},Om=new Set(["query","unsafe"]),yr=3,km=e=>!r.isPropertyAccessExpression(e)||!Om.has(e.getName())?!1:J(e.getExpression(),["sql"]),as=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(!(!X(t)||!r.isIdentifier(t.getNameNode())))return t.getInitializer()},Rm=e=>{const t=as(e);if(t!==void 0||!r.isIdentifier(e))return t;const s=e.getSymbol()?.getDeclarations()[0],n=r.isBindingElement(s)?s.getParent().getParent():void 0;if(!r.isBindingElement(s)||!X(n))return;const i=n.getInitializer(),o=v(i),a=v(o!==void 0&&r.isIdentifier(o)?as(o):o),c=u=>r.isSpreadAssignment(u)||r.isPropertyAssignment(u)&&r.isComputedPropertyName(u.getNameNode()),l=r.isObjectLiteralExpression(a)&&!a.getProperties().some(u=>c(u))?a.getProperty(Ee(s)):void 0;return r.isShorthandPropertyAssignment(l)?l.getNameNode():r.isPropertyAssignment(l)?l.getInitializer():i},Lm=e=>{const t=v(e);if(!t)return!1;if(r.isTemplateExpression(t))return!0;if(r.isBinaryExpression(t))return t.getOperatorToken().getKind()===d.PlusToken;if(!r.isCallExpression(t))return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)&&["concat","join"].includes(s.getName())},Fm=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return!1;const n=e.getArguments().every(o=>t(o));if(s.getName()==="concat")return n&&t(s.getExpression());const i=v(s.getExpression());return s.getName()==="join"&&n&&r.isArrayLiteralExpression(i)&&i.getElements().every(o=>t(o))},xe=(e,t=yr)=>{const s=v(e);return s?r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)||r.isNumericLiteral(s)?!0:r.isTemplateExpression(s)?s.getTemplateSpans().every(n=>xe(n.getExpression(),t)):r.isBinaryExpression(s)?s.getOperatorToken().getKind()===d.PlusToken&&xe(s.getLeft(),t)&&xe(s.getRight(),t):r.isIdentifier(s)?t>0&&xe(as(s),t-1):r.isCallExpression(s)?Fm(s,n=>xe(n,t)):!1:!1},Dm=e=>{const t=v(e);if(!t||xe(t))return!1;let s=t;for(let n=0;s!==void 0&&n<=yr;n+=1){if(Lm(s)||H(s))return!0;const i=Rm(s);s=i===void 0?void 0:v(i)}return!1},_m=(e,t)=>{if(!km(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Dm(s)))return{file:t,line:s.getStartLineNumber(),scope:A(e)}},Mm=(e,t)=>L(e,t,_m),$m=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Km=e=>{for(const[t,s]of $m)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},zm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Km(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Bm=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Vm=(e,t,s=[])=>{const n=Et(e,t,{argIndex:0,scope:"identity",matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Bm,requireUnmodifiedReach:!0});return hs(n,s)},Um=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Wm=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=ai(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},jm=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Um.get(t);return s===void 0?void 0:ui(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},qm=(e,t)=>{const s=jm(e.getExpression());if(s!==void 0)return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s.method,...Wm(e.getArguments()[s.optionsIndex])}},Hm=(e,t)=>L(e,t,qm),Gm=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Ar=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Gm(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>pe(i)||s(i));if(!(n===void 0||pe(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},Ts=(e,t)=>w(e.getFirstAncestor(s=>w(s,t)||pe(s)),t),Ym=(e,t)=>w(e,t)||e.getFirstAncestor(s=>w(s,t))!==void 0,br=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return w(e,t)||Ts(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Ar(e);return s!==void 0&&!Ym(s,t)}return!1},Nr=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)],Qm=e=>Nr(e).some(t=>br(t,e)),Xm=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},Jm=e=>Nr(e).some(t=>br(t,e)||r.isBreakStatement(t)&&w(Ar(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Xm(t)&&Ts(t,e)),Zm=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>Ts(t,e)),eh=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),th=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Ut=(e,t)=>{const s=eh(e);if(!(s===void 0||r.isTrueLiteral(v(s)))||Jm(e)||Zm(e))return;const i=A(e);if(!(i.kind==="module"&&e.getFirstAncestor(pe)!==void 0))return{file:t,kind:th(e),line:e.getStartLineNumber(),scope:i}},sh=(e,t)=>[...ce(e,t,d.WhileStatement,Ut),...ce(e,t,d.ForStatement,Ut),...ce(e,t,d.DoStatement,Ut)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),nh=new Set(["when","where"]),Wt=new Set(["definePolicy","defineShape"]),ih=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Wt.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 Wt.has(i)?i:void 0}const s=t.getText();return Wt.has(s)?s:void 0},rh=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,wr=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(rh(e))return"empty-object";if(r.isParenthesizedExpression(e))return wr(e.getExpression())}},Cs=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),oh=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Cs(t)===e),Pr=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>Cs(t)===e),ah=e=>{const t=oh(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Pr(e).length>0},ch=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>Cs(t)===e),cs=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()==="",lh=(e,t)=>cs(e)||cs(t),dh=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),zn=e=>!cs(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),uh=(e,t,s)=>{const n=dh.get(e);if(n!==void 0)return lh(t,s)?n==="positive"?"negative":"positive":zn(t)||zn(s)?void 0:n},De=e=>{if(r.isParenthesizedExpression(e))return De(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=uh(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=De(e.getLeft()),i=De(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Bn=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}}},fh=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},ph=e=>r.isReturnStatement(e)?e.getExpression()??e:e,gh=e=>{const t=[];for(const s of Pr(e)){const n=De(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of ch(e)){const n=De(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Bn(s.getThenStatement()):Bn(s.getElseStatement())??fh(s);i!==void 0&&t.push(ph(i))}return t},mh=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},hh=(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)||!nh.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&ah(a))for(const c of gh(a)){const l=wr(c);l!==void 0&&i.push({exportName:mh(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},vh=(e,t)=>{const s=[];for(const n of S(e,d.CallExpression)){const i=ih(n);i!==void 0&&s.push(...hh(n,i,t))}return s},Eh=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vh(i,I(t,n)))}return s},xh=new Set(["query","upsert","upsertMany","upsertNow"]),ye=new Set,Sh=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(xh.has(t))return J(e.getExpression(),["vectors"])?t:void 0},Os=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},Ir=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Tr=e=>Ir(e)?.getDeclarations()[0],yh=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Cr=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},Vn=(e,t,s)=>{const n=Ir(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Cr(Tr(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return ks(o,t,s-1)}return H(e)},ks=(e,t,s)=>{const n=Os(e);return di(n)?!1:r.isIdentifier(n)?Vn(n,t,s):H(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>yh(i)&&Vn(i,t,s))},Or=e=>{const t=Cr(Tr(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},oe=(e,t)=>{const s=Os(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...oe(s.getWhenTrue(),t),...oe(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...oe(s.getLeft(),t),...oe(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Or(s);return n===void 0?[]:oe(n,!1)}return[]},Ah=(e,t)=>{const s=oe(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>ut(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},bh=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Nh=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),ut=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Ah(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else bh(n)&&(s=[Nh(n)]);return s},wh=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},Ph=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return ye;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return ye;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},ls=(e,t=!0,s=ye)=>{const n=Os(e);if(r.isIdentifier(n)){const o=t?Or(n):void 0;return o===void 0?[{node:n,parameters:s}]:ls(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?ls(o.getExpression(),t,s):oe(o,!0).flatMap(a=>ut(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=ks(i.getExpression(),ye,1)?Ph(o):ye;return wh(o).flatMap(c=>oe(c,!0).flatMap(l=>ut(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Ih=(e,t)=>{const s=Sh(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?ls(n):oe(n,!0).flatMap(o=>ut(o,!0).map(a=>({node:a,parameters:ye})))).some(({node:o,parameters:a})=>ks(o,a,1))))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s}},Th=(e,t)=>L(e,t,Ih),Ch=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:p,topics:g,wranglerVariables:h,workflows:x}=s;return Ao({adminRoutes:rl(e,t),aiRawRuns:cl(e,t),aiToolSideEffects:xl(e,t),argumentDerivedFetches:Al(e,t),argumentValidators:zl(e,t),authApiCalls:Qo(e,t),authConfigs:Ql(e,t),browserUrlAccesses:ed(e,t),callEdges:n.callEdges,configCalls:cd(e,t),containerKeyAccesses:dd(e,t),containerOverrides:hd(e,t),containers:i,countReads:yd(e,t,f.tables),crons:o,cronTargets:o.flatMap(_=>_.functionPath===void 0?[]:[_.functionPath]),exportSinks:wd(e,t),staleMigrationImports:zm(e,t),failOpenGuards:Od(e,t),flagReads:Dd(e,t),flagSecurityDefaults:Kd(e,t),geoIndexUsages:Vd(e,t),httpActionGuards:eu(e,t),httpHeaderWrites:du(e,t),hyperdriveCalls:Zo(e,t),identityClaimReads:Yu(e,t),imageDeliveryUrlAccesses:Xu(e,t),inserts:n.inserts,kvKeyAccesses:Zu(e,t,a),mailRecipientAccesses:rf(e,t),maskProcedures:oa(e,t),maskStrategies:cf(e,t),mutatorWrites:hf(e,t),nondeterministicCalls:ua(e,t),normalizeIdAuthorizations:kf(e,t),notifyCalls:pa(e,t),notifyConfig:fa(e,t),mutators:l,ownerFieldWrites:kp(e,t,a,l),unrestrictedWhereBranches:Eh(e,t),paymentWebhooks:Dp(e,t),privilegedDispatches:Qp(e,t),procedureProtections:Gg(e,t),queries:n.queries,queues:u,r2sqlCalls:ga(e,t),ratelimitKeySelectors:tm(e,t),rawRowReturns:cm(e,t),relationLoads:um(e,t),rlsProcedures:ma(e,t),schema:f,secretLiterals:Pm(e,t),modules:c,shapes:p,topics:g,softDeleteReads:Cm(e,t),sqlInterpolations:Mm(e,t),storageKeyAccesses:Vm(e,t,a),storageUploads:Hm(e,t),tableWrites:n.tableWrites,rowEffects:ym(e,t,n.tableWrites,n.callEdges),unboundedLoops:sh(e,t),vectorNamespaceAccesses:Th(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:h})},Oh=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"}),kh=(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=>Oh(i))]},Rh=()=>({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"}),Lh=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",Un={error:"ERROR",info:"INFO",warn:"WARN"},Wn={ERROR:2,INFO:0,WARN:1},Fh=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"}),Dh=(e,t)=>{const{advisor:s}=bi(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(Un,n)?Un[n]:void 0;return i===void 0?[...t,Fh(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=>Lh(o)||Wn[o.level]>=Wn[i])},_h=(e,t)=>{const{advisor:s}=bi(e),n=kh(t,s?.accept??[]);return Dh(e,s?.acceptUnreadable===!0?[...n,Rh()]:n)},Mh={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},$h="crons",Kh=Ta.replace(/\.ts$/u,""),Se=(e,t)=>`${Ss(e)}:${t}`,jt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},zh=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Mh[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,...jt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...jt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...jt("workflow",t.workflow,"workflow name")}))],Bh=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Vh=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Bh(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Uh=e=>zh(e).flatMap(t=>Vh(t)),Wh=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:$h,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],jh=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),Oe=(e,t)=>t===void 0?e:{...e,module:t},qh=e=>{const t=new Map,s=new Map,n=jh(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(Se(c.file,c.exportName),l)};for(const c of e.functions){const l=Se(c.filePath,c.exportName),u=[...ha(c.filePath),c.exportName].join(".");o(Oe({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Je(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=Se(c.filePath,c.exportName);o(Oe({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Je(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(Oe({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(Oe({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Je(e.modules,c.filePath)),Se(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(Oe({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Je(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},Se(Kh,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}},Hh=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Gh=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(Se(e.file,e.exportName))??{reason:Hh(e.exportName)},Yh=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Gh(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`}},qt=e=>`${e.from}|${e.kind}|${e.to}`,Qh=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Xh=e=>{const{nodes:t,sites:s}=qh(e),n=new Map,i=new Map;for(const o of[...Wh(e),...Uh(e)]){const a=Yh(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(qt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Qh(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>qt(o).localeCompare(qt(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}},Jh=e=>`${Ni}export const architecture = ${Oa(e,"Record<string, unknown>")};
27
+ `,jn=(e,t="api")=>{const s=new Map;for(const n of e){const i=Ss(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 D("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})}}},Zh=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>wi(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=>Pi(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?[]:Ba)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)},ev=(e,t,s={})=>{if(t===void 0)return;const n=Zh(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
28
+ `);throw new D("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
29
29
  ${i}
30
30
 
31
- Install them with your package manager, then re-run codegen.`)},tv=(e,t)=>{const s=na();for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(ia(i,s))return!0}return!1},sv="createWorker",nv="extend",qn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Hn=e=>{const t=[],s=qn($(e,"backupCron"));s!==void 0&&t.push(s);const n=$(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=qn(i.getNameNode());o!==void 0&&t.push(o)}return t},iv=e=>{const t=k(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===sv)return r.isObjectLiteralExpression(s)?Hn(s):[];if(t!==nv||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=ii(s.getBody());return n===void 0?[]:Hn(n)},rv=(e,t)=>{const s=[];for(const{filePath:n}of Ve(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of S(i,d.CallExpression))s.push(...iv(o))}return[...new Set(s)]},kr=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:kr(e.inner)},ov=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=kr(n);return i!==void 0&&t.has(i)}))},av=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new F("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new F("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},cv=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Vu(s,t),a=Hi(s,t),c=a.claims;for(const M of a.diagnostics)console.warn(`@lunora/codegen: ${M}.`);const l=qa(s,t),u=Ca(s,t),{queues:f,topics:p}=Ha(s,t),g=Ya(n),h=Ua(s,t);av(u,h);const x=Wa(s,t),D=Qa(s,t),N=ja(s,t,u,h),G=rv(s,t),T=Iu(s,t,yi(n)),P=Ga(s,t),se=tv(s,t),ne=ra(s,t);ne.browser=ne.browser||P.usesSandboxBrowser;const ie=ke(n,e.target),_=Xa(ne,ie,{agents:h.length>0,commitOrderedTables:i.tables.some(M=>M.commitOrdered===!0),cronTriggers:N.length>0,crossShardFanout:i.tables.some(M=>rc(M)),containerEgressPolicy:T.containerEgressPolicy,containerRuntimeScheduling:x.some(M=>M.schedulingPolicy==="durable_object"),containerSandboxTools:x.some(M=>M.sandbox===!0),deliveryAuthorization:T.deliveryAuthorization,durableStreams:T.durableStreams,globalTables:i.tables.some(M=>M.shardMode==="global"),liveContext:T.liveContext,liveStreams:T.liveStreams,typedWebSockets:T.typedWebSockets,queues:f.length>0,relationGraph:ov(i),secretValues:se,secrets:T.secrets,services:g.length>0,topics:p.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:P.usesSandboxLoader,workflowRollback:T.workflowRollback,workflowSchedules:u.some(M=>M.schedules!==void 0)}),L=_.usage,re=Va(L),de=_.signals.vectorStore!==!1,ue=_.signals.services===!1?[]:g,K=Ii(n),ee=K??new Set,W=ee.has("lunorash");ev(i,K,{hasVectors:de,scheduler:L.scheduler||N.length>0,storage:L.storage||D.rules.length>0||Object.keys(Ti(i)).length>0,usage:L});const j=z(E(t,"flags.ts")),q=z(E(t,"notify.ts"));return{agents:h,capabilities:re,containers:x,crons:N,dataModelContent:lc(i),declaredDependencies:K,dependencies:ee,entryCronTriggers:G,env:l,featureUsage:L,hasFlags:j,hasNotify:q,authClaims:c,identity:o,platformGate:{..._,diagnostics:[...Ja(n,e.target),..._.diagnostics,...Za(ie,i.vectorIndexes),...T.liveStreams&&T.deliveryAuthorization?[ec(ie)]:[],...T.socketRoutes&&T.deliveryAuthorization?[tc(ie)]:[]]},queues:f,serverContent:ac({agents:h,capabilities:re,containers:x,env:l,hasVectors:de,hasFlags:j,authClaims:c,hasNotify:q,identity:o,queues:f,schema:i,services:ue,storageRuleBuckets:D.rules.map(M=>M.bucket),topics:p,useUmbrella:W,workflows:u}),services:ue,storageRulesMetadata:D,topics:p,usesSandbox:P.usesSandboxBrowser||P.usesSandboxContainer||P.usesSandboxFs,useUmbrella:W,workflows:u}},Rr=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},lv=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},dv=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),uv=/^[\w$]+:[\w$]+$/u,fv=(e,t)=>{const s=ci(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Gn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},pv=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Gn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===fs.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Gn(s):void 0}}},gv=(e,t,s)=>({schedule:{argKeys:pv(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),mv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(gs.has(s))return fv(s,n);if((s==="runAfter"||s==="runAt")&&lv(t)){const l=ci(i)??(r.isStringLiteral(i)&&uv.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...gv(s,n,o)}}const a=dv.get(s),c=a===void 0?void 0:Rr(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},hv=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Lr=e=>C.isOptionalChain(e.compilerNode),vv=(e,t)=>r.isIfStatement(t)?!w(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?w(e,t.getStatement()):r.isForStatement(t)?w(e,t.getStatement())||w(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:pe(t)?t.getFirstAncestor(pe)!==void 0:r.isConditionalExpression(t)?!w(e,t.getCondition()):r.isBinaryExpression(t)?!w(e,t.getLeft())&&hv.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Lr(t)?!w(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Qm(s)),Ev=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&w(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(pe);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&w(o.getFirstAncestor(pe),i))===!0},xv=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&w(e,t.getStatement())||r.isForStatement(t)&&(w(e,t.getStatement())||w(t.getIncrementor(),e)),Sv=(e,t)=>{if(Lr(e)||t==="schedule"&&Ev(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(vv(s,i)){if(!xv(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Yn=(e,t,s)=>{if(s===void 0)return;const n=Sv(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:A(e)}},yv=(e,t)=>[...R(e,t,(s,n)=>Yn(s,n,mv(s))),...ce(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Rr(s,"services");return Yn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Av=new Set(["boolean","number","object","string"]),bv=e=>{const t=e.getName();if(!Av.has(t))return;const s=e.getExpression();return J(s,["flags"])||J(s,["flags","details"])?t:void 0},Nv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=bv(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},wv=(e,t)=>{const s=new Map;for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of S(i,d.CallExpression)){const a=Nv(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Pv=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||dc(o))return;const a=e.getSourceFile().getFilePath();if(uc(i,e,a)){const c=fc(i,e,a,0,new Set);return c===void 0&&pc(o),c}return o},Iv=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Es(t.getNameNode());return s===void 0||s==="namespace"}),Tv=(e,t)=>{for(const{filePath:s}of Ve(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of S(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Iv(a)))return i}}},Cv="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Ov=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Pe(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Cv}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},kv="room:",Rv="__lunora_socket__:",Lv=/^[A-Za-z]\w*$/u,Qn=e=>Lv.test(e),Fv=e=>`${e}:`.startsWith(kv)||`${e}:`.startsWith(Rv),Fr=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Dr=e=>Fr(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),Xn=e=>y(e),Rs=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&y(s)===t),he=(e,t)=>{const s=Pe(e,`defineLiveStream ${t}`);return new F("LIVE_STREAM_NOT_LITERAL",s.message)},_r=(e,t,s)=>{const n=Rs(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw he(n??e,`needs ${s} so codegen can read its topics`);if(Dr(i))throw he(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Dv=(e,t)=>{const s=Xn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw he(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Dr(n))throw he(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Qn(s)||Fv(s))throw new F("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(Rs(n,"key")===void 0)return{fields:[],name:s};const a=_r(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>Xn(l)),c=a.find(l=>!Qn(l));if(c!==void 0)throw new F("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},_v=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw he(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Fr(n))throw he(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=Rs(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw he(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=_r(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:I(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Dv(a,l))}},Mv=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new F("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},$v=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},Kv=(e,t)=>S(e,d.CallExpression).filter(s=>hi(s,"defineLiveStream")).map(s=>{const n=$v(s),i=r.isVariableDeclaration(n)?ms(n,"binding"):void 0;if(i===void 0)throw new F("LIVE_STREAM_NOT_EXPORTED",Pe(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return _v(s,i,t)}),zv=(e,t)=>{const s=b(t).flatMap(n=>Kv(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return Mv(s),s},Bv=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Vv=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Bv(e):!0,Mr=(e,t=!1)=>{for(const s of e.getProperties()){if(Vv(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Mr(n,!0))return!0}return!1},Uv=(e,t)=>{for(const s of b(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Ci(n))for(const o of xs(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Mr(a)))return!0}}return!1},Wv=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=ot(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=ot(a);c!==void 0&&s.push({column:c,strategy:Ai(a),table:i})}}return s},jv=(e,t)=>{const s=new Map;for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Ci(i))for(const a of xs(o))for(const c of Wv(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},qv=["providerSubscriptionId","state"],Hv=["providerEventId","processedAt"],Jn=(e,t)=>t.every(s=>s in e.shape),Gv=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&Jn(t,qv)&&Jn(s,Hv)},Yv=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],Qv=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},Xv=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},Jv="@lunora/privacy",$r="userId",Zn=new Set(["user","users"]),Zv=e=>e.replaceAll("\\","/"),eE="privacy",tE=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),yt=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ke=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Ls=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),sE=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},At=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},nE=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=sE(s,"tables"),i=yt(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Ls(n).map(a=>Ke(a)))t.datasets.set(o,i)},Fs=8,Ne=(e,t=0)=>{if(t>Fs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Ne(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Ne(i,t+1)},iE=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:Ne(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?Ls(n):[],o=new Set(i.map(a=>Ke(a)));for(const a of Yv)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?yt(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ke(a)==="user"&&t.userTables.add(c))}},ei=(e,t,s)=>{t.datasets.set(yt(e.getArguments()[0])??s,s)},rE=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ke(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Kr=(e,t=0)=>{const s=Ne(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Fs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Kr(i.getExpression(),t+1):[rE(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},oE=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Kr(t)},aE=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Ne(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Ls(n):[])t.excluded.set(Ke(i),r.isPropertyAssignment(i)?yt(i.getInitializer())??"":"")},cE=(e,t)=>{switch(At(e)){case"actionCacheDataset":{ei(e,t,"actionCache");break}case"authDataset":{iE(e,t);break}case"defineDataset":{nE(e,t);break}case"documentHistoryDataset":{ei(e,t,"documentHistory");break}}},Ds=e=>e!==void 0&&r.isCallExpression(e)&&At(e)==="defineDataset",zr=e=>e!==void 0&&r.isCallExpression(e)&&tE.has(At(e)??""),lE=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(Ds(i)||zr(i))?n:void 0},Br=(e,t,s=0)=>{const n=Ne(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Fs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Br(i.getExpression(),t,s+1))return!1}else if(!Ds(i)&&!zr(i)){const o=r.isIdentifier(i)?lE(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},dE=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Br(t,s)?s:void 0},uE=(e,t)=>{const s=[];for(const i of S(e,d.CallExpression))if(cE(i,t),At(i)==="definePrivacy"){const o=oE(i);aE(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:dE(o)})}return{declared:S(e,d.VariableDeclaration).filter(i=>Ds(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},fE=(e,t)=>{const s=E(t,"schema.ts"),n=[...b(t),...z(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Zv(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},pE=(e,t,s)=>{if(s?.has(Jv)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Zn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Zn)},i=[],o=[];for(const f of fE(e,t)){const p=uE(f,n);i.push(...p.declared),o.push(...p.privacyCalls)}const a=new Set;for(const f of o){for(const p of f.passed??[])a.add(p);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:Qv(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},Vr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&Vr(n,t)),gE=(e,t)=>e.extensionKey!==eE&&($r in e.shape||Object.values(e.shape).some(s=>Vr(s,t))),mE=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${$r}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,hE=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>gE(o,t.userTables)).map(o=>o.name),[n]=Xv(s,t.classifications);if(n!==void 0)throw new F("PRIVACY_COVERAGE",mE(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new F("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},vE=(e,t)=>{const s=sc(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},EE=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),xE="",SE=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},yE=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===fs.Const?t.getInitializer():void 0},it=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return it(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=yE(e);if(n!==void 0)return it(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},AE=(e,t)=>{if(EE.has(e))return{method:e,tables:it(t)??[xE]}},Ur=(e,t,s)=>e===void 0?void 0:{...e,fields:SE(t,e.method,s)},ti=e=>{const t=St(e,lf);return t===void 0?void 0:Ur({method:t.method,tables:[t.table]},e,1)},bE=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();return Ji(n)!==void 0?ti(e):B(n)?Ur(AE(s,e.getArguments()[0]),e,2):ti(e)},NE=(e,t)=>R(e,t,(s,n)=>{const i=bE(s);if(i===void 0)return;const o=A(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),wE=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),PE=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||U(s,"args")===void 0)return!1}return As(e,t).opaque},IE=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=le(a);c!==void 0&&PE(a,c.receiver)&&s.push(wE(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},TE=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...IE(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},CE=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),ft=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Wr=e=>!e.isAny(),jr=e=>{const t=e.getType();if(!Wr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:CE.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},OE=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},qr={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},kE=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),RE={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},LE=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),FE={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},DE=(e,t,s)=>{if(!t.some(i=>Lo(i)))return RE;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return LE.has(s.typeName)&&!n&&!t.some(i=>Ac(i))?FE:qr},Hr=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:kE(u),p=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${p}`:p,title:"Procedure exists at runtime but is missing from the generated API"}},_E=(e,t,s)=>{const n=[];for(const i of te(e)){const o=r.isIdentifier(i.getNameNode())?Gt(i):[i.getName()],c=o.some(u=>ft(s,t,u))||!OE(i)?void 0:jr(i),[l=i.getName()]=o;c!==void 0&&n.push(Hr(t,l,c,i.getStartLineNumber(),DE(i,o,c)))}return n},ME=(e,t,s)=>{if(ft(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=jr(i.getExpression());o!==void 0&&n.push(Hr(t,"default",o,i.getStartLineNumber(),qr))}return n},$E=(e,t,s)=>[..._E(e,t,s),...ME(e,t,s)],KE=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Gt(n).some(i=>ft(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Gt(n).find(o=>ft(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),zE=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),BE=(e,t,s)=>{const n=[],i=[];for(const a of b(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...$E(c,l,s)),i.push(...KE(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Wr(a.getType()))&&n.push(zE(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},VE=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},UE=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},WE=(e,t)=>R(e,t,(s,n)=>VE(s)?{file:n,line:s.getStartLineNumber(),scope:A(s),workflow:UE(s)}:void 0),Gr=e=>e==="@lunora/workflow",jE=e=>new Set(e.getImportDeclarations().filter(t=>Gr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),qE=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),HE=(e,t)=>{const s=mi(e,"defineWorkflowEvent",Gr),n=jE(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of S(e,d.CallExpression)){if(!qE(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?ms(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new F("WORKFLOW_EVENT_NOT_LITERAL",Pe(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:I(t,e.getFilePath()),type:l.getLiteralValue()})}return i},GE=(e,t)=>{const s=b(t).flatMap(i=>HE(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new F("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},YE=e=>{const t=Ma(e,"compatibility_date"),s=$a(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:Ka(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
31
+ Install them with your package manager, then re-run codegen.`)},tv=(e,t)=>{const s=na();for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(ia(i,s))return!0}return!1},sv="createWorker",nv="extend",qn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Hn=e=>{const t=[],s=qn($(e,"backupCron"));s!==void 0&&t.push(s);const n=$(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=qn(i.getNameNode());o!==void 0&&t.push(o)}return t},iv=e=>{const t=k(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===sv)return r.isObjectLiteralExpression(s)?Hn(s):[];if(t!==nv||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=ii(s.getBody());return n===void 0?[]:Hn(n)},rv=(e,t)=>{const s=[];for(const{filePath:n}of Ve(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of S(i,d.CallExpression))s.push(...iv(o))}return[...new Set(s)]},kr=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:kr(e.inner)},ov=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=kr(n);return i!==void 0&&t.has(i)}))},av=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new D("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new D("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},cv=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Vu(s,t),a=Hi(s,t),c=a.claims;for(const R of a.diagnostics)console.warn(`@lunora/codegen: ${R}.`);const l=qa(s,t),u=Ca(s,t),{queues:f,topics:p}=Ha(s,t),g=Ya(n),h=Ua(s,t);av(u,h);const x=Wa(s,t),_=Qa(s,t),N=ja(s,t,u,h),G=rv(s,t),T=Iu(s,t,yi(n)),P=Ga(s,t),se=tv(s,t),ne=ra(s,t);ne.browser=ne.browser||P.usesSandboxBrowser;const ie=ke(n,e.target),M=Xa(ne,ie,{agents:h.length>0,commitOrderedTables:i.tables.some(R=>R.commitOrdered===!0),cronTriggers:N.length>0,cronWorkflowTriggers:N.some(R=>R.workflow!==void 0),crossShardFanout:i.tables.some(R=>rc(R)),containerEgressPolicy:T.containerEgressPolicy,containerRuntimeScheduling:x.some(R=>R.schedulingPolicy==="durable_object"),containerSandboxTools:x.some(R=>R.sandbox===!0),deliveryAuthorization:T.deliveryAuthorization,durableStreams:T.durableStreams,globalTables:i.tables.some(R=>R.shardMode==="global"),liveContext:T.liveContext,liveStreams:T.liveStreams,typedWebSockets:T.typedWebSockets,queues:f.length>0,relationGraph:ov(i),secretValues:se,secrets:T.secrets,services:g.length>0,topics:p.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:P.usesSandboxLoader,workflowRollback:T.workflowRollback,workflowSchedules:u.some(R=>R.schedules!==void 0)}),F=M.usage,re=Va(F),de=M.signals.vectorStore!==!1,ue=M.signals.services===!1?[]:g,K=Ii(n),ee=K??new Set,W=ee.has("lunorash");ev(i,K,{hasVectors:de,scheduler:F.scheduler||N.length>0,storage:F.storage||_.rules.length>0||Object.keys(Ti(i)).length>0,usage:F});const j=z(E(t,"flags.ts")),q=z(E(t,"notify.ts"));return{agents:h,capabilities:re,containers:x,crons:N,dataModelContent:lc(i),declaredDependencies:K,dependencies:ee,entryCronTriggers:G,env:l,featureUsage:F,hasFlags:j,hasNotify:q,authClaims:c,identity:o,platformGate:{...M,diagnostics:[...Ja(n,e.target),...M.diagnostics,...Za(ie,i.vectorIndexes),...T.liveStreams&&T.deliveryAuthorization?[ec(ie)]:[],...T.socketRoutes&&T.deliveryAuthorization?[tc(ie)]:[]]},queues:f,serverContent:ac({agents:h,capabilities:re,containers:x,env:l,hasVectors:de,hasFlags:j,authClaims:c,hasNotify:q,identity:o,queues:f,schema:i,services:ue,storageRuleBuckets:_.rules.map(R=>R.bucket),topics:p,useUmbrella:W,workflows:u}),services:ue,storageRulesMetadata:_,topics:p,usesSandbox:P.usesSandboxBrowser||P.usesSandboxContainer||P.usesSandboxFs,useUmbrella:W,workflows:u}},Rr=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},lv=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},dv=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),uv=/^[\w$]+:[\w$]+$/u,fv=(e,t)=>{const s=ci(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Gn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},pv=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Gn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===fs.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Gn(s):void 0}}},gv=(e,t,s)=>({schedule:{argKeys:pv(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),mv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(gs.has(s))return fv(s,n);if((s==="runAfter"||s==="runAt")&&lv(t)){const l=ci(i)??(r.isStringLiteral(i)&&uv.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...gv(s,n,o)}}const a=dv.get(s),c=a===void 0?void 0:Rr(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},hv=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Lr=e=>C.isOptionalChain(e.compilerNode),vv=(e,t)=>r.isIfStatement(t)?!w(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?w(e,t.getStatement()):r.isForStatement(t)?w(e,t.getStatement())||w(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:pe(t)?t.getFirstAncestor(pe)!==void 0:r.isConditionalExpression(t)?!w(e,t.getCondition()):r.isBinaryExpression(t)?!w(e,t.getLeft())&&hv.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Lr(t)?!w(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Qm(s)),Ev=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&w(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(pe);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&w(o.getFirstAncestor(pe),i))===!0},xv=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&w(e,t.getStatement())||r.isForStatement(t)&&(w(e,t.getStatement())||w(t.getIncrementor(),e)),Sv=(e,t)=>{if(Lr(e)||t==="schedule"&&Ev(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(vv(s,i)){if(!xv(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Yn=(e,t,s)=>{if(s===void 0)return;const n=Sv(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:A(e)}},yv=(e,t)=>[...L(e,t,(s,n)=>Yn(s,n,mv(s))),...ce(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Rr(s,"services");return Yn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Av=new Set(["boolean","number","object","string"]),bv=e=>{const t=e.getName();if(!Av.has(t))return;const s=e.getExpression();return J(s,["flags"])||J(s,["flags","details"])?t:void 0},Nv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=bv(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},wv=(e,t)=>{const s=new Map;for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of S(i,d.CallExpression)){const a=Nv(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Pv=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||dc(o))return;const a=e.getSourceFile().getFilePath();if(uc(i,e,a)){const c=fc(i,e,a,0,new Set);return c===void 0&&pc(o),c}return o},Iv=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Es(t.getNameNode());return s===void 0||s==="namespace"}),Tv=(e,t)=>{for(const{filePath:s}of Ve(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of S(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Iv(a)))return i}}},Cv="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Ov=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Pe(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Cv}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},kv="room:",Rv="__lunora_socket__:",Lv=/^[A-Za-z]\w*$/u,Qn=e=>Lv.test(e),Fv=e=>`${e}:`.startsWith(kv)||`${e}:`.startsWith(Rv),Fr=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Dr=e=>Fr(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),Xn=e=>y(e),Rs=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&y(s)===t),he=(e,t)=>{const s=Pe(e,`defineLiveStream ${t}`);return new D("LIVE_STREAM_NOT_LITERAL",s.message)},_r=(e,t,s)=>{const n=Rs(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw he(n??e,`needs ${s} so codegen can read its topics`);if(Dr(i))throw he(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Dv=(e,t)=>{const s=Xn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw he(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Dr(n))throw he(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Qn(s)||Fv(s))throw new D("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(Rs(n,"key")===void 0)return{fields:[],name:s};const a=_r(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>Xn(l)),c=a.find(l=>!Qn(l));if(c!==void 0)throw new D("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},_v=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw he(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Fr(n))throw he(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=Rs(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw he(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=_r(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:I(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Dv(a,l))}},Mv=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new D("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},$v=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},Kv=(e,t)=>S(e,d.CallExpression).filter(s=>hi(s,"defineLiveStream")).map(s=>{const n=$v(s),i=r.isVariableDeclaration(n)?ms(n,"binding"):void 0;if(i===void 0)throw new D("LIVE_STREAM_NOT_EXPORTED",Pe(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return _v(s,i,t)}),zv=(e,t)=>{const s=b(t).flatMap(n=>Kv(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return Mv(s),s},Bv=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Vv=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Bv(e):!0,Mr=(e,t=!1)=>{for(const s of e.getProperties()){if(Vv(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Mr(n,!0))return!0}return!1},Uv=(e,t)=>{for(const s of b(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Ci(n))for(const o of xs(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Mr(a)))return!0}}return!1},Wv=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=ot(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=ot(a);c!==void 0&&s.push({column:c,strategy:Ai(a),table:i})}}return s},jv=(e,t)=>{const s=new Map;for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Ci(i))for(const a of xs(o))for(const c of Wv(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},qv=["providerSubscriptionId","state"],Hv=["providerEventId","processedAt"],Jn=(e,t)=>t.every(s=>s in e.shape),Gv=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&Jn(t,qv)&&Jn(s,Hv)},Yv=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],Qv=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},Xv=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},Jv="@lunora/privacy",$r="userId",Zn=new Set(["user","users"]),Zv=e=>e.replaceAll("\\","/"),eE="privacy",tE=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),yt=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ke=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Ls=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),sE=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},At=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},nE=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=sE(s,"tables"),i=yt(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Ls(n).map(a=>Ke(a)))t.datasets.set(o,i)},Fs=8,Ne=(e,t=0)=>{if(t>Fs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Ne(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Ne(i,t+1)},iE=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:Ne(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?Ls(n):[],o=new Set(i.map(a=>Ke(a)));for(const a of Yv)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?yt(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ke(a)==="user"&&t.userTables.add(c))}},ei=(e,t,s)=>{t.datasets.set(yt(e.getArguments()[0])??s,s)},rE=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ke(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Kr=(e,t=0)=>{const s=Ne(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Fs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Kr(i.getExpression(),t+1):[rE(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},oE=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Kr(t)},aE=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Ne(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Ls(n):[])t.excluded.set(Ke(i),r.isPropertyAssignment(i)?yt(i.getInitializer())??"":"")},cE=(e,t)=>{switch(At(e)){case"actionCacheDataset":{ei(e,t,"actionCache");break}case"authDataset":{iE(e,t);break}case"defineDataset":{nE(e,t);break}case"documentHistoryDataset":{ei(e,t,"documentHistory");break}}},Ds=e=>e!==void 0&&r.isCallExpression(e)&&At(e)==="defineDataset",zr=e=>e!==void 0&&r.isCallExpression(e)&&tE.has(At(e)??""),lE=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(Ds(i)||zr(i))?n:void 0},Br=(e,t,s=0)=>{const n=Ne(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Fs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Br(i.getExpression(),t,s+1))return!1}else if(!Ds(i)&&!zr(i)){const o=r.isIdentifier(i)?lE(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},dE=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Br(t,s)?s:void 0},uE=(e,t)=>{const s=[];for(const i of S(e,d.CallExpression))if(cE(i,t),At(i)==="definePrivacy"){const o=oE(i);aE(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:dE(o)})}return{declared:S(e,d.VariableDeclaration).filter(i=>Ds(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},fE=(e,t)=>{const s=E(t,"schema.ts"),n=[...b(t),...z(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Zv(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},pE=(e,t,s)=>{if(s?.has(Jv)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Zn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Zn)},i=[],o=[];for(const f of fE(e,t)){const p=uE(f,n);i.push(...p.declared),o.push(...p.privacyCalls)}const a=new Set;for(const f of o){for(const p of f.passed??[])a.add(p);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:Qv(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},Vr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&Vr(n,t)),gE=(e,t)=>e.extensionKey!==eE&&($r in e.shape||Object.values(e.shape).some(s=>Vr(s,t))),mE=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${$r}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,hE=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>gE(o,t.userTables)).map(o=>o.name),[n]=Xv(s,t.classifications);if(n!==void 0)throw new D("PRIVACY_COVERAGE",mE(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new D("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},vE=(e,t)=>{const s=sc(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},EE=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),xE="",SE=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},yE=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===fs.Const?t.getInitializer():void 0},it=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return it(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=yE(e);if(n!==void 0)return it(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},AE=(e,t)=>{if(EE.has(e))return{method:e,tables:it(t)??[xE]}},Ur=(e,t,s)=>e===void 0?void 0:{...e,fields:SE(t,e.method,s)},ti=e=>{const t=St(e,lf);return t===void 0?void 0:Ur({method:t.method,tables:[t.table]},e,1)},bE=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();return Ji(n)!==void 0?ti(e):B(n)?Ur(AE(s,e.getArguments()[0]),e,2):ti(e)},NE=(e,t)=>L(e,t,(s,n)=>{const i=bE(s);if(i===void 0)return;const o=A(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),wE=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),PE=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||U(s,"args")===void 0)return!1}return As(e,t).opaque},IE=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=le(a);c!==void 0&&PE(a,c.receiver)&&s.push(wE(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},TE=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...IE(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},CE=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),ft=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Wr=e=>!e.isAny(),jr=e=>{const t=e.getType();if(!Wr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:CE.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},OE=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},qr={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},kE=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),RE={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},LE=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),FE={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},DE=(e,t,s)=>{if(!t.some(i=>Lo(i)))return RE;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return LE.has(s.typeName)&&!n&&!t.some(i=>Ac(i))?FE:qr},Hr=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:kE(u),p=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${p}`:p,title:"Procedure exists at runtime but is missing from the generated API"}},_E=(e,t,s)=>{const n=[];for(const i of te(e)){const o=r.isIdentifier(i.getNameNode())?Gt(i):[i.getName()],c=o.some(u=>ft(s,t,u))||!OE(i)?void 0:jr(i),[l=i.getName()]=o;c!==void 0&&n.push(Hr(t,l,c,i.getStartLineNumber(),DE(i,o,c)))}return n},ME=(e,t,s)=>{if(ft(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=jr(i.getExpression());o!==void 0&&n.push(Hr(t,"default",o,i.getStartLineNumber(),qr))}return n},$E=(e,t,s)=>[..._E(e,t,s),...ME(e,t,s)],KE=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Gt(n).some(i=>ft(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Gt(n).find(o=>ft(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),zE=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),BE=(e,t,s)=>{const n=[],i=[];for(const a of b(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...$E(c,l,s)),i.push(...KE(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Wr(a.getType()))&&n.push(zE(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},VE=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},UE=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},WE=(e,t)=>L(e,t,(s,n)=>VE(s)?{file:n,line:s.getStartLineNumber(),scope:A(s),workflow:UE(s)}:void 0),Gr=e=>e==="@lunora/workflow",jE=e=>new Set(e.getImportDeclarations().filter(t=>Gr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),qE=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),HE=(e,t)=>{const s=mi(e,"defineWorkflowEvent",Gr),n=jE(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of S(e,d.CallExpression)){if(!qE(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?ms(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new D("WORKFLOW_EVENT_NOT_LITERAL",Pe(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:I(t,e.getFilePath()),type:l.getLiteralValue()})}return i},GE=(e,t)=>{const s=b(t).flatMap(i=>HE(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new D("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},YE=e=>{const t=Ma(e,"compatibility_date"),s=$a(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:Ka(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
32
32
  `},QE=e=>`// Generated by @lunora/codegen. Do not edit.
33
33
  // Serves the advisor procedure list to the app's Worker, which forwards it to a hosted Studio after the admin check.
34
34
  const PROCEDURES = ${JSON.stringify(e)};
@@ -48,10 +48,10 @@ export default {
48
48
  return new Response(PROCEDURES, { headers: { "Content-Type": "application/json" }, status: 200 });
49
49
  },
50
50
  };
51
- `,XE=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":QE(t),"wrangler.jsonc":YE(e)}:{},JE=(e,t)=>{for(const s of new Set([ta(t),yi(e)])){const n=s===void 0?[]:ya(s);if(s!==void 0&&n.length>0)throw new F("PROJECT_CONFIG_INVALID",`${vo(s)} is invalid:
51
+ `,XE=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":QE(t),"wrangler.jsonc":YE(e)}:{},JE=(e,t)=>{for(const s of new Set([ta(t),yi(e)])){const n=s===void 0?[]:ya(s);if(s!==void 0&&n.length>0)throw new D("PROJECT_CONFIG_INVALID",`${vo(s)} is invalid:
52
52
  ${n.map(i=>` - ${i}`).join(`
53
53
  `)}`)}},ZE=(e,t,s)=>{for(const n of s)t[n]===void 0&&ve(E(e,n),{force:!0});for(const n of[...new Set(s.map(i=>gt(E(e,i))))].toSorted((i,o)=>o.length-i.length))z(n)&&ds(n).length===0&&ve(n,{recursive:!0})},ex=(e,t)=>{for(const s of ds(e,{recursive:!0,withFileTypes:!0})){const n=E(s.parentPath,s.name);s.isFile()&&t[Be(e,n)]===void 0&&ve(n)}},We=(e,t)=>{z(e)&&ze(e,"utf8")===t||ho(e,t,"utf8")},Yr=(e,t)=>{if(t===""){ve(e,{force:!0});return}We(e,t)},tx=(e,t)=>{const s=E(e,"_lunora","studio");pt(s,{recursive:!0});for(const[n,i]of Object.entries(t))Yr(E(s,`${n}.json`),i)},sx=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){ve(s,{force:!0,recursive:!0});return}if(z(s))for(const n of ds(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[Be(e,i)]===void 0&&ve(i)}for(const[n,i]of Object.entries(t))pt(gt(E(e,n)),{recursive:!0}),We(E(e,n),i)},nx=(e,t,s,n)=>{const i=E(e,t);if(n!==void 0)ZE(i,s,n);else if(Object.keys(s).length===0){ve(i,{force:!0,recursive:!0});return}else z(i)&&ex(i,s);for(const[o,a]of Object.entries(s)){const c=E(i,o);pt(gt(c),{recursive:!0}),We(c,a)}},ix=e=>{try{const t=wc(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},rt=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},rx=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,ox=(e,t)=>{z(e)||pt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{We(E(e,n.name),n.content),s.push(n.name);break}case"directory":{nx(e,n.name,n.files,n.owned),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{sx(e,n.files),s.push(...Object.keys(n.files));break}default:Yr(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},ax=e=>{const t=ix(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Tc({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Oc({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
54
54
  `,openApiModuleContent:Cc(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
55
- `,openRpcModuleContent:kc(i)}},cx=".lunora-schema.json",lx=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},dx=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new F("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},ux=8,fx=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:p,useUmbrella:g,workflows:h}=e,x=()=>mc(()=>{const P=Jo(l,a,{lazyFunctions:o}),se=da(l,a);return{functions:P,httpRoutes:hc(l,a),mutators:se}});let{erased:D,value:{functions:N,httpRoutes:G,mutators:T}}=x();Xo(b(a).map(P=>l.getSourceFileOrThrow(P)),P=>Be(a,P.getFilePath())),jn([...N,...T].map(P=>P.filePath)),jn(G.filter(P=>P.stream).map(P=>P.filePath),"http-stream");for(let P=1;;P+=1){const se=u?N:N.filter(K=>K.channel?.kind!=="room"&&K.lifecycle!=="socket"),ne=Kc({agents:t,functions:se,httpRoutes:G,mutators:T,useUmbrella:g,workflows:h}),ie={agents:t,functions:se,lazyFunctions:o,migrations:c,mutators:T,shapes:f,useUmbrella:g,usesSandbox:p},_=Yc(ie),L=Qc(ie),re=zc({functions:N,useUmbrella:g}),de=E(a,"_generated",Oi),ue=[[s,ne],[i,re],[n,_],...Object.entries(L).map(([K,ee])=>[E(de,K),ee])];if(P>=ux||ue.every(([K,ee])=>rx(l,K,ee)))return{apiContent:ne,erased:D,functions:N,functionModulesContent:L,functionsContent:_,httpRoutes:G,internalContent:re,mutators:T};for(const[K,ee]of ue)rt(l,K,ee);({erased:D,value:{functions:N,httpRoutes:G,mutators:T}}=x())}},px=e=>{const t=lx(),s=t?_t.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora");JE(e.projectRoot,n);const i=Aa(n),o=e.lazyFunctions===!0||i,a=ba(n),c=E(n,"schema.ts");if(!z(c))throw new F("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??_a(n);Yo(Pv);const u=Sc(l,c,e.projectRoot);hE(u.tables,pE(l,n,Ii(e.projectRoot)));const{agents:f,authClaims:p,capabilities:g,containers:h,crons:x,dataModelContent:D,dependencies:N,entryCronTriggers:G,env:T,featureUsage:P,hasFlags:se,hasNotify:ne,identity:ie,platformGate:_,queues:L,serverContent:re,services:de,storageRulesMetadata:ue,topics:K,usesSandbox:ee,useUmbrella:W,workflows:j}=cv({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:u,target:e.target});Ov(u,u.jurisdiction===void 0?void 0:Tv(l,n));const q=E(n,"_generated"),M=E(q,"dataModel.ts"),Qr=E(q,"server.ts"),Xr=E(q,"api.ts"),Jr=E(q,"internal.ts"),Zr=E(q,"functions.ts");rt(l,M,D),rt(l,Qr,re);const _s=Object.fromEntries(de.filter(m=>m.rpcEntrypoint!==void 0).flatMap(m=>Object.entries(cc(m,q))));for(const[m,Dt]of Object.entries(_s))rt(l,E(q,m),Dt);const je=Ec(l,n),ge=yc(l,n),bt=_.signals.typedWebSockets!==!1,{apiContent:Ms,erased:eo,functions:Y,functionModulesContent:$s,functionsContent:Ks,httpRoutes:Nt,internalContent:zs,mutators:wt}=fx({agents:f,apiPath:Xr,generatedFunctionsPath:Zr,internalPath:Jr,lazyFunctions:o,roomsSupported:bt,lunoraDirectory:n,migrations:je,project:l,shapes:ge,useUmbrella:W,usesSandbox:ee,workflows:j}),Bs=Pa(l,n),Pt=Ia(Bs,u,[...Y,...Nt].map(m=>m.filePath)),qe=Bs.length>0,Ie=e.lint===!1&&!qe?void 0:{callEdges:yv(l,n),inserts:vc(l,n),queries:on(l,n,Y),tableWrites:NE(l,n),workflowCalls:WE(l,n)},to=Pc(Ie?.queries??on(l,n,Y)),Te=e.lint===!1||Ie===void 0?void 0:Ch(l,n,{callSites:Ie,containers:h,crons:x,functions:Y,modules:Pt,mutators:wt,queues:L,schema:u,shapes:ge,topics:K,workflows:j,wranglerVariables:e.wranglerVariables}),Vs=Te===void 0?[]:_h(e.projectRoot,ug(l,e.projectRoot,n,[...So(Te,{source:"static"}),...BE(l,n,{byName:new Set([...j,...L,...f,...h].map(m=>m.exportName)),byPath:new Set([...Y,...wt,...ge,...je].map(m=>`${m.filePath}:${m.exportName}`))}),...TE(l,n),...gc(eo,n),...Rc(L,e.wranglerQueueProducers)])),so=xc(l,n),Us=jv(l,n);dx(ge,Us,Uv(l,n));const no=se?wv(l,n):[],It=_.signals.vectorStore!==!1,io=nc(ke(e.projectRoot,e.target),"deliveryAuthorization"),Tt=ke(e.projectRoot,e.target)==="cloudflare"?e.studioAssets:void 0,Ce=vE(P,{containerCount:h.length,cronCount:x.length,dependencies:N,hasPaymentTables:Gv(u.tables),queueCount:L.length,storageColumnCount:Object.keys(Ti(u)).length,storageRuleCount:ue.rules.length,vectorIndexCount:u.vectorIndexes.length,target:ke(e.projectRoot,e.target),vectorStoreSupported:It,workflowCount:j.length}),Ws=t?_t.now():0,Ct=Ic(u,je.map(m=>m.id)),Ot=zv(l,n),js=oc({advisories:Vs.filter(m=>m.name!=="procedure_type_check_unavailable"),agents:f,capabilities:g,containers:h,env:T,flagKeys:no,hasFlags:se,hasNotify:ne,hasIpReaders:Y.some(m=>m.readsIp===!0)||ge.some(m=>m.readsIp===!0),hasRooms:bt&&Y.some(m=>m.channel?.kind==="room"),hasSensitiveArgs:f.length>0||Y.some(m=>Da(m)),hasSecretValues:_.signals.secretValues===!0,hasSockets:bt&&Y.some(m=>m.lifecycle==="socket"),lazyFunctions:o,hasVectors:It,liveStreamDeclarations:Ot,liveStreams:_.signals.liveStreams===!0,maskMetadata:Us,mutators:wt,queues:L,rlsMetadata:so,schema:u,schemaSnapshot:Ct,shapes:ge,services:de,storageRules:ue,studioFeatures:Ce,topics:K,useUmbrella:W,workflowEvents:GE(l,n),workflows:j}),qs=Mc(ge,N.has("@lunora/db"),W),Hs=Lc(h,u.jurisdiction),Gs=Fc(j,{lazy:o}),Ys=Dc(f,{lazy:o}),Qs=_c(L,e.wranglerQueueProducers),Xs=Xc(Ot,W),Js=Bc(x),ro=Vc(Ce.scheduler),He=ic(ke(e.projectRoot,e.target)),oo=He.supported?Uc(W):"",ao=Wc(u.tables,W,u.jurisdiction),co=Na(e.projectRoot)?jc(W):"",Zs=qc(u.vectorIndexes),Ge=Gc(u,W),en=$c(N.has("@lunora/seed")),Ye=e.apiSpec??"openapi",Qe=Ye==="openapi"||Ye==="both",lo=Te?.procedureProtections??[],uo=Te===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...lo]},kt=`${JSON.stringify(uo,void 0,2)}
56
- `,Xe=Ye==="openrpc"||Ye==="both",tn=bc(N.has("@lunora/auth")),sn=Nc({agentWorkflows:f.map(m=>m.className),authClaims:p.map(m=>m.name),capabilities:g,emailAgents:f.filter(m=>m.onEmail===!0).map(m=>({className:m.className,exportName:m.exportName})),hasAccess:N.has("@lunora/cloudflare-access"),hasAuth:N.has("@lunora/auth"),hasFramework:N.has("@lunora/astro")||N.has("@lunora/svelte")||N.has("@lunora/vue")||z(E(e.projectRoot,"src","worker.ts")),hasGlobal:u.tables.some(m=>wi(m)),hasHyperdriveGlobal:u.tables.some(m=>Pi(m)),hasKvIntrospector:Ce.kv,hasNotify:ne,hasQueue:L.some(m=>m.mode==="push"),liveStreams:_.signals.liveStreams===!0,liveStreamsWithheld:_.liveStreamsWithheld,liveStreamDeclarations:Ot,hasAdminRevocations:He.supported,hasScheduler:Ce.scheduler,hasSourcedTables:u.tables.some(m=>m.externalSource!==void 0),hasStorage:Ce.storage,hasDeliveryAuthorization:io,hasVectors:It,hasWorkflow:j.length>0,identity:ie,jurisdiction:u.jurisdiction,jurisdictionPinsAuth:u.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:u.tables.map(m=>({name:m.name,shardMode:m.shardMode})),securityHeaders:wa(n),spaAssetsBindings:e.spaAssetsBindings,studioAssetsBinding:Tt?.binding,useUmbrella:W,vectorIndexCount:u.vectorIndexes.length,voiceAgents:f.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsArchitecture:qe,wantsOpenApi:Qe,wantsOpenRpc:Xe}),{openApiContent:Rt,openApiModuleContent:nn,openRpcContent:Lt,openRpcModuleContent:rn}=ax({functions:Y,httpRoutes:Nt,modules:Pt,projectRoot:e.projectRoot,wantsArchitecture:qe}),me=qe&&Ie!==void 0?Xh({...Ie,crons:x,functions:Y,httpRoutes:Nt,modules:Pt,queues:L,schema:u,services:de,topics:K,workflows:j}):void 0,Ft=E(n,cx),fo=z(Ft),po=e.dryRun?[]:ox(q,[{content:sn,kind:"always",name:"app.ts"},{content:D,kind:"always",name:"dataModel.ts"},{content:Ms,kind:"always",name:"api.ts"},{content:zs,kind:"always",name:"internal.ts"},{content:re,kind:"always",name:"server.ts"},{content:Ks,kind:"always",name:"functions.ts"},{files:$s,kind:"directory",name:Oi},{content:js,kind:"always",name:"shard.ts"},{content:Js,kind:"always",name:"crons.ts"},{content:Zs,kind:"always",name:"vectors.ts"},{content:Ge.global,kind:"always",name:"drizzle.global.ts"},{content:Ge.shard,kind:"always",name:"drizzle.shard.ts"},{content:Hs,kind:"optional",name:"containers.ts"},{content:Gs,kind:"optional",name:"workflows.ts"},{content:Ys,kind:"optional",name:"agents.ts"},{content:Qs,kind:"optional",name:"queues.ts"},{content:Xs,kind:"optional",name:"live.ts"},{content:ro,kind:"optional",name:"scheduler.ts"},{content:ao,kind:"optional",name:"shardRegistry.ts"},{content:oo,kind:"optional",name:"adminRevocations.ts"},{content:co,kind:"optional",name:"durableObjects.ts"},{content:en,kind:"optional",name:"seed.ts"},{content:tn,kind:"optional",name:"authModule.ts"},{content:qs,kind:"optional",name:"collections.ts"},{files:_s,kind:"services"},{files:XE(e.projectRoot,kt,a),kind:"directory",name:"companion",owned:za},{content:Qe?Rt:"",kind:"optional",name:"openapi.json"},{content:Qe?nn:"",kind:"optional",name:"openapi.ts"},{content:Xe?Lt:"",kind:"optional",name:"openrpc.json"},{content:Xe?rn:"",kind:"optional",name:"openrpc.ts"},{content:kt,kind:"optional",name:"advisor-procedures.json"},{content:me===void 0?"":`${JSON.stringify(me,void 0,2)}
57
- `,kind:"optional",name:"architecture.json"},{content:me===void 0?"":Jh(me),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&Tt!==void 0&&tx(E(e.projectRoot,Tt.directory),{architecture:me===void 0?"":JSON.stringify(me),openapi:Qe?Rt:"",openrpc:Xe?Lt:""}),!e.dryRun&&!fo&&We(Ft,yo(Ct)),t){const m=_t.now(),Dt=Math.round(m-s),go=Math.round(Ws-s),mo=Math.round(m-Ws);console.error(`@lunora/codegen: codegen took ${Dt.toString()}ms (discovery ${go.toString()}ms, emit ${mo.toString()}ms)`)}return{advisories:Vs,advisorContext:Te,agents:f,architecture:me,containers:h,cronTriggers:[...new Set([...Hc(x),...G])],generated:{advisorProceduresJson:kt,agents:Ys,api:Ms,app:sn,authModule:tn,collections:qs,containers:Hs,crons:Js,dataModel:D,drizzleGlobal:Ge.global,drizzleShard:Ge.shard,functionModules:$s,functions:Ks,internal:zs,live:Xs,openApi:Rt,openApiModule:nn,openRpc:Lt,openRpcModule:rn,queues:Qs,seed:en,server:re,shard:js,vectors:Zs,workflows:Gs},migrations:je,outputDirectory:q,platformDiagnostics:He.diagnostic===void 0?_.diagnostics:[..._.diagnostics,He.diagnostic],queues:L,indexReferences:to,schemaSnapshot:Ct,schemaSnapshotPath:Ft,schemaTables:u.tables,workflows:j,writtenFiles:po}},FS=e=>To(()=>px(e));export{cx as SCHEMA_SNAPSHOT_FILENAME,_a as createCodegenProject,MS as findTsconfig,$S as refreshCodegenProject,FS as runCodegen,KS as tsconfigFingerprint};
55
+ `,openRpcModuleContent:kc(i)}},cx=".lunora-schema.json",lx=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},dx=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new D("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new D("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new D("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},ux=8,fx=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:p,useUmbrella:g,workflows:h}=e,x=()=>mc(()=>{const P=Jo(l,a,{lazyFunctions:o}),se=da(l,a);return{functions:P,httpRoutes:hc(l,a),mutators:se}});let{erased:_,value:{functions:N,httpRoutes:G,mutators:T}}=x();Xo(b(a).map(P=>l.getSourceFileOrThrow(P)),P=>Be(a,P.getFilePath())),jn([...N,...T].map(P=>P.filePath)),jn(G.filter(P=>P.stream).map(P=>P.filePath),"http-stream");for(let P=1;;P+=1){const se=u?N:N.filter(K=>K.channel?.kind!=="room"&&K.lifecycle!=="socket"),ne=Kc({agents:t,functions:se,httpRoutes:G,mutators:T,useUmbrella:g,workflows:h}),ie={agents:t,functions:se,lazyFunctions:o,migrations:c,mutators:T,shapes:f,useUmbrella:g,usesSandbox:p},M=Yc(ie),F=Qc(ie),re=zc({functions:N,useUmbrella:g}),de=E(a,"_generated",Oi),ue=[[s,ne],[i,re],[n,M],...Object.entries(F).map(([K,ee])=>[E(de,K),ee])];if(P>=ux||ue.every(([K,ee])=>rx(l,K,ee)))return{apiContent:ne,erased:_,functions:N,functionModulesContent:F,functionsContent:M,httpRoutes:G,internalContent:re,mutators:T};for(const[K,ee]of ue)rt(l,K,ee);({erased:_,value:{functions:N,httpRoutes:G,mutators:T}}=x())}},px=e=>{const t=lx(),s=t?_t.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora");JE(e.projectRoot,n);const i=Aa(n),o=e.lazyFunctions===!0||i,a=ba(n),c=E(n,"schema.ts");if(!z(c))throw new D("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??_a(n);Yo(Pv);const u=Sc(l,c,e.projectRoot);hE(u.tables,pE(l,n,Ii(e.projectRoot)));const{agents:f,authClaims:p,capabilities:g,containers:h,crons:x,dataModelContent:_,dependencies:N,entryCronTriggers:G,env:T,featureUsage:P,hasFlags:se,hasNotify:ne,identity:ie,platformGate:M,queues:F,serverContent:re,services:de,storageRulesMetadata:ue,topics:K,usesSandbox:ee,useUmbrella:W,workflows:j}=cv({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:u,target:e.target});Ov(u,u.jurisdiction===void 0?void 0:Tv(l,n));const q=E(n,"_generated"),R=E(q,"dataModel.ts"),Qr=E(q,"server.ts"),Xr=E(q,"api.ts"),Jr=E(q,"internal.ts"),Zr=E(q,"functions.ts");rt(l,R,_),rt(l,Qr,re);const _s=Object.fromEntries(de.filter(m=>m.rpcEntrypoint!==void 0).flatMap(m=>Object.entries(cc(m,q))));for(const[m,Dt]of Object.entries(_s))rt(l,E(q,m),Dt);const je=Ec(l,n),ge=yc(l,n),bt=M.signals.typedWebSockets!==!1,{apiContent:Ms,erased:eo,functions:Y,functionModulesContent:$s,functionsContent:Ks,httpRoutes:Nt,internalContent:zs,mutators:wt}=fx({agents:f,apiPath:Xr,generatedFunctionsPath:Zr,internalPath:Jr,lazyFunctions:o,roomsSupported:bt,lunoraDirectory:n,migrations:je,project:l,shapes:ge,useUmbrella:W,usesSandbox:ee,workflows:j}),Bs=Pa(l,n),Pt=Ia(Bs,u,[...Y,...Nt].map(m=>m.filePath)),qe=Bs.length>0,Ie=e.lint===!1&&!qe?void 0:{callEdges:yv(l,n),inserts:vc(l,n),queries:on(l,n,Y),tableWrites:NE(l,n),workflowCalls:WE(l,n)},to=Pc(Ie?.queries??on(l,n,Y)),Te=e.lint===!1||Ie===void 0?void 0:Ch(l,n,{callSites:Ie,containers:h,crons:x,functions:Y,modules:Pt,mutators:wt,queues:F,schema:u,shapes:ge,topics:K,workflows:j,wranglerVariables:e.wranglerVariables}),Vs=Te===void 0?[]:_h(e.projectRoot,ug(l,e.projectRoot,n,[...So(Te,{source:"static"}),...BE(l,n,{byName:new Set([...j,...F,...f,...h].map(m=>m.exportName)),byPath:new Set([...Y,...wt,...ge,...je].map(m=>`${m.filePath}:${m.exportName}`))}),...TE(l,n),...gc(eo,n),...Rc(F,e.wranglerQueueProducers)])),so=xc(l,n),Us=jv(l,n);dx(ge,Us,Uv(l,n));const no=se?wv(l,n):[],It=M.signals.vectorStore!==!1,io=nc(ke(e.projectRoot,e.target),"deliveryAuthorization"),Tt=ke(e.projectRoot,e.target)==="cloudflare"?e.studioAssets:void 0,Ce=vE(P,{containerCount:h.length,cronCount:x.length,dependencies:N,hasPaymentTables:Gv(u.tables),queueCount:F.length,storageColumnCount:Object.keys(Ti(u)).length,storageRuleCount:ue.rules.length,vectorIndexCount:u.vectorIndexes.length,target:ke(e.projectRoot,e.target),vectorStoreSupported:It,workflowCount:j.length}),Ws=t?_t.now():0,Ct=Ic(u,je.map(m=>m.id)),Ot=zv(l,n),js=oc({advisories:Vs.filter(m=>m.name!=="procedure_type_check_unavailable"),agents:f,capabilities:g,containers:h,env:T,flagKeys:no,hasFlags:se,hasNotify:ne,hasIpReaders:Y.some(m=>m.readsIp===!0)||ge.some(m=>m.readsIp===!0),hasRooms:bt&&Y.some(m=>m.channel?.kind==="room"),hasSensitiveArgs:f.length>0||Y.some(m=>Da(m)),hasSecretValues:M.signals.secretValues===!0,hasSockets:bt&&Y.some(m=>m.lifecycle==="socket"),lazyFunctions:o,hasVectors:It,liveStreamDeclarations:Ot,liveStreams:M.signals.liveStreams===!0,maskMetadata:Us,mutators:wt,queues:F,rlsMetadata:so,schema:u,schemaSnapshot:Ct,shapes:ge,services:de,storageRules:ue,studioFeatures:Ce,topics:K,useUmbrella:W,workflowEvents:GE(l,n),workflows:j}),qs=Mc(ge,N.has("@lunora/db"),W),Hs=Lc(h,u.jurisdiction),Gs=Fc(j,{lazy:o}),Ys=Dc(f,{lazy:o}),Qs=_c(F,e.wranglerQueueProducers),Xs=Xc(Ot,W),Js=Bc(x),ro=Vc(Ce.scheduler),He=ic(ke(e.projectRoot,e.target)),oo=He.supported?Uc(W):"",ao=Wc(u.tables,W,u.jurisdiction),co=Na(e.projectRoot)?jc(W):"",Zs=qc(u.vectorIndexes),Ge=Gc(u,W),en=$c(N.has("@lunora/seed")),Ye=e.apiSpec??"openapi",Qe=Ye==="openapi"||Ye==="both",lo=Te?.procedureProtections??[],uo=Te===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...lo]},kt=`${JSON.stringify(uo,void 0,2)}
56
+ `,Xe=Ye==="openrpc"||Ye==="both",tn=bc(N.has("@lunora/auth")),sn=Nc({agentWorkflows:f.map(m=>m.className),authClaims:p.map(m=>m.name),capabilities:g,emailAgents:f.filter(m=>m.onEmail===!0).map(m=>({className:m.className,exportName:m.exportName})),hasAccess:N.has("@lunora/cloudflare-access"),hasAuth:N.has("@lunora/auth"),hasFramework:N.has("@lunora/astro")||N.has("@lunora/svelte")||N.has("@lunora/vue")||z(E(e.projectRoot,"src","worker.ts")),hasGlobal:u.tables.some(m=>wi(m)),hasHyperdriveGlobal:u.tables.some(m=>Pi(m)),hasKvIntrospector:Ce.kv,hasNotify:ne,hasQueue:F.some(m=>m.mode==="push"),liveStreams:M.signals.liveStreams===!0,liveStreamsWithheld:M.liveStreamsWithheld,liveStreamDeclarations:Ot,hasAdminRevocations:He.supported,hasScheduler:Ce.scheduler,hasSourcedTables:u.tables.some(m=>m.externalSource!==void 0),hasStorage:Ce.storage,hasDeliveryAuthorization:io,hasVectors:It,hasWorkflow:j.length>0,identity:ie,jurisdiction:u.jurisdiction,jurisdictionPinsAuth:u.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:u.tables.map(m=>({name:m.name,shardMode:m.shardMode})),securityHeaders:wa(n),spaAssetsBindings:e.spaAssetsBindings,studioAssetsBinding:Tt?.binding,useUmbrella:W,vectorIndexCount:u.vectorIndexes.length,voiceAgents:f.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsArchitecture:qe,wantsOpenApi:Qe,wantsOpenRpc:Xe}),{openApiContent:Rt,openApiModuleContent:nn,openRpcContent:Lt,openRpcModuleContent:rn}=ax({functions:Y,httpRoutes:Nt,modules:Pt,projectRoot:e.projectRoot,wantsArchitecture:qe}),me=qe&&Ie!==void 0?Xh({...Ie,crons:x,functions:Y,httpRoutes:Nt,modules:Pt,queues:F,schema:u,services:de,topics:K,workflows:j}):void 0,Ft=E(n,cx),fo=z(Ft),po=e.dryRun?[]:ox(q,[{content:sn,kind:"always",name:"app.ts"},{content:_,kind:"always",name:"dataModel.ts"},{content:Ms,kind:"always",name:"api.ts"},{content:zs,kind:"always",name:"internal.ts"},{content:re,kind:"always",name:"server.ts"},{content:Ks,kind:"always",name:"functions.ts"},{files:$s,kind:"directory",name:Oi},{content:js,kind:"always",name:"shard.ts"},{content:Js,kind:"always",name:"crons.ts"},{content:Zs,kind:"always",name:"vectors.ts"},{content:Ge.global,kind:"always",name:"drizzle.global.ts"},{content:Ge.shard,kind:"always",name:"drizzle.shard.ts"},{content:Hs,kind:"optional",name:"containers.ts"},{content:Gs,kind:"optional",name:"workflows.ts"},{content:Ys,kind:"optional",name:"agents.ts"},{content:Qs,kind:"optional",name:"queues.ts"},{content:Xs,kind:"optional",name:"live.ts"},{content:ro,kind:"optional",name:"scheduler.ts"},{content:ao,kind:"optional",name:"shardRegistry.ts"},{content:oo,kind:"optional",name:"adminRevocations.ts"},{content:co,kind:"optional",name:"durableObjects.ts"},{content:en,kind:"optional",name:"seed.ts"},{content:tn,kind:"optional",name:"authModule.ts"},{content:qs,kind:"optional",name:"collections.ts"},{files:_s,kind:"services"},{files:XE(e.projectRoot,kt,a),kind:"directory",name:"companion",owned:za},{content:Qe?Rt:"",kind:"optional",name:"openapi.json"},{content:Qe?nn:"",kind:"optional",name:"openapi.ts"},{content:Xe?Lt:"",kind:"optional",name:"openrpc.json"},{content:Xe?rn:"",kind:"optional",name:"openrpc.ts"},{content:kt,kind:"optional",name:"advisor-procedures.json"},{content:me===void 0?"":`${JSON.stringify(me,void 0,2)}
57
+ `,kind:"optional",name:"architecture.json"},{content:me===void 0?"":Jh(me),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&Tt!==void 0&&tx(E(e.projectRoot,Tt.directory),{architecture:me===void 0?"":JSON.stringify(me),openapi:Qe?Rt:"",openrpc:Xe?Lt:""}),!e.dryRun&&!fo&&We(Ft,yo(Ct)),t){const m=_t.now(),Dt=Math.round(m-s),go=Math.round(Ws-s),mo=Math.round(m-Ws);console.error(`@lunora/codegen: codegen took ${Dt.toString()}ms (discovery ${go.toString()}ms, emit ${mo.toString()}ms)`)}return{advisories:Vs,advisorContext:Te,agents:f,architecture:me,containers:h,cronTriggers:[...new Set([...Hc(x),...G])],generated:{advisorProceduresJson:kt,agents:Ys,api:Ms,app:sn,authModule:tn,collections:qs,containers:Hs,crons:Js,dataModel:_,drizzleGlobal:Ge.global,drizzleShard:Ge.shard,functionModules:$s,functions:Ks,internal:zs,live:Xs,openApi:Rt,openApiModule:nn,openRpc:Lt,openRpcModule:rn,queues:Qs,seed:en,server:re,shard:js,vectors:Zs,workflows:Gs},migrations:je,outputDirectory:q,platformDiagnostics:He.diagnostic===void 0?M.diagnostics:[...M.diagnostics,He.diagnostic],queues:F,indexReferences:to,schemaSnapshot:Ct,schemaSnapshotPath:Ft,schemaTables:u.tables,workflows:j,writtenFiles:po}},FS=e=>To(()=>px(e));export{cx as SCHEMA_SNAPSHOT_FILENAME,_a as createCodegenProject,MS as findTsconfig,$S as refreshCodegenProject,FS as runCodegen,KS as tsconfigFingerprint};
@@ -1 +1 @@
1
- import{LunoraError as x}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,warnIfSecondsLeading as O,compileCronSchedule as S}from"@lunora/scheduler";import I from"@lunora/scheduler/validate";import{SyntaxKind as p,Node as i}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as b}from"./module-specifiers-BctA0m_p.mjs";import{listLunoraSourceFiles as y,declarationLineOf as $,lunoraRelativePath as P,functionKeyOf as v}from"./isTestPath-Uwb5a6Kq.mjs";import{a as D}from"./property-name-7cBlgK_O.mjs";const F=new Set([...A,"cron"]),V=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(i.isImportSpecifier(r))return b(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},k=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const n=r.getInitializer();if(n?.getKind()!==p.CallExpression)continue;const s=n.getExpression();i.isIdentifier(s)&&V(s)&&t.add(r.getName())}return t},j=e=>{let t=e;for(;i.isCallExpression(t)||i.isPropertyAccessExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},L=(e,t)=>{const r=e.getArguments()[t];return r&&(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)||i.isNumericLiteral(e))return e.getLiteralValue();if(i.isTrueLiteral(e))return!0;if(i.isFalseLiteral(e))return!1;if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken){const r=e.getOperand();if(i.isNumericLiteral(r))return-r.getLiteralValue()}if(i.isObjectLiteralExpression(e))return d(e,t);if(i.isArrayLiteralExpression(e))return e.getElements().map(r=>_(r,t));throw f(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},d=(e,t)=>{const r={};for(const n of e.getProperties()){if(!i.isPropertyAssignment(n))throw f(n,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const s=n.getInitializer();s&&(r[D(n)]=_(s,t))}return r},C=(e,t,r)=>{const n=e.getArguments()[t];if(!n||!i.isPropertyAccessExpression(n))throw f(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const s=v(n);if(s===void 0)throw f(n,`Cron job "${r}" function reference must be of the form internal.<…path>.fn (or api.<…path>.fn).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});return s},h=e=>({workflow:{className:e.className,exportName:e.exportName}}),w=e=>({workflow:{className:e.className,exportName:e.exportName}}),T=(e,t,r,n,s,o)=>{const a=e.getExpression();if(!i.isIdentifier(a)||a.getText()!==t)return;const c=r.get(e.getName());if(c)return o(c);throw f(e,`Cron job "${n}" targets ${t}.${e.getName()}, but no such ${s} is declared in lunora/${s}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},U=(e,t,r,n,s)=>{const o=e.getArguments()[t];if(o&&i.isPropertyAccessExpression(o)){const a=T(o,"workflows",n,r,"workflow",h);if(a)return a;const c=T(o,"agents",s,r,"agent",w);return c||{functionPath:C(e,t,r)}}if(o&&i.isIdentifier(o)){const a=n.get(o.getText()),c=s.get(o.getText());if(a&&c)throw f(o,`Cron job "${r}" references "${o.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(a)return h(a);if(c)return w(c);throw f(o,`Cron job "${r}" references "${o.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:C(e,t,r)}},M=/^@lunora\/scheduler:\s*/u,K=(e,t)=>{const r=L(e,1);if(r===void 0)throw f(e,`Cron job "${t}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!I(r))throw f(e,`Cron job "${t}" has an invalid cron expression "${r}" — expected 5 or 6 space-separated fields.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});return O(r,`cron expression for job "${t}"`),r},z=(e,t,r)=>{const n=e.getArguments()[1];if(!n||!i.isObjectLiteralExpression(n))throw f(e,`Cron job "${r}" must pass an object-literal schedule to ".${t}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});try{return S(t,d(n,r),r)}catch(s){if(s instanceof R)throw s;const o=s instanceof Error?s.message.replace(M,""):String(s);throw f(e,o,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},H=(e,t,r,n,s)=>{const o=t.getName();if(!F.has(o)||!r.has(j(t.getExpression())??""))return;const a=L(e,0);if(a===void 0||a.trim()==="")throw f(e,`A cron ".${o}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});const c=o==="cron"?K(e,a):z(e,o,a),u=U(e,2,a,n,s),l=e.getArguments()[3];return{args:l&&i.isObjectLiteralExpression(l)?d(l,a):{},cron:c,name:a,...u}},q=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new x("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},ee=(e,t,r=[],n=[])=>{const s=y(t),o=[],a=new Map(r.map(u=>[u.exportName,u])),c=new Map(n.map(u=>[u.exportName,u]));for(const u of s){const l=e.getSourceFile(u)??e.addSourceFileAtPath(u),g=k(l);if(g.size!==0)for(const m of l.getDescendantsOfKind(p.CallExpression)){const N=m.getExpression();if(!i.isPropertyAccessExpression(N))continue;const E=H(m,N,g,a,c);E&&o.push({...E,file:P(t,u),line:$(m)})}}return o.sort((u,l)=>u.name.localeCompare(l.name)),q(o),o};export{ee as default};
1
+ import{LunoraError as x}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,warnIfSecondsLeading as O,compileCronSchedule as S}from"@lunora/scheduler";import I from"@lunora/scheduler/validate";import{SyntaxKind as p,Node as i}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as b}from"./module-specifiers-BctA0m_p.mjs";import{listLunoraSourceFiles as y,declarationLineOf as $,lunoraRelativePath as P,functionKeyOf as v}from"./isTestPath-Uwb5a6Kq.mjs";import{a as D}from"./property-name-7cBlgK_O.mjs";const F=new Set([...A,"cron"]),V=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(i.isImportSpecifier(r))return b(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},k=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const n=r.getInitializer();if(n?.getKind()!==p.CallExpression)continue;const s=n.getExpression();i.isIdentifier(s)&&V(s)&&t.add(r.getName())}return t},j=e=>{let t=e;for(;i.isCallExpression(t)||i.isPropertyAccessExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},L=(e,t)=>{const r=e.getArguments()[t];return r&&(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)||i.isNumericLiteral(e))return e.getLiteralValue();if(i.isTrueLiteral(e))return!0;if(i.isFalseLiteral(e))return!1;if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken){const r=e.getOperand();if(i.isNumericLiteral(r))return-r.getLiteralValue()}if(i.isObjectLiteralExpression(e))return d(e,t);if(i.isArrayLiteralExpression(e))return e.getElements().map(r=>_(r,t));throw f(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},d=(e,t)=>{const r={};for(const n of e.getProperties()){if(!i.isPropertyAssignment(n))throw f(n,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const s=n.getInitializer();s&&(r[D(n)]=_(s,t))}return r},C=(e,t,r)=>{const n=e.getArguments()[t];if(!n||!i.isPropertyAccessExpression(n))throw f(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const s=v(n);if(s===void 0)throw f(n,`Cron job "${r}" function reference must be of the form internal.<…path>.fn (or api.<…path>.fn).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});return s},h=e=>({workflow:{className:e.className,exportName:e.exportName}}),w=e=>({workflow:{className:e.className,exportName:e.exportName}}),T=(e,t,r,n,s,o)=>{const a=e.getExpression();if(!i.isIdentifier(a)||a.getText()!==t)return;const c=r.get(e.getName());if(c)return o(c);throw f(e,`Cron job "${n}" targets ${t}.${e.getName()}, but no such ${s} is declared in lunora/${s}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},U=(e,t,r,n,s)=>{const o=e.getArguments()[t];if(o&&i.isPropertyAccessExpression(o)){const a=T(o,"workflows",n,r,"workflow",h);if(a)return a;const c=T(o,"agents",s,r,"agent",w);return c||{functionPath:C(e,t,r)}}if(o&&i.isIdentifier(o)){const a=n.get(o.getText()),c=s.get(o.getText());if(a&&c)throw f(o,`Cron job "${r}" references "${o.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(a)return h(a);if(c)return w(c);throw f(o,`Cron job "${r}" references "${o.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:C(e,t,r)}},M=/^@lunora\/scheduler:\s*/u,K=(e,t)=>{const r=L(e,1);if(r===void 0)throw f(e,`Cron job "${t}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!I(r))throw f(e,`Cron job "${t}" has an invalid cron expression "${r}" — expected 5 or 6 space-separated fields that occur on at least one date.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});return O(r,`cron expression for job "${t}"`),r},z=(e,t,r)=>{const n=e.getArguments()[1];if(!n||!i.isObjectLiteralExpression(n))throw f(e,`Cron job "${r}" must pass an object-literal schedule to ".${t}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});try{return S(t,d(n,r),r)}catch(s){if(s instanceof R)throw s;const o=s instanceof Error?s.message.replace(M,""):String(s);throw f(e,o,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},H=(e,t,r,n,s)=>{const o=t.getName();if(!F.has(o)||!r.has(j(t.getExpression())??""))return;const a=L(e,0);if(a===void 0||a.trim()==="")throw f(e,`A cron ".${o}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});const c=o==="cron"?K(e,a):z(e,o,a),u=U(e,2,a,n,s),l=e.getArguments()[3];return{args:l&&i.isObjectLiteralExpression(l)?d(l,a):{},cron:c,name:a,...u}},q=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new x("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},ee=(e,t,r=[],n=[])=>{const s=y(t),o=[],a=new Map(r.map(u=>[u.exportName,u])),c=new Map(n.map(u=>[u.exportName,u]));for(const u of s){const l=e.getSourceFile(u)??e.addSourceFileAtPath(u),g=k(l);if(g.size!==0)for(const m of l.getDescendantsOfKind(p.CallExpression)){const N=m.getExpression();if(!i.isPropertyAccessExpression(N))continue;const E=H(m,N,g,a,c);E&&o.push({...E,file:P(t,u),line:$(m)})}}return o.sort((u,l)=>u.name.localeCompare(l.name)),q(o),o};export{ee as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.422",
3
+ "version": "1.0.0-alpha.423",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{NODE_CAPABILITIES as g,CLOUDFLARE_CAPABILITIES as b,CELLD_CAPABILITIES as y}from"@lunora/platform";import{r as f}from"./project-config-file-DR7xrrNB.mjs";const m="cloudflare",S=t=>{const{target:e}=f(t);return e!==void 0&&e.length>0?e:void 0},I=(t,e)=>e??S(t)??m,z=(t,e)=>{if(e!==void 0)return[];const{target:r,unreadable:a}=f(t);return a!==!0||r!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${m}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${m}" }\`), or pass \`--target\`.`,target:m}]},_={max:1536,min:32},E=(t,e)=>{if(t!=="cloudflare")return[];const{max:r,min:a}=_,i=`${String(a)}-${String(r)}`;return e.filter(({dimensions:o})=>o!==void 0&&(!Number.isInteger(o)||o<a||o>r)).map(({dimensions:o,name:s})=>({level:"warn",message:`Vector index "${s}" declares ${String(o)} dimensions; Cloudflare Vectorize accepts ${i}, so creating a Vectorize index for it fails at deploy.`,name:"platform_vector_dimensions_out_of_range",remediation:`If a Vectorize index backs "${s}", use ${i} dimensions (many embedding models can truncate output to fit). Ignore this if another store, such as pgvector, backs it.`,target:t}))},u={celld:y,cloudflare:b,node:g},O=(t,e)=>{const r=u[t];if(r===void 0)return!0;const a=r.features[e]?.level;return a==="native"||a==="emulated"},D=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),k={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:"secrets"},w=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","deliveryAuthorization","durableStreams","globalTables","liveStreams","queues","relationGraph","secrets","secretValues","services","topics","typedWebSockets","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],h={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",deliveryAuthorization:"delivery authorization (`.deliveryAuthorization(...)` on the app builder)",cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",liveContext:"the live publisher (`ctx.live`)",liveStreams:"live topic streams (`defineLiveStream`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",secretValues:"human-supplied secret values (`requestSecretTool`, held for one agent step)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",typedWebSockets:"typed WebSocket routes and rooms (`defineWebSocket` / `defineRoom`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},T=(t,e,r)=>({level:"error",message:`${e.name} does not support ${h[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:r}),x=(t,e)=>({level:"error",message:`${t.name} withholds live streams, so ctx.live is not available on the "${e}" target, but this app reads ctx.live.`,name:"platform_unsupported_feature",remediation:'Remove the ctx.live usage, or deploy to a target whose capability matrix marks "liveStreams" as native or emulated.',target:e}),P=t=>({level:"error",message:"This app declares defineLiveStream topics and enables delivery authorization. With delivery authorization on, the shard answers every /_lunora/live/* request with 501, so the live streams cannot be served.",name:"platform_live_stream_delivery_authorization",remediation:"Remove the defineLiveStream declarations, or remove the .deliveryAuthorization(...) call. Live streams and delivery authorization cannot be combined.",target:t}),W=t=>({level:"error",message:"This app declares defineWebSocket routes and enables delivery authorization. With delivery authorization on, the shard answers every route upgrade with 501, so the routes cannot be served.",name:"platform_socket_delivery_authorization",remediation:"Remove the defineWebSocket declarations, or remove the .deliveryAuthorization(...) call. Socket routes and delivery authorization cannot be combined.",target:t}),A=(t,e,r)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${h[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:r}),$=t=>{const{diagnostics:e,gatedSignals:r,matrix:a,reported:i,signals:o,target:s}=t;for(const n of w){if(o[n]!==!0)continue;const d=a.features[n]?.level;d!=="unsupported"&&d!==void 0||(r[n]=!1,!i.has(n)&&e.push(d==="unsupported"?T(n,a,s):A(n,a,s)))}},R=(t,e,r,a={})=>{const i={...t},o={...a},s=[],n=new Set;for(const[l,c]of Object.entries(k)){if(c===null||!t[l])continue;const v=e.features[c]?.level;v==="unsupported"?(i[l]=!1,n.add(c),s.push({feature:l,level:"error",message:`${e.name} does not support "${l}" (ctx.${l}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${l} usage, or deploy to a target whose capability matrix marks "${c}" as native or emulated.`,target:r})):v===void 0&&(i[l]=!1,n.add(c),s.push({feature:l,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${l}" (ctx.${l}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${c}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:r}))}$({diagnostics:s,gatedSignals:o,matrix:e,reported:n,signals:a,target:r});const d=e.features.liveStreams?.level,p=d===void 0||d==="unsupported";return a.liveContext===!0&&p&&s.push(x(e,r)),{diagnostics:s,liveStreamsWithheld:p,signals:o,usage:i}},F=(t,e,r={})=>{const a=u[e];return a===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],liveStreamsWithheld:!1,signals:{...r},usage:{...t}}:R(t,a,e,r)},j=t=>{const e=u[t];if(e===void 0)return{supported:!0};const r=e.features.adminTokenRevocation?.level;return r!==void 0&&r!=="unsupported"?{supported:!0}:{diagnostic:{level:"warn",message:`${e.name} ${r===void 0?"does not declare a support level for":"does not support"} named admin tokens, so codegen omits the admin revocation store (\`_generated/adminRevocations.ts\` and the builder's \`.adminRevocations()\`). The root LUNORA_ADMIN_TOKEN is the only admin credential here.`,name:r===void 0?"platform_undeclared_feature":"platform_unsupported_feature",remediation:'Use the root admin token, or deploy to a target whose capability matrix marks "adminTokenRevocation" as native or emulated.',target:t},supported:!1}},N=t=>{const e=u[t];if(e===void 0)return;const r=Object.entries(e.features).filter(([,a])=>a.level==="unsupported").map(([a])=>a).toSorted((a,i)=>a.localeCompare(i));return{id:e.id,name:e.name,unsupported:r}};export{k as CAPABILITY_TO_FEATURE,m as DEFAULT_TARGET,j as gateAdminTokenRevocation,R as gateAgainstMatrix,F as gatePlatformFeatures,P as liveStreamsDeliveryAuthorizationDiagnostic,O as platformFeatureAvailable,D as platformMatrixIds,S as readProjectTarget,z as readTargetDiagnostics,I as resolveCodegenTarget,W as socketRoutesDeliveryAuthorizationDiagnostic,N as studioPlatformFor,E as vectorizeDimensionDiagnostics};