@lunora/codegen 1.0.0-alpha.28 → 1.0.0-alpha.281

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.
Files changed (120) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +4046 -1242
  4. package/dist/index.d.ts +4046 -1242
  5. package/dist/index.mjs +1 -34
  6. package/dist/packem_shared/AGENTS_FILENAME-Dntm1vDe.mjs +1 -0
  7. package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
  8. package/dist/packem_shared/CONTAINERS_FILENAME-D5xnZUl6.mjs +1 -0
  9. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_TARGET-GPPgJNTn.mjs +1 -0
  11. package/dist/packem_shared/FLAGS_FILENAME-C1RHlinh.mjs +1 -0
  12. package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +1 -0
  13. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  14. package/dist/packem_shared/MUTATORS_FILENAME-YOl15Grm.mjs +1 -0
  15. package/dist/packem_shared/NOTIFY_FILENAME-B8Wb9kiq.mjs +1 -0
  16. package/dist/packem_shared/OPENRPC_VERSION-DnYKkFP6.mjs +3 -0
  17. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  18. package/dist/packem_shared/QUEUES_FILENAME-hTuq7XDL.mjs +1 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-iUdBnBmw.mjs +11 -0
  20. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  21. package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
  22. package/dist/packem_shared/SHAPES_FILENAME-BrqrIhBv.mjs +1 -0
  23. package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
  24. package/dist/packem_shared/WORKFLOWS_FILENAME-eLdktkM5.mjs +1 -0
  25. package/dist/packem_shared/attribution-DqqCSywo.mjs +1 -0
  26. package/dist/packem_shared/buildOpenApiDocument-D_8TtHK1.mjs +3 -0
  27. package/dist/packem_shared/capabilitiesUsedBy-CmSX6ODG.mjs +1 -0
  28. package/dist/packem_shared/chain-DmRSLvAh.mjs +1 -0
  29. package/dist/packem_shared/classify-procedure-call-HrUyDQX0.mjs +1 -0
  30. package/dist/packem_shared/context-property-calls-0qzW2Joh.mjs +1 -0
  31. package/dist/packem_shared/context-root-DKsAPUmn.mjs +1 -0
  32. package/dist/packem_shared/database-calls-CBlsQTga.mjs +1 -0
  33. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  34. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  35. package/dist/packem_shared/discoverAuthApiCalls-CeFyWdQy.mjs +1 -0
  36. package/dist/packem_shared/discoverCrons-DBuEbNrB.mjs +1 -0
  37. package/dist/packem_shared/discoverFunctions-BswBeUWK.mjs +1 -0
  38. package/dist/packem_shared/discoverHttpRoutes-6utMwfNf.mjs +1 -0
  39. package/dist/packem_shared/discoverHyperdriveCalls-HGl9zBnw.mjs +1 -0
  40. package/dist/packem_shared/discoverInserts-Ao36AnSp.mjs +1 -0
  41. package/dist/packem_shared/discoverMaskProcedures-B29pl7an.mjs +1 -0
  42. package/dist/packem_shared/discoverMigrations-CM6L8k6b.mjs +1 -0
  43. package/dist/packem_shared/discoverNondeterministicCalls-C6iIjMHn.mjs +1 -0
  44. package/dist/packem_shared/discoverQueries-4lacKgx_.mjs +1 -0
  45. package/dist/packem_shared/discoverR2sqlCalls-BDomQsRO.mjs +1 -0
  46. package/dist/packem_shared/discoverRlsMetadata-CTQN6hgU.mjs +1 -0
  47. package/dist/packem_shared/discoverRlsProcedures-DllbV6_E.mjs +1 -0
  48. package/dist/packem_shared/discoverSandboxUsage-ejLtE6Ky.mjs +1 -0
  49. package/dist/packem_shared/discoverSchema-C3WOG-xt.mjs +1 -0
  50. package/dist/packem_shared/discoverStorageRulesMetadata-CyZ44b1b.mjs +1 -0
  51. package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
  52. package/dist/packem_shared/emitAgents-BedQefBj.mjs +1 -0
  53. package/dist/packem_shared/emitApi-Zx6VPN-7.mjs +135 -0
  54. package/dist/packem_shared/emitApp-CBIXVzkw.mjs +864 -0
  55. package/dist/packem_shared/emitCrons-Gd8jD8jF.mjs +96 -0
  56. package/dist/packem_shared/emitDataModel-DdtjdNg3.mjs +113 -0
  57. package/dist/packem_shared/emitDrizzleSchema-CpOGYfyl.mjs +15 -0
  58. package/dist/packem_shared/emitFunctions-BeKgL3dl.mjs +241 -0
  59. package/dist/packem_shared/emitServer-DlOheWku.mjs +1 -0
  60. package/dist/packem_shared/emitShard-CngydZFL.mjs +1 -0
  61. package/dist/packem_shared/exported-procedure-chains--nYG8cid.mjs +1 -0
  62. package/dist/packem_shared/fingerprintSchemaSources-C4PkhFFQ.mjs +1 -0
  63. package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
  64. package/dist/packem_shared/handler-reference-CpEEELL0.mjs +1 -0
  65. package/dist/packem_shared/index-BfaSHMNi.mjs +1 -0
  66. package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
  67. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  68. package/dist/packem_shared/isTestPath-CiIyKqhF.mjs +1 -0
  69. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  70. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  71. package/dist/packem_shared/loadProjectConfig-DGqGWOfa.mjs +1 -0
  72. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  73. package/dist/packem_shared/modules-Cuogms61.mjs +1 -0
  74. package/dist/packem_shared/parse-validator-DYdT7Hyf.mjs +1 -0
  75. package/dist/packem_shared/project-config-file-Bv2l-Kmm.mjs +1 -0
  76. package/dist/packem_shared/qualifiers-DEdXn5wP.mjs +1 -0
  77. package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
  78. package/dist/packem_shared/readServiceBindings-DuE9xlvV.mjs +1 -0
  79. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  80. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  81. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  82. package/dist/packem_shared/server-DSUfd6Tc.mjs +368 -0
  83. package/dist/packem_shared/shard-BTfJuEeP.mjs +1438 -0
  84. package/dist/packem_shared/shard-runtime-CkaEBSdL.mjs +326 -0
  85. package/dist/packem_shared/shared-DnCokNcE.mjs +13 -0
  86. package/dist/packem_shared/unwrap-handler-return-BTKoWeJc.mjs +1 -0
  87. package/package.json +17 -7
  88. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  89. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  90. package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
  91. package/dist/packem_shared/GENERATED_HEADER-Bq7mlUUg.mjs +0 -3269
  92. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  93. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  94. package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
  95. package/dist/packem_shared/OPENRPC_VERSION-CPz5aJ8A.mjs +0 -60
  96. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  97. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BSBSVXEv.mjs +0 -1153
  98. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  99. package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
  100. package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
  101. package/dist/packem_shared/buildOpenApiDocument-DLAW4ldJ.mjs +0 -183
  102. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  103. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  104. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  105. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  106. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  107. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  108. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  109. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  110. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  111. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  112. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  113. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  114. package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
  115. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  116. package/dist/packem_shared/emitApp-YuSwauCv.mjs +0 -675
  117. package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
  118. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  119. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  120. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,11 @@
1
+ import{existsSync as k,mkdirSync as js,rmSync as ft,readdirSync as ar,readFileSync as cr,writeFileSync as lr}from"node:fs";import{join as h,dirname as me,relative as dr}from"node:path";import{performance as st}from"node:perf_hooks";import{runAdvisor as ur}from"@lunora/advisor";import{LunoraError as X}from"@lunora/errors";import{readJsonSync as fr}from"@visulima/fs";import{SyntaxKind as d,Node as i,ts as gr,Project as rs}from"ts-morph";import{serializeSchemaSnapshot as pr}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as mr}from"./formatAdvisories-DwmUKYuc.mjs";import{r as hr,a as S,s as vr,b as Er}from"./project-config-file-Bv2l-Kmm.mjs";import{a as Oe,d as xr,r as Sr}from"./modules-Cuogms61.mjs";import{WORKFLOWS_FILENAME as Ar,discoverWorkflows as yr}from"./WORKFLOWS_FILENAME-eLdktkM5.mjs";import{r as br}from"./json-data-Chfs2Cz5.mjs";import{G as Nr}from"./shared-DnCokNcE.mjs";import{n as Pr,s as Ws}from"./dispatch-namespace-DwTjD7BU.mjs";import{CAPABILITIES as wr,usedCapabilities as Ir}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Hs,isHyperdriveGlobalTable as Gs}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Cr}from"./AGENTS_FILENAME-Dntm1vDe.mjs";import{discoverContainers as Tr}from"./CONTAINERS_FILENAME-D5xnZUl6.mjs";import Or from"./discoverCrons-DBuEbNrB.mjs";import{diagnosticAt as Se}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as Ue}from"./module-specifiers-WF8iAydP.mjs";import{a as Ys,b as W,d as U,f as D,g as Nt,c as v,w as Pt,k as Rr,l as kr,h as Fr,j as gt,i as Dr}from"./attribution-DqqCSywo.mjs";import{contextPropertiesRead as Lr,discoverFeatureUsage as Mr}from"./capabilitiesUsedBy-CmSX6ODG.mjs";import _r from"./readPackageDependencies-RHhGiz0k.mjs";import{listLunoraSourceFiles as x,unwrapExpression as E,listSecurityScanFiles as Ve,objectLiteralFromCallbackBody as Qs,propertyInitializer as C,lunoraRelativePath as T,bindingKeyName as Ae,collectCallRows as O,findObjectProperty as M,collectSecurityCallRows as Kr,isSameNode as A,isFunctionLike as J,collectNodeRows as le,RUN_METHODS as Xs,functionKeyOf as Js,limitNameOf as Zs,optionsObjectLiteral as en,handlerOf as Br,chainRootOf as wt,outermostValueWrapper as I,isWriteTarget as qe,isConstDeclaration as te,returningFunctionOf as pt,walkChain as zr,memberAccessOf as $r,functionReferenceSegments as Ur,isTestPath as Vr}from"./isTestPath-CiIyKqhF.mjs";import{discoverQueueDeclarations as qr}from"./QUEUES_FILENAME-hTuq7XDL.mjs";import{discoverSandboxUsage as jr}from"./discoverSandboxUsage-ejLtE6Ky.mjs";import{resolveServiceBindings as Wr}from"./readServiceBindings-DuE9xlvV.mjs";import Hr from"./discoverStorageRulesMetadata-CyZ44b1b.mjs";import{a as y,c as H,d as tn,e as Gr}from"./classify-procedure-call-HrUyDQX0.mjs";import{i as Yr}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as Qr,resolveCodegenTarget as sn,readTargetDiagnostics as Xr,studioPlatformFor as Jr}from"./DEFAULT_TARGET-GPPgJNTn.mjs";import{b as nn,e as Zr}from"./shard-BTfJuEeP.mjs";import{e as ei,a as ti}from"./server-DSUfd6Tc.mjs";import{emitDataModel as si}from"./emitDataModel-DdtjdNg3.mjs";import{a as is,r as nt,i as q,b as ni,m as rn,c as je,e as on,E as an,C as cn,d as ri,f as ii,g as oi}from"./context-root-DKsAPUmn.mjs";import{r as We,s as ai}from"./parse-validator-DYdT7Hyf.mjs";import ci from"./discoverAuthApiCalls-CeFyWdQy.mjs";import{i as li,a as di,e as ui,b as fi,d as gi,c as pi}from"./unwrap-handler-return-BTKoWeJc.mjs";import mi from"./discoverFunctions-BswBeUWK.mjs";import hi from"./discoverHttpRoutes-6utMwfNf.mjs";import vi from"./discoverHyperdriveCalls-HGl9zBnw.mjs";import Ei from"./discoverInserts-Ao36AnSp.mjs";import{m as It,a as Le,s as ln,d as xi}from"./index-BfaSHMNi.mjs";import{e as dn}from"./exported-procedure-chains--nYG8cid.mjs";import Si from"./discoverMigrations-CM6L8k6b.mjs";import{i as $,r as un}from"./database-calls-CBlsQTga.mjs";import{MUTATORS_FILENAME as Ai,isDefineMutatorCallee as yi,mutatorServerImplOf as bi,discoverMutators as Ni}from"./MUTATORS_FILENAME-YOl15Grm.mjs";import Pi from"./discoverNondeterministicCalls-C6iIjMHn.mjs";import{discoverNotifyConfig as wi,discoverNotifyCalls as Ii}from"./NOTIFY_FILENAME-B8Wb9kiq.mjs";import Ci from"./discoverQueries-4lacKgx_.mjs";import Ti from"./discoverR2sqlCalls-BDomQsRO.mjs";import Oi from"./discoverRlsProcedures-DllbV6_E.mjs";import Ri from"./discoverRlsMetadata-CTQN6hgU.mjs";import ki from"./discoverSchema-C3WOG-xt.mjs";import{secretKindOf as Fi,redact as Di,isHeuristicSecretKind as Li,isSecretishName as Mi}from"./redact-Cy14LEnc.mjs";import{discoverShapes as _i}from"./SHAPES_FILENAME-BrqrIhBv.mjs";import{i as Ki}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as Bi}from"./emitApp-CBIXVzkw.mjs";import{buildOpenApiDocument as zi,emitOpenApiModule as $i}from"./buildOpenApiDocument-D_8TtHK1.mjs";import{buildOpenRpcDocument as Ui,emitOpenRpcModule as Vi}from"./OPENRPC_VERSION-DnYKkFP6.mjs";import{buildSchemaSnapshot as qi}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{v as ji,t as Wi,u as Hi,s as Gi,w as Yi}from"./shard-runtime-CkaEBSdL.mjs";import{emitCollections as Qi,emitSeed as Xi,emitApi as Ji,emitInternalApi as Zi}from"./emitApi-Zx6VPN-7.mjs";import{emitCrons as eo,emitScheduler as to,emitShardRegistry as so,emitDurableObjects as no,emitVectors as ro,emitWranglerCronTriggers as io}from"./emitCrons-Gd8jD8jF.mjs";import oo from"./emitDrizzleSchema-CpOGYfyl.mjs";import ao from"./emitFunctions-BeKgL3dl.mjs";const os={error:"ERROR",info:"INFO",warn:"WARN"},as={ERROR:2,INFO:0,WARN:1},co=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"}),lo=(e,t)=>{const{advisor:s}=hr(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,r=n!==void 0&&Object.hasOwn(os,n)?os[n]:void 0;return r===void 0?[...t,co(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=>as[o.level]>=as[r])},uo={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},fo="crons",go=Ar.replace(/\.ts$/u,""),ce=(e,t)=>`${Ws(e)}:${t}`,rt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},po=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${uo[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,...rt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...rt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...rt("workflow",t.workflow,"workflow name")}))],mo=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",ho=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:mo(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},vo=e=>po(e).flatMap(t=>ho(t)),Eo=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}`,r=s??n;return{file:fo,from:`cron:${t.name}`,kind:"trigger",line:0,...r===void 0?{reason:"the cron has no target"}:{to:r}}})],xo=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),pe=(e,t)=>t===void 0?e:{...e,module:t},So=e=>{const t=new Map,s=new Map,n=xo(e.modules),r=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&r(l,c.id)},a=(c,l)=>{c!==void 0&&r(ce(c.file,c.exportName),l)};for(const c of e.functions){const l=ce(c.filePath,c.exportName),u=[...Pr(c.filePath),c.exportName].join(".");o(pe({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Oe(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ce(c.filePath,c.exportName);o(pe({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Oe(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(pe({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(pe({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Oe(e.modules,c.filePath)),ce(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(pe({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Oe(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ce(go,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}},Ao=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,yo=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ce(e.file,e.exportName))??{reason:Ao(e.exportName)},bo=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=yo(e,t);if("reason"in n)return n;const{to:r}=e;return s.has(r)?{drawn:n.map(o=>({from:o,kind:e.kind,to:r}))}:{reason:`${r} is not declared`}},it=e=>`${e.from}|${e.kind}|${e.to}`,No=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Po=e=>{const{nodes:t,sites:s}=So(e),n=new Map,r=new Map;for(const o of[...Eo(e),...vo(e)]){const a=bo(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(it(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};r.set(No(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>it(o).localeCompare(it(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:[...r.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},wo=e=>`${Nr}export const architecture = ${br(e,"Record<string, unknown>")};
2
+ `,cs=(e,t="api")=>{const s=new Map;for(const n of e){const r=Ws(n),o=s.get(r);if(o===void 0){s.set(r,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${r}" twice and the dispatch key "${r}:<fn>" would be ambiguous`:`the generated api.ts would declare "${r}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new X("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${r}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Io=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:r=!1,usage:o}=t,a=[];e.tables.some(c=>Hs(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=>Gs(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`"}),r&&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?[]:wr)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)},Co=(e,t,s={})=>{if(t===void 0)return;const n=Io(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const r=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
3
+ `);throw new X("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
4
+ ${r}
5
+
6
+ Install them with your package manager, then re-run codegen.`)},To="env.ts",Oo=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Ue(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Ro=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Ue(n.getModuleSpecifierValue())}return!1},ko=e=>{if(i.isIdentifier(e))return Oo(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&Ro(t)}return!1},Fo=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!ko(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Se(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=Ys(s,"member");a!==void 0&&t.push({exportName:a})}return t},Do=(e,t)=>{const s=h(t,To);if(!k(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=Fo(n);if(r.length!==0){if(r.length>1)throw Se(n,`lunora/env.ts declares ${r.length.toString()} defineEnv() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},fn="identity.ts",Lo=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Ue(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Mo=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Ue(n.getModuleSpecifierValue())}return!1},_o=e=>{if(i.isIdentifier(e))return Lo(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&Mo(t)}return!1},Ko=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!_o(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Se(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Ys(s,"member");a!==void 0&&t.push({exportName:a})}return t},Bo=(e,t)=>{const s=h(t,fn);if(!k(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=Ko(n);if(r.length!==0){if(r.length>1)throw Se(n,`lunora/identity.ts declares ${r.length.toString()} defineIdentity() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},zo=new Set(["allowedHosts","deniedHosts","interceptHttps"]),$o=(e,t)=>{const s=E(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return E(e.getDescendantsOfKind(d.VariableDeclaration).find(r=>r.getName()===n)?.getInitializer())},Uo=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(S(s));if(!i.isPropertyAssignment(s)||!t.has(S(s)))return!1;const n=E(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Vo=new Set(["durable"]),qo=new Set(["rollback"]),jo=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},Wo=new Map([["defineContainer",{keys:zo,signal:"containerEgressPolicy"}],["defineStep",{keys:qo,signal:"workflowRollback"}],["stream",{keys:Vo,signal:"durableStreams"}]]),Ho=(e,t)=>{const s=Wo.get(jo(t));if(s!==void 0)return t.getArguments().some(n=>Uo($o(e,n),s.keys))?s.signal:void 0},Go=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Lr(r).has("secrets"));for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=Ho(r,o);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},Yo="createWorker",Qo="extend",ls=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,ds=e=>{const t=[],s=ls(C(e,"backupCron"));s!==void 0&&t.push(s);const n=C(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)&&!i.isMethodDeclaration(r))continue;const o=ls(r.getNameNode());o!==void 0&&t.push(o)}return t},Xo=e=>{const t=y(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Yo)return i.isObjectLiteralExpression(s)?ds(s):[];if(t!==Qo||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=Qs(s.getBody());return n===void 0?[]:ds(n)},Jo=(e,t)=>{const s=[];for(const{filePath:n}of Ve(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression))s.push(...Xo(o))}return[...new Set(s)]},gn=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:gn(e.inner)},Zo=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const r=gn(n);return r!==void 0&&t.has(r)}))},ea=(e,t)=>{const s=new Map,n=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const o=s.get(r.name);if(o!==void 0)throw new X("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${o} and agent "${r.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(r.className);if(a!==void 0)throw new X("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${a} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},ta=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:r}=e,o=Bo(s,t),a=Do(s,t),c=yr(s,t),{queues:l,topics:u}=qr(s,t),p=Wr(n),f=Cr(s,t);ea(c,f);const m=Tr(s,t),b=Hr(s,t),_=Or(s,t,c,f),G=Jo(s,t),L=Go(s,t),N=jr(s,t),z=Mr(s,t);z.browser=z.browser||N.usesSandboxBrowser;const K=Qr(z,sn(n,e.target),{agents:f.length>0,commitOrderedTables:r.tables.some(F=>F.commitOrdered===!0),cronTriggers:_.length>0,crossShardFanout:r.tables.some(F=>Yr(F)),containerEgressPolicy:L.containerEgressPolicy,containerRuntimeScheduling:m.some(F=>F.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(F=>F.sandbox===!0),durableStreams:L.durableStreams,globalTables:r.tables.some(F=>F.shardMode==="global"),queues:l.length>0,relationGraph:Zo(r),secrets:L.secrets,services:p.length>0,topics:u.length>0,vectorStore:r.vectorIndexes.length>0,workerLoaders:N.usesSandboxLoader,workflowRollback:L.workflowRollback,workflowSchedules:c.some(F=>F.schedules!==void 0)}),P=K.usage,ne=Ir(P),re=K.signals.vectorStore!==!1,ue=K.signals.services===!1?[]:p,ie=_r(n),ye=ie??new Set,V=ye.has("lunorash");Co(r,ie,{hasVectors:re,scheduler:P.scheduler||_.length>0,storage:P.storage||b.rules.length>0||Object.keys(nn(r)).length>0,usage:P});const B=k(h(t,"flags.ts")),R=k(h(t,"notify.ts"));return{agents:f,capabilities:ne,containers:m,crons:_,dataModelContent:si(r),declaredDependencies:ie,dependencies:ye,entryCronTriggers:G,env:a,featureUsage:P,hasFlags:B,hasNotify:R,identity:o,platformGate:{...K,diagnostics:[...Xr(n,e.target),...K.diagnostics]},queues:l,serverContent:ei({agents:f,capabilities:ne,containers:m,env:a,hasVectors:re,hasFlags:B,hasNotify:R,identity:o,queues:l,schema:r,services:ue,storageRuleBuckets:b.rules.map(F=>F.bucket),topics:u,useUmbrella:V,workflows:c}),services:ue,storageRulesMetadata:b,topics:u,usesSandbox:N.usesSandboxBrowser||N.usesSandboxContainer||N.usesSandboxFs,useUmbrella:V,workflows:c}},pn=new Set(["delete","get","head","options","patch","post","put"]),sa=new Set(["handler","stream"]),na=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,us=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),ra=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!pn.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},ia=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||pn.has(n.getName()))break;s=n.getExpression()}return ra(s)},oa=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(us.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&us.has(s.getText()))return!0}return!1},aa=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!sa.has(n.getName()))return;const r=ia(s);if(!r||!na.test(r.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&oa(o);return{exportName:U(e)??e.getName(),file:t,method:r.method,path:r.path,usesGuard:a}},ca=(e,t)=>{const s=[];for(const n of W(e)){const r=aa(n,t);r&&s.push(r)}return s},la=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ca(r,T(t,n)))}return s},da=e=>{const t=e.getText(),s=n=>{const r=n.getNameNode();return i.isIdentifier(r)&&r.getText()===t};for(const n of e.getAncestors())if(!(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)&&!i.isFunctionDeclaration(n)))for(const r of n.getParameters()){const o=r.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},ua=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isObjectBindingPattern(s))return;const n=s.getParent();if(i.isBindingElement(n)){t=n;continue}return i.isParameterDeclaration(n)?Ae(t):void 0}},fa=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=i.isFunctionLikeDeclaration(o)||i.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(i.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&is(a)}))return!1;const n=D(e),r=i.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return r!==void 0&&(i.isParameterDeclaration(n)||i.isBindingElement(n))&&is(r)},fs=(e,t)=>{const s=e.getParent();if(i.isPropertyAccessExpression(s)&&s.getNameNode()===e||i.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=da(e);return n!==void 0&&ua(n)===t?!0:t==="args"&&fa(e)},mn=(e,t)=>i.isIdentifier(e)?fs(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>fs(s,t)),ga=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},gs=e=>{const t=i.isIdentifier(e)?D(e):void 0;return i.isVariableDeclaration(t)&&i.isIdentifier(t.getNameNode())&&!Nt(t)?t.getInitializer():void 0},mt=e=>mn(e,"args"),Z=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let r,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(r=c,o=l)}return r},j=e=>{if(mt(e))return!0;const t=Z(e);return t!==void 0&&mt(t)},pa=e=>{if(i.isCallExpression(e)||i.isNewExpression(e))return!1;const t=Z(e);return t===void 0||!(i.isCallExpression(t)||i.isNewExpression(t))},se=e=>{if(nt(e))return!0;const t=gs(e);if(t!==void 0&&nt(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(r=>{const o=gs(r);return o!==void 0&&nt(o)})},Re=(e,t)=>mn(e,t),ma=(e,t)=>{if(Re(e,t))return!0;const s=Z(e);if(s!==void 0&&Re(s,t))return!0;const n=ga(e);if(n!==void 0){const r=Z(n);return r!==void 0&&Re(r,t)}return!1},ha=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:q(e.getExpression(),["ai"]),va=(e,t)=>{if(!ha(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)||se(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},Ea=(e,t)=>O(e,t,va),xa=new Set(["generateText","streamText"]),Sa=new Set(["messages","prompt","system"]),Aa=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],ya=(e,t)=>Aa.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ba=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=[ni(t.getExpression()),t.getExpression().getText()].find(r=>r!==void 0&&ya(r,s));return n===void 0?void 0:`${n}.${s}`},Na=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ba(t);if(s!==void 0)return s}},Pa=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],r=n?.getNameNode();if(r===void 0||!i.isObjectBindingPattern(r))return t;for(const o of r.getElements()){const a=Ae(o),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},wa=e=>{if(mt(e))return!0;const t=Pa(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},Ia=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Sa.has(S(t)))continue;const s=t.getInitializer();if(s!==void 0&&wa(s))return!0}return!1},Ca=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=y(n.getExpression());if(r===void 0||!xa.has(r))continue;const[o]=n.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(y(c.getExpression())==="tool"&&(a=Na(c),a!==void 0))break;a!==void 0&&s.push({scope:v(n),file:t,line:n.getStartLineNumber(),method:r,sideEffect:a,userInputDerived:Ia(o)})}return s},Ta=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ca(r,T(t,n)))}return s},Oa=e=>q(e,["fetch"]),Ra=(e,t)=>{if(!Oa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},ka=(e,t)=>O(e,t,Ra),Ct=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=We(s.getExpression());return n===void 0||Ct(n,t)})}finally{t.delete(e)}},Fa=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=M(t,"args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),r=n===void 0?void 0:We(n);return r===void 0?{objects:[],opaque:!0}:{objects:[r],opaque:Ct(r)}},Da=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const r=n.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&i.isExpression(o)?We(o):void 0;a===void 0?s=!0:(t.push(a),s||=Ct(a))}n=r.getExpression()}return{objects:t,opaque:s}},Tt=(e,t)=>t?Da(t):Fa(e),hn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=We(s.getExpression());return n===void 0?[]:hn(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[S(s)]:[]})}finally{t.delete(e)}},La=e=>e.flatMap(t=>hn(t,new Set)),Ma=new Set(["check","length","max"]),ht=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},_a=e=>[e,...e.getDescendants()].filter(t=>ht(t)!==void 0),Ka=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(Ma.has(s.getName()))return!0;t=n}},Ba=e=>{const t=[],s=[];for(const n of e)for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=_a(o),c=S(r);a.some(l=>ht(l)==="any")?t.push(c):a.some(l=>ht(l)==="string"&&!Ka(l))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},za=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=H(s);if(n?.visibility!=="public")return;const{objects:r}=Tt(s,n.receiver),{anyArgs:o,unboundedStringArgs:a}=Ba(r);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:U(e)??e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},$a=(e,t)=>{const s=[];for(const n of W(e)){const r=za(n,t);r&&s.push(r)}return s},Ua=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...$a(r,T(t,n)))}return s},ot=e=>e?.getKind()===d.TrueKeyword,Va=e=>e?.getKind()===d.FalseKeyword,qa=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,ja=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Wa=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&y(t.getExpression())==="scim"),Ha=e=>e!==void 0&&i.isCallExpression(e)&&ja.has(y(e.getExpression())??""),Ga=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Ya=e=>{const t=C(e,"advanced"),s=C(e,"emailAndPassword"),n=C(e,"session");return{analyzable:!0,disableCsrfCheck:ot(C(t,"disableCSRFCheck")),emailPasswordEnabled:ot(C(s,"enabled")),requireEmailVerification:ot(C(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Wa(C(e,"plugins"))&&Ha(C(e,"database")),secureCookiesDisabled:Va(C(t,"useSecureCookies")),sessionFreshAgeZero:qa(C(n,"freshAge")),trustedOriginsWildcard:Ga(C(e,"trustedOrigins"))}},Qa=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Xa=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),r=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?Ya(s):Qa();return{scope:v(e),file:t,line:e.getStartLineNumber(),...r}},Ja=(e,t)=>Kr(e,t,Xa),Za=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return rn(e.getExpression(),t.matchReceiver)?s:void 0},ec=(e,t,s)=>{const n=Za(e.getExpression(),s);if(n===void 0)return;const r=e.getArguments()[s.argIndex];if(!(!r||!j(r)||se(r))&&!(s.requireUnmodifiedReach===!0&&!pa(r)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:n}},He=(e,t,s)=>O(e,t,(n,r)=>ec(n,r,s)),tc=new Set(["content","pdf","scrape","screenshot"]),sc=(e,t)=>He(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:tc}),nc=e=>i.isDoStatement(e)||i.isForInStatement(e)||i.isForOfStatement(e)||i.isForStatement(e)||i.isWhileStatement(e),vn=e=>{const t=e.getLabel()?.getText(),s=r=>t!==void 0?i.isLabeledStatement(r)&&r.getLabel().getText()===t:nc(r)||i.isBreakStatement(e)&&i.isSwitchStatement(r);let n=e.getFirstAncestor(r=>J(r)||s(r));if(!(n===void 0||J(n))){for(;i.isContinueStatement(e)&&i.isLabeledStatement(n);)n=n.getStatement();return n}},Ot=(e,t)=>A(e.getFirstAncestor(s=>A(s,t)||J(s)),t),rc=(e,t)=>A(e,t)||e.getFirstAncestor(s=>A(s,t))!==void 0,En=(e,t)=>{if(i.isReturnStatement(e)||i.isThrowStatement(e))return A(e,t)||Ot(e,t);if(i.isBreakStatement(e)||i.isContinueStatement(e)){const s=vn(e);return s!==void 0&&!rc(s,t)}return!1},xn=e=>[...i.isBreakStatement(e)||i.isContinueStatement(e)||i.isReturnStatement(e)||i.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],ic=e=>xn(e).some(t=>En(t,e)),Sn=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},oc=e=>{if(!i.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||i.isIdentifier(t)&&t.getText()==="scheduler"},ac=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),cc=/^[\w$]+:[\w$]+$/u,lc=(e,t)=>{const s=Js(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},dc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),[n,r]=e.getArguments();if(Xs.has(s))return lc(s,n);if((s==="runAfter"||s==="runAt")&&oc(t)){const c=Js(r)??(i.isStringLiteral(r)&&cc.test(r.getLiteralText())?r.getLiteralText():void 0);return c===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:c}}const o=ac.get(s),a=o===void 0?void 0:Sn(t,o.surface);return o===void 0||a===void 0?void 0:{kind:o.kind,target:a}},uc=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),An=e=>gr.isOptionalChain(e.compilerNode),fc=(e,t)=>i.isIfStatement(t)?!A(e,t.getExpression()):i.isWhileStatement(t)||i.isForInStatement(t)||i.isForOfStatement(t)?A(e,t.getStatement()):i.isForStatement(t)?A(e,t.getStatement())||A(t.getIncrementor(),e):i.isCaseClause(t)||i.isDefaultClause(t)||i.isCatchClause(t)?!0:J(t)?t.getFirstAncestor(J)!==void 0:i.isConditionalExpression(t)?!A(e,t.getCondition()):i.isBinaryExpression(t)?!A(e,t.getLeft())&&uc.has(t.getOperatorToken().getKind()):(i.isCallExpression(t)||i.isElementAccessExpression(t))&&An(t)?!A(e,t.getExpression()):i.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&ic(s)),gc=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(i.isAwaitExpression(s)||i.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=i.isVariableDeclaration(s)||i.isBinaryExpression(s)&&A(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,r=e.getFirstAncestor(J);return n||r?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&A(o.getFirstAncestor(J),r))===!0},pc=(e,t)=>{if(An(e)||t==="schedule"&&gc(e))return!0;let s=e;for(let n=s.getParent();n!==void 0&&!i.isSourceFile(n);n=n.getParent()){if(fc(s,n))return!0;s=n}return!1},ps=(e,t,s)=>s===void 0?void 0:{...s,...pc(e,s.kind)?{conditional:!0}:{},file:t,line:e.getStartLineNumber(),scope:v(e)},mc=(e,t)=>[...O(e,t,(s,n)=>ps(s,n,dc(s))),...le(e,t,d.PropertyAccessExpression,(s,n)=>{const r=Sn(s,"services");return ps(s,n,r===void 0?void 0:{kind:"invoke",target:r})})],hc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),vc=new Set(["RateLimiter"]),Ec=new Set(["extend"]),ms="lunora",xc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],yn=e=>{const t=[],s=[];let n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=S(r);t.push(o),r.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(S(r))}return{analyzable:!n,presentKeys:t,trueKeys:s}},vt=e=>e&&i.isObjectLiteralExpression(e)?yn(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Sc=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Qs(t.getBody());return s?yn(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Ac=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=y(n.getExpression());r!==void 0&&(hc.has(r)?s.push({callee:r,file:t,line:n.getStartLineNumber(),...vt(n.getArguments()[0])}):Ec.has(r)&&s.push({callee:r,file:t,line:n.getStartLineNumber(),...Sc(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const r=y(n.getExpression());r===void 0||!vc.has(r)||s.push({callee:r,file:t,line:n.getStartLineNumber(),...vt(n.getArguments()[0])})}return s},yc=(e,t)=>{for(const s of xc){const n=h(t,s);if(!k(n))continue;const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of r.getDescendantsOfKind(d.CallExpression))y(a.getExpression())===ms&&o.push({callee:ms,file:s,line:a.getStartLineNumber(),...vt(a.getArguments()[0])});return o}return[]},bc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Ve(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ac(o,n))}return s.push(...yc(e,me(t))),s},hs="ctx.containers.",Nc=e=>{if(!e.startsWith(hs))return!1;const t=e.slice(hs.length);return t.length>0&&!t.includes(".")},Pc=(e,t)=>He(e,t,{argIndex:0,matchReceiver:Nc,methods:new Set(["get"])}),wc=new Set(["allow","deny","setAllowed"]),Ic=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=M(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Cc=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Ic(e)))return{detail:"enableInternet: true",scope:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Tc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!wc.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Oc=(e,t)=>Cc(e,t)??Tc(e,t),Rc=(e,t)=>O(e,t,Oc),kc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Fc=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return kc.has(s)?s:void 0},Dc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const r=S(n);t.push(r);const o=n.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(r);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(S(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Lc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Ve(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=Fc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&i.isObjectLiteralExpression(l)?Dc(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},Mc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),_c=new Set(["dbRateLimit","rateLimit"]),Kc=e=>{const t=en(e);if(!t)return!1;const s=M(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Bc=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=Mc.get(s);if(n!==void 0)return{callee:s,scope:v(e),failOpen:Kc(e.getArguments()[n]),file:t,limitName:_c.has(s)?Zs(e):"",line:e.getStartLineNumber()}},zc=(e,t)=>O(e,t,Bc),$c=new Set(["boolean","number","object","string"]),Uc=e=>{const t=e.getName();if(!$c.has(t))return;const s=e.getExpression();return q(s,["flags"])||q(s,["flags","details"])?t:void 0},Vc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=Uc(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const r=n.getLiteralValue();return r.length>0?{key:r,type:s}:void 0},qc=(e,t)=>{const s=new Map;for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=Vc(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,r])=>({key:n,type:r})).toSorted((n,r)=>n.key.localeCompare(r.key))},jc=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=H(t);if(s?.kind!=="query")return;const n=Br(t,s.receiver);return n?{exportName:U(e)??e.getName(),handler:n}:void 0},vs=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Wc=e=>{const t=vs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=vs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Hc=(e,t)=>{const s=[];for(const n of je(e.handler,"flags"))s.push({callee:Wc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Gc=(e,t)=>{const s=[];for(const n of W(e)){const r=jc(n);r&&s.push(...Hc(r,t))}return s},Yc=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gc(r,T(t,n)))}return s},Qc=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:q(e.getExpression(),["flags"]),Xc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Jc=(e,t)=>{if(!Qc(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const r=s.getLiteralValue(),o=Xc(n);if(!(r.length===0||o===void 0))return{defaultValue:o,scope:v(e),file:t,key:r,line:e.getStartLineNumber()}},Zc=(e,t)=>O(e,t,Jc),el=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 r=n.getTypeAtLocation(e),o=r.getText(e);if(!o||o==="any"||o==="never"||li(o))return;const a=e.getSourceFile().getFilePath();if(di(r,e,a)){const c=ui(r,e,a,0,new Set);return c===void 0&&fi(o),c}return o},tl=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},sl=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},nl=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of r.getDescendantsOfKind(d.CallExpression))tl(a)&&s.push({file:o,indexName:sl(a),line:a.getStartLineNumber()})}return s},Ee=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,bn=e=>{const t=e.getArguments()[0],s=Ee(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=M(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?Ee(n.getInitializer()):void 0},rl=new Set(["delete","get","head","options","patch","post","put"]),il=new Set(["handler","stream"]),ol=new Set(["runAction","runMutation"]),al=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),xe=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,Nn=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(Ae(s)===t){const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0}}},Es=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:Nn(s,"ctx")},xs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:Nn(s,"request")},Ss=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const r of n){const o=r.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(ol.has(a)&&xe(c,t))return a;if(al.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&xe(c.getExpression(),t))return`db.${a}`}},As=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&xe(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const r=n.getNameNode();if(!(!i.isObjectBindingPattern(r)||!xe(n.getInitializer(),t))){for(const o of r.getElements())if(Ae(o)==="auth")return!0}}return!1},cl=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,ll=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&xe(n.getExpression(),t)},dl=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],Pn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:dl(s)},ul=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const r=n.getParent();if(!i.isCallExpression(r))return[];const o=r.getExpression();if(!i.isPropertyAccessExpression(o))return[];const a=o.getExpression();return i.isIdentifier(a)?Pn(t,a.getText()):[]}return[]},fl=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=Pn(s,t.getText());return n.length>0?n:ul(t,s)},ys=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(r=>ll(r,t)&&fl(r).some(o=>cl.test(o)))},gl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!il.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const r=n.getName();if(rl.has(r)){const o=n.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?r.toUpperCase():void 0}s=n.getExpression()}},pl=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ee(e.getArguments()[0]),l=c&&Es(c,!0);if(!c||l===void 0||ys(c,xs(c,!0)))return;const u=Ss(c,l);return u===void 0?void 0:{scope:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:As(c,l),sideEffect:u}}const n=gl(e);if(n===void 0)return;const r=Ee(e.getArguments()[0]),o=r&&Es(r,!1);if(!r||o===void 0||ys(r,xs(r,!1)))return;const a=Ss(r,o);return a===void 0?void 0:{scope:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:As(r,o),sideEffect:a}},ml=(e,t)=>O(e,t,pl),hl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),vl=new Set(["append","set"]),wn=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",bs=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>hl.has(y(n.getExpression())??"")&&Re(n,t)),El=(e,t)=>{if(bs(e,t))return!0;const s=Z(e);return s!==void 0&&bs(s,t)},Et=(e,t)=>ma(e,t)&&!El(e,t),xl=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Z(e);return t!==void 0&&i.isNewExpression(t)&&y(t.getExpression())==="Headers"},Me=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=Z(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Rt=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const r=n.getInitializer();r!==void 0&&Et(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:wn(n.getNameNode()),line:r.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const r=n.getNameNode();Et(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:S(n),line:r.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const r=Me(n.getExpression());r!==void 0&&Rt(r,t,s)}},In=(e,t)=>{const s=Me(e);if(s===void 0)return;const n=M(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const r=Me(n.getInitializer());r!==void 0&&Rt(r,"response-init",t)},Sl=(e,t)=>{const s=y(e.getExpression());if(s==="Response")In(e.getArguments()[1],t);else if(s==="Headers"){const n=Me(e.getArguments()[0]);n!==void 0&&Rt(n,"headers-ctor",t)}},Al=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),r=s.getExpression();if(n==="json"&&i.isIdentifier(r)&&r.getText()==="Response"){In(e.getArguments()[1],t);return}if(vl.has(n)&&xl(r)){const o=e.getArguments()[1];o!==void 0&&Et(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:wn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},yl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Sl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Al(s,t)},bl=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Ee(e.getArguments()[0]);if(n===void 0)return[];const r=n.getParameters()[1];if(r===void 0)return[];const o=r.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return yl(n,{scope:v(e),relativePath:t,requestName:o.getText(),rows:a}),a},Nl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...bl(n,t));return s},Pl=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Nl(r,T(t,n)))}return s},wl=new Set(["auth","context.auth"]),Il="userId",Cl=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(S(s))}return t},Tl=(e,t)=>{const s=h(t,fn);if(!k(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){if(y(r.getExpression())!=="defineIdentity")continue;const[o]=r.getArguments();return o&&i.isObjectLiteralExpression(o)?Cl(o):void 0}},Ns=e=>{if(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return wl.has(t.getText())||q(t,["auth"])?e:void 0},Ol=e=>{if(i.isPropertyAccessExpression(e)&&Ns(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Ns(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Ps=(e,t,s)=>{const n=Ol(e);return n===void 0?void 0:{declared:n===Il||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:v(e)}},Rl=(e,t)=>{const s=Tl(e,t);return s===void 0?[]:[...le(e,t,d.PropertyAccessExpression,(n,r)=>Ps(n,r,s)),...le(e,t,d.ElementAccessExpression,(n,r)=>Ps(n,r,s))]},kl=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=C(s,"key");if(!(!n||!j(n)||se(n)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},Fl=(e,t)=>O(e,t,kl),Dl=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=vr(t.getNameNode());return s===void 0||s==="namespace"}),Ll=(e,t)=>{for(const{filePath:s}of Ve(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){const o=r.getExpression(),[a]=r.getArguments();if(!(!i.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!i.isObjectLiteralExpression(a)||Dl(a)))return r}}},Ml="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",_l=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Se(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 (${Ml}). 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})},Kl=new Set(["delete","get","getRaw","getWithMetadata","put"]),Bl=(e,t,s=[])=>{const n=He(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:Kl});return Pt(n,s)},zl=new Set(["queue","send"]),ws=new Set(["bcc","cc","to"]),$l=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!zl.has(t))return;const s=e.getExpression();return q(s,["mail"])||q(s,["email"])?t:void 0},Ul=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return ws.has(S(t))&&j(n)&&!se(n)}if(!i.isPropertyAssignment(t)||!ws.has(S(t)))return!1;const s=t.getInitializer();return s!==void 0&&j(s)&&!se(s)}):!1,Vl=(e,t)=>{const s=$l(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Ul(n)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},ql=(e,t)=>O(e,t,Vl),jl=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,Wl=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?jl(e):!0,Cn=(e,t=!1)=>{for(const s of e.getProperties()){if(Wl(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||Cn(n,!0))return!0}return!1},Hl=(e,t)=>{for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:r}of dn(n))for(const o of It(r)){const a=o.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||Cn(a)))return!0}}return!1},Gl=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const r=Le(n);if(r===void 0||!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!i.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Le(a);c!==void 0&&s.push({column:c,strategy:ln(a),table:r})}}return s},Yl=(e,t)=>{const s=new Map;for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of dn(r))for(const a of It(o))for(const c of Gl(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Ql=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){const a=Le(o);if(a===void 0||!i.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Le(l);if(u===void 0)continue;const p=ln(l);p!=="custom"&&r.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:p,table:a})}}return r},Xl=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;return n?.receiver?It(n.receiver).flatMap(r=>Ql(r,U(e)??e.getName(),t)):[]},Jl=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of W(r))s.push(...Xl(a,o))}return s},Zl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},ed=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=M(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},td=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return yi(s.getExpression())?s:void 0},sd=e=>{const t=td(e),s=t===void 0?void 0:ed(t);if(s===void 0)return[];const n=e.getNameNode(),r=i.isIdentifier(n)?U(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Zl(o)).map(o=>({exportName:r,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},nd=e=>e.getVariableDeclarations().flatMap(t=>sd(t)),rd=(e,t)=>{const s=h(t,Ai);if(!k(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return nd(n)},id=new Set(["delete","get","patch"]),od=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),ad=new Set(["auth","identity","session","user"]),cd=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),ld=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!$(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},dd=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},ud=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),fd=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,gd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>ud(s.getExpression(),t)&&fd(s.getThenStatement())),pd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const r=n.getName();if(!id.has(r))continue;const o=n.getExpression();if(!($(o)||i.isPropertyAccessExpression(o)&&$(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return r}},md=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>on(wt(s))!==void 0)),hd=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>cd.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),vd=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(od.has(t.getText()))return!0;return[...ad].some(t=>je(e,t).length>0)?!0:md(e)||hd(e)},Ed=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=H(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const r=bn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&tn(n.receiver,"use","rls"),a=vd(r),c=new Set,l=[];for(const u of r.getDescendantsOfKind(d.CallExpression)){const p=ld(u);if(p===void 0)continue;const f=dd(u);if(f===void 0||c.has(f)||!gd(r,f))continue;const m=pd(r,f);m!==void 0&&(c.add(f),l.push({exportName:U(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:p,usesRls:o,visibility:n.visibility}))}return l},xd=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of W(r))s.push(...Ed(a,o))}return s},Tn=(e,t)=>{const s=i.isIdentifier(e)&&t!==void 0?D(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?i.isIdentifier(t.getNameNode()):i.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Sd=e=>{const t=I(e),s=t.getParent();return(i.isPropertyAccessExpression(s)||i.isElementAccessExpression(s))&&s.getExpression()===t&&!qe(s)},Ad=e=>{const t=I(e).getParent();return i.isVariableDeclaration(t)&&i.isObjectBindingPattern(t.getNameNode())},yd=e=>{const s=I(e).getParent();if(i.isSpreadAssignment(s)||i.isSpreadElement(s)){const n=s.getParent();return(i.isObjectLiteralExpression(n)||i.isArrayLiteralExpression(n))&&!qe(n)}return i.isTemplateSpan(s)&&!i.isTaggedTemplateExpression(s.getParent().getParent())},_e=e=>{const t=D(e);return t===void 0||kr(t.getSourceFile())},xt=(e,t)=>{const s=I(e),n=s.getParent();if(!i.isCallExpression(n))return!1;const r=n.getArguments().indexOf(s),o=E(n.getExpression());if(r===-1||o===void 0)return!1;if(i.isIdentifier(o))return o.getText()==="structuredClone"&&_e(o);if(Tn(wt(o),t))return!(i.isPropertyAccessExpression(o)&&an.has(o.getName()))||i.isExpressionStatement(I(i.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!i.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!i.isIdentifier(a)||!_e(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"&&r>0;default:return!1}},ke={kind:"opaque"},bd={kind:"unreached"},Nd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>i.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>i.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&i.isFunctionDeclaration(n)?n:void 0},St=e=>{const t=E(e);if(i.isArrowFunction(t)||i.isFunctionExpression(t))return t;const s=i.isIdentifier(t)?D(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(i.isFunctionDeclaration(s)){const r=Nd(s);return r===void 0||Nt(r)?void 0:r}const n=te(s)?E(s.getInitializer()):void 0;return i.isArrowFunction(n)||i.isFunctionExpression(n)?n:void 0},On=(e,t,s)=>{const n=t.getArguments(),r=n.indexOf(s),o=r===-1||n.slice(0,r+1).some(l=>i.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[r];return o?ke:c===void 0?a.some(l=>l.isRestParameter())?ke:bd:c.isRestParameter()?ke:{kind:"parameter",parameter:c}},Pd=e=>{const t=I(e),s=t.getParent();if(!i.isCallExpression(s)||s.getExpression()===t)return;const n=St(s.getExpression());return n===void 0?ke:On(n,s,t)},wd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Id=e=>i.isForInStatement(e)?e.getExpression():i.isConditionalExpression(e)?e.getCondition():i.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Rn=e=>{const t=I(e),s=t.getParent();if(i.isIfStatement(s)||i.isWhileStatement(s)||i.isDoStatement(s)||i.isSwitchStatement(s)||i.isCaseClause(s)||i.isTypeOfExpression(s)||i.isVoidExpression(s)||i.isComputedPropertyName(s))return!0;if(i.isTemplateSpan(s))return!i.isTaggedTemplateExpression(s.getParent().getParent());const n=Id(s);if(n!==void 0)return A(n,t);if(i.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!i.isBinaryExpression(s))return!1;const r=s.getOperatorToken().getKind(),o=r>=d.FirstAssignment&&r<=d.LastAssignment,a=r===d.QuestionQuestionToken||r===d.BarBarToken||r===d.AmpersandAmpersandToken;return!o&&!a},Cd=4,kn=(e,t,s=0)=>{if(Rr(e))return!0;if(Sd(e)){const r=I(e).getParent(),o=i.isElementAccessExpression(r)?r.getArgumentExpression():void 0,a=i.isStringLiteral(o)?o.getLiteralValue():void 0,c=i.isPropertyAccessExpression(r)?r.getName():a;return c===void 0||!wd.has(c)}if(Ad(e)||yd(e)||Rn(e)||xt(e,t))return!0;const n=Pd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Td(n.parameter,s+1)},Is=new WeakMap,Td=(e,t=0)=>{const s=e.getNameNode();if(!i.isIdentifier(s))return!0;const n=Is.get(e.compilerNode);if(n!==void 0)return n;if(t>Cd)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||D(a)?.compilerNode!==e.compilerNode||kn(a,void 0,t));return(o||t===0)&&Is.set(e.compilerNode,o),o},Cs=new WeakMap,Od=(e,t)=>{const s=i.isFunctionExpression(e)?e.getNameNode():void 0;if(!i.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(r=>{if(r===s||!n.has(r.getText()))return!1;const o=D(r)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Rd=(e,t,s)=>{const{context:n,impl:r}=e,o=Cs.get(r.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=i.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(f=>{const m=f.getNameNode();return i.isIdentifier(m)?[m]:[]}),l=new Map(c.map(f=>[f.getText(),f.getParentOrThrow().compilerNode])),u=f=>i.isIdentifier(a)?kn(f,n):!qe(f),p=!Od(r,s)&&c.every(f=>(f.getSymbol()?.getDeclarations().length??0)===1)&&r.getDescendantsOfKind(d.Identifier).every(f=>{const m=f.getText();if(m==="arguments")return!1;const b=l.get(m);return b===void 0||c.includes(f)||D(f)?.compilerNode!==b?!0:u(f)});return Cs.set(r.compilerNode,p),p},Ts=new WeakMap,kd=e=>{let t=Ts.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=bi(s);return n===void 0?[]:[[n.compilerNode,s]]})),Ts.set(e.compilerNode,t)),t},Fd=e=>{const t=kd(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[r,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:r,impl:s,mutatorName:U(n)??n.getName()};return a!==void 0&&Rd(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},Dd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Ld=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),At=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Fn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>i.isIdentifier(t.getNameNode())),Md=e=>{const t=I(e),s=t.getParent();if(i.isVariableDeclaration(s))return A(s.getInitializer(),t)?s:void 0;const n=i.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return i.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},_d=e=>{const t=Md(e);return t===void 0?void 0:i.isIdentifier(t.getNameNode())?i.isForOfStatement(t.getParent().getParent())||te(t)?[t]:void 0:Fn(t)},he=e=>e.isUnion()?e.getUnionTypes().every(t=>he(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>he(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ke=(e,t,s)=>{const n=i.isCallExpression(e)?E(e.getExpression()):void 0;return i.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Fe=e=>{const t=E(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=t.getBody();return i.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(r=>i.isFunctionLikeDeclaration(r))===t).map(n=>n.getExpression()):[s]},Kd=e=>{const t=i.isCallExpression(e)?E(e.getExpression()):void 0,s=i.isPropertyAccessExpression(t)?t.getExpression():void 0;return i.isPropertyAccessExpression(t)&&i.isIdentifier(s)&&Ld.get(s.getText())?.has(t.getName())===!0&&_e(s)},Bd=e=>{const t=pt(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=I(t),n=s.getParent();return i.isCallExpression(n)&&n.getArguments().includes(s)&&Ke(n,cn)?n:void 0},zd=(e,t)=>{if(!(i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=I(e),n=s.getParent();return!i.isCallExpression(n)||n.getExpression()!==s?e:Ke(n,Dd,t)?n:void 0},$d=(e,t)=>{if(i.isAwaitExpression(e))return e;if(i.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=i.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Ud=(e,t)=>{if(i.isArrayLiteralExpression(e))return e;const n=i.isSpreadElement(e)||i.isSpreadAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isPropertyAssignment(e)&&A(e.getInitializer(),t)?e.getParent():void 0;return i.isArrayLiteralExpression(n)||i.isObjectLiteralExpression(n)?n:void 0},Os=e=>{const t=I(e),s=t.getParent();if(s===void 0)return;const n=i.isCallExpression(s)&&s.getArguments().includes(t)&&Kd(s);return zd(s,t)??$d(s,t)??Ud(s,t)??(n?s:Bd(t))},Vd=5e4,Dn=()=>({inProgress:new Set,verdicts:new Map});class qd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Vd&&this.cut()}memoized(t,s,n){const r=n.verdicts.get(t);if(r!==void 0)return r;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 jd=8,Wd=8;class Hd{budget;scope;taint;verdicts=Dn();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!he(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],r=new Set,o=(c,l)=>{r.has(c.compilerNode)||(r.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 r)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,r){const o=t.getNameNode();if(!i.isIdentifier(o)){for(const l of i.isParameterDeclaration(t)?Fn(t):[])r(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=jd?this.budget.cut():(r(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(I(l),!0,a,0))&&(t===n||!he(t.getType()))}valueCompromises(t,s,n,r){let o=t;for(let m=Os(o);m!==void 0;m=Os(o)){if(i.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=I(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&he(o.getType());if(qe(o))return!c&&(!i.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=_d(o);if(u!==void 0)return u.some(m=>n(m,!0));const p=i.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(i.isCallExpression(p)&&p.getExpression()===a)return this.methodCallCompromises(p,n);const f=this.nestedReturningFunctionOf(o);return f!==void 0?this.resultCompromises(f,n,r)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const r=I(t).getParent();if(n>=Wd)return this.budget.cut();if(i.isCallExpression(r))return r.getExpression()===I(t)?this.valueCompromises(r,!1,s,n+1):!Ke(r,At);const o=i.isFunctionDeclaration(t)?t:r,a=i.isFunctionDeclaration(o)||te(o)?o.getNameNode():void 0;return o===void 0||!i.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=I(c),u=l.getParent();return!i.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(r=>Fe(r)===void 0).some(r=>this.taint.isTaintedValue(r,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ke(t,At)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const r=St(n);return r!==void 0&&this.taint.isInImpl(r)?r.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(i.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const r=i.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&i.isCallExpression(r))return!xt(n,this.scope.context)&&this.isOpaqueCallTainted(r.getExpression(),r.getArguments(),n);if(i.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(i.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return i.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(xt(s,this.scope.context))return!1;const r=St(t.getExpression()),o=r===void 0?void 0:On(r,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&r!==void 0&&this.taint.isInImpl(r)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||i.isExpressionStatement(s)||i.isForStatement(s)||i.isElementAccessExpression(s)||Rn(t)||A(pt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const r=!i.isIdentifier(E(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||r)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=pt(t);return A(s,this.scope.impl)?void 0:s}}const Gd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Yd=e=>{const t=E(e);if(!i.isIdentifier(t))return i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t);const s=D(t),n=i.isVariableDeclaration(s)?E(s.getInitializer()):void 0;return s===void 0||i.isFunctionDeclaration(s)||i.isParameterDeclaration(s)||i.isArrowFunction(n)||i.isFunctionExpression(n)},Qd=new Set(["all","allSettled","any","race"]),Rs=e=>i.isParameterDeclaration(e)?e:i.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,at=8;class Xd{budget=new qd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Dn();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Hd(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,at)?!1:(i.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(r=>Fr(r)&&this.isIdentifierTainted(r))}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 r of this.referencesByName.get(s)??[]){const o=D(r)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],r])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(r=>r.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(f=>f.getInitializer())].some(f=>f!==void 0&&this.isTaintedValue(f,!1)))return!0;const n=t.getParentOrThrow(),r=i.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(f=>f.compilerNode===t.compilerNode):-1,o=I(n),a=o.getParent();if(r===-1)return!0;if(i.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,r,t.isRestParameter());const f=E(a.getExpression());if(!i.isPropertyAccessExpression(f)||!At.has(f.getName()))return!0;const m=a.getArguments().filter(b=>b!==o);return this.isTaintedValue(f.getExpression(),!0)||m.some(b=>this.isTaintedValue(b,!1))}const c=i.isVariableDeclaration(a)&&te(a)?a:void 0,l=i.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!i.isIdentifier(u))return!0;const p=this.referencesTo(l,u.getText());return p.length===0||p.some(f=>{const m=I(f),b=m.getParent();return!i.isCallExpression(b)||b.getExpression()!==m||this.isCallSiteTainted(b,r,t.isRestParameter())})}isCallSiteTainted(t,s,n){const r=t.getArguments(),o=r.findIndex(c=>i.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return r.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=E(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getExpression():void 0,a=i.isPropertyAccessExpression(n)&&i.isIdentifier(r)&&r.getText()==="Promise"&&_e(r)&&Qd.has(n.getName())?E(t.getArguments()[0]):void 0;if(i.isArrayLiteralExpression(a)){const p=a.getElements();return p.length>0&&p.every(f=>!i.isSpreadElement(f)&&this.isRootedInContext(f,s))}const c=i.isCallExpression(a)?E(a.getExpression()):void 0,l=i.isCallExpression(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="map"?E(a.getArguments()[0]):void 0,u=l===void 0?void 0:Fe(l);return u!==void 0&&u.length>0&&u.every(p=>p!==void 0&&this.isRootedInContext(p,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=D(t),r=Rs(n);if(r!==void 0)return this.isSource(r);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(i.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(i.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=i.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return i.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=E(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getName():void 0;return r!==void 0&&an.has(r)?!1:r!==void 0&&cn.has(r)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Fe(a)!==void 0)&&(r===void 0||!Gd.has(r))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(r,o=[])=>{const a=wt(r),c=i.isIdentifier(a)?Rs(D(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(r,s)||!this.isTaintedValue(r,!1)};return t.getArguments().every(r=>{const o=Fe(r);if(o===void 0)return!Yd(r)&&n(r);const a=E(r),c=i.isArrowFunction(a)||i.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=zr(t,u=>this.callChainVerdict(u,s)),r=n.root;if(n.verdict!==void 0)return n.verdict;if(Tn(r,this.scope.context))return!0;const o=i.isIdentifier(r)?D(r):void 0,a=i.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=te(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=i.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(i.isBindingElement(l)||i.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(i.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(i.isForOfStatement(s)||i.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),r=Nt(t);if(n===void 0||r)return!0;if(this.isRootedInContext(n,at))return!1;if(this.variableDepth>=at)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const ks=new WeakMap,Jd=e=>{const t=ks.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Xd(e);return ks.set(e.impl.compilerNode,s),s},Zd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),eu=new Set(["insert","insertManyUnsafe","patch","replace"]),tu=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();return eu.has(t)&&ri(e.getExpression())?t:void 0},su=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},nu=(e,t)=>{const s=$r(e);return s?.member===t?E(s.object):void 0},Fs=(e,t)=>i.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,Ln=(e,t,s,n=1)=>{const r=nu(e,s);if(r!==void 0)return Fs(r,t);const o=i.isIdentifier(e)?D(e):void 0;if(i.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&Ae(o)===s&&i.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||te(l)&&Fs(E(l.getInitializer()),t))}const a=te(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Ln(a,t,s,n-1)},yt=e=>{const t=E(e)??e;return i.isConditionalExpression(t)?[...yt(t.getWhenTrue()),...yt(t.getWhenFalse())]:[t]},ru=(e,t,s)=>{const n=[],r=s===void 0?void 0:Jd(s);for(const o of e.getProperties()){let a,c;if(i.isPropertyAssignment(o)?(a=S(o),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=S(o),c=o.getNameNode()),a===void 0||c===void 0||!Zd.has(a))continue;if(yt(c).some(u=>r===void 0?j(u)&&!ii(u):r.isTaintedValue(u,!0))){const u=t.ownerField===a&&s?.pristine===!0&&Ln(c,s.parameter,a);n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...u&&{ownerScoped:!0}})}}return n},iu=(e,t,s)=>{const n=tu(e.getExpression()),r=n===void 0?void 0:e.getArguments()[1];if(n===void 0||r===void 0)return[];const o=su(r,n);if(o.length===0)return[];const a=v(e),c=Fd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>ru(u,l,c))},ou=(e,t,s=[],n=[])=>{const r=new Map(n.map(a=>[`${a.filePath}:${a.exportName}`,a.owner])),o=O(e,t,(a,c)=>iu(a,c,l=>r.get(`${c}:${l}`)));return Pt(o,s)},au=["providerSubscriptionId","state"],cu=["providerEventId","processedAt"],Ds=(e,t)=>t.every(s=>s in e.shape),lu=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&&Ds(t,au)&&Ds(s,cu)},du=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),uu=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,fu=e=>{const t=M(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?uu(t.getInitializer()):void 0},gu=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!du.has(s))return;const[n]=e.getArguments(),r=n&&i.isObjectLiteralExpression(n)?fu(n):void 0;return{callee:s,scope:v(e),file:t,line:e.getStartLineNumber(),...r===void 0?{}:{toleranceSeconds:r}}},pu=(e,t)=>O(e,t,gu),mu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),hu=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},vu=(e,t)=>{const s=e.getArguments()[t];if(!s||!i.isObjectLiteralExpression(s))return;const n=M(s,"handler");if(n===void 0||!i.isPropertyAssignment(n))return;const r=n.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Mn=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},_n=(e,t)=>e===t||e.startsWith(`${t}.`),Kn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Ls=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},Bn=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Ls(s));return i.isIdentifier(e)&&Ls(e)&&t.push(e),t},Eu=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},xu=e=>{const t=Mn(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const r=n.getInitializer(),o=i.isVariableDeclarationList(r)?r.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Su=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:xu(e),r=new Set,o=a=>Kn(a).some(c=>n.some(l=>_n(c.getText(),l)))?!0:Bn(a).some(c=>r.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Eu(a))r.add(l)}return{names:r,prefixes:n}},Au=(e,t)=>Kn(e).some(s=>t.prefixes.some(n=>_n(s.getText(),n)))?!0:Bn(e).some(s=>t.names.has(s.getText())),yu=e=>{const t=Ur(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},bu=(e,t,s)=>{const n=Mn(e,0);if(n===void 0)return[];const r=Su(e,t,n),o=new Set([n,...r.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!i.isPropertyAccessExpression(l)||!Xs.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Au(u,r))continue;const p=yu(c.getArguments()[0]);p!==void 0&&a.push({dispatchKind:t,file:s,scope:v(c),line:c.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return a},Nu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=hu(n),o=r===void 0?void 0:mu.get(r);if(o===void 0)continue;const a=vu(n,o);a!==void 0&&s.push(...bu(a,r==="defineWorkflow"?"workflow":"queue",t))}return s},Pu=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Nu(r,T(t,n)))}return s},Ms={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},_s=new Set(["account","credential","member","passkey","session","user"]),wu=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Iu=e=>{const s=wu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return _s.has(s)||_s.has(n)},Cu=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Tu=(e,t)=>{const{objects:s,opaque:n}=Tt(e,t);return La(s).some(r=>Cu(r))?!0:n?void 0:!1},Ou=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!M(t,"captcha"),usesRateLimit:!!M(t,"rateLimit")}},Ru=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},De={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},ku=e=>{const t=Ru(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Ou(t);return{...De,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ms?{...De,[Ms[s]]:!0}:De},Fu=e=>{const t={...De};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const r=n.getName()==="use"?s.getArguments()[0]:void 0;if(r){const o=ku(r);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Du=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Lu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Du.has(t.getName()))return!1;const s=t.getExpression();if(!$(s))return!1;const r=e.getArguments()[0];return!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?!1:Iu(r.getLiteralText())},Mu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Ks=new Set(["queues","scheduler","topics","workflows"]),_u=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Mu.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Ks.has(s.getName())&&oi(s.getExpression()))return!0;s=s.getExpression()}const n=on(s);return n?.length===1&&Ks.has(n[0]??"")},Ku=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},zn=new Set(["generateObject","generateText","streamObject","streamText"]),Bu=e=>{const t=y(e.getExpression());return t!==void 0&&zn.has(t)},zu=e=>{const t=y(e.getExpression());if(t===void 0||!zn.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!M(s,"maxOutputTokens")},$u=new Set(["log","span","trace"]),Uu=new Set(["ai"]),Vu=new Set(["email","mail"]),qu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),ct=(e,t)=>[...t].some(s=>je(e,s).length>0),ju=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Wu=new Set(["every","filter","flatMap","forEach","map","some"]),Hu=new Set(["all","allSettled","race"]),Gu=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Wu.has(n))return t;const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="Promise"&&Hu.has(n))return t},Yu=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(ju.has(t.getKind())){const s=Gu(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Qu=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Xu=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ju=e=>{let t=!1,s=!0;for(const n of[...qu].flatMap(r=>je(e,r))){const r=Xu(n);r&&(t=!0,!Yu(r)&&!Qu(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Zu=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Bs="lunora-advisor-exempt",ef=/^[\s*/]+/u,tf=/[\w-]/u,sf=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
7
+ `);for(const n of s.split(`
8
+ `)){const r=n.replace(ef,"");if(!r.startsWith(Bs))continue;const o=r.slice(Bs.length);if(tf.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},nf=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=M(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},rf=(e,t)=>{const s=nf(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),r=s.getText(),o=n.getVariableDeclaration(r)?.getInitializer();return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:n.getFunction(r)},of=e=>{let t=!1,s=!1,n=!1,r=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(Lu(l)&&(o=!0),_u(l)&&(t=!0),Ku(l)&&(r=!0),Bu(l)&&(s=!0),zu(l)&&(n=!0),o&&t&&r&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ju(e);return{callsMail:ct(e,Vu),emitsEvent:ct(e,$u),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||ct(e,Uu),throwsBareError:Zu(e),unboundedAiGeneration:n,usesInsertManyUnsafe:r,writesUserTable:o}},af=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=H(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const r=n.receiver?Fu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=rf(e,s);return{...o?of(o):{},...sf(e),...r,analyzableBody:o!==void 0,exportName:U(e)??e.getName(),file:t,hasEmailArg:Tu(s,n.receiver),kind:n.kind,visibility:n.visibility}},cf=(e,t)=>{const s=[];for(const n of W(e)){const r=af(n,t);r&&s.push(r)}return s},lf=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...cf(r,T(t,n)))}return s},df=new Set(["dbRateLimit","rateLimit"]),uf=e=>i.isArrowFunction(e)?e.getBody():e,ff=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},$n=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Un=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const r=n.getParent();return!(i.isPropertyAccessExpression(r)&&r.getNameNode()===n)})},gf=(e,t)=>j(e)||t!==void 0&&Un(e,t).some(s=>$n(s)),pf=(e,t)=>t===void 0?se(e):Un(e,t).some(s=>!$n(s)),mf=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!df.has(s))return;const n=C(en(e.getArguments()[2]),"key");if(!n)return;const r=uf(n),o=ff(n);if(!(!gf(r,o)||pf(r,o)))return{callee:s,scope:v(e),file:t,limitName:Zs(e),line:e.getStartLineNumber()}},hf=(e,t)=>O(e,t,mf),vf=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Ef=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!vf.has(t.getName()))return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&$(s.getExpression()))return s.getName()},xf=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&$(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Sf=e=>{let t=E(e)??e;for(;i.isAwaitExpression(t);)t=E(t.getExpression())??t.getExpression();return t},Vn=(e,t=!1)=>{const s=Sf(e);if(i.isIdentifier(s)){if(t)return;const n=Z(s);return n===void 0?void 0:Vn(n,!0)}if(i.isCallExpression(s))return Ef(s)??xf(s)},Af=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const r=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=n.getExpression();r===e&&o!==void 0&&s.push(o)}return s},yf=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=H(s);if(n?.kind!=="query")return[];const r=bn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&Gr(n.receiver,"output"),a=n.receiver!==void 0&&tn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Af(r)){const p=Vn(u);p===void 0||c.has(p)||(c.add(p),l.push({exportName:U(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:p,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},bf=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of W(r))s.push(...yf(a,o))}return s},Nf=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(S(s));return t},Pf=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=un(o);if(a===void 0)continue;const c=Nf(C(a.options,"with"));c.length!==0&&r.push({exportName:U(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return r},wf=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of W(r))s.push(...Pf(a,o))}return s},Be=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Be(e.getLeft()),s=Be(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},If=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Be(t)!==void 0},Cf=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return S(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Tf=(e,t,s)=>Li(e)?!Vr(s)&&Mi(Cf(t)):!0,Of=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],r=new Set;for(const o of n){if(If(o))continue;const a=Be(o);if(a===void 0)continue;const c=Fi(a);if(c===void 0||!Tf(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;r.has(u)||(r.add(u),s.push({file:t,kind:c,line:l,preview:Di(a)}))}return s},Rf=(e,t)=>{const s=[];for(const n of x(t,{includeSkipped:!0})){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Of(r,T(t,n)))}return s},kf=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=un(o);if(a===void 0)continue;const c=C(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),u=!l&&j(c);!l&&!u||r.push({exportName:U(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return r},Ff=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of W(r))s.push(...kf(a,o))}return s},Df=new Set(["query","unsafe"]),Lf=e=>!i.isPropertyAccessExpression(e)||!Df.has(e.getName())?!1:q(e.getExpression(),["sql"]),Mf=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),_f=(e,t)=>{if(!Lf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Mf(s)))return{file:t,line:s.getStartLineNumber(),scope:v(e)}},Kf=(e,t)=>O(e,t,_f),Bf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],zf=e=>{for(const[t,s]of Bf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},$f=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=zf(a);c!==void 0&&s.push({file:T(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Uf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Vf=(e,t,s=[])=>{const n=He(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Uf,requireUnmodifiedReach:!0});return Pt(n,s)},qf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),jf=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Wf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=S(r);t.push(o),o==="expiresInSeconds"&&(s=jf(r.getInitializer()));continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(S(r))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Hf=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=qf.get(t);return s===void 0?void 0:rn(e.getExpression(),r=>r==="ctx.storage"||r.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Gf=(e,t)=>{const s=Hf(e.getExpression());if(s!==void 0)return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...Wf(e.getArguments()[s.optionsIndex])}},Yf=(e,t)=>O(e,t,Gf),Qf=(e,t)=>{const s=Jr(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,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")}},Xf=new Set(["delete","hardDelete","patch","replace","restore"]),Jf=new Set(["insertMany","insertManyUnsafe","patchWhere"]),Zf=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),zs=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],r=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return r.length===n.length?r:[]},eg=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const r=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return r===void 0?[]:zs(r,e)}return zs(s,e)},$s="",tg=(e,t)=>{if(Jf.has(e))return{method:e,tables:[t!==void 0&&i.isStringLiteral(t)?t.getLiteralText():$s]};if(Xf.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:eg(t,e);return{method:e,tables:s.length===0?[$s]:s}}},sg=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if($(n))return tg(s,e.getArguments()[0]);if(Zf.has(s)&&i.isPropertyAccessExpression(n)&&$(n.getExpression()))return{method:s,tables:[n.getName()]}},ng=(e,t)=>O(e,t,(s,n)=>{const r=sg(s);if(r===void 0)return;const o=v(s),a=s.getStartLineNumber();return r.tables.map(c=>({file:n,line:a,method:r.method,scope:o,table:c}))}),rg=e=>{const t=i.isCallExpression(e)?e.getExpression():void 0;return i.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},ig=e=>xn(e).some(t=>En(t,e)||i.isBreakStatement(t)&&A(vn(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>rg(t)&&Ot(t,e)),og=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>Ot(t,e)),ag=e=>i.isDoStatement(e)||i.isWhileStatement(e)?e.getExpression():e.getCondition(),cg=e=>i.isDoStatement(e)?"do":i.isWhileStatement(e)?"while":"for",lt=(e,t)=>{const s=ag(e);if(!(s===void 0||i.isTrueLiteral(E(s)))||ig(e)||og(e))return;const r=v(e);if(!(r.kind==="module"&&e.getFirstAncestor(J)!==void 0))return{file:t,kind:cg(e),line:e.getStartLineNumber(),scope:r}},lg=(e,t)=>[...le(e,t,d.WhileStatement,lt),...le(e,t,d.ForStatement,lt),...le(e,t,d.DoStatement,lt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),dg=(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"}),ug=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||M(s,"args")===void 0)return!1}return Tt(e,t).opaque},fg=(e,t)=>{const s=[],n=(r,o)=>{const a=r.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=H(a);c!==void 0&&ug(a,c.receiver)&&s.push(dg(t,o,a.getStartLineNumber()))};for(const r of e.getVariableStatements().filter(o=>o.isExported()))for(const o of r.getDeclarations())n(o,o.getName());return s},gg=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n);r!==void 0&&s.push(...fg(r,T(t,n)))}return s.toSorted((n,r)=>n.cacheKey.localeCompare(r.cacheKey))},pg=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)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. 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."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["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"}]]),ze=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),qn=e=>!e.isAny(),jn=e=>{const t=e.getType();if(!qn(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:pg.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},mg=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Wn={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."},hg=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.`}),vg={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)."},Eg=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),xg={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)."},Sg=(e,t,s)=>{if(!t.some(r=>Dr(r)))return vg;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Eg.has(s.typeName)&&!n&&!t.some(r=>Ki(r))?xg:Wn},Hn=(e,t,s,n,r)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,p=u===void 0?r:hg(u),f=c===void 0?p.remediation:`${c} ${p.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 — ${p.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};\`. ${f}`:f,title:"Procedure exists at runtime but is missing from the generated API"}},Ag=(e,t,s)=>{const n=[];for(const r of W(e)){const o=i.isIdentifier(r.getNameNode())?gt(r):[r.getName()],c=o.some(u=>ze(s,t,u))||!mg(r)?void 0:jn(r),[l=r.getName()]=o;c!==void 0&&n.push(Hn(t,l,c,r.getStartLineNumber(),Sg(r,o,c)))}return n},yg=(e,t,s)=>{if(ze(s,t,"default"))return[];const n=[];for(const r of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!i.isIdentifier(o.getExpression()))){const o=jn(r.getExpression());o!==void 0&&n.push(Hn(t,"default",o,r.getStartLineNumber(),Wn))}return n},bg=(e,t,s)=>[...Ag(e,t,s),...yg(e,t,s)],Ng=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>i.isIdentifier(n.getNameNode())).filter(n=>gt(n).some(r=>ze(s,t,r))).filter(n=>{const r=n.getInitializer();return r!==void 0&&i.isCallExpression(r)&&i.isPropertyAccessExpression(r.getExpression())}).map(n=>{const r=gt(n).find(o=>ze(s,t,o))??n.getName();return{declaration:n,exportName:r,relativePath:t}}),Pg=({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"}),wg=(e,t,s)=>{const n=[],r=[];for(const a of x(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=T(t,a);n.push(...bg(c,l,s)),r.push(...Ng(c,l,s))}const[o]=r;return o!==void 0&&r.every(({declaration:a})=>!qn(a.getType()))&&n.push(Pg(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Ig=new Set(["when","where"]),dt=new Set(["definePolicy","defineShape"]),Cg=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return dt.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const r=n.getNameNode().getText();return dt.has(r)?r:void 0}const s=t.getText();return dt.has(s)?s:void 0},Tg=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Gn=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Tg(e))return"empty-object";if(i.isParenthesizedExpression(e))return Gn(e.getExpression())}},kt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Og=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>kt(t)===e),Yn=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>kt(t)===e),Rg=e=>{const t=Og(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Yn(e).length>0},kg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>kt(t)===e),bt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",Fg=(e,t)=>bt(e)||bt(t),Dg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Us=e=>!bt(e)&&(i.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Lg=(e,t,s)=>{const n=Dg.get(e);if(n!==void 0)return Fg(t,s)?n==="positive"?"negative":"positive":Us(t)||Us(s)?void 0:n},ve=e=>{if(i.isParenthesizedExpression(e))return ve(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Lg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=ve(e.getLeft()),r=ve(e.getRight());return n===r?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},Vs=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},Mg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},_g=e=>i.isReturnStatement(e)?e.getExpression()??e:e,Kg=e=>{const t=[];for(const s of Yn(e)){const n=ve(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of kg(e)){const n=ve(s.getExpression());if(n==="indeterminate")continue;const r=n==="negative"?Vs(s.getThenStatement()):Vs(s.getElseStatement())??Mg(s);r!==void 0&&t.push(_g(r))}return t},Bg=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},zg=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)||!Ig.has(S(o)))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Rg(a))for(const c of Kg(a)){const l=Gn(c);l!==void 0&&r.push({exportName:Bg(e),file:s,form:l,key:S(o),line:c.getStartLineNumber(),owner:t})}}return r},$g=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=Cg(n);r!==void 0&&s.push(...zg(n,r,t))}return s},Ug=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...$g(r,T(t,n)))}return s},Vg=new Set(["query","upsert","upsertNow"]),qg=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Vg.has(t))return q(e.getExpression(),["vectors"])?t:void 0},jg=(e,t)=>{const s=qg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const r=C(n,"namespace");if(!(!r||!j(r)||se(r)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},Wg=(e,t)=>O(e,t,jg),Hg=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},Gg=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Yg=(e,t)=>O(e,t,(s,n)=>Hg(s)?{file:n,line:s.getStartLineNumber(),scope:v(s),workflow:Gg(s)}:void 0),Qg=".lunora-schema.json",$e=(e,t)=>{k(e)&&cr(e,"utf8")===t||lr(e,t,"utf8")},Xg=(e,t)=>{if(t===""){ft(e,{force:!0});return}$e(e,t)},Jg=(e,t)=>{const s=h(e,"services");if(Object.keys(t).length===0){ft(s,{force:!0,recursive:!0});return}if(k(s))for(const n of ar(s,{recursive:!0,withFileTypes:!0})){const r=h(n.parentPath,n.name);n.isFile()&&t[dr(e,r)]===void 0&&ft(r)}for(const[n,r]of Object.entries(t))js(me(h(e,n)),{recursive:!0}),$e(h(e,n),r)},Zg=e=>{try{const t=fr(h(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},ep=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},tp=e=>{let t=k(e)?e:me(e);for(;t&&t!==me(t);){const s=h(t,"tsconfig.json");if(k(s))return s;t=me(t)}},qs=e=>e.replaceAll("\\","/"),sp=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new X("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 r=t.columns.length>0;for(const o of e){if(o.table===void 0){if(r)throw new X("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 X("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})}},de=(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)},ut=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,np=8,rp=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:r,lunoraDirectory:o,migrations:a,project:c,shapes:l,usesSandbox:u,useUmbrella:p,workflows:f}=e,m=()=>pi(()=>{const N=mi(c,o),z=Ni(c,o);return{functions:N,httpRoutes:hi(c,o),mutators:z}});let{erased:b,value:{functions:_,httpRoutes:G,mutators:L}}=m();cs([..._,...L].map(N=>N.filePath)),cs(G.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const z=Ji({agents:t,functions:_,httpRoutes:G,mutators:L,useUmbrella:p,workflows:f}),K=ao({agents:t,functions:_,migrations:a,mutators:L,shapes:l,useUmbrella:p,usesSandbox:u}),P=Zi({functions:_,useUmbrella:p});if(N>=np||ut(c,s,z)&&ut(c,r,P)&&ut(c,n,K))return{apiContent:z,erased:b,functions:_,functionsContent:K,httpRoutes:G,internalContent:P,mutators:L};de(c,s,z),de(c,r,P),de(c,n,K),{erased:b,value:{functions:_,httpRoutes:G,mutators:L}}=m()}},ip=e=>{const t=tp(e);return t?new rs({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new rs({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Sm=(e,t)=>{const s=x(t),n=h(t,"schema.ts");k(n)&&s.push(n);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const r=new Set(s.map(c=>qs(c))),o=qs(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!r.has(l)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const l=c.getFilePath();if(!(l===o||l.startsWith(a)||l.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Am=e=>{const t=ep(),s=t?st.now():0,n=h(e.projectRoot,e.lunoraDirectory??"lunora"),r=h(n,"schema.ts");if(!k(r))throw new X("INTERNAL",`schema.ts not found at ${r}`);const o=e.project??ip(n);ai(el);const a=ki(o,r,e.projectRoot),{agents:c,capabilities:l,containers:u,crons:p,dataModelContent:f,dependencies:m,entryCronTriggers:b,env:_,featureUsage:G,hasFlags:L,hasNotify:N,identity:z,platformGate:K,queues:P,serverContent:ne,services:re,storageRulesMetadata:ue,topics:ie,usesSandbox:ye,useUmbrella:V,workflows:B}=ta({lunoraDirectory:n,project:o,projectRoot:e.projectRoot,schema:a,target:e.target});_l(a,a.jurisdiction===void 0?void 0:Ll(o,n));const R=h(n,"_generated"),F=h(R,"dataModel.ts"),Qn=h(R,"server.ts"),Xn=h(R,"api.ts"),Jn=h(R,"internal.ts"),Zn=h(R,"functions.ts");de(o,F,f),de(o,Qn,ne);const Ge=Object.fromEntries(re.filter(g=>g.rpcEntrypoint!==void 0).flatMap(g=>Object.entries(ti(g,R))));for(const[g,w]of Object.entries(Ge))de(o,h(R,g),w);const be=Si(o,n),oe=_i(o,n),{apiContent:Ft,erased:er,functions:Y,functionsContent:Dt,httpRoutes:Ye,internalContent:Lt,mutators:Ne}=rp({agents:c,apiPath:Xn,generatedFunctionsPath:Zn,internalPath:Jn,lunoraDirectory:n,migrations:be,project:o,shapes:oe,useUmbrella:V,usesSandbox:ye,workflows:B}),Mt=xr(o,n),Qe=Sr(Mt,a,[...Y,...Ye].map(g=>g.filePath)),Pe=Mt.length>0,Q=e.lint===!1&&!Pe?void 0:{callEdges:mc(o,n),inserts:Ei(o,n),queries:Ci(o,n),tableWrites:ng(o,n),workflowCalls:Yg(o,n)},we=e.lint===!1||Q===void 0?void 0:mr({adminRoutes:la(o,n),aiRawRuns:Ea(o,n),aiToolSideEffects:Ta(o,n),argumentDerivedFetches:ka(o,n),argumentValidators:Ua(o,n),authApiCalls:ci(o,n),authConfigs:Ja(o,n),browserUrlAccesses:sc(o,n),callEdges:Q.callEdges,configCalls:bc(o,n),containerKeyAccesses:Pc(o,n),containerOverrides:Rc(o,n),containers:u,exportSinks:Lc(o,n),staleMigrationImports:$f(o,n),failOpenGuards:zc(o,n),flagReads:Yc(o,n),flagSecurityDefaults:Zc(o,n),geoIndexUsages:nl(o,n),httpActionGuards:ml(o,n),httpHeaderWrites:Pl(o,n),hyperdriveCalls:vi(o,n),identityClaimReads:Rl(o,n),imageDeliveryUrlAccesses:Fl(o,n),inserts:Q.inserts,kvKeyAccesses:Bl(o,n,Y),mailRecipientAccesses:ql(o,n),maskProcedures:xi(o,n),maskStrategies:Jl(o,n),mutatorWrites:rd(o,n),nondeterministicCalls:Pi(o,n),normalizeIdAuthorizations:xd(o,n),notifyCalls:Ii(o,n),notifyConfig:wi(o,n),mutators:Ne,ownerFieldWrites:ou(o,n,Y,Ne),unrestrictedWhereBranches:Ug(o,n),paymentWebhooks:pu(o,n),privilegedDispatches:Pu(o,n),procedureProtections:lf(o,n),queries:Q.queries,queues:P,r2sqlCalls:Ti(o,n),ratelimitKeySelectors:hf(o,n),rawRowReturns:bf(o,n),relationLoads:wf(o,n),rlsProcedures:Oi(o,n),schema:a,secretLiterals:Rf(o,n),modules:Qe,shapes:oe,softDeleteReads:Ff(o,n),sqlInterpolations:Kf(o,n),storageKeyAccesses:Vf(o,n,Y),storageUploads:Yf(o,n),tableWrites:Q.tableWrites,unboundedLoops:lg(o,n),vectorNamespaceAccesses:Wg(o,n),workflowCalls:Q.workflowCalls,workflows:B,wranglerVariables:e.wranglerVariables}),_t=we===void 0?[]:lo(e.projectRoot,[...ur(we,{source:"static"}),...wg(o,n,{byName:new Set([...B,...P,...c,...u].map(g=>g.exportName)),byPath:new Set([...Y,...Ne,...oe,...be].map(g=>`${g.filePath}:${g.exportName}`))}),...gg(o,n),...gi(er,n),...ji(P,e.wranglerQueueProducers)]),tr=Ri(o,n),Kt=Yl(o,n);sp(oe,Kt,Hl(o,n));const sr=L?qc(o,n):[],Xe=K.signals.vectorStore!==!1,fe=Qf(G,{containerCount:u.length,cronCount:p.length,dependencies:m,hasPaymentTables:lu(a.tables),queueCount:P.length,storageColumnCount:Object.keys(nn(a)).length,storageRuleCount:ue.rules.length,vectorIndexCount:a.vectorIndexes.length,target:sn(e.projectRoot,e.target),vectorStoreSupported:Xe,workflowCount:B.length}),Bt=t?st.now():0,Je=qi(a,be.map(g=>g.id)),zt=Zr({advisories:_t.filter(g=>g.name!=="procedure_type_check_unavailable"),advisorProcedures:we?.procedureProtections??[],agents:c,capabilities:l,containers:u,env:_,flagKeys:sr,hasFlags:L,hasNotify:N,hasVectors:Xe,maskMetadata:Kt,mutators:Ne,queues:P,rlsMetadata:tr,schema:a,schemaSnapshot:Je,shapes:oe,services:re,storageRules:ue,studioFeatures:fe,topics:ie,useUmbrella:V,workflows:B}),$t=Qi(oe,m.has("@lunora/db"),V),Ut=Wi(u,a.jurisdiction),Vt=Hi(B),qt=Gi(c),jt=Yi(P,e.wranglerQueueProducers),Wt=eo(p),nr=to(fe.scheduler),rr=so(a.tables,V),ir=Er(e.projectRoot)?no(V):"",Ht=ro(a.vectorIndexes),Ie=oo(a,V),Gt=Xi(m.has("@lunora/seed")),Ce=e.apiSpec??"openapi",Ze=Ce==="openapi"||Ce==="both",et=Ce==="openrpc"||Ce==="both",Yt=Bi({capabilities:l,emailAgents:c.filter(g=>g.onEmail===!0).map(g=>({className:g.className,exportName:g.exportName})),hasAccess:m.has("@lunora/cloudflare-access"),hasAuth:m.has("@lunora/auth"),hasFramework:m.has("@lunora/astro")||m.has("@lunora/svelte")||m.has("@lunora/vue")||k(h(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(g=>Hs(g)),hasHyperdriveGlobal:a.tables.some(g=>Gs(g)),hasKvIntrospector:fe.kv,hasNotify:N,hasQueue:P.some(g=>g.mode==="push"),hasScheduler:fe.scheduler,hasSourcedTables:a.tables.some(g=>g.externalSource!==void 0),hasStorage:fe.storage,hasVectors:Xe,hasWorkflow:B.length>0,identity:z,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(g=>({name:g.name,shardMode:g.shardMode})),useUmbrella:V,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(g=>g.voice===!0&&g.voiceBindingName!==void 0).map(g=>({bindingName:g.voiceBindingName,exportName:g.exportName})),wantsArchitecture:Pe,wantsOpenApi:Ze,wantsOpenRpc:et}),Qt=Zg(e.projectRoot),Xt=Pe?Qe:[],Jt=zi({functions:Y,httpRoutes:Ye,modules:Xt,version:Qt}),Zt=Ui({functions:Y,modules:Xt,version:Qt}),es=`${JSON.stringify(Jt,void 0,2)}
9
+ `,ts=`${JSON.stringify(Zt,void 0,2)}
10
+ `,ge=Pe&&Q!==void 0?Po({...Q,crons:p,functions:Y,httpRoutes:Ye,modules:Qe,queues:P,schema:a,services:re,topics:ie,workflows:B}):void 0,ss=$i(Jt),ns=Vi(Zt),tt=h(n,Qg),or=k(tt),Te=[];if(!e.dryRun){k(R)||js(R,{recursive:!0});const g=(ee,ae)=>{$e(h(R,ee),ae),Te.push(ee)},w=(ee,ae)=>{Xg(h(R,ee),ae),ae!==""&&Te.push(ee)};g("app.ts",Yt),g("dataModel.ts",f),g("api.ts",Ft),g("internal.ts",Lt),g("server.ts",ne),g("functions.ts",Dt),g("shard.ts",zt),g("crons.ts",Wt),g("vectors.ts",Ht),g("drizzle.global.ts",Ie.global),g("drizzle.shard.ts",Ie.shard),w("containers.ts",Ut),w("workflows.ts",Vt),w("agents.ts",qt),w("queues.ts",jt),w("scheduler.ts",nr),w("shardRegistry.ts",rr),w("durableObjects.ts",ir),w("seed.ts",Gt),w("collections.ts",$t),Jg(R,Ge),Te.push(...Object.keys(Ge)),w("openapi.json",Ze?es:""),w("openapi.ts",Ze?ss:""),w("openrpc.json",et?ts:""),w("openrpc.ts",et?ns:""),w("architecture.json",ge===void 0?"":`${JSON.stringify(ge,void 0,2)}
11
+ `),w("architecture.ts",ge===void 0?"":wo(ge)),(!or||e.updateSchemaBaseline===!0)&&$e(tt,pr(Je))}if(t){const g=st.now(),w=Math.round(g-s),ee=Math.round(Bt-s),ae=Math.round(g-Bt);console.error(`@lunora/codegen: codegen took ${w.toString()}ms (discovery ${ee.toString()}ms, emit ${ae.toString()}ms)`)}return{advisories:_t,advisorContext:we,agents:c,architecture:ge,containers:u,cronTriggers:[...new Set([...io(p),...b])],generated:{agents:qt,api:Ft,app:Yt,collections:$t,containers:Ut,crons:Wt,dataModel:f,drizzleGlobal:Ie.global,drizzleShard:Ie.shard,functions:Dt,internal:Lt,openApi:es,openApiModule:ss,openRpc:ts,openRpcModule:ns,queues:jt,seed:Gt,server:ne,shard:zt,vectors:Ht,workflows:Vt},migrations:be,outputDirectory:R,platformDiagnostics:K.diagnostics,queues:P,schemaSnapshot:Je,schemaSnapshotPath:tt,workflows:B,writtenFiles:Te}};export{Qg as SCHEMA_SNAPSHOT_FILENAME,ip as createCodegenProject,tp as findTsconfig,Sm as refreshCodegenProject,Am as runCodegen};
@@ -0,0 +1,2 @@
1
+ const m=(e,t=2166136261)=>{let i=t;for(let o=0;o<e.length;o+=1)i^=e.charCodeAt(o),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},S=e=>`${m(e,2166136261)}${m(e,16777619)}`,H=1;function w(e){const t={},i=Object.keys(e);i.sort();for(const o of i)t[o]=e[o];return t}const O=e=>`${JSON.stringify(e,void 0,2)}
2
+ `,P=e=>S(O(e)),c=e=>typeof e=="object"&&e!==null,x=e=>c(e)&&c(e.fields)&&c(e.indexes)&&c(e.relations)&&typeof e.shardMode=="string",J=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let t;try{t=JSON.parse(e)}catch(o){return{error:`baseline is not valid JSON: ${o instanceof Error?o.message:String(o)}`,status:"invalid"}}if(!c(t)||t.version!==1||!c(t.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[o,r]of Object.entries(t.tables))if(!x(r))return{error:`baseline table "${o}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof t.jurisdiction=="string"?t.jurisdiction:void 0,migrationIds:Array.isArray(t.migrationIds)?t.migrationIds:[],tables:t.tables,version:1},status:"ok"}},F=(e,t)=>e.unique===t.unique&&e.fields.length===t.fields.length&&e.fields.every((i,o)=>i===t.fields[o]),y=e=>e.unique!==void 0,p=({nullable:e,optional:t,refined:i,unique:o,...r})=>JSON.stringify(w(r)),g=e=>({form:JSON.stringify([p(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),v=e=>e.kind==="union"&&e.members?e.members.map(t=>g(t)):[g({...e,nullable:!1,optional:!1})],T=(e,t)=>{if(t.kind!=="union")return!1;const i=v(t);return v(e).every(o=>i.some(r=>r.form===o.form&&(o.refined||!r.refined)))},a=e=>{switch(e.kind){case"array":return`array(${e.of?a(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?a(e.key):"?"}, ${e.of?a(e.of):"?"})`;case"union":return(e.members??[]).map(t=>a(t)).join(" | ");default:return e.kind}},l=(e,t,i)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:i,table:e,type:t}),f=(e,t,i)=>({remediation:"none",scope:"table",severity:"safe",summary:i,table:e,type:t}),_=(e,t,i,o,r)=>{if(!(i.kind===o.kind&&(!r||p(i)===p(o))))return r&&T(i,o)?f(e,"widenedFieldShape",`field ${e}.${t} widened: ${a(i)} → ${a(o)} — every stored value stays valid`):i.kind!==o.kind?l(e,"changedFieldKind",`field ${e}.${t} changed type: ${i.kind} → ${o.kind} — add a data migration to convert existing values`):l(e,"changedFieldShape",`field ${e}.${t} changed shape: ${a(i)} → ${a(o)} — stored values were written against the old shape; add a data migration to convert them`)},j=(e,t,i,o)=>{const r=[];return i.unique!==o.unique&&r.push(o.unique===!0?l(e,"addedFieldConstraint",`field ${e}.${t} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):f(e,"relaxedFieldConstraint",`field ${e}.${t} is no longer unique`)),i.nullable!==o.nullable&&r.push(o.nullable===!0?f(e,"relaxedFieldConstraint",`field ${e}.${t} became nullable`):l(e,"addedFieldConstraint",`field ${e}.${t} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),i.refined!==o.refined&&r.push(o.refined===!0?l(e,"addedFieldConstraint",`field ${e}.${t} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):f(e,"relaxedFieldConstraint",`field ${e}.${t} dropped its validation refinement`)),r},q=(e,t,i,o)=>{const r=[],n=y(i)&&y(o),s=_(e,t,i,o,n);return s&&r.push(s),n&&r.push(...j(e,t,i,o)),i.optional&&!o.optional?r.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${t} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!i.optional&&o.optional&&r.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${t} became optional`,table:e,type:"fieldRequiredToOptional"}),r},E=(e,t,i)=>i.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${t}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${t} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},A=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.fields)){const s=t.fields[r];s===void 0?o.push(E(e,r,n)):o.push(...q(e,r,s,n))}for(const r of Object.keys(t.fields))i.fields[r]===void 0&&o.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${r} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},M=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.indexes)){const s=t.indexes[r];if(s===void 0){o.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${r} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${r} on ${e}`,table:e,type:"addedIndex"});continue}F(s,n)||o.push({remediation:"code",severity:"breaking",summary:`index ${r} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const r of Object.keys(t.indexes))i.indexes[r]===void 0&&o.push({remediation:"code",severity:"breaking",summary:`removed index ${r} on ${e} — a query that used \`.withIndex("${r}")\` would break`,table:e,scope:"table",type:"removedIndex"})},C=(e,t,i,o)=>{for(const r of Object.keys(i.relations))t.relations[r]===void 0&&o.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${r}`,table:e,type:"addedRelation"});for(const r of Object.keys(t.relations))i.relations[r]===void 0&&o.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${r}`,table:e,type:"removedRelation"})},$="shardBy:_unknown_",u="global",I=(e,t)=>e===u&&t.startsWith(`${u}:`)||t===u&&e.startsWith(`${u}:`),R=(e,t,i)=>{if(t===i)return i!==$?void 0:{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} declares a non-literal .shardBy(...) key, so codegen cannot read which column partitions it — every such key records as "${$}" and two DIFFERENT keys would compare equal. Pass the shard key as a string literal; until then this is reported on every run, because the alternative is a silent pass on a re-home that strands every row (export/import is the only way back).`,table:e,type:"changedShardMode"};if(!I(t,i))return{remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${t} → ${i} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}},b=e=>e.memory!==void 0,k=e=>e.after??0,d=e=>e.after===void 0?`.ttl("${e.field}")`:`.ttl("${e.field}", { after: ${String(e.after)} })`,V=(e,t,i)=>{if(t===void 0&&i===void 0)return;const o=h=>({remediation:"backfill",scope:"table",severity:"breaking",summary:h,table:e,type:"changedTtlPolicy"}),r=h=>({remediation:"none",scope:"table",severity:"safe",summary:h,table:e,type:"changedTtlPolicy"});if(i===void 0)return r(`table ${e} dropped its TTL policy — its rows are no longer swept`);if(t===void 0)return o(`table ${e} gained a TTL policy ${d(i)} — every row already past the cutoff is deleted on the next alarm sweep; add a data migration to refresh or clear "${i.field}" on the rows written before it`);if(t.field!==i.field)return o(`table ${e} moved its TTL to a different column: ${d(t)} → ${d(i)} — rows are now expired by a column they were never written against; add a data migration to populate "${i.field}"`);const n=k(t),s=k(i);return s<n?o(`table ${e} shortened its TTL: ${d(t)} → ${d(i)} — rows that were not expired under the old offset are deleted on the next alarm sweep; add a data migration to refresh "${i.field}" on the rows that must survive`):s>n?r(`table ${e} lengthened its TTL: ${d(t)} → ${d(i)}`):void 0},L=(e,t,i)=>{const o=[];return t.memory!==i.memory&&o.push(i.memory===!0?{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} became a .memory() table — every row is deleted in every shard on the next Durable Object cold start, and no data migration survives that; export the rows first if they must be kept, or revert`,table:e,type:"changedMemoryMode"}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer a .memory() table — its rows now survive a cold start`,table:e,type:"changedMemoryMode"}),t.commitOrdered!==i.commitOrdered&&o.push(i.commitOrdered===!0?{remediation:"backfill",scope:"table",severity:"breaking",summary:`table ${e} became .commitOrdered() — rows written before it carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed never offers them; add a data migration over the table to stamp them (the rewrite allocates a sequence)`,table:e,type:"changedCommitOrdering"}:{remediation:"code",scope:"table",severity:"breaking",summary:`table ${e} is no longer .commitOrdered() — new rows carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed stops advancing without erroring; update the consumers before deploying`,table:e,type:"changedCommitOrdering"}),o},D=(e,t,i,o)=>{const r=R(e,t.shardMode,i.shardMode);if(r&&o.push(r),b(t)&&b(i)){o.push(...L(e,t,i));const n=V(e,t.ttl,i.ttl);n&&o.push(n)}A(e,t,i,o),M(e,t,i,o),C(e,t,i,o)},B=(e,t)=>{const i=[],o=e?.tables??{};for(const[r,n]of Object.entries(t.tables)){const s=o[r];if(s===void 0){i.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${r}`,table:r,type:"addedTable"});continue}D(r,s,n,i)}for(const r of Object.keys(o))t.tables[r]===void 0&&i.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${r} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:r,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==t.jurisdiction){const r=e.jurisdiction??"(none)",n=t.jurisdiction??"(none)";i.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${r} to ${n} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:i}};export{H as SCHEMA_SNAPSHOT_VERSION,a as describeShape,q as diffExistingField,B as diffSchemaSnapshots,P as hashSchemaSnapshot,x as isValidTableSnapshot,J as parseSnapshotJson,O as serializeSchemaSnapshot,w as sortKeys};