@lunora/codegen 1.0.0-alpha.223 → 1.0.0-alpha.224
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-CoCRXlsC.mjs → SCHEMA_SNAPSHOT_FILENAME-Dz-I9yuA.mjs} +5 -5
- package/dist/packem_shared/{discoverSchema-Buzj8y8m.mjs → discoverSchema-QO1eQYjw.mjs} +1 -1
- package/dist/packem_shared/{emitApp-DCNd7kfS.mjs → emitApp-Pd7CNFXQ.mjs} +4 -1
- package/package.json +10 -10
package/dist/index.d.mts
CHANGED
|
@@ -467,12 +467,12 @@ interface SchemaIR {
|
|
|
467
467
|
*/
|
|
468
468
|
jurisdiction?: JurisdictionIR;
|
|
469
469
|
/**
|
|
470
|
-
* `.jurisdiction("…", {
|
|
471
|
-
*
|
|
472
|
-
*
|
|
473
|
-
* project that has
|
|
470
|
+
* `.jurisdiction("…", { pinAuth: true })` — the acknowledgement that
|
|
471
|
+
* DO-backed auth, unpinned before, moves into the jurisdiction (and so to a
|
|
472
|
+
* new, empty object until its rows are copied). Without it codegen refuses a
|
|
473
|
+
* project that has DO-backed auth, and does not pin it.
|
|
474
474
|
*/
|
|
475
|
-
|
|
475
|
+
jurisdictionPinsAuth?: true;
|
|
476
476
|
/**
|
|
477
477
|
* Set when `defineSchema(...).rls("required")` was chained onto the schema —
|
|
478
478
|
* every table's `ctx.db` write path is denied without an RLS-covering
|
|
@@ -3457,11 +3457,11 @@ interface EmitAppOptions {
|
|
|
3457
3457
|
/** Schema declares `.jurisdiction("…")` → pin every DO the worker reaches (shards, fan-out, scheduler, containers, voice sessions, DO-backed auth) to the Cloudflare data-residency jurisdiction. */
|
|
3458
3458
|
jurisdiction?: JurisdictionIR;
|
|
3459
3459
|
/**
|
|
3460
|
-
* `.jurisdiction("…", {
|
|
3461
|
-
*
|
|
3462
|
-
*
|
|
3460
|
+
* `.jurisdiction("…", { pinAuth: true })`. DO-backed auth is pinned only
|
|
3461
|
+
* then: unacknowledged, pinning would resolve every user to a new, empty
|
|
3462
|
+
* auth object (codegen refuses a project it can see doing that).
|
|
3463
3463
|
*/
|
|
3464
|
-
|
|
3464
|
+
jurisdictionPinsAuth?: boolean;
|
|
3465
3465
|
/**
|
|
3466
3466
|
* Every table the schema declares. Emitted as a literal `listSchemaTables`
|
|
3467
3467
|
* so export can answer "every table" with a real list: shard discovery is
|
package/dist/index.d.ts
CHANGED
|
@@ -467,12 +467,12 @@ interface SchemaIR {
|
|
|
467
467
|
*/
|
|
468
468
|
jurisdiction?: JurisdictionIR;
|
|
469
469
|
/**
|
|
470
|
-
* `.jurisdiction("…", {
|
|
471
|
-
*
|
|
472
|
-
*
|
|
473
|
-
* project that has
|
|
470
|
+
* `.jurisdiction("…", { pinAuth: true })` — the acknowledgement that
|
|
471
|
+
* DO-backed auth, unpinned before, moves into the jurisdiction (and so to a
|
|
472
|
+
* new, empty object until its rows are copied). Without it codegen refuses a
|
|
473
|
+
* project that has DO-backed auth, and does not pin it.
|
|
474
474
|
*/
|
|
475
|
-
|
|
475
|
+
jurisdictionPinsAuth?: true;
|
|
476
476
|
/**
|
|
477
477
|
* Set when `defineSchema(...).rls("required")` was chained onto the schema —
|
|
478
478
|
* every table's `ctx.db` write path is denied without an RLS-covering
|
|
@@ -3457,11 +3457,11 @@ interface EmitAppOptions {
|
|
|
3457
3457
|
/** Schema declares `.jurisdiction("…")` → pin every DO the worker reaches (shards, fan-out, scheduler, containers, voice sessions, DO-backed auth) to the Cloudflare data-residency jurisdiction. */
|
|
3458
3458
|
jurisdiction?: JurisdictionIR;
|
|
3459
3459
|
/**
|
|
3460
|
-
* `.jurisdiction("…", {
|
|
3461
|
-
*
|
|
3462
|
-
*
|
|
3460
|
+
* `.jurisdiction("…", { pinAuth: true })`. DO-backed auth is pinned only
|
|
3461
|
+
* then: unacknowledged, pinning would resolve every user to a new, empty
|
|
3462
|
+
* auth object (codegen refuses a project it can see doing that).
|
|
3463
3463
|
*/
|
|
3464
|
-
|
|
3464
|
+
jurisdictionPinsAuth?: boolean;
|
|
3465
3465
|
/**
|
|
3466
3466
|
* Every table the schema declares. Emitted as a literal `listSchemaTables`
|
|
3467
3467
|
* so export can answer "every table" with a real list: shard discovery is
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs";import{default as h}from"./packem_shared/discoverCrons-MfKw7IFf.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-BedPDCsR.mjs";import{default as D}from"./packem_shared/discoverFunctions-BsmX-sEq.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-BcXI9CNt.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs";import{default as y}from"./packem_shared/discoverInserts-CFJ3IVeI.mjs";import{d as W}from"./packem_shared/index-BoaHhVtM.mjs";import{default as V}from"./packem_shared/discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-B-f4jO-x.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-BO4qC77y.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CPmAGL0W.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-CgmfgDTS.mjs";import{default as xe}from"./packem_shared/discoverSchema-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs";import{default as h}from"./packem_shared/discoverCrons-MfKw7IFf.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-BedPDCsR.mjs";import{default as D}from"./packem_shared/discoverFunctions-BsmX-sEq.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-BcXI9CNt.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs";import{default as y}from"./packem_shared/discoverInserts-CFJ3IVeI.mjs";import{d as W}from"./packem_shared/index-BoaHhVtM.mjs";import{default as V}from"./packem_shared/discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-B-f4jO-x.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-BO4qC77y.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CPmAGL0W.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-CgmfgDTS.mjs";import{default as xe}from"./packem_shared/discoverSchema-QO1eQYjw.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-zJgzynXR.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-D8VYflWt.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-6YJU3YbV.mjs";import{emitApp as We}from"./packem_shared/emitApp-Pd7CNFXQ.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-D1dd4rBh.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-DAxS0CaZ.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-CkKqxaOb.mjs";import{loadProjectConfig as ir,readProjectConfigLiterals as mr}from"./packem_shared/loadProjectConfig-CKsFNgn3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as fr,createCodegenProject as pr,findTsconfig as cr,refreshCodegenProject as nr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Dz-I9yuA.mjs";import{SchemaSnapshotParseError as xr,buildSchemaSnapshot as Er,evaluateSchemaDrift as Ar,parseSchemaSnapshot as ur}from"./packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Cr,validatorIrToJsonSchema as Or}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Mr,SDK_TARGETS as Tr,generateSdk as _r}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Lr,secretKindOf as Fr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Pr,findSolutionByMessage as Dr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as Ur,findProjectConfigFile as br}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{isTypedSchema as jr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Cr as LUNORA_ERROR_CODES,Pr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,Ur as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,fr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Mr as SDK_LANGUAGES,Tr as SDK_TARGETS,Ae as SHAPES_FILENAME,xr as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,Er as buildSchemaSnapshot,pr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Ar as evaluateSchemaDrift,Dr as findLunoraSolution,br as findProjectConfigFile,cr as findTsconfig,m as formatAdvisories,_r as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,jr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,ir as loadProjectConfig,ur as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,mr as readProjectConfigLiterals,tr as readProjectTarget,Lr as redact,nr as refreshCodegenProject,sr as resolveCodegenTarget,lr as runCodegen,Nr as schemaFromIr,Fr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Or as validatorIrToJsonSchema};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{existsSync as w,mkdirSync as Rs,readFileSync as $t,writeFileSync as Ls,rmSync as Ds}from"node:fs";import{join as y,dirname as ae}from"node:path";import{performance as we}from"node:perf_hooks";import{runAdvisor as ks}from"@lunora/advisor";import{LunoraError as
|
|
2
|
-
`);throw new
|
|
1
|
+
import{existsSync as w,mkdirSync as Rs,readFileSync as $t,writeFileSync as Ls,rmSync as Ds}from"node:fs";import{join as y,dirname as ae}from"node:path";import{performance as we}from"node:perf_hooks";import{runAdvisor as ks}from"@lunora/advisor";import{LunoraError as K}from"@lunora/errors";import{SyntaxKind as l,Node as o,VariableDeclarationKind as Ms,Project as dt}from"ts-morph";import{serializeSchemaSnapshot as Ks}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as _s}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as zs}from"./loadProjectConfig-CKsFNgn3.mjs";import{s as $s}from"./paths-C-9fwEgQ.mjs";import{C as ce,o as Ut,j as Us,f as qs,k as Bs,b as js,c as Vs,m as Ws,e as Hs,p as Gs,d as Ys,i as Qs,l as Xs,g as Zs,q as Js,n as en,a as tn,h as sn}from"./emit-6YJU3YbV.mjs";import{isD1GlobalTable as qt,isHyperdriveGlobalTable as Bt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as nn}from"./AGENTS_FILENAME-DoPI92Wu.mjs";import{discoverContainers as rn}from"./CONTAINERS_FILENAME-B6TFs82W.mjs";import on from"./discoverCrons-MfKw7IFf.mjs";import{diagnosticAt as ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as pe}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,bindingKeyName as Q,propertyKeyName as E,unwrapExpression as X,listSecurityScanFiles as me,objectLiteralFromCallbackBody as jt,propertyInitializer as b,lunoraRelativePath as x,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as an,limitNameOf as Vt,optionsObjectLiteral as Wt,isContextIdentifier as Fe,handlerOf as cn,isDatabaseAccessor as _,readTargetOf as Ht,enclosingExportName as ln}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import un from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as dn}from"./QUEUES_FILENAME-CxkPcMH1.mjs";import{discoverSandboxUsage as fn}from"./discoverSandboxUsage-CgmfgDTS.mjs";import gn from"./discoverStorageRulesMetadata-D8VYflWt.mjs";import{a as A,c as z,d as Gt,e as pn}from"./classify-procedure-call-BztLe76A.mjs";import{discoverWorkflows as mn}from"./WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{gatePlatformFeatures as hn,resolveCodegenTarget as vn,readTargetDiagnostics as xn}from"./DEFAULT_TARGET-CkKqxaOb.mjs";import{i as k,a as U,e as S,r as En,b as Sn,s as he,c as yn,f as An,d as bn}from"./queries-B-f4jO-x.mjs";import{r as ve,s as Nn}from"./parse-validator-C94Yiabo.mjs";import Pn from"./discoverAuthApiCalls-FxrdBeVt.mjs";import{i as wn,a as In,e as Tn,b as Cn,d as Fn,c as On}from"./unwrap-handler-return-CoV_GK33.mjs";import Rn from"./discoverFunctions-BsmX-sEq.mjs";import Ln from"./discoverHttpRoutes-BcXI9CNt.mjs";import Dn from"./discoverHyperdriveCalls-D9qXqTq3.mjs";import kn from"./discoverInserts-CFJ3IVeI.mjs";import{m as Me,a as ue,s as Yt,d as Mn}from"./index-BoaHhVtM.mjs";import{e as Qt}from"./exported-procedure-chains-CmCDiPBV.mjs";import Kn from"./discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as _n,isDefineMutatorCallee as zn,discoverMutators as $n}from"./MUTATORS_FILENAME-B6cKrN_m.mjs";import Un from"./discoverNondeterministicCalls-CSQ_GDcA.mjs";import{discoverNotifyConfig as qn,discoverNotifyCalls as Bn}from"./NOTIFY_FILENAME-Cri3NT5U.mjs";import jn from"./discoverR2sqlCalls-fu7fC0i_.mjs";import Vn from"./discoverRlsProcedures-BO4qC77y.mjs";import Wn from"./discoverRlsMetadata-CPmAGL0W.mjs";import Hn from"./discoverSchema-QO1eQYjw.mjs";import{secretKindOf as Gn,redact as Yn,isHeuristicSecretKind as Qn,isSecretishName as Xn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Zn}from"./SHAPES_FILENAME-zJgzynXR.mjs";import{emitApp as Jn}from"./emitApp-Pd7CNFXQ.mjs";import{buildOpenApiDocument as er,emitOpenApiModule as tr}from"./buildOpenApiDocument-D1dd4rBh.mjs";import{buildOpenRpcDocument as sr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-DAxS0CaZ.mjs";import{buildSchemaSnapshot as rr}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const ft={error:"ERROR",info:"INFO",warn:"WARN"},gt={ERROR:2,INFO:0,WARN:1},ir=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"}),or=(e,t)=>{const{advisor:s}=zs(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(ft,n)?ft[n]:void 0;return i===void 0?[...t,ir(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(r=>gt[r.level]>=gt[i])},pt=(e,t="api")=>{const s=new Map;for(const n of e){const i=$s(n),r=s.get(i);if(r===void 0){s.set(i,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new K("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},ar=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:r}=t,a=[];e.tables.some(c=>qt(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=>Bt(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:ce)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},cr=(e,t,s={})=>{if(t===void 0)return;const n=ar(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const i=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
2
|
+
`);throw new K("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${i}
|
|
4
4
|
|
|
5
|
-
Install them with your package manager, then re-run codegen.`)},lr="env.ts",ur=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return pe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&pe(n.getModuleSpecifierValue())}return!1},fr=e=>{if(o.isIdentifier(e))return ur(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&dr(t)}return!1},gr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!fr(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ee(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},pr=(e,t)=>{const s=y(t,lr);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=gr(n);if(i.length!==0){if(i.length>1)throw ee(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},mt="ctx",Xt=e=>{const t=new Set,s=new Set([mt]),n=r=>{if(o.isObjectBindingPattern(r))for(const a of r.getElements()){const c=Q(a);c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if(Q(r)!==mt)continue;const a=r.getNameNode();o.isIdentifier(a)?s.add(a.getText()):n(a)}const i=r=>o.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))i(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&i(a)&&n(r.getNameNode())}return t},mr=(e,t)=>{const s=Object.fromEntries(ce.map(n=>[n.key,!1]));for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Xt(i);for(const c of ce)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(ce.every(c=>s[c.key]))break}return s},Jt="identity.ts",hr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return pe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},vr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&pe(n.getModuleSpecifierValue())}return!1},xr=e=>{if(o.isIdentifier(e))return hr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&vr(t)}return!1},Er=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!xr(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ee(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Sr=(e,t)=>{const s=y(t,Jt);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Er(n);if(i.length!==0){if(i.length>1)throw ee(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},yr=(e,t)=>{const s=X(t);if(s===void 0||!o.isIdentifier(s))return s;const n=s.getText();return X(e.getDescendantsOfKind(l.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},Ar=e=>e!==void 0&&o.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t))return E(t)==="durable";if(!o.isPropertyAssignment(t)||E(t)!=="durable")return!1;const s=t.getInitializer();return s===void 0||X(s)?.getText()!=="false"}),br=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Xt(i).has("secrets")),s.durableStreams||(s.durableStreams=i.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(o.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>Ar(yr(i,u)))})),s.durableStreams&&s.secrets)break}return s},Nr="createWorker",Pr="extend",ht=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,vt=e=>{const t=[],s=ht(b(e,"backupCron"));s!==void 0&&t.push(s);const n=b(e,"crons");if(n===void 0||!o.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!o.isPropertyAssignment(i)&&!o.isMethodDeclaration(i))continue;const r=ht(i.getNameNode());r!==void 0&&t.push(r)}return t},wr=e=>{const t=A(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Nr)return o.isObjectLiteralExpression(s)?vt(s):[];if(t!==Pr||!(o.isArrowFunction(s)||o.isFunctionExpression(s)))return[];const n=jt(s.getBody());return n===void 0?[]:vt(n)},Ir=(e,t)=>{const s=[];for(const{filePath:n}of me(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression))s.push(...wr(r))}return[...new Set(s)]},Zt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Zt(e.inner)},Tr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Zt(n);return i!==void 0&&t.has(i)}))},Cr=(e,t)=>{const s=new Map,n=new Map,i=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),i.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(r.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Fr=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,r=Sr(s,t),a=pr(s,t),c=mn(s,t),u=dn(s,t),d=nn(s,t);Cr(c,d);const m=rn(s,t),h=gn(s,t),R=on(s,t,c,d),_=Ir(s,t),g=br(s,t),I=fn(s,t),N=mr(s,t);N.browser=N.browser||I.usesSandboxBrowser;const O=hn(N,vn(n,e.target),{agents:d.length>0,commitOrderedTables:i.tables.some(P=>P.commitOrdered===!0),cronTriggers:R.length>0,crossShardFanout:i.tables.some(P=>typeof P.shardMode=="object"),durableStreams:g.durableStreams,globalTables:i.tables.some(P=>P.shardMode==="global"),queues:u.length>0,relationGraph:Tr(i),secrets:g.secrets,vectorStore:i.vectorIndexes.length>0}),v=O.usage,D=O.signals.vectorStore!==!1,q=un(n),H=q??new Set,te=H.has("lunorash");cr(i,q,{hasVectors:D,scheduler:v.scheduler||R.length>0,storage:v.storage||h.rules.length>0||Object.keys(Ut(i)).length>0,usage:v});const $=w(y(t,"flags.ts")),L=w(y(t,"notify.ts"));return{agents:d,containers:m,crons:R,dataModelContent:qs(i),declaredDependencies:q,dependencies:H,entryCronTriggers:_,env:a,featureUsage:v,hasFlags:$,hasNotify:L,identity:r,platformGate:{...O,diagnostics:[...xn(n,e.target),...O.diagnostics]},queues:u,serverContent:Us({agents:d,containers:m,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:v.browser,hasVectors:D,hasFlags:$,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:L,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:r,queues:u,schema:i,storageRuleBuckets:h.rules.map(P=>P.bucket),useUmbrella:te,workflows:c}),storageRulesMetadata:h,usesSandbox:I.usesSandboxBrowser||I.usesSandboxContainer||I.usesSandboxFs,useUmbrella:te,workflows:c}},es=new Set(["delete","get","head","options","patch","post","put"]),Or=new Set(["handler","stream"]),Rr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,xt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Lr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!es.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Dr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||es.has(n.getName()))break;s=n.getExpression()}return Lr(s)},kr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(xt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&xt.has(s.getText()))return!0}return!1},Mr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!Or.has(n.getName()))return;const i=Dr(s);if(!i||!Rr.test(i.path))return;const r=s.getArguments()[0],a=r!==void 0&&(o.isArrowFunction(r)||o.isFunctionExpression(r))&&kr(r);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},_r=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Mr(i,t);r&&s.push(r)}return s},Kr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(..._r(i,x(t,n)))}return s},zr=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",$r=(e,t)=>{if(!zr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!M(s)||U(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},Ur=(e,t)=>F(e,t,$r),qr=new Set(["generateText","streamText"]),Br=new Set(["messages","prompt","system"]),jr=[{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"]}],Vr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const i of jr)if(i.methods.has(s)&&i.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Wr=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Vr(t);if(s!==void 0)return s}},Hr=e=>{const t=new Set,s=e.getFirstAncestor(r=>o.isArrowFunction(r)||o.isFunctionExpression(r)||o.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const r of i.getElements()){const a=Q(r),c=r.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Gr=e=>{if(En(e))return!0;const t=Hr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Yr=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!Br.has(E(t)))continue;const s=t.getInitializer();if(s!==void 0&&Gr(s))return!0}return!1},Qr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=A(n.getExpression());if(i===void 0||!qr.has(i))continue;const[r]=n.getArguments();if(r===void 0||!o.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(A(c.getExpression())==="tool"&&(a=Wr(c),a!==void 0))break;a!==void 0&&s.push({exportName:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Yr(r)})}return s},Xr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qr(i,x(t,n)))}return s},Jr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},Zr=(e,t)=>{if(!Jr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!M(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},ei=(e,t)=>F(e,t,Zr),_e=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!o.isSpreadAssignment(s))return!1;const n=ve(s.getExpression());return n===void 0||_e(n,t)})}finally{t.delete(e)}},ti=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=C(t,"args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:ve(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:_e(i)}},si=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const i=n.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&o.isExpression(r)?ve(r):void 0;a===void 0?s=!0:(t.push(a),s||=_e(a))}n=i.getExpression()}return{objects:t,opaque:s}},Ke=(e,t)=>t?si(t):ti(e),ts=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(o.isSpreadAssignment(s)){const n=ve(s.getExpression());return n===void 0?[]:ts(n,t)}return o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)?[E(s)]:[]})}finally{t.delete(e)}},ni=e=>e.flatMap(t=>ts(t,new Set)),ri=new Set(["check","length","max"]),Oe=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!(!o.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},ii=e=>[e,...e.getDescendants()].filter(t=>Oe(t)!==void 0),oi=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!o.isCallExpression(n)||n.getExpression()!==s)return!1;if(ri.has(s.getName()))return!0;t=n}},ai=e=>{const t=[],s=[];for(const n of e)for(const i of n.getProperties()){if(!o.isPropertyAssignment(i))continue;const r=i.getInitializer();if(!r)continue;const a=ii(r),c=E(i);a.some(u=>Oe(u)==="any")?t.push(c):a.some(u=>Oe(u)==="string"&&!oi(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},ci=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:i}=Ke(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=ai(i);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},li=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=ci(i,t);r&&s.push(r)}return s},ui=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...li(i,x(t,n)))}return s},Ie=e=>e?.getKind()===l.TrueKeyword,di=e=>e?.getKind()===l.FalseKeyword,fi=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,gi=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),pi=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&A(t.getExpression())==="scim"),mi=e=>e!==void 0&&o.isCallExpression(e)&&gi.has(A(e.getExpression())??""),hi=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),vi=e=>{const t=b(e,"advanced"),s=b(e,"emailAndPassword"),n=b(e,"session");return{analyzable:!0,disableCsrfCheck:Ie(b(t,"disableCSRFCheck")),emailPasswordEnabled:Ie(b(s,"enabled")),requireEmailVerification:Ie(b(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:pi(b(e,"plugins"))&&mi(b(e,"database")),secureCookiesDisabled:di(b(t,"useSecureCookies")),sessionFreshAgeZero:fi(b(n,"freshAge")),trustedOriginsWildcard:hi(b(e,"trustedOrigins"))}},xi=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Ei=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(r=>o.isSpreadAssignment(r)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?vi(s):xi();return{exportName:S(e),file:t,line:e.getStartLineNumber(),...i}},Si=(e,t)=>an(e,t,Ei),yi=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Ai=(e,t,s)=>{const n=yi(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!M(i)||U(i))&&!(s.requireUnmodifiedReach===!0&&!Sn(i)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:n}},bi=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const r=Ai(i,t,s);r&&n.push(r)}return n},xe=(e,t,s)=>{const n=[];for(const i of p(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...bi(r,x(t,i),s))}return n},Ni=new Set(["content","pdf","scrape","screenshot"]),Pi=(e,t)=>xe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ni}),wi=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Ii=new Set(["RateLimiter"]),Ti=new Set(["extend"]),Et="lunora",Ci=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ss=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=E(i);t.push(r),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(E(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Re=e=>e&&o.isObjectLiteralExpression(e)?ss(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Fi=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&jt(t.getBody());return s?ss(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Oi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=A(n.getExpression());i!==void 0&&(wi.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Re(n.getArguments()[0])}):Ti.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Fi(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const i=A(n.getExpression());i===void 0||!Ii.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Re(n.getArguments()[0])})}return s},Ri=(e,t)=>{for(const s of Ci){const n=y(t,s);if(!w(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of i.getDescendantsOfKind(l.CallExpression))A(a.getExpression())===Et&&r.push({callee:Et,file:s,line:a.getStartLineNumber(),...Re(a.getArguments()[0])});return r}return[]},Li=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of me(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Oi(r,n))}return s.push(...Ri(e,ae(t))),s},St="ctx.containers.",Di=e=>{if(!e.startsWith(St))return!1;const t=e.slice(St.length);return t.length>0&&!t.includes(".")},ki=(e,t)=>xe(e,t,{argIndex:0,matchReceiver:Di,methods:new Set(["get"])}),Mi=new Set(["allow","deny","setAllowed"]),_i=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=C(t,"enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Ki=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!_i(e)))return{detail:"enableInternet: true",exportName:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},zi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Mi.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},$i=(e,t)=>Ki(e,t)??zi(e,t),Ui=(e,t)=>F(e,t,$i),qi=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Bi=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return qi.has(s)?s:void 0},ji=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const i=E(n);t.push(i);const r=n.getInitializer();r&&o.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(E(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Vi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of me(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Bi(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?ji(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Wi=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Hi=new Set(["dbRateLimit","rateLimit"]),Gi=e=>{const t=Wt(e);if(!t)return!1;const s=C(t,"failOpen");return s!==void 0&&o.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},Yi=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const n=Wi.get(s);if(n!==void 0)return{callee:s,exportName:S(e),failOpen:Gi(e.getArguments()[n]),file:t,limitName:Hi.has(s)?Vt(e):"",line:e.getStartLineNumber()}},Qi=(e,t)=>F(e,t,Yi),Xi=new Set(["boolean","number","object","string"]),Ji=e=>{const t=e.getName();if(!Xi.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Fe(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Fe(n.getExpression()))return t},Zi=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=Ji(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},eo=(e,t)=>{const s=new Map;for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression)){const a=Zi(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},to=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=cn(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},yt=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},so=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=yt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=yt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},no=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const i=so(n);i!==void 0&&s.push({callee:i,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},ro=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=to(i);r&&s.push(...no(r,t))}return s},io=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ro(i,x(t,n)))}return s},oo=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Fe(t.getExpression())},ao=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},co=(e,t)=>{if(!oo(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),r=ao(n);if(!(i.length===0||r===void 0))return{defaultValue:r,exportName:S(e),file:t,key:i,line:e.getStartLineNumber()}},lo=(e,t)=>F(e,t,co),uo=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),r=i.getText(e);if(!r||r==="any"||r==="never"||wn(r))return;const a=e.getSourceFile().getFilePath();if(In(i,e,a)){const c=Tn(i,e,a,0,new Set);return c===void 0&&Cn(r),c}return r},fo=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},go=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},po=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression))fo(a)&&s.push({file:r,indexName:go(a),line:a.getStartLineNumber()})}return s},J=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,ns=e=>{const t=e.getArguments()[0],s=J(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=C(t,"handler");return n!==void 0&&o.isPropertyAssignment(n)?J(n.getInitializer()):void 0},mo=new Set(["delete","get","head","options","patch","post","put"]),ho=new Set(["handler","stream"]),vo=new Set(["runAction","runMutation"]),xo=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Z=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,rs=(e,t)=>{if(!(e===void 0||!o.isObjectBindingPattern(e))){for(const s of e.getElements())if(Q(s)===t){const i=s.getNameNode();return o.isIdentifier(i)?i.getText():void 0}}},At=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?o.isIdentifier(s)?s.getText():void 0:rs(s,"ctx")},bt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&o.isIdentifier(s)?s.getText():void 0:rs(s,"request")},Nt=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const i of n){const r=i.getExpression();if(!o.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(vo.has(a)&&Z(c,t))return a;if(xo.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&Z(c.getExpression(),t))return`db.${a}`}},Pt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Z(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getNameNode();if(!(!o.isObjectBindingPattern(i)||!Z(n.getInitializer(),t))){for(const r of i.getElements())if(Q(r)==="auth")return!0}}return!1},Eo=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,So=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return o.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Z(n.getExpression(),t)},yo=e=>[...o.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],is=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:yo(s)},Ao=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!o.isArrowFunction(n)&&!o.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!o.isCallExpression(i))return[];const r=i.getExpression();if(!o.isPropertyAccessExpression(r))return[];const a=r.getExpression();return o.isIdentifier(a)?is(t,a.getText()):[]}return[]},bo=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(o.isStringLiteral(t))return[t.getLiteralText()];if(!o.isIdentifier(t))return[];const s=e.getSourceFile(),n=is(s,t.getText());return n.length>0?n:Ao(t,s)},wt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return o.isCallExpression(s)&&n.unshift(s),n.some(i=>So(i,t)&&bo(i).some(r=>Eo.test(r)))},No=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ho.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const i=n.getName();if(mo.has(i)){const r=n.getExpression();return o.isIdentifier(r)&&r.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Po=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=J(e.getArguments()[0]),u=c&&At(c,!0);if(!c||u===void 0||wt(c,bt(c,!0)))return;const d=Nt(c,u);return d===void 0?void 0:{exportName:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Pt(c,u),sideEffect:d}}const n=No(e);if(n===void 0)return;const i=J(e.getArguments()[0]),r=i&&At(i,!1);if(!i||r===void 0||wt(i,bt(i,!1)))return;const a=Nt(i,r);return a===void 0?void 0:{exportName:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Pt(i,r),sideEffect:a}},wo=(e,t)=>F(e,t,Po),Io=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),To=new Set(["append","set"]),os=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",It=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Io.has(A(n.getExpression())??"")&&An(n,t)),Co=(e,t)=>{if(It(e,t))return!0;const s=he(e);return s!==void 0&&It(s,t)},Le=(e,t)=>yn(e,t)&&!Co(e,t),Fo=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=he(e);return t!==void 0&&o.isNewExpression(t)&&A(t.getExpression())==="Headers"},de=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=he(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},ze=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Le(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:os(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Le(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:E(n),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const i=de(n.getExpression());i!==void 0&&ze(i,t,s)}},as=(e,t)=>{const s=de(e);if(s===void 0)return;const n=C(s,"headers");if(n===void 0||!o.isPropertyAssignment(n))return;const i=de(n.getInitializer());i!==void 0&&ze(i,"response-init",t)},Oo=(e,t)=>{const s=A(e.getExpression());if(s==="Response")as(e.getArguments()[1],t);else if(s==="Headers"){const n=de(e.getArguments()[0]);n!==void 0&&ze(n,"headers-ctor",t)}},Ro=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){as(e.getArguments()[1],t);return}if(To.has(n)&&Fo(i)){const r=e.getArguments()[1];r!==void 0&&Le(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:os(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Lo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Oo(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Ro(s,t)},Do=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=J(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const r=i.getNameNode();if(!o.isIdentifier(r))return[];const a=[];return Lo(n,{exportName:S(e),relativePath:t,requestName:r.getText(),rows:a}),a},ko=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Do(n,t));return s},Mo=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ko(i,x(t,n)))}return s},_o=new Set(["auth","context.auth","ctx.auth"]),Ko="userId",zo=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(E(s))}return t},$o=(e,t)=>{const s=y(t,Jt);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){if(A(i.getExpression())!=="defineIdentity")continue;const[r]=i.getArguments();return r&&o.isObjectLiteralExpression(r)?zo(r):void 0}},Tt=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return _o.has(e.getExpression().getText())?e:void 0},Uo=e=>{if(o.isPropertyAccessExpression(e)&&Tt(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&Tt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},qo=(e,t,s)=>{const n=[];for(const i of e.getDescendants()){const r=Uo(i);r!==void 0&&n.push({declared:r===Ko||s.has(r),exportName:S(i),file:t,key:r,line:i.getStartLineNumber()})}return n},Bo=(e,t)=>{const s=$o(e,t);if(s===void 0)return[];const n=[];for(const i of p(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...qo(r,x(t,i),s))}return n},jo=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=b(s,"key");if(!(!n||!M(n)||U(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},Vo=(e,t)=>F(e,t,jo),Wo=e=>{if(o.isComputedPropertyName(e)){const t=e.getExpression();return o.isStringLiteral(t)||o.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return o.isStringLiteral(e)?e.getLiteralValue():e.getText()},Ho=e=>e.getProperties().some(t=>{if(o.isSpreadAssignment(t))return!0;const s=Wo(t.getNameNode());return s===void 0||s==="namespace"}),Go=(e,t)=>{for(const{filePath:s}of me(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){const r=i.getExpression(),[a]=i.getArguments();if(!(!o.isPropertyAccessExpression(r)||r.getName()!=="auth"||a===void 0)&&(!o.isObjectLiteralExpression(a)||Ho(a)))return i}}},Yo="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Qo=(e,t,s)=>{if(e.jurisdiction===void 0||e.jurisdictionPinsAuthAndVoice===!0)return;const n=t.filter(a=>a.voice===!0).map(a=>`"${a.exportName}"`),i=[...s===void 0?[]:["DO-backed auth (users, sessions, accounts, credentials)"],...n.length===0?[]:[`the voice sessions of agent(s) ${n.join(", ")} (transcripts)`]];if(i.length===0)return;const r=`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has ${i.join(" and ")}. Those objects are now pinned too, which resolves them to NEW, EMPTY objects: existing data stays in the unpinned ones. Move or discard that data first (${Yo}), then acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuthAndVoice: true })\`. For D1-mode auth the acknowledgement changes nothing.`;throw s!==void 0?ee(s,r,{code:"JURISDICTION_MOVE",status:422}):new k("JURISDICTION_MOVE",`@lunora/codegen: ${r}`,{status:422})},Xo=new Set(["delete","get","getRaw","getWithMetadata","put"]),Jo=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return xe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:Xo}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Zo=new Set(["queue","send"]),Ct=new Set(["bcc","cc","to"]),ea=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Zo.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},ta=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ct.has(E(t))&&M(n)&&!U(n)}if(!o.isPropertyAssignment(t)||!Ct.has(E(t)))return!1;const s=t.getInitializer();return s!==void 0&&M(s)&&!U(s)}):!1,sa=(e,t)=>{const s=ea(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!ta(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},na=(e,t)=>F(e,t,sa),ra=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,ia=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?ra(e):!0,cs=(e,t=!1)=>{for(const s of e.getProperties()){if(ia(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||cs(n,!0))return!0}return!1},oa=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Qt(n))for(const r of Me(i)){const a=r.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||cs(a)))return!0}}return!1},aa=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=ue(n);if(i===void 0||!o.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!o.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=ue(a);c!==void 0&&s.push({column:c,strategy:Yt(a),table:i})}}return s},ca=(e,t)=>{const s=new Map;for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Qt(i))for(const a of Me(r))for(const c of aa(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},la=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){const a=ue(r);if(a===void 0||!o.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=ue(u);if(d===void 0)continue;const m=Yt(u);m!=="custom"&&i.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:m,table:a})}}return i},ua=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;return n?.receiver?Me(n.receiver).flatMap(i=>la(i,e.getName(),t)):[]},da=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ua(c,r))}return s},fa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return K(s)},ga=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=C(t,"server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},pa=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return zn(s.getExpression())?s:void 0},ma=e=>{const t=pa(e),s=t===void 0?void 0:ga(t);if(s===void 0)return[];const n=e.getNameNode(),i=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>fa(r)).map(r=>({exportName:i,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},ha=e=>e.getVariableDeclarations().flatMap(t=>ma(t)),va=(e,t)=>{const s=y(t,Kn);if(!w(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return ha(n)},xa=new Set(["delete","get","patch"]),Ea=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Sa=new Set(["auth","identity","session","user"]),ya=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Aa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!K(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},ba=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},Na=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Pa=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,wa=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Na(s.getExpression(),t)&&Pa(s.getThenStatement())),Ia=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const i=n.getName();if(!xa.has(i))continue;const r=n.getExpression();if(!(K(r)||o.isPropertyAccessExpression(r)&&K(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return i}},Ta=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},Ca=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Ta(s)==="ctx")),Fa=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>ya.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),Oa=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Ea.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Sa.has(t.getName()))return!0}return Ca(e)||Fa(e)},Ra=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=ns(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Gt(n.receiver,"use","rls"),a=Oa(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const m=Aa(d);if(m===void 0)continue;const h=ba(d);if(h===void 0||c.has(h)||!wa(i,h))continue;const R=Ia(i,h);R!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,table:m,usesRls:r,visibility:n.visibility}))}return u},La=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ra(c,r))}return s},Da=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ka=new Set(["insert","insertManyUnsafe","patch","replace"]),Ma=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!ka.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},_a=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},Ft=(e,t)=>{if(o.isPropertyAccessExpression(e)){const s=e.getExpression();return o.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(o.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return o.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&o.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},Ka=e=>{if(!o.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(o.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let i,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!o.isVariableDeclarationList(c)||c.getDeclarationKind()!==Ms.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(i=u,r=d)}return i},za=(e,t)=>{if(Ft(e,t))return!0;const s=Ka(e);return s!==void 0&&Ft(s,t)},$a=(e,t,s,n,i)=>{const r=[];for(const a of e.getProperties()){let c,u;if(o.isPropertyAssignment(a)?(c=E(a),u=a.getInitializer()):o.isShorthandPropertyAssignment(a)&&(c=E(a),u=a.getNameNode()),!(c===void 0||u===void 0||!Da.has(c))&&M(u)&&!U(u)){const d=S(s),m=i(d)===c&&za(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...m&&{ownerScoped:!0}})}}return r},Ua=(e,t,s)=>{const n=Ma(e.getExpression());if(n===void 0)return[];const i=e.getArguments()[1];return i?_a(i,n).flatMap(r=>$a(r,n,e,t,s)):[]},qa=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const r of Ua(i,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Ba=(e,t,s=[],n=[])=>{const i=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of p(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);i.push(...qa(c,u,d=>r.get(`${u}:${d}`)??{}))}return i},ja=["providerSubscriptionId","state"],Va=["providerEventId","processedAt"],Ot=(e,t)=>t.every(s=>s in e.shape),Wa=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Ot(t,ja)&&Ot(s,Va)},Ha=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Ga=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ya=e=>{const t=C(e,"webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?Ga(t.getInitializer()):void 0},Qa=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Ha.has(s))return;const[n]=e.getArguments(),i=n&&o.isObjectLiteralExpression(n)?Ya(n):void 0;return{callee:s,exportName:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Xa=(e,t)=>F(e,t,Qa),Ja=new Set(["defineQueue","defineWorkflow"]),Za=new Set(["run","runAction","runMutation","runQuery"]),ec=new Set(["api","internal"]),tc=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},sc=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=C(t,"handler");if(s===void 0||!o.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(o.isArrowFunction(n)||o.isFunctionExpression(n)))return n},ls=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},us=(e,t)=>e===t||e.startsWith(`${t}.`),ds=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},Rt=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},fs=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Rt(s));return o.isIdentifier(e)&&Rt(e)&&t.push(e),t},nc=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},rc=e=>{const t=ls(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),r=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;r&&o.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ic=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:rc(e),i=new Set,r=a=>ds(a).some(c=>n.some(u=>us(c.getText(),u)))?!0:fs(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of nc(a))i.add(u)}return{names:i,prefixes:n}},oc=(e,t)=>ds(e).some(s=>t.prefixes.some(n=>us(s.getText(),n)))?!0:fs(e).some(s=>t.names.has(s.getText())),ac=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!ec.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},cc=(e,t,s)=>{const n=ls(e,0);if(n===void 0)return[];const i=ic(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!Za.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!oc(u,i))continue;const d=ac(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:S(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},lc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=tc(n);if(i===void 0||!Ja.has(i))continue;const r=sc(n);r!==void 0&&s.push(...cc(r,i==="defineQueue"?"queue":"workflow",t))}return s},uc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lc(i,x(t,n)))}return s},Lt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Dt=new Set(["account","credential","member","passkey","session","user"]),dc=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),fc=e=>{const s=dc(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Dt.has(s)||Dt.has(n)},gc=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},pc=(e,t)=>{const{objects:s,opaque:n}=Ke(e,t);return ni(s).some(i=>gc(i))?!0:n?void 0:!1},mc=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!C(t,"captcha"),usesRateLimit:!!C(t,"rateLimit")}},hc=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},le={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},vc=e=>{const t=hc(e),s=t?A(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=mc(t);return{...le,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Lt?{...le,[Lt[s]]:!0}:le},xc=e=>{const t={...le};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const r=vc(i);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Ec=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Sc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Ec.has(t.getName()))return!1;const s=t.getExpression();if(!K(s))return!1;const i=e.getArguments()[0];return!i||!(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))?!1:fc(i.getLiteralText())},yc=new Set(["create","runAfter","runAt","send","sendBatch"]),Ac=new Set(["queues","scheduler","workflows"]),bc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!yc.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Ac.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return K(s)},gs=new Set(["generateObject","generateText","streamObject","streamText"]),Pc=e=>{const t=A(e.getExpression());return t!==void 0&&gs.has(t)},wc=e=>{const t=A(e.getExpression());if(t===void 0||!gs.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!C(s,"maxOutputTokens")},Ic=new Set(["log","span","trace"]),Tc=new Set(["ai"]),Cc=new Set(["email","mail"]),Fc=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),Te=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),Oc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Rc=new Set(["every","filter","flatMap","forEach","map","some"]),Lc=new Set(["all","allSettled","race"]),Dc=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(Rc.has(n))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&Lc.has(n))return t},kc=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Oc.has(t.getKind())){const s=Dc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Mc=e=>{let t=e;for(;;){const s=t.getParent();if(!o.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(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},_c=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Kc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Fc.has(n.getName()))continue;const i=n.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const r=_c(n);r&&(t=!0,!kc(r)&&!Mc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},zc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),kt="lunora-advisor-exempt",$c=/^[\s*/]+/u,Uc=/[\w-]/u,qc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
5
|
+
Install them with your package manager, then re-run codegen.`)},lr="env.ts",ur=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return pe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&pe(n.getModuleSpecifierValue())}return!1},fr=e=>{if(o.isIdentifier(e))return ur(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&dr(t)}return!1},gr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!fr(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ee(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},pr=(e,t)=>{const s=y(t,lr);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=gr(n);if(i.length!==0){if(i.length>1)throw ee(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},mt="ctx",Xt=e=>{const t=new Set,s=new Set([mt]),n=r=>{if(o.isObjectBindingPattern(r))for(const a of r.getElements()){const c=Q(a);c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if(Q(r)!==mt)continue;const a=r.getNameNode();o.isIdentifier(a)?s.add(a.getText()):n(a)}const i=r=>o.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))i(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&i(a)&&n(r.getNameNode())}return t},mr=(e,t)=>{const s=Object.fromEntries(ce.map(n=>[n.key,!1]));for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Xt(i);for(const c of ce)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(ce.every(c=>s[c.key]))break}return s},Zt="identity.ts",hr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return pe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},vr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&pe(n.getModuleSpecifierValue())}return!1},xr=e=>{if(o.isIdentifier(e))return hr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&vr(t)}return!1},Er=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!xr(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ee(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Sr=(e,t)=>{const s=y(t,Zt);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Er(n);if(i.length!==0){if(i.length>1)throw ee(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},yr=(e,t)=>{const s=X(t);if(s===void 0||!o.isIdentifier(s))return s;const n=s.getText();return X(e.getDescendantsOfKind(l.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},Ar=e=>e!==void 0&&o.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t))return E(t)==="durable";if(!o.isPropertyAssignment(t)||E(t)!=="durable")return!1;const s=t.getInitializer();return s===void 0||X(s)?.getText()!=="false"}),br=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Xt(i).has("secrets")),s.durableStreams||(s.durableStreams=i.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(o.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>Ar(yr(i,u)))})),s.durableStreams&&s.secrets)break}return s},Nr="createWorker",Pr="extend",ht=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,vt=e=>{const t=[],s=ht(b(e,"backupCron"));s!==void 0&&t.push(s);const n=b(e,"crons");if(n===void 0||!o.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!o.isPropertyAssignment(i)&&!o.isMethodDeclaration(i))continue;const r=ht(i.getNameNode());r!==void 0&&t.push(r)}return t},wr=e=>{const t=A(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Nr)return o.isObjectLiteralExpression(s)?vt(s):[];if(t!==Pr||!(o.isArrowFunction(s)||o.isFunctionExpression(s)))return[];const n=jt(s.getBody());return n===void 0?[]:vt(n)},Ir=(e,t)=>{const s=[];for(const{filePath:n}of me(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression))s.push(...wr(r))}return[...new Set(s)]},Jt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Jt(e.inner)},Tr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Jt(n);return i!==void 0&&t.has(i)}))},Cr=(e,t)=>{const s=new Map,n=new Map,i=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),i.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new K("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new K("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(r.className);if(u!==void 0)throw new K("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Fr=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,r=Sr(s,t),a=pr(s,t),c=mn(s,t),u=dn(s,t),d=nn(s,t);Cr(c,d);const m=rn(s,t),h=gn(s,t),R=on(s,t,c,d),M=Ir(s,t),g=br(s,t),I=fn(s,t),N=mr(s,t);N.browser=N.browser||I.usesSandboxBrowser;const O=hn(N,vn(n,e.target),{agents:d.length>0,commitOrderedTables:i.tables.some(P=>P.commitOrdered===!0),cronTriggers:R.length>0,crossShardFanout:i.tables.some(P=>typeof P.shardMode=="object"),durableStreams:g.durableStreams,globalTables:i.tables.some(P=>P.shardMode==="global"),queues:u.length>0,relationGraph:Tr(i),secrets:g.secrets,vectorStore:i.vectorIndexes.length>0}),v=O.usage,D=O.signals.vectorStore!==!1,q=un(n),H=q??new Set,te=H.has("lunorash");cr(i,q,{hasVectors:D,scheduler:v.scheduler||R.length>0,storage:v.storage||h.rules.length>0||Object.keys(Ut(i)).length>0,usage:v});const $=w(y(t,"flags.ts")),L=w(y(t,"notify.ts"));return{agents:d,containers:m,crons:R,dataModelContent:qs(i),declaredDependencies:q,dependencies:H,entryCronTriggers:M,env:a,featureUsage:v,hasFlags:$,hasNotify:L,identity:r,platformGate:{...O,diagnostics:[...xn(n,e.target),...O.diagnostics]},queues:u,serverContent:Us({agents:d,containers:m,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:v.browser,hasVectors:D,hasFlags:$,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:L,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:r,queues:u,schema:i,storageRuleBuckets:h.rules.map(P=>P.bucket),useUmbrella:te,workflows:c}),storageRulesMetadata:h,usesSandbox:I.usesSandboxBrowser||I.usesSandboxContainer||I.usesSandboxFs,useUmbrella:te,workflows:c}},es=new Set(["delete","get","head","options","patch","post","put"]),Or=new Set(["handler","stream"]),Rr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,xt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Lr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!es.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Dr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||es.has(n.getName()))break;s=n.getExpression()}return Lr(s)},kr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(xt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&xt.has(s.getText()))return!0}return!1},Mr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!Or.has(n.getName()))return;const i=Dr(s);if(!i||!Rr.test(i.path))return;const r=s.getArguments()[0],a=r!==void 0&&(o.isArrowFunction(r)||o.isFunctionExpression(r))&&kr(r);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Kr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Mr(i,t);r&&s.push(r)}return s},_r=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Kr(i,x(t,n)))}return s},zr=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",$r=(e,t)=>{if(!zr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!k(s)||U(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},Ur=(e,t)=>F(e,t,$r),qr=new Set(["generateText","streamText"]),Br=new Set(["messages","prompt","system"]),jr=[{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"]}],Vr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const i of jr)if(i.methods.has(s)&&i.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Wr=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Vr(t);if(s!==void 0)return s}},Hr=e=>{const t=new Set,s=e.getFirstAncestor(r=>o.isArrowFunction(r)||o.isFunctionExpression(r)||o.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const r of i.getElements()){const a=Q(r),c=r.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Gr=e=>{if(En(e))return!0;const t=Hr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Yr=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!Br.has(E(t)))continue;const s=t.getInitializer();if(s!==void 0&&Gr(s))return!0}return!1},Qr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=A(n.getExpression());if(i===void 0||!qr.has(i))continue;const[r]=n.getArguments();if(r===void 0||!o.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(A(c.getExpression())==="tool"&&(a=Wr(c),a!==void 0))break;a!==void 0&&s.push({exportName:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Yr(r)})}return s},Xr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qr(i,x(t,n)))}return s},Zr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},Jr=(e,t)=>{if(!Zr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!k(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},ei=(e,t)=>F(e,t,Jr),Ke=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!o.isSpreadAssignment(s))return!1;const n=ve(s.getExpression());return n===void 0||Ke(n,t)})}finally{t.delete(e)}},ti=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=C(t,"args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:ve(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Ke(i)}},si=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const i=n.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&o.isExpression(r)?ve(r):void 0;a===void 0?s=!0:(t.push(a),s||=Ke(a))}n=i.getExpression()}return{objects:t,opaque:s}},_e=(e,t)=>t?si(t):ti(e),ts=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(o.isSpreadAssignment(s)){const n=ve(s.getExpression());return n===void 0?[]:ts(n,t)}return o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)?[E(s)]:[]})}finally{t.delete(e)}},ni=e=>e.flatMap(t=>ts(t,new Set)),ri=new Set(["check","length","max"]),Oe=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!(!o.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},ii=e=>[e,...e.getDescendants()].filter(t=>Oe(t)!==void 0),oi=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!o.isCallExpression(n)||n.getExpression()!==s)return!1;if(ri.has(s.getName()))return!0;t=n}},ai=e=>{const t=[],s=[];for(const n of e)for(const i of n.getProperties()){if(!o.isPropertyAssignment(i))continue;const r=i.getInitializer();if(!r)continue;const a=ii(r),c=E(i);a.some(u=>Oe(u)==="any")?t.push(c):a.some(u=>Oe(u)==="string"&&!oi(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},ci=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:i}=_e(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=ai(i);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},li=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=ci(i,t);r&&s.push(r)}return s},ui=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...li(i,x(t,n)))}return s},Ie=e=>e?.getKind()===l.TrueKeyword,di=e=>e?.getKind()===l.FalseKeyword,fi=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,gi=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),pi=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&A(t.getExpression())==="scim"),mi=e=>e!==void 0&&o.isCallExpression(e)&&gi.has(A(e.getExpression())??""),hi=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),vi=e=>{const t=b(e,"advanced"),s=b(e,"emailAndPassword"),n=b(e,"session");return{analyzable:!0,disableCsrfCheck:Ie(b(t,"disableCSRFCheck")),emailPasswordEnabled:Ie(b(s,"enabled")),requireEmailVerification:Ie(b(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:pi(b(e,"plugins"))&&mi(b(e,"database")),secureCookiesDisabled:di(b(t,"useSecureCookies")),sessionFreshAgeZero:fi(b(n,"freshAge")),trustedOriginsWildcard:hi(b(e,"trustedOrigins"))}},xi=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Ei=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(r=>o.isSpreadAssignment(r)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?vi(s):xi();return{exportName:S(e),file:t,line:e.getStartLineNumber(),...i}},Si=(e,t)=>an(e,t,Ei),yi=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Ai=(e,t,s)=>{const n=yi(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!k(i)||U(i))&&!(s.requireUnmodifiedReach===!0&&!Sn(i)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:n}},bi=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const r=Ai(i,t,s);r&&n.push(r)}return n},xe=(e,t,s)=>{const n=[];for(const i of p(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...bi(r,x(t,i),s))}return n},Ni=new Set(["content","pdf","scrape","screenshot"]),Pi=(e,t)=>xe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ni}),wi=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Ii=new Set(["RateLimiter"]),Ti=new Set(["extend"]),Et="lunora",Ci=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ss=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=E(i);t.push(r),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(E(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Re=e=>e&&o.isObjectLiteralExpression(e)?ss(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Fi=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&jt(t.getBody());return s?ss(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Oi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=A(n.getExpression());i!==void 0&&(wi.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Re(n.getArguments()[0])}):Ti.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Fi(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const i=A(n.getExpression());i===void 0||!Ii.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Re(n.getArguments()[0])})}return s},Ri=(e,t)=>{for(const s of Ci){const n=y(t,s);if(!w(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of i.getDescendantsOfKind(l.CallExpression))A(a.getExpression())===Et&&r.push({callee:Et,file:s,line:a.getStartLineNumber(),...Re(a.getArguments()[0])});return r}return[]},Li=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of me(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Oi(r,n))}return s.push(...Ri(e,ae(t))),s},St="ctx.containers.",Di=e=>{if(!e.startsWith(St))return!1;const t=e.slice(St.length);return t.length>0&&!t.includes(".")},ki=(e,t)=>xe(e,t,{argIndex:0,matchReceiver:Di,methods:new Set(["get"])}),Mi=new Set(["allow","deny","setAllowed"]),Ki=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=C(t,"enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},_i=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Ki(e)))return{detail:"enableInternet: true",exportName:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},zi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Mi.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},$i=(e,t)=>_i(e,t)??zi(e,t),Ui=(e,t)=>F(e,t,$i),qi=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Bi=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return qi.has(s)?s:void 0},ji=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const i=E(n);t.push(i);const r=n.getInitializer();r&&o.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(E(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Vi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of me(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Bi(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?ji(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Wi=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Hi=new Set(["dbRateLimit","rateLimit"]),Gi=e=>{const t=Wt(e);if(!t)return!1;const s=C(t,"failOpen");return s!==void 0&&o.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},Yi=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const n=Wi.get(s);if(n!==void 0)return{callee:s,exportName:S(e),failOpen:Gi(e.getArguments()[n]),file:t,limitName:Hi.has(s)?Vt(e):"",line:e.getStartLineNumber()}},Qi=(e,t)=>F(e,t,Yi),Xi=new Set(["boolean","number","object","string"]),Zi=e=>{const t=e.getName();if(!Xi.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Fe(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Fe(n.getExpression()))return t},Ji=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=Zi(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},eo=(e,t)=>{const s=new Map;for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression)){const a=Ji(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},to=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=cn(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},yt=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},so=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=yt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=yt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},no=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const i=so(n);i!==void 0&&s.push({callee:i,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},ro=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=to(i);r&&s.push(...no(r,t))}return s},io=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ro(i,x(t,n)))}return s},oo=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Fe(t.getExpression())},ao=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},co=(e,t)=>{if(!oo(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),r=ao(n);if(!(i.length===0||r===void 0))return{defaultValue:r,exportName:S(e),file:t,key:i,line:e.getStartLineNumber()}},lo=(e,t)=>F(e,t,co),uo=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),r=i.getText(e);if(!r||r==="any"||r==="never"||wn(r))return;const a=e.getSourceFile().getFilePath();if(In(i,e,a)){const c=Tn(i,e,a,0,new Set);return c===void 0&&Cn(r),c}return r},fo=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},go=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},po=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression))fo(a)&&s.push({file:r,indexName:go(a),line:a.getStartLineNumber()})}return s},Z=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,ns=e=>{const t=e.getArguments()[0],s=Z(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=C(t,"handler");return n!==void 0&&o.isPropertyAssignment(n)?Z(n.getInitializer()):void 0},mo=new Set(["delete","get","head","options","patch","post","put"]),ho=new Set(["handler","stream"]),vo=new Set(["runAction","runMutation"]),xo=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),J=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,rs=(e,t)=>{if(!(e===void 0||!o.isObjectBindingPattern(e))){for(const s of e.getElements())if(Q(s)===t){const i=s.getNameNode();return o.isIdentifier(i)?i.getText():void 0}}},At=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?o.isIdentifier(s)?s.getText():void 0:rs(s,"ctx")},bt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&o.isIdentifier(s)?s.getText():void 0:rs(s,"request")},Nt=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const i of n){const r=i.getExpression();if(!o.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(vo.has(a)&&J(c,t))return a;if(xo.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&J(c.getExpression(),t))return`db.${a}`}},Pt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&J(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getNameNode();if(!(!o.isObjectBindingPattern(i)||!J(n.getInitializer(),t))){for(const r of i.getElements())if(Q(r)==="auth")return!0}}return!1},Eo=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,So=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return o.isPropertyAccessExpression(n)&&n.getName()==="headers"&&J(n.getExpression(),t)},yo=e=>[...o.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],is=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:yo(s)},Ao=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!o.isArrowFunction(n)&&!o.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!o.isCallExpression(i))return[];const r=i.getExpression();if(!o.isPropertyAccessExpression(r))return[];const a=r.getExpression();return o.isIdentifier(a)?is(t,a.getText()):[]}return[]},bo=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(o.isStringLiteral(t))return[t.getLiteralText()];if(!o.isIdentifier(t))return[];const s=e.getSourceFile(),n=is(s,t.getText());return n.length>0?n:Ao(t,s)},wt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return o.isCallExpression(s)&&n.unshift(s),n.some(i=>So(i,t)&&bo(i).some(r=>Eo.test(r)))},No=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ho.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const i=n.getName();if(mo.has(i)){const r=n.getExpression();return o.isIdentifier(r)&&r.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Po=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Z(e.getArguments()[0]),u=c&&At(c,!0);if(!c||u===void 0||wt(c,bt(c,!0)))return;const d=Nt(c,u);return d===void 0?void 0:{exportName:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Pt(c,u),sideEffect:d}}const n=No(e);if(n===void 0)return;const i=Z(e.getArguments()[0]),r=i&&At(i,!1);if(!i||r===void 0||wt(i,bt(i,!1)))return;const a=Nt(i,r);return a===void 0?void 0:{exportName:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Pt(i,r),sideEffect:a}},wo=(e,t)=>F(e,t,Po),Io=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),To=new Set(["append","set"]),os=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",It=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Io.has(A(n.getExpression())??"")&&An(n,t)),Co=(e,t)=>{if(It(e,t))return!0;const s=he(e);return s!==void 0&&It(s,t)},Le=(e,t)=>yn(e,t)&&!Co(e,t),Fo=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=he(e);return t!==void 0&&o.isNewExpression(t)&&A(t.getExpression())==="Headers"},de=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=he(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},ze=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Le(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:os(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Le(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:E(n),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const i=de(n.getExpression());i!==void 0&&ze(i,t,s)}},as=(e,t)=>{const s=de(e);if(s===void 0)return;const n=C(s,"headers");if(n===void 0||!o.isPropertyAssignment(n))return;const i=de(n.getInitializer());i!==void 0&&ze(i,"response-init",t)},Oo=(e,t)=>{const s=A(e.getExpression());if(s==="Response")as(e.getArguments()[1],t);else if(s==="Headers"){const n=de(e.getArguments()[0]);n!==void 0&&ze(n,"headers-ctor",t)}},Ro=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){as(e.getArguments()[1],t);return}if(To.has(n)&&Fo(i)){const r=e.getArguments()[1];r!==void 0&&Le(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:os(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Lo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Oo(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Ro(s,t)},Do=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Z(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const r=i.getNameNode();if(!o.isIdentifier(r))return[];const a=[];return Lo(n,{exportName:S(e),relativePath:t,requestName:r.getText(),rows:a}),a},ko=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Do(n,t));return s},Mo=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ko(i,x(t,n)))}return s},Ko=new Set(["auth","context.auth","ctx.auth"]),_o="userId",zo=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(E(s))}return t},$o=(e,t)=>{const s=y(t,Zt);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){if(A(i.getExpression())!=="defineIdentity")continue;const[r]=i.getArguments();return r&&o.isObjectLiteralExpression(r)?zo(r):void 0}},Tt=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Ko.has(e.getExpression().getText())?e:void 0},Uo=e=>{if(o.isPropertyAccessExpression(e)&&Tt(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&Tt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},qo=(e,t,s)=>{const n=[];for(const i of e.getDescendants()){const r=Uo(i);r!==void 0&&n.push({declared:r===_o||s.has(r),exportName:S(i),file:t,key:r,line:i.getStartLineNumber()})}return n},Bo=(e,t)=>{const s=$o(e,t);if(s===void 0)return[];const n=[];for(const i of p(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...qo(r,x(t,i),s))}return n},jo=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=b(s,"key");if(!(!n||!k(n)||U(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},Vo=(e,t)=>F(e,t,jo),Wo=e=>{if(o.isComputedPropertyName(e)){const t=e.getExpression();return o.isStringLiteral(t)||o.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return o.isStringLiteral(e)?e.getLiteralValue():e.getText()},Ho=e=>e.getProperties().some(t=>{if(o.isSpreadAssignment(t))return!0;const s=Wo(t.getNameNode());return s===void 0||s==="namespace"}),Go=(e,t)=>{for(const{filePath:s}of me(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){const r=i.getExpression(),[a]=i.getArguments();if(!(!o.isPropertyAccessExpression(r)||r.getName()!=="auth"||a===void 0)&&(!o.isObjectLiteralExpression(a)||Ho(a)))return i}}},Yo="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Qo=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ee(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 (${Yo}). 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})},Xo=new Set(["delete","get","getRaw","getWithMetadata","put"]),Zo=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return xe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:Xo}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Jo=new Set(["queue","send"]),Ct=new Set(["bcc","cc","to"]),ea=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Jo.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},ta=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ct.has(E(t))&&k(n)&&!U(n)}if(!o.isPropertyAssignment(t)||!Ct.has(E(t)))return!1;const s=t.getInitializer();return s!==void 0&&k(s)&&!U(s)}):!1,sa=(e,t)=>{const s=ea(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!ta(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},na=(e,t)=>F(e,t,sa),ra=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,ia=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?ra(e):!0,cs=(e,t=!1)=>{for(const s of e.getProperties()){if(ia(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||cs(n,!0))return!0}return!1},oa=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Qt(n))for(const r of Me(i)){const a=r.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||cs(a)))return!0}}return!1},aa=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=ue(n);if(i===void 0||!o.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!o.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=ue(a);c!==void 0&&s.push({column:c,strategy:Yt(a),table:i})}}return s},ca=(e,t)=>{const s=new Map;for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Qt(i))for(const a of Me(r))for(const c of aa(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},la=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){const a=ue(r);if(a===void 0||!o.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=ue(u);if(d===void 0)continue;const m=Yt(u);m!=="custom"&&i.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:m,table:a})}}return i},ua=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;return n?.receiver?Me(n.receiver).flatMap(i=>la(i,e.getName(),t)):[]},da=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ua(c,r))}return s},fa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},ga=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=C(t,"server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},pa=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return zn(s.getExpression())?s:void 0},ma=e=>{const t=pa(e),s=t===void 0?void 0:ga(t);if(s===void 0)return[];const n=e.getNameNode(),i=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>fa(r)).map(r=>({exportName:i,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},ha=e=>e.getVariableDeclarations().flatMap(t=>ma(t)),va=(e,t)=>{const s=y(t,_n);if(!w(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return ha(n)},xa=new Set(["delete","get","patch"]),Ea=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Sa=new Set(["auth","identity","session","user"]),ya=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Aa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},ba=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},Na=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Pa=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,wa=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Na(s.getExpression(),t)&&Pa(s.getThenStatement())),Ia=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const i=n.getName();if(!xa.has(i))continue;const r=n.getExpression();if(!(_(r)||o.isPropertyAccessExpression(r)&&_(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return i}},Ta=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},Ca=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Ta(s)==="ctx")),Fa=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>ya.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),Oa=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Ea.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Sa.has(t.getName()))return!0}return Ca(e)||Fa(e)},Ra=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=ns(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Gt(n.receiver,"use","rls"),a=Oa(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const m=Aa(d);if(m===void 0)continue;const h=ba(d);if(h===void 0||c.has(h)||!wa(i,h))continue;const R=Ia(i,h);R!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,table:m,usesRls:r,visibility:n.visibility}))}return u},La=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ra(c,r))}return s},Da=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ka=new Set(["insert","insertManyUnsafe","patch","replace"]),Ma=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!ka.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},Ka=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},Ft=(e,t)=>{if(o.isPropertyAccessExpression(e)){const s=e.getExpression();return o.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(o.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return o.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&o.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},_a=e=>{if(!o.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(o.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let i,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!o.isVariableDeclarationList(c)||c.getDeclarationKind()!==Ms.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(i=u,r=d)}return i},za=(e,t)=>{if(Ft(e,t))return!0;const s=_a(e);return s!==void 0&&Ft(s,t)},$a=(e,t,s,n,i)=>{const r=[];for(const a of e.getProperties()){let c,u;if(o.isPropertyAssignment(a)?(c=E(a),u=a.getInitializer()):o.isShorthandPropertyAssignment(a)&&(c=E(a),u=a.getNameNode()),!(c===void 0||u===void 0||!Da.has(c))&&k(u)&&!U(u)){const d=S(s),m=i(d)===c&&za(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...m&&{ownerScoped:!0}})}}return r},Ua=(e,t,s)=>{const n=Ma(e.getExpression());if(n===void 0)return[];const i=e.getArguments()[1];return i?Ka(i,n).flatMap(r=>$a(r,n,e,t,s)):[]},qa=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const r of Ua(i,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Ba=(e,t,s=[],n=[])=>{const i=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of p(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);i.push(...qa(c,u,d=>r.get(`${u}:${d}`)??{}))}return i},ja=["providerSubscriptionId","state"],Va=["providerEventId","processedAt"],Ot=(e,t)=>t.every(s=>s in e.shape),Wa=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Ot(t,ja)&&Ot(s,Va)},Ha=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Ga=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ya=e=>{const t=C(e,"webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?Ga(t.getInitializer()):void 0},Qa=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Ha.has(s))return;const[n]=e.getArguments(),i=n&&o.isObjectLiteralExpression(n)?Ya(n):void 0;return{callee:s,exportName:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Xa=(e,t)=>F(e,t,Qa),Za=new Set(["defineQueue","defineWorkflow"]),Ja=new Set(["run","runAction","runMutation","runQuery"]),ec=new Set(["api","internal"]),tc=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},sc=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=C(t,"handler");if(s===void 0||!o.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(o.isArrowFunction(n)||o.isFunctionExpression(n)))return n},ls=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},us=(e,t)=>e===t||e.startsWith(`${t}.`),ds=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},Rt=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},fs=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Rt(s));return o.isIdentifier(e)&&Rt(e)&&t.push(e),t},nc=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},rc=e=>{const t=ls(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),r=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;r&&o.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ic=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:rc(e),i=new Set,r=a=>ds(a).some(c=>n.some(u=>us(c.getText(),u)))?!0:fs(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of nc(a))i.add(u)}return{names:i,prefixes:n}},oc=(e,t)=>ds(e).some(s=>t.prefixes.some(n=>us(s.getText(),n)))?!0:fs(e).some(s=>t.names.has(s.getText())),ac=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!ec.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},cc=(e,t,s)=>{const n=ls(e,0);if(n===void 0)return[];const i=ic(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!Ja.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!oc(u,i))continue;const d=ac(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:S(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},lc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=tc(n);if(i===void 0||!Za.has(i))continue;const r=sc(n);r!==void 0&&s.push(...cc(r,i==="defineQueue"?"queue":"workflow",t))}return s},uc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lc(i,x(t,n)))}return s},Lt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Dt=new Set(["account","credential","member","passkey","session","user"]),dc=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),fc=e=>{const s=dc(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Dt.has(s)||Dt.has(n)},gc=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},pc=(e,t)=>{const{objects:s,opaque:n}=_e(e,t);return ni(s).some(i=>gc(i))?!0:n?void 0:!1},mc=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!C(t,"captcha"),usesRateLimit:!!C(t,"rateLimit")}},hc=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},le={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},vc=e=>{const t=hc(e),s=t?A(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=mc(t);return{...le,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Lt?{...le,[Lt[s]]:!0}:le},xc=e=>{const t={...le};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const r=vc(i);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Ec=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Sc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Ec.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const i=e.getArguments()[0];return!i||!(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))?!1:fc(i.getLiteralText())},yc=new Set(["create","runAfter","runAt","send","sendBatch"]),Ac=new Set(["queues","scheduler","workflows"]),bc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!yc.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Ac.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},gs=new Set(["generateObject","generateText","streamObject","streamText"]),Pc=e=>{const t=A(e.getExpression());return t!==void 0&&gs.has(t)},wc=e=>{const t=A(e.getExpression());if(t===void 0||!gs.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!C(s,"maxOutputTokens")},Ic=new Set(["log","span","trace"]),Tc=new Set(["ai"]),Cc=new Set(["email","mail"]),Fc=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),Te=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),Oc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Rc=new Set(["every","filter","flatMap","forEach","map","some"]),Lc=new Set(["all","allSettled","race"]),Dc=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(Rc.has(n))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&Lc.has(n))return t},kc=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Oc.has(t.getKind())){const s=Dc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Mc=e=>{let t=e;for(;;){const s=t.getParent();if(!o.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(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Kc=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},_c=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Fc.has(n.getName()))continue;const i=n.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const r=Kc(n);r&&(t=!0,!kc(r)&&!Mc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},zc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),kt="lunora-advisor-exempt",$c=/^[\s*/]+/u,Uc=/[\w-]/u,qc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
6
|
`);for(const n of s.split(`
|
|
7
|
-
`)){const i=n.replace($c,"");if(!i.startsWith(kt))continue;const r=i.slice(kt.length);if(Uc.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Bc=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=C(t,"handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},jc=(e,t)=>{const s=Bc(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),r=n.getVariableDeclaration(i)?.getInitializer();return r&&(o.isArrowFunction(r)||o.isFunctionExpression(r))?r:n.getFunction(i)},Vc=e=>{let t=!1,s=!1,n=!1,i=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Sc(u)&&(r=!0),bc(u)&&(t=!0),Nc(u)&&(i=!0),Pc(u)&&(s=!0),wc(u)&&(n=!0),r&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Kc(e);return{callsMail:Te(e,Cc),emitsEvent:Te(e,Ic),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Te(e,Tc),throwsBareError:zc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:r}},Wc=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?xc(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=jc(e,s);return{...r?Vc(r):{},...qc(e),...i,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:pc(s,n.receiver),kind:n.kind,visibility:n.visibility}},Hc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Wc(i,t);r&&s.push(r)}return s},Gc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hc(i,x(t,n)))}return s},Yc=new Set(["dbRateLimit","rateLimit"]),Qc=e=>o.isArrowFunction(e)?e.getBody():e,Xc=e=>{if(!o.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&o.isIdentifier(t)?t:void 0},ps=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},ms=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(o.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},Jc=(e,t)=>M(e)||t!==void 0&&ms(e,t).some(s=>ps(s)),Zc=(e,t)=>t===void 0?U(e):ms(e,t).some(s=>!ps(s)),el=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Yc.has(s))return;const n=b(Wt(e.getArguments()[2]),"key");if(!n)return;const i=Qc(n),r=Xc(n);if(!(!Jc(i,r)||Zc(i,r)))return{callee:s,exportName:S(e),file:t,limitName:Vt(e),line:e.getStartLineNumber()}},tl=(e,t)=>F(e,t,el),sl=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),nl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!sl.has(t.getName()))return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&K(s.getExpression()))return s.getName()},rl=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&K(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},il=e=>{let t=X(e)??e;for(;o.isAwaitExpression(t);)t=X(t.getExpression())??t.getExpression();return t},hs=(e,t=!1)=>{const s=il(e);if(o.isIdentifier(s)){if(t)return;const n=he(s);return n===void 0?void 0:hs(n,!0)}if(o.isCallExpression(s))return nl(s)??rl(s)},ol=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const i=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),r=n.getExpression();i===e&&r!==void 0&&s.push(r)}return s},al=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query")return[];const i=ns(s);if(i===void 0)return[];const r=n.receiver!==void 0&&pn(n.receiver,"output"),a=n.receiver!==void 0&&Gt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of ol(i)){const m=hs(d);m===void 0||c.has(m)||(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:m,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},cl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...al(c,r))}return s},ll=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(E(s));return t},ul=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Ht(r);if(a===void 0)continue;const c=ll(b(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},dl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ul(c,r))}return s},fe=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=fe(e.getLeft()),s=fe(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},fl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&fe(t)!==void 0},gl=/(?:^|\/)__tests__\//u,pl=/\.(?:spec|test)$/u,ml=e=>gl.test(e)||pl.test(e),hl=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return E(t);if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},vl=(e,t,s)=>Qn(e)?!ml(s)&&Xn(hl(t)):!0,xl=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const r of n){if(fl(r))continue;const a=fe(r);if(a===void 0)continue;const c=Gn(a);if(c===void 0||!vl(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:Yn(a)}))}return s},El=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...xl(i,x(t,n)))}return s},Sl=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Ht(r);if(a===void 0)continue;const c=b(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&M(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},yl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sl(c,r))}return s},Al=new Set(["query","unsafe"]),bl=e=>{if(!o.isPropertyAccessExpression(e)||!Al.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},Nl=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Pl=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",wl=(e,t)=>{if(!bl(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Nl(s)))return{exportName:Pl(e),file:t,line:s.getStartLineNumber()}},Il=(e,t)=>F(e,t,wl),Tl=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Cl=e=>{for(const[t,s]of Tl)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Fl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Cl(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Ol=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Rl=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return xe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Ol,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Ll=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Dl=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,kl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=E(i);t.push(r),r==="expiresInSeconds"&&(s=Dl(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(E(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Ml=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ll.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},_l=(e,t)=>{const s=Ml(e.getExpression());if(s!==void 0)return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...kl(e.getArguments()[s.optionsIndex])}},Kl=(e,t)=>F(e,t,_l),zl=(e,t)=>({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")}),$l=(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"}),Ul=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!o.isObjectLiteralExpression(s)||C(s,"args")===void 0)return!1}return Ke(e,t).opaque},ql=(e,t)=>{const s=[],n=(i,r)=>{const a=i.getInitializer();if(a===void 0||!o.isCallExpression(a))return;const c=z(a);c!==void 0&&Ul(a,c.receiver)&&s.push($l(t,r,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations())n(r,r.getName());return s},Bl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...ql(i,x(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},jl=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."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ee=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),vs=e=>!e.isAny(),$e=e=>{const t=e.getType();if(!vs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:jl.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},xs=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},Es={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."},Vl=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.`}),Wl={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},Ue=(e,t,s,n,i)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,m=d===void 0?i:Vl(d),h=c===void 0?m.remediation:`${c} ${m.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. 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 \`${u}\` but was not registered — ${m.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},Hl=(e,t,s)=>{const n=[];for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations()){const a=r.getName();if(Ee(s,t,a)||!xs(r))continue;const c=$e(r);c!==void 0&&n.push(Ue(t,a,c,r.getStartLineNumber(),Es))}return n},Gl=(e,t,s)=>{if(Ee(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=$e(i.getExpression());r!==void 0&&n.push(Ue(t,"default",r,i.getStartLineNumber(),Es))}return n},Yl=(e,t,s)=>{const n=[];for(const i of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of i.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(Ee(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!xs(c))continue;const u=$e(c);u!==void 0&&n.push(Ue(t,a,u,r.getStartLineNumber(),Wl))}return n},Ql=(e,t,s)=>[...Hl(e,t,s),...Gl(e,t,s),...Yl(e,t,s)],Xl=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>Ee(s,t,n.getName())).filter(n=>{const i=n.getInitializer();return i!==void 0&&o.isCallExpression(i)&&o.isPropertyAccessExpression(i.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),Jl=({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"}),Zl=(e,t,s)=>{const n=[],i=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...Ql(c,u,s)),i.push(...Xl(c,u,s))}const[r]=i;return r!==void 0&&i.every(({declaration:a})=>!vs(a.getType()))&&n.push(Jl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},eu=new Set(["when","where"]),Ce=new Set(["definePolicy","defineShape"]),tu=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Ce.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const i=n.getNameNode().getText();return Ce.has(i)?i:void 0}const s=t.getText();return Ce.has(s)?s:void 0},su=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,Ss=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(su(e))return"empty-object";if(o.isParenthesizedExpression(e))return Ss(e.getExpression())}},qe=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),nu=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>qe(t)===e),ys=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>qe(t)===e),ru=e=>{const t=nu(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||ys(e).length>0},iu=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>qe(t)===e),De=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",ou=(e,t)=>De(e)||De(t),au=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Mt=e=>!De(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),cu=(e,t,s)=>{const n=au.get(e);if(n!==void 0)return ou(t,s)?n==="positive"?"negative":"positive":Mt(t)||Mt(s)?void 0:n},Y=e=>{if(o.isParenthesizedExpression(e))return Y(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=cu(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=Y(e.getLeft()),i=Y(e.getRight());return n===i?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},_t=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},lu=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},uu=e=>o.isReturnStatement(e)?e.getExpression()??e:e,du=e=>{const t=[];for(const s of ys(e)){const n=Y(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of iu(e)){const n=Y(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?_t(s.getThenStatement()):_t(s.getElseStatement())??lu(s);i!==void 0&&t.push(uu(i))}return t},fu=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},gu=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)||!eu.has(E(r)))continue;const a=r.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&ru(a))for(const c of du(a)){const u=Ss(c);u!==void 0&&i.push({exportName:fu(e),file:s,form:u,key:E(r),line:c.getStartLineNumber(),owner:t})}}return i},pu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=tu(n);i!==void 0&&s.push(...gu(n,i,t))}return s},mu=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pu(i,x(t,n)))}return s},hu=new Set(["query","upsert","upsertNow"]),vu=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(hu.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},xu=(e,t)=>{const s=vu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=b(n,"namespace");if(!(!i||!M(i)||U(i)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},Eu=(e,t)=>F(e,t,xu),Su=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},yu=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Au=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!Su(a))continue;const c=ln(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:yu(a)})}}return s},bu=".lunora-schema.json",ke=(e,t)=>{w(e)&&$t(e,"utf8")===t||Ls(e,t,"utf8")},Nu=(e,t)=>{if(t===""){Ds(e,{force:!0});return}ke(e,t)},Pu=e=>{const t=y(e,"package.json");if(w(t))try{const s=JSON.parse($t(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},wu=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Iu=e=>{let t=w(e)?e:ae(e);for(;t&&t!==ae(t);){const s=y(t,"tsconfig.json");if(w(s))return s;t=ae(t)}},Kt=e=>e.replaceAll("\\","/"),Tu=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("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) (${r}), 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 r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const i=t.columns.length>0;for(const r of e){if(r.table===void 0){if(i)throw new k("MASK_UNSUPPORTED",`defineShape "${r.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 "${r.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(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.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})}},ge=(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)},zt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Cu=8,Fu=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:i,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:m}=e,h=()=>On(()=>{const N=Rn(a,i),O=$n(a,i);return{functions:N,httpRoutes:Ln(a,i),mutators:O}});let{erased:R,value:{functions:_,httpRoutes:g,mutators:I}}=h();pt([..._,...I].map(N=>N.filePath)),pt(g.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const O=tn({agents:t,functions:_,httpRoutes:g,mutators:I,useUmbrella:d,workflows:m}),v=sn({agents:t,functions:_,migrations:r,mutators:I,shapes:c,useUmbrella:d,usesSandbox:u});if(N>=Cu||zt(a,s,O)&&zt(a,n,v))return{apiContent:O,erased:R,functions:_,functionsContent:v,httpRoutes:g,mutators:I};ge(a,s,O),ge(a,n,v),{erased:R,value:{functions:_,httpRoutes:g,mutators:I}}=h()}},Ou=e=>{const t=Iu(e);return t?new dt({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new dt({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Id=(e,t)=>{const s=p(t),n=y(t,"schema.ts");w(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>Kt(c))),r=Kt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Td=e=>{const t=wu(),s=t?we.now():0,n=y(e.projectRoot,e.lunoraDirectory??"lunora"),i=y(n,"schema.ts");if(!w(i))throw new k("INTERNAL",`schema.ts not found at ${i}`);const r=e.project??Ou(n);Nn(uo);const a=Hn(r,i,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:m,dependencies:h,entryCronTriggers:R,env:_,featureUsage:g,hasFlags:I,hasNotify:N,identity:O,platformGate:v,queues:D,serverContent:q,storageRulesMetadata:H,usesSandbox:te,useUmbrella:$,workflows:L}=Fr({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target});Qo(a,c,a.jurisdiction===void 0?void 0:Go(r,n));const P=y(n,"_generated"),As=y(P,"dataModel.ts"),bs=y(P,"server.ts"),Ns=y(P,"api.ts"),Ps=y(P,"functions.ts");ge(r,As,m),ge(r,bs,q);const se=_n(r,n),j=Jn(r,n),{apiContent:Be,erased:ws,functions:V,functionsContent:je,httpRoutes:Is,mutators:ne}=Fu({agents:c,apiPath:Ns,generatedFunctionsPath:Ps,lunoraDirectory:n,migrations:se,project:r,shapes:j,useUmbrella:$,usesSandbox:te,workflows:L}),re=e.lint===!1?void 0:Ks({adminRoutes:Kr(r,n),aiRawRuns:Ur(r,n),aiToolSideEffects:Xr(r,n),argumentDerivedFetches:ei(r,n),argumentValidators:ui(r,n),authApiCalls:Pn(r,n),authConfigs:Si(r,n),browserUrlAccesses:Pi(r,n),configCalls:Li(r,n),containerKeyAccesses:ki(r,n),containerOverrides:Ui(r,n),containers:u,exportSinks:Vi(r,n),staleMigrationImports:Fl(r,n),failOpenGuards:Qi(r,n),flagReads:io(r,n),flagSecurityDefaults:lo(r,n),geoIndexUsages:po(r,n),httpActionGuards:wo(r,n),httpHeaderWrites:Mo(r,n),hyperdriveCalls:Dn(r,n),identityClaimReads:Bo(r,n),imageDeliveryUrlAccesses:Vo(r,n),inserts:kn(r,n),kvKeyAccesses:Jo(r,n,V),mailRecipientAccesses:na(r,n),maskProcedures:Mn(r,n),maskStrategies:da(r,n),mutatorWrites:va(r,n),nondeterministicCalls:Un(r,n),normalizeIdAuthorizations:La(r,n),notifyCalls:Bn(r,n),notifyConfig:qn(r,n),mutators:ne,ownerFieldWrites:Ba(r,n,V,ne),unrestrictedWhereBranches:mu(r,n),paymentWebhooks:Xa(r,n),privilegedDispatches:uc(r,n),procedureProtections:Gc(r,n),queries:bn(r,n),queues:D,r2sqlCalls:jn(r,n),ratelimitKeySelectors:tl(r,n),rawRowReturns:cl(r,n),relationLoads:dl(r,n),rlsProcedures:Vn(r,n),schema:a,secretLiterals:El(r,n),shapes:j,softDeleteReads:yl(r,n),sqlInterpolations:Il(r,n),storageKeyAccesses:Rl(r,n,V),storageUploads:Kl(r,n),vectorNamespaceAccesses:Eu(r,n),workflowCalls:Au(r,n),workflows:L,wranglerVariables:e.wranglerVariables}),Ve=re===void 0?[]:or(e.projectRoot,[...ks(re,{source:"static"}),...Zl(r,n,{byName:new Set([...L,...D,...c,...u].map(f=>f.exportName)),byPath:new Set([...V,...ne,...j,...se].map(f=>`${f.filePath}:${f.exportName}`))}),...Bl(r,n),...Fn(ws,n)]),Ts=Wn(r,n),We=ca(r,n);Tu(j,We,oa(r,n));const Cs=I?eo(r,n):[],Se=v.signals.vectorStore!==!1,G=zl(g,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:Wa(a.tables),queueCount:D.length,storageColumnCount:Object.keys(Ut(a)).length,storageRuleCount:H.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:Se,workflowCount:L.length}),He=t?we.now():0,ye=rr(a,se.map(f=>f.id)),Ge=Bs({advisories:Ve.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:re?.procedureProtections??[],agents:c,containers:u,env:_,flagKeys:Cs,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:I,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:N,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:Se,hasX402:g.x402,maskMetadata:We,mutators:ne,queues:D,rlsMetadata:Ts,schema:a,schemaSnapshot:ye,shapes:j,storageRules:H,studioFeatures:G,useUmbrella:$,workflows:L}),Ye=js(j,h.has("@lunora/db"),$),Qe=Vs(u,a.jurisdiction),Xe=Ws(L),Je=Hs(c),Ze=Gs(D),et=Ys(d),Fs=Qs(G.scheduler),tt=Xs(a.vectorIndexes),ie=Js(a,$),st=Zs(h.has("@lunora/seed")),oe=e.apiSpec??"openapi",Ae=oe==="openapi"||oe==="both",be=oe==="openrpc"||oe==="both",nt=Zn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue"),hasGlobal:a.tables.some(f=>qt(f)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>Bt(f)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:G.kv,hasNotify:N,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:D.some(f=>f.mode==="push"),hasScheduler:G.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:G.storage,hasVectors:Se,hasWorkflow:L.length>0,hasX402:g.x402,identity:O,jurisdiction:a.jurisdiction,jurisdictionPinsAuthAndVoice:a.jurisdictionPinsAuthAndVoice===!0,tableNames:a.tables.map(f=>f.name),useUmbrella:$,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:Ae,wantsOpenRpc:be}),rt=Pu(e.projectRoot),it=er({functions:V,httpRoutes:Is,version:rt}),ot=sr({functions:V,version:rt}),at=`${JSON.stringify(it,void 0,2)}
|
|
7
|
+
`)){const i=n.replace($c,"");if(!i.startsWith(kt))continue;const r=i.slice(kt.length);if(Uc.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Bc=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=C(t,"handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},jc=(e,t)=>{const s=Bc(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),r=n.getVariableDeclaration(i)?.getInitializer();return r&&(o.isArrowFunction(r)||o.isFunctionExpression(r))?r:n.getFunction(i)},Vc=e=>{let t=!1,s=!1,n=!1,i=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Sc(u)&&(r=!0),bc(u)&&(t=!0),Nc(u)&&(i=!0),Pc(u)&&(s=!0),wc(u)&&(n=!0),r&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=_c(e);return{callsMail:Te(e,Cc),emitsEvent:Te(e,Ic),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Te(e,Tc),throwsBareError:zc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:r}},Wc=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?xc(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=jc(e,s);return{...r?Vc(r):{},...qc(e),...i,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:pc(s,n.receiver),kind:n.kind,visibility:n.visibility}},Hc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Wc(i,t);r&&s.push(r)}return s},Gc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hc(i,x(t,n)))}return s},Yc=new Set(["dbRateLimit","rateLimit"]),Qc=e=>o.isArrowFunction(e)?e.getBody():e,Xc=e=>{if(!o.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&o.isIdentifier(t)?t:void 0},ps=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},ms=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(o.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},Zc=(e,t)=>k(e)||t!==void 0&&ms(e,t).some(s=>ps(s)),Jc=(e,t)=>t===void 0?U(e):ms(e,t).some(s=>!ps(s)),el=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Yc.has(s))return;const n=b(Wt(e.getArguments()[2]),"key");if(!n)return;const i=Qc(n),r=Xc(n);if(!(!Zc(i,r)||Jc(i,r)))return{callee:s,exportName:S(e),file:t,limitName:Vt(e),line:e.getStartLineNumber()}},tl=(e,t)=>F(e,t,el),sl=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),nl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!sl.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},rl=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},il=e=>{let t=X(e)??e;for(;o.isAwaitExpression(t);)t=X(t.getExpression())??t.getExpression();return t},hs=(e,t=!1)=>{const s=il(e);if(o.isIdentifier(s)){if(t)return;const n=he(s);return n===void 0?void 0:hs(n,!0)}if(o.isCallExpression(s))return nl(s)??rl(s)},ol=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const i=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),r=n.getExpression();i===e&&r!==void 0&&s.push(r)}return s},al=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query")return[];const i=ns(s);if(i===void 0)return[];const r=n.receiver!==void 0&&pn(n.receiver,"output"),a=n.receiver!==void 0&&Gt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of ol(i)){const m=hs(d);m===void 0||c.has(m)||(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:m,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},cl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...al(c,r))}return s},ll=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(E(s));return t},ul=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Ht(r);if(a===void 0)continue;const c=ll(b(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},dl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ul(c,r))}return s},fe=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=fe(e.getLeft()),s=fe(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},fl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&fe(t)!==void 0},gl=/(?:^|\/)__tests__\//u,pl=/\.(?:spec|test)$/u,ml=e=>gl.test(e)||pl.test(e),hl=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return E(t);if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},vl=(e,t,s)=>Qn(e)?!ml(s)&&Xn(hl(t)):!0,xl=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const r of n){if(fl(r))continue;const a=fe(r);if(a===void 0)continue;const c=Gn(a);if(c===void 0||!vl(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:Yn(a)}))}return s},El=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...xl(i,x(t,n)))}return s},Sl=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Ht(r);if(a===void 0)continue;const c=b(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&k(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},yl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sl(c,r))}return s},Al=new Set(["query","unsafe"]),bl=e=>{if(!o.isPropertyAccessExpression(e)||!Al.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},Nl=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Pl=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",wl=(e,t)=>{if(!bl(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Nl(s)))return{exportName:Pl(e),file:t,line:s.getStartLineNumber()}},Il=(e,t)=>F(e,t,wl),Tl=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Cl=e=>{for(const[t,s]of Tl)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Fl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Cl(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Ol=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Rl=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return xe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Ol,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Ll=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Dl=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,kl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=E(i);t.push(r),r==="expiresInSeconds"&&(s=Dl(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(E(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Ml=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ll.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Kl=(e,t)=>{const s=Ml(e.getExpression());if(s!==void 0)return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...kl(e.getArguments()[s.optionsIndex])}},_l=(e,t)=>F(e,t,Kl),zl=(e,t)=>({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")}),$l=(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"}),Ul=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!o.isObjectLiteralExpression(s)||C(s,"args")===void 0)return!1}return _e(e,t).opaque},ql=(e,t)=>{const s=[],n=(i,r)=>{const a=i.getInitializer();if(a===void 0||!o.isCallExpression(a))return;const c=z(a);c!==void 0&&Ul(a,c.receiver)&&s.push($l(t,r,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations())n(r,r.getName());return s},Bl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...ql(i,x(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},jl=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."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ee=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),vs=e=>!e.isAny(),$e=e=>{const t=e.getType();if(!vs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:jl.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},xs=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},Es={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."},Vl=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.`}),Wl={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},Ue=(e,t,s,n,i)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,m=d===void 0?i:Vl(d),h=c===void 0?m.remediation:`${c} ${m.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. 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 \`${u}\` but was not registered — ${m.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},Hl=(e,t,s)=>{const n=[];for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations()){const a=r.getName();if(Ee(s,t,a)||!xs(r))continue;const c=$e(r);c!==void 0&&n.push(Ue(t,a,c,r.getStartLineNumber(),Es))}return n},Gl=(e,t,s)=>{if(Ee(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=$e(i.getExpression());r!==void 0&&n.push(Ue(t,"default",r,i.getStartLineNumber(),Es))}return n},Yl=(e,t,s)=>{const n=[];for(const i of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of i.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(Ee(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!xs(c))continue;const u=$e(c);u!==void 0&&n.push(Ue(t,a,u,r.getStartLineNumber(),Wl))}return n},Ql=(e,t,s)=>[...Hl(e,t,s),...Gl(e,t,s),...Yl(e,t,s)],Xl=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>Ee(s,t,n.getName())).filter(n=>{const i=n.getInitializer();return i!==void 0&&o.isCallExpression(i)&&o.isPropertyAccessExpression(i.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),Zl=({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"}),Jl=(e,t,s)=>{const n=[],i=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...Ql(c,u,s)),i.push(...Xl(c,u,s))}const[r]=i;return r!==void 0&&i.every(({declaration:a})=>!vs(a.getType()))&&n.push(Zl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},eu=new Set(["when","where"]),Ce=new Set(["definePolicy","defineShape"]),tu=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Ce.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const i=n.getNameNode().getText();return Ce.has(i)?i:void 0}const s=t.getText();return Ce.has(s)?s:void 0},su=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,Ss=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(su(e))return"empty-object";if(o.isParenthesizedExpression(e))return Ss(e.getExpression())}},qe=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),nu=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>qe(t)===e),ys=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>qe(t)===e),ru=e=>{const t=nu(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||ys(e).length>0},iu=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>qe(t)===e),De=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",ou=(e,t)=>De(e)||De(t),au=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Mt=e=>!De(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),cu=(e,t,s)=>{const n=au.get(e);if(n!==void 0)return ou(t,s)?n==="positive"?"negative":"positive":Mt(t)||Mt(s)?void 0:n},Y=e=>{if(o.isParenthesizedExpression(e))return Y(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=cu(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=Y(e.getLeft()),i=Y(e.getRight());return n===i?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},Kt=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},lu=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},uu=e=>o.isReturnStatement(e)?e.getExpression()??e:e,du=e=>{const t=[];for(const s of ys(e)){const n=Y(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of iu(e)){const n=Y(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Kt(s.getThenStatement()):Kt(s.getElseStatement())??lu(s);i!==void 0&&t.push(uu(i))}return t},fu=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},gu=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)||!eu.has(E(r)))continue;const a=r.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&ru(a))for(const c of du(a)){const u=Ss(c);u!==void 0&&i.push({exportName:fu(e),file:s,form:u,key:E(r),line:c.getStartLineNumber(),owner:t})}}return i},pu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=tu(n);i!==void 0&&s.push(...gu(n,i,t))}return s},mu=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pu(i,x(t,n)))}return s},hu=new Set(["query","upsert","upsertNow"]),vu=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(hu.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},xu=(e,t)=>{const s=vu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=b(n,"namespace");if(!(!i||!k(i)||U(i)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},Eu=(e,t)=>F(e,t,xu),Su=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},yu=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Au=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!Su(a))continue;const c=ln(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:yu(a)})}}return s},bu=".lunora-schema.json",ke=(e,t)=>{w(e)&&$t(e,"utf8")===t||Ls(e,t,"utf8")},Nu=(e,t)=>{if(t===""){Ds(e,{force:!0});return}ke(e,t)},Pu=e=>{const t=y(e,"package.json");if(w(t))try{const s=JSON.parse($t(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},wu=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Iu=e=>{let t=w(e)?e:ae(e);for(;t&&t!==ae(t);){const s=y(t,"tsconfig.json");if(w(s))return s;t=ae(t)}},_t=e=>e.replaceAll("\\","/"),Tu=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new K("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) (${r}), 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 r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const i=t.columns.length>0;for(const r of e){if(r.table===void 0){if(i)throw new K("MASK_UNSUPPORTED",`defineShape "${r.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 "${r.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(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new K("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.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})}},ge=(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)},zt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Cu=8,Fu=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:i,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:m}=e,h=()=>On(()=>{const N=Rn(a,i),O=$n(a,i);return{functions:N,httpRoutes:Ln(a,i),mutators:O}});let{erased:R,value:{functions:M,httpRoutes:g,mutators:I}}=h();pt([...M,...I].map(N=>N.filePath)),pt(g.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const O=tn({agents:t,functions:M,httpRoutes:g,mutators:I,useUmbrella:d,workflows:m}),v=sn({agents:t,functions:M,migrations:r,mutators:I,shapes:c,useUmbrella:d,usesSandbox:u});if(N>=Cu||zt(a,s,O)&&zt(a,n,v))return{apiContent:O,erased:R,functions:M,functionsContent:v,httpRoutes:g,mutators:I};ge(a,s,O),ge(a,n,v),{erased:R,value:{functions:M,httpRoutes:g,mutators:I}}=h()}},Ou=e=>{const t=Iu(e);return t?new dt({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new dt({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Id=(e,t)=>{const s=p(t),n=y(t,"schema.ts");w(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>_t(c))),r=_t(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Td=e=>{const t=wu(),s=t?we.now():0,n=y(e.projectRoot,e.lunoraDirectory??"lunora"),i=y(n,"schema.ts");if(!w(i))throw new K("INTERNAL",`schema.ts not found at ${i}`);const r=e.project??Ou(n);Nn(uo);const a=Hn(r,i,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:m,dependencies:h,entryCronTriggers:R,env:M,featureUsage:g,hasFlags:I,hasNotify:N,identity:O,platformGate:v,queues:D,serverContent:q,storageRulesMetadata:H,usesSandbox:te,useUmbrella:$,workflows:L}=Fr({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target});Qo(a,a.jurisdiction===void 0?void 0:Go(r,n));const P=y(n,"_generated"),As=y(P,"dataModel.ts"),bs=y(P,"server.ts"),Ns=y(P,"api.ts"),Ps=y(P,"functions.ts");ge(r,As,m),ge(r,bs,q);const se=Kn(r,n),j=Zn(r,n),{apiContent:Be,erased:ws,functions:V,functionsContent:je,httpRoutes:Is,mutators:ne}=Fu({agents:c,apiPath:Ns,generatedFunctionsPath:Ps,lunoraDirectory:n,migrations:se,project:r,shapes:j,useUmbrella:$,usesSandbox:te,workflows:L}),re=e.lint===!1?void 0:_s({adminRoutes:_r(r,n),aiRawRuns:Ur(r,n),aiToolSideEffects:Xr(r,n),argumentDerivedFetches:ei(r,n),argumentValidators:ui(r,n),authApiCalls:Pn(r,n),authConfigs:Si(r,n),browserUrlAccesses:Pi(r,n),configCalls:Li(r,n),containerKeyAccesses:ki(r,n),containerOverrides:Ui(r,n),containers:u,exportSinks:Vi(r,n),staleMigrationImports:Fl(r,n),failOpenGuards:Qi(r,n),flagReads:io(r,n),flagSecurityDefaults:lo(r,n),geoIndexUsages:po(r,n),httpActionGuards:wo(r,n),httpHeaderWrites:Mo(r,n),hyperdriveCalls:Dn(r,n),identityClaimReads:Bo(r,n),imageDeliveryUrlAccesses:Vo(r,n),inserts:kn(r,n),kvKeyAccesses:Zo(r,n,V),mailRecipientAccesses:na(r,n),maskProcedures:Mn(r,n),maskStrategies:da(r,n),mutatorWrites:va(r,n),nondeterministicCalls:Un(r,n),normalizeIdAuthorizations:La(r,n),notifyCalls:Bn(r,n),notifyConfig:qn(r,n),mutators:ne,ownerFieldWrites:Ba(r,n,V,ne),unrestrictedWhereBranches:mu(r,n),paymentWebhooks:Xa(r,n),privilegedDispatches:uc(r,n),procedureProtections:Gc(r,n),queries:bn(r,n),queues:D,r2sqlCalls:jn(r,n),ratelimitKeySelectors:tl(r,n),rawRowReturns:cl(r,n),relationLoads:dl(r,n),rlsProcedures:Vn(r,n),schema:a,secretLiterals:El(r,n),shapes:j,softDeleteReads:yl(r,n),sqlInterpolations:Il(r,n),storageKeyAccesses:Rl(r,n,V),storageUploads:_l(r,n),vectorNamespaceAccesses:Eu(r,n),workflowCalls:Au(r,n),workflows:L,wranglerVariables:e.wranglerVariables}),Ve=re===void 0?[]:or(e.projectRoot,[...ks(re,{source:"static"}),...Jl(r,n,{byName:new Set([...L,...D,...c,...u].map(f=>f.exportName)),byPath:new Set([...V,...ne,...j,...se].map(f=>`${f.filePath}:${f.exportName}`))}),...Bl(r,n),...Fn(ws,n)]),Ts=Wn(r,n),We=ca(r,n);Tu(j,We,oa(r,n));const Cs=I?eo(r,n):[],Se=v.signals.vectorStore!==!1,G=zl(g,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:Wa(a.tables),queueCount:D.length,storageColumnCount:Object.keys(Ut(a)).length,storageRuleCount:H.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:Se,workflowCount:L.length}),He=t?we.now():0,ye=rr(a,se.map(f=>f.id)),Ge=Bs({advisories:Ve.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:re?.procedureProtections??[],agents:c,containers:u,env:M,flagKeys:Cs,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:I,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:N,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:Se,hasX402:g.x402,maskMetadata:We,mutators:ne,queues:D,rlsMetadata:Ts,schema:a,schemaSnapshot:ye,shapes:j,storageRules:H,studioFeatures:G,useUmbrella:$,workflows:L}),Ye=js(j,h.has("@lunora/db"),$),Qe=Vs(u,a.jurisdiction),Xe=Ws(L),Ze=Hs(c),Je=Gs(D),et=Ys(d),Fs=Qs(G.scheduler),tt=Xs(a.vectorIndexes),ie=Zs(a,$),st=Js(h.has("@lunora/seed")),oe=e.apiSpec??"openapi",Ae=oe==="openapi"||oe==="both",be=oe==="openrpc"||oe==="both",nt=Jn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue"),hasGlobal:a.tables.some(f=>qt(f)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>Bt(f)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:G.kv,hasNotify:N,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:D.some(f=>f.mode==="push"),hasScheduler:G.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:G.storage,hasVectors:Se,hasWorkflow:L.length>0,hasX402:g.x402,identity:O,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tableNames:a.tables.map(f=>f.name),useUmbrella:$,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:Ae,wantsOpenRpc:be}),rt=Pu(e.projectRoot),it=er({functions:V,httpRoutes:Is,version:rt}),ot=sr({functions:V,version:rt}),at=`${JSON.stringify(it,void 0,2)}
|
|
8
8
|
`,ct=`${JSON.stringify(ot,void 0,2)}
|
|
9
|
-
`,lt=tr(it),ut=nr(ot),Ne=y(n,bu),Os=w(Ne),Pe=[];if(!e.dryRun){w(P)||Rs(P,{recursive:!0});const f=(B,W)=>{ke(y(P,B),W),Pe.push(B)},T=(B,W)=>{Nu(y(P,B),W),W!==""&&Pe.push(B)};f("app.ts",nt),f("dataModel.ts",m),f("api.ts",Be),f("server.ts",q),f("functions.ts",je),f("shard.ts",Ge),f("crons.ts",et),f("vectors.ts",tt),f("drizzle.global.ts",ie.global),f("drizzle.shard.ts",ie.shard),T("containers.ts",Qe),T("workflows.ts",Xe),T("agents.ts",
|
|
9
|
+
`,lt=tr(it),ut=nr(ot),Ne=y(n,bu),Os=w(Ne),Pe=[];if(!e.dryRun){w(P)||Rs(P,{recursive:!0});const f=(B,W)=>{ke(y(P,B),W),Pe.push(B)},T=(B,W)=>{Nu(y(P,B),W),W!==""&&Pe.push(B)};f("app.ts",nt),f("dataModel.ts",m),f("api.ts",Be),f("server.ts",q),f("functions.ts",je),f("shard.ts",Ge),f("crons.ts",et),f("vectors.ts",tt),f("drizzle.global.ts",ie.global),f("drizzle.shard.ts",ie.shard),T("containers.ts",Qe),T("workflows.ts",Xe),T("agents.ts",Ze),T("queues.ts",Je),T("scheduler.ts",Fs),T("seed.ts",st),T("collections.ts",Ye),T("openapi.json",Ae?at:""),T("openapi.ts",Ae?lt:""),T("openrpc.json",be?ct:""),T("openrpc.ts",be?ut:""),(!Os||e.updateSchemaBaseline===!0)&&ke(Ne,Ks(ye))}if(t){const f=we.now(),T=Math.round(f-s),B=Math.round(He-s),W=Math.round(f-He);console.error(`@lunora/codegen: codegen took ${T.toString()}ms (discovery ${B.toString()}ms, emit ${W.toString()}ms)`)}return{advisories:Ve,advisorContext:re,agents:c,containers:u,cronTriggers:[...new Set([...en(d),...R])],generated:{agents:Ze,api:Be,app:nt,collections:Ye,containers:Qe,crons:et,dataModel:m,drizzleGlobal:ie.global,drizzleShard:ie.shard,functions:je,openApi:at,openApiModule:lt,openRpc:ct,openRpcModule:ut,queues:Je,seed:st,server:q,shard:Ge,vectors:tt,workflows:Xe},migrations:se,outputDirectory:P,platformDiagnostics:v.diagnostics,queues:D,schemaSnapshot:ye,schemaSnapshotPath:Ne,workflows:L,writtenFiles:Pe}};export{bu as SCHEMA_SNAPSHOT_FILENAME,Ou as createCodegenProject,Iu as findTsconfig,Id as refreshCodegenProject,Td as runCodegen};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as C}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as R}from"node:module";import{join as F}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{r as V,p as B}from"./parse-validator-C94Yiabo.mjs";const q=(e,n)=>`table "${e}" is .global() and declares vector index "${n}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,J=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},U=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:U(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=m(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=J(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([a,o])=>[a,m(o)]));break}case"record":{s.valueType=m(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=m(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(a=>m(a));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,n)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(t).map(([r,a])=>[r,m(a)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([o,l])=>G(l,o)),r=e.vectorIndexes??{},a=Object.entries(r??{}).map(([o,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:o,table:l.table??""}));return{bareTables:s,bareVectorIndexes:a,key:n}},H=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},Q=e=>{const n=H(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const a=r.getModuleSpecifierValue();for(const o of r.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===n)return{importedName:o.getName(),moduleSpecifier:a,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:a,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:a,propertyPath:[]}}},X=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},Y=(e,n)=>{const t=Q(e);if(t)try{const s=R(F(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),a=s(r),o=X(a,t);return typeof o!="object"||o===null?void 0:W(o)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,n)=>{const t=u(e,n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=b(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},x=(e,n)=>{const t=b(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},O=(e,n)=>{const t=b(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},h=(e,n)=>{const t=b(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},A=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,n)=>{const t=h(e,n);return t!==void 0&&t.length>0?t:void 0},N=(e,n,t,s,r)=>{let a=e;for(;;){const o=a.getParent();if(!o||!i.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!i.isCallExpression(l))break;if(o.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw f(c,`unknown ${t} ${JSON.stringify(g)} — expected ${r}`);return g}a=l}},ne=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,re=new Set(["cascade","restrict","set null"]),se=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),ie=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),P=/^[A-Za-z_$][\w$]*$/u,w=(e,n)=>{if(se.has(e))throw f(n,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(ie.has(e))throw f(n,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!P.test(e))throw f(n,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`)},oe=e=>e&&re.has(e)?e:void 0,ae=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},le=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,a]=n.getArguments();if(!r||!i.isStringLiteral(r))throw f(r??n,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const o=r.getLiteralText();let l="_unknown_",c="_id",g;return a&&i.isObjectLiteralExpression(a)&&(l=d(a,"field")??l,c=d(a,"references")??c,g=s==="one"?oe(d(a,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:o}},ce=e=>{const n=ae(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=le(s);r&&t.push(r)}return t},de=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),a=`${s}${r.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${a}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},fe=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=u(e,"unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},ue=e=>{const[n,t,s]=e,r=fe(s),a=y(n),o=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of o)if(!i.isStringLiteral(c))throw f(c,`index "${a}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>i.isStringLiteral(c));for(const c of l)de(c,c.getLiteralText(),a);return{fields:l.map(c=>c.getLiteralText()),name:a,unique:r}},pe=e=>{const[n,t]=e;let s="_unknown_",r,a,o,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=h(t,"filterFields"),a=d(t,"language"),o=O(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:a,name:y(n),staged:o,strategy:l}},ge=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"precision")),{field:s,name:y(n),precision:r}},me=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=x(t,"after")),{after:r,field:s}},be=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},xe=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const a=u(t,"sortBy");if(a&&i.isPropertyAssignment(a)){const o=a.getInitializer();o&&i.isArrayLiteralExpression(o)&&(s=o.getElements().map(l=>be(l)).filter(l=>l!==void 0))}r=h(t,"partitionBy")}return{name:y(n),partitionBy:r,sortBy:s}},he=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:A(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},ye=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},ve=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=u(e,"field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},Ee=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:te(n,"columns"),hasReconcile:u(n,"reconcileEveryMs")!==void 0,hasSoftDelete:u(n,"softDeleteColumn")!==void 0,hasTenantBy:u(n,"tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},Ie=(e,n,t,s)=>{switch(n){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ge(t));break}case"global":{e.shardMode="global",e.globalBackend=ye(t);break}case"index":{e.indexes.push(ue(t));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(xe(t));break}case"relations":{const r=t[0];r&&e.relations.push(...ce(r));break}case"searchIndex":{e.searchIndexes.push(pe(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:ve(t[0])};break}case"source":{e.externalSource=Ee(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=me(t);break}case"vectorize":{const r=he(t,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],we=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const a of L){const o=`${r.name}${a}`;if(!s.has(o))continue;const l=a==="__vocab"?`the \`fts5vocab\` companion for "${o}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${o}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw f(e,`table "${n}" declares search indexes "${r.name}" and "${o}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${o}" as its "${a}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Se=(e,n,t)=>{if(t.ttl!==void 0&&t.shardMode==="global")throw f(e,ne(n))},_=(e,n)=>{const t={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const a=r.getExpression(),o=r.getArguments();if(i.isPropertyAccessExpression(a))Ie(t,a.getName(),o,n),r=a.getExpression();else if(i.isIdentifier(a)&&a.getText()==="defineTable"){const l=o[0];if(l&&i.isObjectLiteralExpression(l))s=B(l);else if(l)throw f(l,`table "${n}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),we(e,n,t.searchIndexes),Se(e,n,t),{commitOrdered:t.commitOrdered,externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,memory:t.memory,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},j=(e,n=[],t=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const o=V(r.getExpression());o!==void 0&&!s.has(o)&&j(o,n,t,s);continue}if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(a){const o=I(r);if(w(o,r.getNameNode()),t.has(o))throw f(r.getNameNode(),`defineSchema({...}): table "${o}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(o),n.push(_(a,o))}}return n},ke=e=>{const n=u(e,"source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},Te=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),a=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:A(d(s,"metric")),name:a,table:ke(s)}},$=e=>{const n=[];for(const t of e.getProperties()){const s=Te(t);s&&n.push(s)}return n},S=(e,n)=>`${e}_${n}`,Le=(e,n)=>{if(!P.test(e))throw f(n,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,n,t)=>t.has(e)?S(n,e):e,Oe=(e,n,t)=>{const s=S(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:E(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:E(r.table,n,t)}))}},Ae=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ne=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},Pe=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},_e=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},je=(e,n)=>{const t=Ae(e);if(t){if(i.isPropertyAccessExpression(n)){const s=_e(t);return s?b(s,n.getName()):void 0}return t}},$e=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,Ne(n))return n;const s=Pe(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,o=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=je(o,n)}},De=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),keyNode:n,options:t}},ze=e=>{const n=u(e,"tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(!a)continue;const o=I(r);w(o,r.getNameNode()),s.push(_(a,o))}return s},Me=e=>{const n=u(e,"vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:$(t)},D=(e,n,t,s)=>{Le(e,s);const r=new Set(n.map(l=>l.name)),a=n.map(l=>Oe(l,e,r)),o=t.map(l=>({...l,name:S(e,l.name),table:E(l.table,e,r)}));return{tables:a,vectorIndexes:o}},Ce=(e,n,t)=>D(e,ze(t),Me(t),n),Re=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=$e(t);if(!s){if(n!==void 0){const a=Y(t,n);if(a){for(const o of a.bareTables)w(o.name,t);return D(a.key,a.bareTables,a.bareVectorIndexes,t)}}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=De(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Ce(r.key,r.keyNode,r.options)},Fe=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},Ve=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=[];for(const a of Fe(e)){const o=Re(a,t);if(o){for(const l of o.tables){if(s.has(l.name))throw f(a,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...o.vectorIndexes)}}return r},Be=new Set(["eu","fedramp","us"]),qe=e=>N(e,"jurisdiction","jurisdiction",Be,'"eu", "us", or "fedramp"'),Je=e=>{let n=e;for(;;){const t=n.getParent(),s=t?.getParent();if(!t||!i.isPropertyAccessExpression(t)||!s||!i.isCallExpression(s))return!1;if(t.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&O(r,"pinAuthAndVoice")===!0}n=s}},Ue=new Set(["required"]),Ke=e=>N(e,"rls","rls mode",Ue,'"required"'),et=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(C.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${n}`);const a=r.getArguments()[0];if(!a||!i.isObjectLiteralExpression(a))throw f(r,"defineSchema() expects an object literal");const o=j(a),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Ve(r,o,t),k=[...o.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(o.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw f(r,q(v.table,v.name));return{jurisdiction:qe(r),...Je(r)?{jurisdictionPinsAuthAndVoice:!0}:{},rlsMode:Ke(r),tables:o,vectorIndexes:k}};export{et as default};
|
|
1
|
+
import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as C}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as R}from"node:module";import{join as F}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{r as B,p as V}from"./parse-validator-C94Yiabo.mjs";const q=(e,n)=>`table "${e}" is .global() and declares vector index "${n}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,J=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},U=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:U(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=m(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=J(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([a,o])=>[a,m(o)]));break}case"record":{s.valueType=m(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=m(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(a=>m(a));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,n)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(t).map(([r,a])=>[r,m(a)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([o,l])=>G(l,o)),r=e.vectorIndexes??{},a=Object.entries(r??{}).map(([o,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:o,table:l.table??""}));return{bareTables:s,bareVectorIndexes:a,key:n}},H=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},Q=e=>{const n=H(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const a=r.getModuleSpecifierValue();for(const o of r.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===n)return{importedName:o.getName(),moduleSpecifier:a,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:a,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:a,propertyPath:[]}}},X=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},Y=(e,n)=>{const t=Q(e);if(t)try{const s=R(F(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),a=s(r),o=X(a,t);return typeof o!="object"||o===null?void 0:W(o)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,n)=>{const t=u(e,n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=b(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},x=(e,n)=>{const t=b(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},O=(e,n)=>{const t=b(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},h=(e,n)=>{const t=b(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},A=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,n)=>{const t=h(e,n);return t!==void 0&&t.length>0?t:void 0},N=(e,n,t,s,r)=>{let a=e;for(;;){const o=a.getParent();if(!o||!i.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!i.isCallExpression(l))break;if(o.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw f(c,`unknown ${t} ${JSON.stringify(g)} — expected ${r}`);return g}a=l}},ne=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,re=new Set(["cascade","restrict","set null"]),se=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),ie=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),P=/^[A-Za-z_$][\w$]*$/u,w=(e,n)=>{if(se.has(e))throw f(n,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(ie.has(e))throw f(n,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!P.test(e))throw f(n,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`)},oe=e=>e&&re.has(e)?e:void 0,ae=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},le=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,a]=n.getArguments();if(!r||!i.isStringLiteral(r))throw f(r??n,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const o=r.getLiteralText();let l="_unknown_",c="_id",g;return a&&i.isObjectLiteralExpression(a)&&(l=d(a,"field")??l,c=d(a,"references")??c,g=s==="one"?oe(d(a,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:o}},ce=e=>{const n=ae(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=le(s);r&&t.push(r)}return t},de=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),a=`${s}${r.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${a}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},fe=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=u(e,"unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},ue=e=>{const[n,t,s]=e,r=fe(s),a=y(n),o=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of o)if(!i.isStringLiteral(c))throw f(c,`index "${a}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>i.isStringLiteral(c));for(const c of l)de(c,c.getLiteralText(),a);return{fields:l.map(c=>c.getLiteralText()),name:a,unique:r}},pe=e=>{const[n,t]=e;let s="_unknown_",r,a,o,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=h(t,"filterFields"),a=d(t,"language"),o=O(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:a,name:y(n),staged:o,strategy:l}},ge=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"precision")),{field:s,name:y(n),precision:r}},me=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=x(t,"after")),{after:r,field:s}},be=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},xe=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const a=u(t,"sortBy");if(a&&i.isPropertyAssignment(a)){const o=a.getInitializer();o&&i.isArrayLiteralExpression(o)&&(s=o.getElements().map(l=>be(l)).filter(l=>l!==void 0))}r=h(t,"partitionBy")}return{name:y(n),partitionBy:r,sortBy:s}},he=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:A(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},ye=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},ve=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=u(e,"field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},Ee=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:te(n,"columns"),hasReconcile:u(n,"reconcileEveryMs")!==void 0,hasSoftDelete:u(n,"softDeleteColumn")!==void 0,hasTenantBy:u(n,"tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},Ie=(e,n,t,s)=>{switch(n){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ge(t));break}case"global":{e.shardMode="global",e.globalBackend=ye(t);break}case"index":{e.indexes.push(ue(t));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(xe(t));break}case"relations":{const r=t[0];r&&e.relations.push(...ce(r));break}case"searchIndex":{e.searchIndexes.push(pe(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:ve(t[0])};break}case"source":{e.externalSource=Ee(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=me(t);break}case"vectorize":{const r=he(t,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],we=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const a of L){const o=`${r.name}${a}`;if(!s.has(o))continue;const l=a==="__vocab"?`the \`fts5vocab\` companion for "${o}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${o}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw f(e,`table "${n}" declares search indexes "${r.name}" and "${o}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${o}" as its "${a}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Se=(e,n,t)=>{if(t.ttl!==void 0&&t.shardMode==="global")throw f(e,ne(n))},_=(e,n)=>{const t={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const a=r.getExpression(),o=r.getArguments();if(i.isPropertyAccessExpression(a))Ie(t,a.getName(),o,n),r=a.getExpression();else if(i.isIdentifier(a)&&a.getText()==="defineTable"){const l=o[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw f(l,`table "${n}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),we(e,n,t.searchIndexes),Se(e,n,t),{commitOrdered:t.commitOrdered,externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,memory:t.memory,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},j=(e,n=[],t=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const o=B(r.getExpression());o!==void 0&&!s.has(o)&&j(o,n,t,s);continue}if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(a){const o=I(r);if(w(o,r.getNameNode()),t.has(o))throw f(r.getNameNode(),`defineSchema({...}): table "${o}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(o),n.push(_(a,o))}}return n},ke=e=>{const n=u(e,"source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},Te=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),a=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:A(d(s,"metric")),name:a,table:ke(s)}},$=e=>{const n=[];for(const t of e.getProperties()){const s=Te(t);s&&n.push(s)}return n},S=(e,n)=>`${e}_${n}`,Le=(e,n)=>{if(!P.test(e))throw f(n,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,n,t)=>t.has(e)?S(n,e):e,Oe=(e,n,t)=>{const s=S(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:E(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:E(r.table,n,t)}))}},Ae=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ne=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},Pe=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},_e=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},je=(e,n)=>{const t=Ae(e);if(t){if(i.isPropertyAccessExpression(n)){const s=_e(t);return s?b(s,n.getName()):void 0}return t}},$e=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,Ne(n))return n;const s=Pe(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,o=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=je(o,n)}},De=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),keyNode:n,options:t}},ze=e=>{const n=u(e,"tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(!a)continue;const o=I(r);w(o,r.getNameNode()),s.push(_(a,o))}return s},Me=e=>{const n=u(e,"vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:$(t)},D=(e,n,t,s)=>{Le(e,s);const r=new Set(n.map(l=>l.name)),a=n.map(l=>Oe(l,e,r)),o=t.map(l=>({...l,name:S(e,l.name),table:E(l.table,e,r)}));return{tables:a,vectorIndexes:o}},Ce=(e,n,t)=>D(e,ze(t),Me(t),n),Re=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=$e(t);if(!s){if(n!==void 0){const a=Y(t,n);if(a){for(const o of a.bareTables)w(o.name,t);return D(a.key,a.bareTables,a.bareVectorIndexes,t)}}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=De(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Ce(r.key,r.keyNode,r.options)},Fe=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},Be=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=[];for(const a of Fe(e)){const o=Re(a,t);if(o){for(const l of o.tables){if(s.has(l.name))throw f(a,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...o.vectorIndexes)}}return r},Ve=new Set(["eu","fedramp","us"]),qe=e=>N(e,"jurisdiction","jurisdiction",Ve,'"eu", "us", or "fedramp"'),Je=e=>{let n=e;for(;;){const t=n.getParent(),s=t?.getParent();if(!t||!i.isPropertyAccessExpression(t)||!s||!i.isCallExpression(s))return!1;if(t.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&O(r,"pinAuth")===!0}n=s}},Ue=new Set(["required"]),Ke=e=>N(e,"rls","rls mode",Ue,'"required"'),et=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(C.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${n}`);const a=r.getArguments()[0];if(!a||!i.isObjectLiteralExpression(a))throw f(r,"defineSchema() expects an object literal");const o=j(a),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Be(r,o,t),k=[...o.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(o.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw f(r,q(v.table,v.name));return{jurisdiction:qe(r),...Je(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:Ke(r),tables:o,vectorIndexes:k}};export{et as default};
|
|
@@ -137,7 +137,7 @@ import{A as w,G as y}from"./emit-6YJU3YbV.mjs";const k=e=>`has${e.charAt(0).toUp
|
|
|
137
137
|
: {}),`]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
|
|
138
138
|
${a.join(`
|
|
139
139
|
`)}
|
|
140
|
-
`:""},B=e=>e.jurisdiction&&e.
|
|
140
|
+
`:""},B=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
|
|
141
141
|
// The schema's jurisdiction pins the auth object like every other DO.
|
|
142
142
|
jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",P=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
143
143
|
options.schedulerDO = this.schedulerDeclaration.namespace(env);
|
|
@@ -216,6 +216,9 @@ ${a.join(`
|
|
|
216
216
|
// The audit log lives in the object like every other auth table, so the feed
|
|
217
217
|
// reads through it rather than querying D1.
|
|
218
218
|
options.authAuditReader = authWiring.auditReader;
|
|
219
|
+
// Set only once auth is pinned to a jurisdiction: copies the users left in the
|
|
220
|
+
// un-pinned object across (\`__lunora_admin__:copyAuthToJurisdiction\`).
|
|
221
|
+
options.authJurisdictionMove = authWiring.jurisdictionMove;
|
|
219
222
|
// \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
|
|
220
223
|
// from the worker, which DO storage does not allow. The studio's auth pages
|
|
221
224
|
// therefore report "not configured" in this mode rather than silently
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.224",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
51
|
-
"@lunora/container": "1.0.0-alpha.
|
|
52
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
53
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
54
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
55
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
56
|
-
"@lunora/values": "1.0.0-alpha.
|
|
57
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.163",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.144",
|
|
51
|
+
"@lunora/container": "1.0.0-alpha.60",
|
|
52
|
+
"@lunora/errors": "1.0.0-alpha.44",
|
|
53
|
+
"@lunora/platform": "1.0.0-alpha.40",
|
|
54
|
+
"@lunora/queue": "1.0.0-alpha.72",
|
|
55
|
+
"@lunora/scheduler": "1.0.0-alpha.90",
|
|
56
|
+
"@lunora/values": "1.0.0-alpha.55",
|
|
57
|
+
"@lunora/workflow": "1.0.0-alpha.66",
|
|
58
58
|
"jiti": "^2.7.0",
|
|
59
59
|
"quicktype-core": "^26.0.0",
|
|
60
60
|
"ts-morph": "^28.0.0"
|