@lunora/codegen 1.0.0-alpha.319 → 1.0.0-alpha.320
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 +23 -2
- package/dist/index.d.ts +23 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-CjbDYC2a.mjs → NOTIFY_FILENAME-bAt7J3cs.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bo67h-3B.mjs +11 -0
- package/dist/packem_shared/chain-Cm6BMT8g.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-DVxdUhZt.mjs +1 -0
- package/dist/packem_shared/{context-property-calls-Bw8u2Pz4.mjs → context-property-calls-Cn3upNgZ.mjs} +1 -1
- package/dist/packem_shared/{context-root-YkWLB6M2.mjs → context-root-BdxINX-T.mjs} +1 -1
- package/dist/packem_shared/{database-calls-BnVUlTx_.mjs → database-calls-BKozZUEW.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-CZgLhsMn.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-DV4IglLE.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-DUbjhNzk.mjs → discoverInserts-BjxXCACZ.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-DE-8CDen.mjs +1 -0
- package/dist/packem_shared/{discoverNondeterministicCalls-D7Ovq8ae.mjs → discoverNondeterministicCalls-DvhyKM-f.mjs} +1 -1
- package/dist/packem_shared/{discoverQueries-BNqjOBY_.mjs → discoverQueries-C8E7TeRT.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-DVcfMO6-.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-CbdfaVep.mjs → discoverRlsMetadata-QRsWRQbM.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-BeLdV5RT.mjs → discoverRlsProcedures-Du7ITNTQ.mjs} +1 -1
- package/dist/packem_shared/{discoverStorageRulesMetadata-BBMy9JVZ.mjs → discoverStorageRulesMetadata-ClzKLdCV.mjs} +1 -1
- package/dist/packem_shared/{emitAgents-DuSp0uSJ.mjs → emitAgents-CR2_X_ov.mjs} +1 -1
- package/dist/packem_shared/emitFunctions-rjyb7h7k.mjs +422 -0
- package/dist/packem_shared/{emitShard-Ddgmq6De.mjs → emitShard-D3Po46nf.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-DAl7xBBx.mjs → exported-procedure-chains-BNBUkXui.mjs} +1 -1
- package/dist/packem_shared/{index-DvmKcoFV.mjs → index-JnqBWRYO.mjs} +1 -1
- package/dist/packem_shared/{shard-DYYhXxEG.mjs → shard-CsOnD3Na.mjs} +226 -117
- package/dist/packem_shared/{shard-runtime-BQ6ZNigW.mjs → shard-runtime-BpoCV-aM.mjs} +13 -8
- package/package.json +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DwqkR6hn.mjs +0 -11
- package/dist/packem_shared/chain-CubC5VoS.mjs +0 -1
- package/dist/packem_shared/classify-procedure-call-CcgP-9I0.mjs +0 -1
- package/dist/packem_shared/discoverFunctions-5Zy6K4uA.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DFbp-ILH.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-BfVFPpAJ.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-TNwsmYje.mjs +0 -1
- package/dist/packem_shared/emitFunctions-amc10WSc.mjs +0 -291
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as b}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as N}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{a as l,G as g}from"./shared-DnCokNcE.mjs";import{s as
|
|
1
|
+
import{r as b}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as N}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{a as l,G as g}from"./shared-DnCokNcE.mjs";import{s as k}from"./platform-8oj7iXQy.mjs";const I=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
2
2
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
3
3
|
this.ensureMigrated();
|
|
4
4
|
|
|
@@ -98,7 +98,7 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
|
|
|
98
98
|
|
|
99
99
|
return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
|
|
100
100
|
}
|
|
101
|
-
`;return{constant:a,evaluateOverride:u,subscriptionOverride:c}},
|
|
101
|
+
`;return{constant:a,evaluateOverride:u,subscriptionOverride:c}},R=()=>({build:`
|
|
102
102
|
const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
|
|
103
103
|
// Correlate AI-Gateway-routed calls with the Lunora trace: thread the
|
|
104
104
|
// function path + trace id into createAi, which folds them into the
|
|
@@ -133,7 +133,7 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
|
|
|
133
133
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
134
134
|
: x402Stub;
|
|
135
135
|
`,configField:`
|
|
136
|
-
x402?: (env: Record<string, unknown>) => X402PayConfig;`,importLines:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],stub:f("x402Stub: X402Pay","ctx.x402: no pay rail configured. Pass `x402` to createShardDO().",["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}),A={access:S,ai:
|
|
136
|
+
x402?: (env: Record<string, unknown>) => X402PayConfig;`,importLines:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],stub:f("x402Stub: X402Pay","ctx.x402: no pay rail configured. Pass `x402` to createShardDO().",["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}),A={access:S,ai:R,r2sql:w,x402:L},C=e=>e.shardBinding==="bespoke",_=e=>typeof e.shardBinding=="object",m=" ",F=(e,r,t)=>{const n=`${e}Binding`,{factory:a}=t;let u=`(${n} as ${r})`;if(a!==void 0){const c=`${n} as ${t.bindingType??r}`;u=a.option===void 0?`${a.name}(${c})`:`${a.name}({ ${a.option}: ${c} })`}return`${n} ? ${u} : ${e}Stub`},O=(e,r,t)=>{const n=F(e,r,t),a=`${m}const ${e}Binding = config.${e}?.(env) ?? (env as Record<string, unknown>).${t.envName};
|
|
137
137
|
`,u=t.unvouchableReads??[];return u.length===0?`
|
|
138
138
|
${a}${m}const ${e}: ${r} = ${n};
|
|
139
139
|
`:`
|
|
@@ -280,7 +280,7 @@ ${r}
|
|
|
280
280
|
const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
|
|
281
281
|
${r}
|
|
282
282
|
];
|
|
283
|
-
`}},ee=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{l(n.exportName,`topic export "${n.exportName}"`);const a=
|
|
283
|
+
`}},ee=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{l(n.exportName,`topic export "${n.exportName}"`);const a=k(r,n.exportName).map(u=>`{ binding: "${u.bindingName}", exportName: "${u.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${a}] },`}).join(`
|
|
284
284
|
`);return{build:`
|
|
285
285
|
const topics = createTopicContext(env, LUNORA_TOPICS);
|
|
286
286
|
`,contextField:`
|
|
@@ -314,13 +314,18 @@ const ${e} = ${b(n,r)};
|
|
|
314
314
|
return ${e};
|
|
315
315
|
}
|
|
316
316
|
`}),re=e=>{if(e.length===0)return{constant:"",override:""};const r={workflows:e.map(t=>({className:t.className,exportName:t.exportName,name:t.name}))};return v("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",r,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},oe=e=>{if(e.length===0)return{constant:"",override:""};const r={queues:e.map(t=>({binding:t.bindingName,...t.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:t.tuning.deadLetterQueue},exportName:t.exportName,mode:t.mode,name:t.name,...t.topic===void 0?{}:{topic:t.topic}}))};return v("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",r,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},P=["attach","cancelPayment","cancelSubscription","capturePayment","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","refundPayment","track"],se=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
|
|
317
|
-
|
|
317
|
+
const paymentsByContext = new WeakMap<object, LunoraPayment>();
|
|
318
318
|
`,configField:`
|
|
319
319
|
payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
|
|
320
320
|
get payments(): LunoraPayment {
|
|
321
|
-
payments
|
|
322
|
-
|
|
323
|
-
|
|
321
|
+
let payments = paymentsByContext.get(this);
|
|
322
|
+
|
|
323
|
+
if (payments === undefined) {
|
|
324
|
+
payments = config.payment
|
|
325
|
+
? paymentsFromContext({ auth: { userId: userId ?? null }, db: this.db as unknown as LunoraPaymentDbLike }, config.payment(env))
|
|
326
|
+
: paymentStub;
|
|
327
|
+
paymentsByContext.set(this, payments);
|
|
328
|
+
}
|
|
324
329
|
|
|
325
330
|
return payments;
|
|
326
331
|
},`,stub:f("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",P,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},ae=(e,r,t,n,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","DeliveryAuthorization","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{j as a,M as b,Q as c,Z as d,K as e,ee as f,te as g,H as h,z as i,ne as j,se as k,re as l,oe as m,D as n,ae as o,I as p,U as q,f as r,V as s,G as t,J as u,Y as v,X as w};
|
package/package.json
CHANGED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{existsSync as L,mkdirSync as fn,readFileSync as Wi,writeFileSync as qi,rmSync as xt,readdirSync as Hi}from"node:fs";import{dirname as gn,join as E,relative as ji}from"node:path";import{performance as ct}from"node:perf_hooks";import{runAdvisor as Gi}from"@lunora/advisor";import{LunoraError as G}from"@lunora/errors";import{serializeSchemaSnapshot as Yi}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Qi}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,ts as Xi,VariableDeclarationKind as Ji}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as w,bindingKeyName as re,collectCallRows as I,findObjectProperty as _,collectSecurityCallRows as Zi,propertyInitializer as C,listSecurityScanFiles as Ue,objectLiteralFromCallbackBody as pn,limitNameOf as mn,optionsObjectLiteral as hn,handlerOf as er,collectNodeRows as ee,chainRootOf as Lt,outermostValueWrapper as P,isWriteTarget as We,isSameNode as S,unwrapExpression as h,isConstDeclaration as te,memberAccessOf as vn,returningFunctionOf as St,walkChain as tr,RUN_METHODS as En,functionReferenceSegments as sr,isTestPath as nr,isFunctionLike as se,functionKeyOf as xn}from"./isTestPath-B81lOULB.mjs";import{b as X,d as W,f as O,g as Dt,c as v,a as Sn,w as Mt,k as ir,l as rr,h as or,m as ar,j as At,i as cr}from"./attribution-hVBriwzy.mjs";import{a as Ss,r as lt,i as Y,b as lr,m as An,c as qe,e as _t,E as yn,C as bn,d as dr,f as ur,g as fr}from"./context-root-YkWLB6M2.mjs";import{a as b,i as gr,c as Z,d as Nn,e as pr,f as mr}from"./classify-procedure-call-CcgP-9I0.mjs";import{a as y,r as Pn,s as hr,b as vr}from"./project-config-file-BV7RR-l6.mjs";import{a as Er,b as He}from"./module-specifiers-WF8iAydP.mjs";import{r as je,s as xr}from"./parse-validator-IDBKIT7M.mjs";import Sr from"./discoverAuthApiCalls-xs0ONfI-.mjs";import{i as D,r as wn}from"./database-calls-BnVUlTx_.mjs";import Ar from"./discoverHyperdriveCalls-DFbp-ILH.mjs";import{diagnosticAt as ye}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Kt,a as Me,s as In,d as yr}from"./index-DvmKcoFV.mjs";import{MUTATORS_FILENAME as br,isDefineMutatorCallee as Nr,mutatorServerImplOf as Pr,discoverMutators as wr}from"./MUTATORS_FILENAME-Jkk8Zgkb.mjs";import Ir from"./discoverNondeterministicCalls-D7Ovq8ae.mjs";import{discoverNotifyConfig as Cr,discoverNotifyCalls as Tr}from"./NOTIFY_FILENAME-CjbDYC2a.mjs";import Or from"./discoverR2sqlCalls-TNwsmYje.mjs";import kr from"./discoverRlsProcedures-BeLdV5RT.mjs";import{s as Bt,n as Rr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Fr,redact as Lr,isHeuristicSecretKind as Dr,isSecretishName as Mr}from"./redact-Cy14LEnc.mjs";import{a as Oe,d as _r,r as Kr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as Br,discoverWorkflows as zr}from"./WORKFLOWS_FILENAME-CdeS224T.mjs";import{r as $r}from"./json-data-Chfs2Cz5.mjs";import{G as Vr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Ur}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as wv,refreshCodegenProject as Iv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as Wr,usedCapabilities as qr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Cn,isHyperdriveGlobalTable as Tn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Hr}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as jr}from"./CONTAINERS_FILENAME-dFRtAyIe.mjs";import Gr from"./discoverCrons-DBnCama4.mjs";import{contextPropertiesRead as Yr,discoverFeatureUsage as Qr}from"./capabilitiesUsedBy-QgSZyE0T.mjs";import On from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Xr}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as Jr}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as Zr}from"./readServiceBindings-DvqIThzd.mjs";import eo from"./discoverStorageRulesMetadata-BBMy9JVZ.mjs";import{resolveCodegenTarget as kn,gatePlatformFeatures as to,readTargetDiagnostics as so,vectorizeDimensionDiagnostics as no,studioPlatformFor as io}from"./DEFAULT_TARGET-B0FkdiZq.mjs";import{i as ro}from"./schema-BgM8A3XV.mjs";import{b as Rn,e as oo}from"./shard-DYYhXxEG.mjs";import{e as ao,a as co}from"./server-DAvi_bv_.mjs";import{emitDataModel as lo}from"./emitDataModel-BskFt9Wv.mjs";import{i as uo,a as fo,e as go,b as po,d as mo,c as ho}from"./unwrap-handler-return-CeaOifqX.mjs";import vo from"./discoverFunctions-5Zy6K4uA.mjs";import Eo from"./discoverHttpRoutes-WBAqBcfK.mjs";import xo from"./discoverInserts-DUbjhNzk.mjs";import{e as Fn}from"./exported-procedure-chains-DAl7xBBx.mjs";import So from"./discoverMigrations-C9mLIhGZ.mjs";import Ao from"./discoverQueries-BNqjOBY_.mjs";import yo from"./discoverRlsMetadata-CbdfaVep.mjs";import bo from"./discoverSchema-BtsX-CN9.mjs";import{discoverShapes as No}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as Po}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as wo}from"./emitApp-BEe4wd3R.mjs";import{readJsonSync as Io}from"@visulima/fs";import{buildSchemaSnapshot as Co}from"./SchemaSnapshotParseError-BRJT7c2k.mjs";import{buildOpenApiDocument as To,emitOpenApiModule as Oo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as ko,emitOpenRpcModule as Ro}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as Fo,t as Lo,u as Do,s as Mo,w as _o}from"./shard-runtime-BQ6ZNigW.mjs";import{emitCollections as Ko,emitSeed as Bo,emitApi as zo,emitInternalApi as $o}from"./emitApi-CDgIPAG2.mjs";import{emitCrons as Vo,emitScheduler as Uo,emitShardRegistry as Wo,emitDurableObjects as qo,emitVectors as Ho,emitWranglerCronTriggers as jo}from"./emitCrons-BQW2lviZ.mjs";import Go from"./emitDrizzleSchema-DitcRZ1a.mjs";import Yo from"./emitFunctions-amc10WSc.mjs";const Ln=new Set(["delete","get","head","options","patch","post","put"]),Qo=new Set(["handler","stream"]),Xo=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,As=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Jo=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ln.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Zo=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||Ln.has(n.getName()))break;s=n.getExpression()}return Jo(s)},ea=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(As.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&As.has(s.getText()))return!0}return!1},ta=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Qo.has(n.getName()))return;const i=Zo(s);if(!i||!Xo.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&ea(o);return{exportName:W(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},sa=(e,t)=>{const s=[];for(const n of X(e)){const i=ta(n,t);i&&s.push(i)}return s},na=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sa(i,w(t,n)))}return s},ia=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},ra=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?re(t):void 0}},oa=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Ss(a)}))return!1;const n=O(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Ss(i)},ys=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=ia(e);return n!==void 0&&ra(n)===t?!0:t==="args"&&oa(e)},Dn=(e,t)=>r.isIdentifier(e)?ys(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>ys(s,t)),aa=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},bs=e=>{const t=r.isIdentifier(e)?O(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Dt(t)?t.getInitializer():void 0},yt=e=>Dn(e,"args"),Q=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},U=e=>{if(yt(e))return!0;const t=Q(e);return t!==void 0&&yt(t)},ca=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=Q(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},oe=e=>{if(lt(e))return!0;const t=bs(e);if(t!==void 0&<(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=bs(i);return o!==void 0&<(o)})},ke=(e,t)=>Dn(e,t),la=(e,t)=>{if(ke(e,t))return!0;const s=Q(e);if(s!==void 0&&ke(s,t))return!0;const n=aa(e);if(n!==void 0){const i=Q(n);return i!==void 0&&ke(i,t)}return!1},da=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Y(e.getExpression(),["ai"]),ua=(e,t)=>{if(!da(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!U(s)||oe(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},fa=(e,t)=>I(e,t,ua),ga=new Set(["generateText","streamText"]),pa=new Set(["messages","prompt","system"]),ma=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],ha=(e,t)=>ma.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),va=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[lr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&ha(i,s));return n===void 0?void 0:`${n}.${s}`},Ea=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=va(t);if(s!==void 0)return s}},xa=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=re(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Sa=e=>{if(yt(e))return!0;const t=xa(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},Aa=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!pa.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&Sa(s))return!0}return!1},ya=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());if(i===void 0||!ga.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(b(c.getExpression())==="tool"&&(a=Ea(c),a!==void 0))break;a!==void 0&&s.push({scope:v(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Aa(o)})}return s},ba=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ya(i,w(t,n)))}return s},Na=e=>Y(e,["fetch"]),Pa=(e,t)=>{if(!Na(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!U(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},wa=(e,t)=>I(e,t,Pa),zt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=je(s.getExpression());return n===void 0||zt(n,t)})}finally{t.delete(e)}},Ia=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=_(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:je(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:zt(i)}},Ca=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?je(o):void 0;a===void 0?s=!0:(t.push(a),s||=zt(a))}n=i.getExpression()}return{objects:t,opaque:s}},$t=(e,t)=>t?Ca(t):Ia(e),Mn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=je(s.getExpression());return n===void 0?[]:Mn(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Ta=e=>e.flatMap(t=>Mn(t,new Set)),Oa=new Set(["check","length","max"]),bt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(Oa.has(s.getName()))return!0;t=n}},Nt=e=>Er(e)||e==="@lunora/values",ka=e=>{const t=new Set(["v"]);for(const s of gr(e,"v",Nt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Nt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Ra=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},Fa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),La=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Nt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Vt=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return Fa(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&La(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Da=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},Ma=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},_a=e=>r.isReturnStatement(e)?e.getExpression():void 0,Ka=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Ma(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=_a(t);return s?[s]:[]}),_n=(e,t)=>{if(Vt(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return _n(e.getExpression(),t)},Ba=(e,t)=>{const s=Da(e.getExpression(),e.getSourceFile());if(!s)return[];const n=bt(e),i=new Set(Ka(s).map(o=>_n(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Vt(o,t);return a===void 0?[]:[{bounded:bt(o)||n&&i.has(o),factory:a}]})},za=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Vt(s,t),i=n===void 0?[]:[{bounded:bt(s),factory:n}];return r.isCallExpression(s)?[...i,...Ba(s,t)]:i}),$a=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=za(a,t),l=y(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Va=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=Z(n);if(i?.visibility!=="public")return;const{objects:o}=$t(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=$a(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:W(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Ua=(e,t)=>{const s=[],n=ka(e),i={destructured:Ra(e,n),namespaces:n};for(const o of X(e)){const a=Va(o,t,i);a&&s.push(a)}return s},Wa=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ua(i,w(t,n)))}return s},dt=e=>e?.getKind()===d.TrueKeyword,qa=e=>e?.getKind()===d.FalseKeyword,Ha=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,ja=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Ga=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&b(t.getExpression())==="scim"),Ya=e=>e!==void 0&&r.isCallExpression(e)&&ja.has(b(e.getExpression())??""),Qa=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),Xa=e=>{const t=C(e,"advanced"),s=C(e,"emailAndPassword"),n=C(e,"session");return{analyzable:!0,disableCsrfCheck:dt(C(t,"disableCSRFCheck")),emailPasswordEnabled:dt(C(s,"enabled")),requireEmailVerification:dt(C(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Ga(C(e,"plugins"))&&Ya(C(e,"database")),secureCookiesDisabled:qa(C(t,"useSecureCookies")),sessionFreshAgeZero:Ha(C(n,"freshAge")),trustedOriginsWildcard:Qa(C(e,"trustedOrigins"))}},Ja=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Za=(e,t)=>{if(b(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?Xa(s):Ja();return{scope:v(e),file:t,line:e.getStartLineNumber(),...i}},ec=(e,t)=>Zi(e,t,Za),tc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return An(e.getExpression(),t.matchReceiver)?s:void 0},sc=(e,t,s)=>{const n=tc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!U(i)||oe(i))&&!(s.requireUnmodifiedReach===!0&&!ca(i)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:n}},Ge=(e,t,s)=>I(e,t,(n,i)=>sc(n,i,s)),nc=new Set(["content","pdf","scrape","screenshot"]),ic=(e,t)=>Ge(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:nc}),rc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),oc=new Set(["RateLimiter"]),ac=new Set(["extend"]),Ns="lunora",cc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Kn=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Pt=e=>e&&r.isObjectLiteralExpression(e)?Kn(e):{analyzable:!1,presentKeys:[],trueKeys:[]},lc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&pn(t.getBody());return s?Kn(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},dc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());i!==void 0&&(rc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Pt(n.getArguments()[0])}):ac.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...lc(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=b(n.getExpression());i===void 0||!oc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Pt(n.getArguments()[0])})}return s},uc=(e,t)=>{for(const s of cc){const n=E(t,s);if(!L(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))b(a.getExpression())===Ns&&o.push({callee:Ns,file:s,line:a.getStartLineNumber(),...Pt(a.getArguments()[0])});return o}return[]},fc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ue(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...dc(o,n))}return s.push(...uc(e,gn(t))),s},Ps="ctx.containers.",gc=e=>{if(!e.startsWith(Ps))return!1;const t=e.slice(Ps.length);return t.length>0&&!t.includes(".")},pc=(e,t)=>Ge(e,t,{argIndex:0,matchReceiver:gc,methods:new Set(["get"])}),mc=new Set(["allow","deny","setAllowed"]),hc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=_(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},vc=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!hc(e)))return{detail:"enableInternet: true",scope:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Ec=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!mc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},xc=(e,t)=>vc(e,t)??Ec(e,t),Sc=(e,t)=>I(e,t,xc),Ac=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(D(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&D(s.getExpression())?s.getName():void 0},yc=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&D(s)?1:0]},bc=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Nc=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>bc.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Pc=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return I(e,t,(i,o)=>{const a=Ac(i);if(a===void 0)return;const c=Nc(yc(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:v(i),table:a}})},wc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Ic=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return wc.has(s)?s:void 0},Cc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=y(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Tc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ue(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=Ic(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Cc(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},Oc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),kc=new Set(["dbRateLimit","rateLimit"]),Rc=e=>{const t=hn(e);if(!t)return!1;const s=_(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Fc=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=Oc.get(s);if(n!==void 0)return{callee:s,scope:v(e),failOpen:Rc(e.getArguments()[n]),file:t,limitName:kc.has(s)?mn(e):"",line:e.getStartLineNumber()}},Lc=(e,t)=>I(e,t,Fc),Dc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=Z(t);if(s?.kind!=="query")return;const n=er(t,s.receiver);return n?{exportName:W(e)??e.getName(),handler:n}:void 0},ws=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Mc=e=>{const t=ws(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=ws(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},_c=(e,t)=>{const s=[];for(const n of qe(e.handler,"flags"))s.push({callee:Mc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Kc=(e,t)=>{const s=[];for(const n of X(e)){const i=Dc(n);i&&s.push(..._c(i,t))}return s},Bc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Kc(i,w(t,n)))}return s},zc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Y(e.getExpression(),["flags"]),$c=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Vc=(e,t)=>{if(!zc(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=$c(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:v(e),file:t,key:i,line:e.getStartLineNumber()}},Uc=(e,t)=>I(e,t,Vc),Wc=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},qc=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Hc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of i.getDescendantsOfKind(d.CallExpression))Wc(a)&&s.push({file:o,indexName:qc(a),line:a.getStartLineNumber()})}return s},xe=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,Bn=e=>{const t=e.getArguments()[0],s=xe(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=_(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?xe(n.getInitializer()):void 0},jc=new Set(["delete","get","head","options","patch","post","put"]),Gc=new Set(["handler","stream"]),Yc=new Set(["runAction","runMutation"]),Qc=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Se=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,zn=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(re(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Is=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:zn(s,"ctx")},Cs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:zn(s,"request")},Ts=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Yc.has(a)&&Se(c,t))return a;if(Qc.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Se(c.getExpression(),t))return`db.${a}`}},Os=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Se(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Se(n.getInitializer(),t))){for(const o of i.getElements())if(re(o)==="auth")return!0}}return!1},Xc=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Jc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Se(n.getExpression(),t)},Zc=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],$n=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Zc(s)},el=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?$n(t,a.getText()):[]}return[]},tl=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=$n(s,t.getText());return n.length>0?n:el(t,s)},ks=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>Jc(i,t)&&tl(i).some(o=>Xc.test(o)))},sl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Gc.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(jc.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},nl=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=xe(e.getArguments()[0]),l=c&&Is(c,!0);if(!c||l===void 0||ks(c,Cs(c,!0)))return;const u=Ts(c,l);return u===void 0?void 0:{scope:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Os(c,l),sideEffect:u}}const n=sl(e);if(n===void 0)return;const i=xe(e.getArguments()[0]),o=i&&Is(i,!1);if(!i||o===void 0||ks(i,Cs(i,!1)))return;const a=Ts(i,o);return a===void 0?void 0:{scope:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Os(i,o),sideEffect:a}},il=(e,t)=>I(e,t,nl),rl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ol=new Set(["append","set"]),Vn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Rs=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>rl.has(b(n.getExpression())??"")&&ke(n,t)),al=(e,t)=>{if(Rs(e,t))return!0;const s=Q(e);return s!==void 0&&Rs(s,t)},wt=(e,t)=>la(e,t)&&!al(e,t),cl=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&r.isNewExpression(t)&&b(t.getExpression())==="Headers"},_e=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Ut=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&wt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Vn(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();wt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=_e(n.getExpression());i!==void 0&&Ut(i,t,s)}},Un=(e,t)=>{const s=_e(e);if(s===void 0)return;const n=_(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=_e(n.getInitializer());i!==void 0&&Ut(i,"response-init",t)},ll=(e,t)=>{const s=b(e.getExpression());if(s==="Response")Un(e.getArguments()[1],t);else if(s==="Headers"){const n=_e(e.getArguments()[0]);n!==void 0&&Ut(n,"headers-ctor",t)}},dl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){Un(e.getArguments()[1],t);return}if(ol.has(n)&&cl(i)){const o=e.getArguments()[1];o!==void 0&&wt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Vn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},ul=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))ll(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))dl(s,t)},fl=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=xe(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return ul(n,{scope:v(e),relativePath:t,requestName:o.getText(),rows:a}),a},gl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...fl(n,t));return s},pl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...gl(i,w(t,n)))}return s},Wn="identity.ts",ml=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return He(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},hl=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&He(n.getModuleSpecifierValue())}return!1},vl=e=>{if(r.isIdentifier(e))return ml(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&hl(t)}return!1},El=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!vl(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ye(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Sn(s,"member");a!==void 0&&t.push({exportName:a})}return t},xl=(e,t)=>{const s=E(t,Wn);if(!L(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=El(n);if(i.length!==0){if(i.length>1)throw ye(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Sl=new Set(["auth","context.auth"]),Al="userId",yl=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(y(s))}return t},bl=(e,t)=>{const s=E(t,Wn);if(!L(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(b(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?yl(o):void 0}},Fs=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Sl.has(t.getText())||Y(t,["auth"])?e:void 0},Nl=e=>{if(r.isPropertyAccessExpression(e)&&Fs(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Fs(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},Ls=(e,t,s)=>{const n=Nl(e);return n===void 0?void 0:{declared:n===Al||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:v(e)}},Pl=(e,t)=>{const s=bl(e,t);return s===void 0?[]:[...ee(e,t,d.PropertyAccessExpression,(n,i)=>Ls(n,i,s)),...ee(e,t,d.ElementAccessExpression,(n,i)=>Ls(n,i,s))]},wl=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=C(s,"key");if(!(!n||!U(n)||oe(n)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},Il=(e,t)=>I(e,t,wl),Cl=new Set(["delete","get","getRaw","getWithMetadata","put"]),Tl=(e,t,s=[])=>{const n=Ge(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Cl});return Mt(n,s)},Ol=new Set(["queue","send"]),Ds=new Set(["bcc","cc","to"]),kl=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ol.has(t))return;const s=e.getExpression();return Y(s,["mail"])||Y(s,["email"])?t:void 0},Rl=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ds.has(y(t))&&U(n)&&!oe(n)}if(!r.isPropertyAssignment(t)||!Ds.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&U(s)&&!oe(s)}):!1,Fl=(e,t)=>{const s=kl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Rl(n)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},Ll=(e,t)=>I(e,t,Fl),Dl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Me(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Me(l);if(u===void 0)continue;const f=In(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Ml=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Z(s):void 0;return n?.receiver?Kt(n.receiver).flatMap(i=>Dl(i,W(e)??e.getName(),t)):[]},_l=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of X(i))s.push(...Ml(a,o))}return s},Kl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return D(s)},Bl=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=_(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},zl=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Nr(s.getExpression())?s:void 0},$l=e=>{const t=zl(e),s=t===void 0?void 0:Bl(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?W(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Kl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Vl=e=>e.getVariableDeclarations().flatMap(t=>$l(t)),Ul=(e,t)=>{const s=E(t,br);if(!L(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Vl(n)},Wl=new Set(["delete","get","patch"]),ql=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Hl=new Set(["auth","identity","session","user"]),jl=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Gl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!D(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Yl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},Ql=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Xl=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Jl=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Ql(s.getExpression(),t)&&Xl(s.getThenStatement())),Zl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Wl.has(i))continue;const o=n.getExpression();if(!(D(o)||r.isPropertyAccessExpression(o)&&D(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},ed=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>_t(Lt(s))!==void 0)),td=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>jl.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),sd=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(ql.has(t.getText()))return!0;return[...Hl].some(t=>qe(e,t).length>0)?!0:ed(e)||td(e)},nd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Bn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Nn(n.receiver,"use","rls"),a=sd(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=Gl(u);if(f===void 0)continue;const g=Yl(u);if(g===void 0||c.has(g)||!Jl(i,g))continue;const p=Zl(i,g);p!==void 0&&(c.add(g),l.push({exportName:W(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:f,usesRls:o,visibility:n.visibility}))}return l},id=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of X(i))s.push(...nd(a,o))}return s},qn=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?O(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},rd=e=>{const t=P(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!We(s)},od=e=>{const t=P(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},ad=e=>{const s=P(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!We(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},Ke=e=>{const t=O(e);return t===void 0||rr(t.getSourceFile())},It=(e,t)=>{const s=P(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&Ke(o);if(qn(Lt(o),t))return!(r.isPropertyAccessExpression(o)&&yn.has(o.getName()))||r.isExpressionStatement(P(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!Ke(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},Re={kind:"opaque"},cd={kind:"unreached"},ld=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Ct=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?O(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=ld(s);return i===void 0||Dt(i)?void 0:i}const n=te(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Hn=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?Re:c===void 0?a.some(l=>l.isRestParameter())?Re:cd:c.isRestParameter()?Re:{kind:"parameter",parameter:c}},dd=e=>{const t=P(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Ct(s.getExpression());return n===void 0?Re:Hn(n,s,t)},ud=new Set(["__defineGetter__","__defineSetter__","__proto__"]),fd=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,jn=e=>{const t=P(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=fd(s);if(n!==void 0)return S(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},gd=4,Gn=(e,t,s=0)=>{if(ir(e))return!0;if(rd(e)){const i=P(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!ud.has(c)}if(od(e)||ad(e)||jn(e)||It(e,t))return!0;const n=dd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&pd(n.parameter,s+1)},Ms=new WeakMap,pd=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Ms.get(e.compilerNode);if(n!==void 0)return n;if(t>gd)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||O(a)?.compilerNode!==e.compilerNode||Gn(a,void 0,t));return(o||t===0)&&Ms.set(e.compilerNode,o),o},_s=new WeakMap,md=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=O(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},hd=(e,t,s)=>{const{context:n,impl:i}=e,o=_s.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const p=g.getNameNode();return r.isIdentifier(p)?[p]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?Gn(g,n):!We(g),f=!md(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const p=g.getText();if(p==="arguments")return!1;const x=l.get(p);return x===void 0||c.includes(g)||O(g)?.compilerNode!==x?!0:u(g)});return _s.set(i.compilerNode,f),f},Ks=new WeakMap,vd=e=>{let t=Ks.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Pr(s);return n===void 0?[]:[[n.compilerNode,s]]})),Ks.set(e.compilerNode,t)),t},Ed=e=>{const t=vd(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:W(n)??n.getName()};return a!==void 0&&hd(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},ut="args",he=e=>{const t=vn(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===ut?t.member:void 0}if(!r.isIdentifier(e))return;const s=O(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=te(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&re(i)===ut||r.isIdentifier(o)&&o.getText()===ut?re(s):void 0},xd=new Set(["auth","identity","user"]),Tt=e=>{const t=i=>{const o=_t(i);return o!==void 0&&o.length>0&&xd.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=Q(s);return n!==void 0&&t(n)},Yn=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=he(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?Q(n):void 0;if(o!==void 0)for(const a of Yn(o,t-1))s.add(a)}return s},Fe=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Fe(n),...Fe(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=he(h(u)??u);return g===void 0?[]:Fe(f).filter(p=>p===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=he(h(n)??n),c=he(h(i)??i);return a!==void 0&&Tt(i)&&o.push(a),c!==void 0&&Tt(n)&&o.push(c),o},Sd=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&pr(i.getExpression(),"defineIdentityGuard")},Ad=e=>{if(!Sd(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=he(h(s)??s),o=t.some((a,c)=>c!==n&&Tt(a));return i!==void 0&&o?[i]:[]})},yd=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},bd=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Bs=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},Nd=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Pd=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&Bs(n,e)&&yd(n.getThenStatement()))for(const i of Fe(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&Nd(n)&&Bs(n,e))for(const i of Ad(n))s.add(i);return s},wd=(e,t)=>{const s=Yn(t);if(s.size===0)return!1;const n=e.getFirstAncestor(bd);if(n===void 0)return!1;const i=Pd(n,e.getStart());return[...s].every(o=>i.has(o))},Id=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Cd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Ot=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Qn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Td=e=>{const t=P(e),s=t.getParent();if(r.isVariableDeclaration(s))return S(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Od=e=>{const t=Td(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||te(t)?[t]:void 0:Qn(t)},ve=e=>e.isUnion()?e.getUnionTypes().every(t=>ve(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>ve(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Be=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Le=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},kd=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&Cd.get(s.getText())?.has(t.getName())===!0&&Ke(s)},Rd=e=>{const t=St(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=P(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Be(n,bn)?n:void 0},Fd=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=P(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Be(n,Id,t)?n:void 0},Ld=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Dd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&S(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},zs=e=>{const t=P(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&kd(s);return Fd(s,t)??Ld(s,t)??Dd(s,t)??(n?s:Rd(t))},Md=5e4,Xn=()=>({inProgress:new Set,verdicts:new Map});class _d{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Md&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Kd=8,Bd=8;class zd{budget;scope;taint;verdicts=Xn();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!ve(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Qn(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Kd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(P(l),!0,a,0))&&(t===n||!ve(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let p=zs(o);p!==void 0;p=zs(o)){if(r.isCallExpression(p)&&this.callbackCompromises(p,n))return!0;o=P(p)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&ve(o.getType());if(We(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Od(o);if(u!==void 0)return u.some(p=>n(p,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=P(t).getParent();if(n>=Bd)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===P(t)?this.valueCompromises(i,!1,s,n+1):!Be(i,Ot);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||te(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=P(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Le(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Be(t,Ot)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Ct(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!It(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(It(s,this.scope.context))return!1;const i=Ct(t.getExpression()),o=i===void 0?void 0:Hn(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||jn(t)||S(St(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=St(t);return S(s,this.scope.impl)?void 0:s}}const $d=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Vd=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=O(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Ud=new Set(["all","allSettled","any","race"]),$s=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,ft=8;class Wd{budget=new _d;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Xn();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new zd(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,ft)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>or(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=O(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=P(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Ot.has(g.getName()))return!0;const p=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(g.getExpression(),!0)||p.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&te(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const p=P(g),x=p.getParent();return!r.isCallExpression(x)||x.getExpression()!==p||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&Ke(i)&&Ud.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Le(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=O(t),i=$s(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&yn.has(i)?!1:i!==void 0&&bn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Le(a)!==void 0)&&(i===void 0||!$d.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Lt(i),c=r.isIdentifier(a)?$s(O(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Le(i);if(o===void 0)return!Vd(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=tr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(qn(i,this.scope.context))return!0;const o=r.isIdentifier(i)?O(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=te(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=Dt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,ft))return!1;if(this.variableDepth>=ft)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Vs=new WeakMap,qd=e=>{const t=Vs.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Wd(e);return Vs.set(e.impl.compilerNode,s),s},Hd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),jd=new Set(["insert","insertManyUnsafe","patch","replace"]),Gd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return jd.has(t)&&dr(e.getExpression())?t:void 0},Yd=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},Qd=(e,t)=>{const s=vn(e);return s?.member===t?h(s.object):void 0},Us=(e,t)=>r.isIdentifier(e)&&O(e)?.compilerNode===t.compilerNode,Jn=(e,t,s,n=1)=>{const i=Qd(e,s);if(i!==void 0)return Us(i,t);const o=r.isIdentifier(e)?O(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&re(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||te(l)&&Us(h(l.getInitializer()),t))}const a=te(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Jn(a,t,s,n-1)},kt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...kt(t.getWhenTrue()),...kt(t.getWhenFalse())]:[t]},Xd=(e,t,s)=>{const n=[],i=s===void 0?void 0:qd(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Hd.has(a))continue;const l=kt(c).filter(f=>i===void 0?U(f)&&!ur(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&Jn(c,s.parameter,a),g=l.every(p=>wd(t.call,p));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Jd=(e,t,s)=>{const n=Gd(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=Yd(i,n);if(o.length===0)return[];const a=v(e),c=Ed(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Xd(u,l,c))},Zd=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=I(e,t,(c,l)=>Jd(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Mt(o,s).map(c=>ar(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},eu=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),tu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,su=e=>{const t=_(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?tu(t.getInitializer()):void 0},nu=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!eu.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?su(n):void 0;return{callee:s,scope:v(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},iu=(e,t)=>I(e,t,nu),ru=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),ou=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},au=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=_(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Zn=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},ei=(e,t)=>e===t||e.startsWith(`${t}.`),ti=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},Ws=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},si=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Ws(s));return r.isIdentifier(e)&&Ws(e)&&t.push(e),t},cu=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},lu=e=>{const t=Zn(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},du=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:lu(e),i=new Set,o=a=>ti(a).some(c=>n.some(l=>ei(c.getText(),l)))?!0:si(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of cu(a))i.add(l)}return{names:i,prefixes:n}},uu=(e,t)=>ti(e).some(s=>t.prefixes.some(n=>ei(s.getText(),n)))?!0:si(e).some(s=>t.names.has(s.getText())),fu=e=>{const t=sr(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},gu=(e,t,s)=>{const n=Zn(e,0);if(n===void 0)return[];const i=du(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!En.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!uu(u,i))continue;const f=fu(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:v(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},pu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=ou(n),o=i===void 0?void 0:ru.get(i);if(o===void 0)continue;const a=au(n,o);a!==void 0&&s.push(...gu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},mu=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pu(i,w(t,n)))}return s},qs={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Hs=new Set(["account","credential","member","passkey","session","user"]),hu=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),vu=e=>{const s=hu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Hs.has(s)||Hs.has(n)},Eu=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},xu=(e,t)=>{const{objects:s,opaque:n}=$t(e,t);return Ta(s).some(i=>Eu(i))?!0:n?void 0:!1},Su=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!_(t,"captcha"),usesRateLimit:!!_(t,"rateLimit")}},Au=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},De={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},yu=e=>{const t=Au(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Su(t);return{...De,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in qs?{...De,[qs[s]]:!0}:De},bu=e=>{const t={...De};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=yu(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Nu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Pu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Nu.has(t.getName()))return!1;const s=t.getExpression();if(!D(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:vu(i.getLiteralText())},wu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),js=new Set(["queues","scheduler","topics","workflows"]),Iu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!wu.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&js.has(s.getName())&&fr(s.getExpression()))return!0;s=s.getExpression()}const n=_t(s);return n?.length===1&&js.has(n[0]??"")},Cu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return D(s)},ni=new Set(["generateObject","generateText","streamObject","streamText"]),Tu=e=>{const t=b(e.getExpression());return t!==void 0&&ni.has(t)},Ou=e=>{const t=b(e.getExpression());if(t===void 0||!ni.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!_(s,"maxOutputTokens")},ku=new Set(["log","span","trace"]),Ru=new Set(["ai"]),Fu=new Set(["email","mail"]),Lu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),gt=(e,t)=>[...t].some(s=>qe(e,s).length>0),ii=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Du=new Set(["every","filter","flatMap","forEach","map","some"]),Mu=new Set(["all","allSettled","race"]),ri=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(Du.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Mu.has(n))return t},_u=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(ii.has(t.getKind())){const s=ri(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Ku=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(ii.has(t.getKind())){if(t=ri(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Bu=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(p=>{const x=p.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(p.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},zu=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},$u=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Vu=e=>{let t=!1,s=!0;for(const n of[...Lu].flatMap(i=>qe(e,i))){const i=$u(n);i&&(t=!0,!_u(i)&&!zu(i)&&!Bu(i)&&!Ku(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Uu=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),Gs="lunora-advisor-exempt",Wu=/^[\s*/]+/u,qu=/[\w-]/u,Hu=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
2
|
-
`);for(const n of s.split(`
|
|
3
|
-
`)){const i=n.replace(Wu,"");if(!i.startsWith(Gs))continue;const o=i.slice(Gs.length);if(qu.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},ju=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=_(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Gu=(e,t)=>{const s=ju(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},Yu=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(Pu(l)&&(o=!0),Iu(l)&&(t=!0),Cu(l)&&(i=!0),Tu(l)&&(s=!0),Ou(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Vu(e);return{callsMail:gt(e,Fu),emitsEvent:gt(e,ku),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||gt(e,Ru),throwsBareError:Uu(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},Qu=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=Z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?bu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Gu(e,s);return{...o?Yu(o):{},...Hu(e),...i,analyzableBody:o!==void 0,exportName:W(e)??e.getName(),file:t,hasEmailArg:xu(s,n.receiver),kind:n.kind,visibility:n.visibility}},Xu=(e,t)=>{const s=[];for(const n of X(e)){const i=Qu(n,t);i&&s.push(i)}return s},Ju=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xu(i,w(t,n)))}return s},Zu=new Set(["dbRateLimit","rateLimit"]),ef=e=>r.isArrowFunction(e)?e.getBody():e,tf=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},oi=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},ai=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},sf=(e,t)=>U(e)||t!==void 0&&ai(e,t).some(s=>oi(s)),nf=(e,t)=>t===void 0?oe(e):ai(e,t).some(s=>!oi(s)),rf=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Zu.has(s))return;const n=C(hn(e.getArguments()[2]),"key");if(!n)return;const i=ef(n),o=tf(n);if(!(!sf(i,o)||nf(i,o)))return{callee:s,scope:v(e),file:t,limitName:mn(e),line:e.getStartLineNumber()}},of=(e,t)=>I(e,t,rf),af=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),cf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!af.has(t.getName()))return;const s=t.getExpression();if(D(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&D(s.getExpression()))return s.getName()},lf=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&D(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},df=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},ci=(e,t=!1)=>{const s=df(e);if(r.isIdentifier(s)){if(t)return;const n=Q(s);return n===void 0?void 0:ci(n,!0)}if(r.isCallExpression(s))return cf(s)??lf(s)},uf=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},ff=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Z(s);if(n?.kind!=="query")return[];const i=Bn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&mr(n.receiver,"output"),a=n.receiver!==void 0&&Nn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of uf(i)){const f=ci(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:W(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},gf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of X(i))s.push(...ff(a,o))}return s},pf=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(y(s));return t},mf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Z(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=wn(o);if(a===void 0)continue;const c=pf(C(a.options,"with"));c.length!==0&&i.push({exportName:W(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},hf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of X(i))s.push(...mf(a,o))}return s},V=(e,t)=>`${e}:${t}`,Ys=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},vf=(e,t)=>[...ee(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Ys(s,n,s.getName(),s.isExported()):void 0),...ee(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Ys(i,n,s.getName(),i.isExported()):void 0})],Ef=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=w(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(V(c,a))},xf=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Sf=(e,t)=>{const s=new Map(e.map(n=>[V(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(V(i.file,i.name))?.set(xf(n),{fields:n.fields,method:n.method,table:n.table})}return s},Af=(e,t,s)=>e.node.getDescendantsOfKind(d.CallExpression).map(n=>Ef(n,t,s)).filter(n=>n!==void 0),yf=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(V(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(V(o.file,o.name))?.push(a)}},bf=(e,t,s)=>{const n=new Map(e.map(a=>[V(a.file,a.name),a])),i=new Map(e.map(a=>[`${Bt(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[V(a.file,a.name),Af(a,n,t)]));return yf(s,n,i,o),o},Nf=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Pf=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(V(i.file,i.name))??[])Nf(t.get(V(i.file,i.name)),t.get(V(o.file,o.name)))&&(n=!0)}},wf=(e,t,s,n)=>{const i=vf(e,t),o=Sf(i,s);return Pf(i,o,bf(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(V(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},ze=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=ze(e.getLeft()),s=ze(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},If=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&ze(t)!==void 0},Cf=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return y(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Tf=(e,t,s)=>Dr(e)?!nr(s)&&Mr(Cf(t)):!0,Of=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(If(o))continue;const a=ze(o);if(a===void 0)continue;const c=Fr(a);if(c===void 0||!Tf(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:Lr(a)}))}return s},kf=(e,t)=>{const s=[];for(const n of A(t,{includeSkipped:!0})){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Of(i,w(t,n)))}return s},Rf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Z(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=wn(o);if(a===void 0)continue;const c=C(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&U(c);!l&&!u||i.push({exportName:W(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Ff=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of X(i))s.push(...Rf(a,o))}return s},Lf=new Set(["query","unsafe"]),Df=e=>!r.isPropertyAccessExpression(e)||!Lf.has(e.getName())?!1:Y(e.getExpression(),["sql"]),Mf=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),_f=(e,t)=>{if(!Df(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Mf(s)))return{file:t,line:s.getStartLineNumber(),scope:v(e)}},Kf=(e,t)=>I(e,t,_f),Bf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],zf=e=>{for(const[t,s]of Bf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},$f=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=zf(a);c!==void 0&&s.push({file:w(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Vf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Uf=(e,t,s=[])=>{const n=Ge(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Vf,requireUnmodifiedReach:!0});return Mt(n,s)},Wf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),qf=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Hf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),o==="expiresInSeconds"&&(s=qf(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},jf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Wf.get(t);return s===void 0?void 0:An(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Gf=(e,t)=>{const s=jf(e.getExpression());if(s!==void 0)return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...Hf(e.getArguments()[s.optionsIndex])}},Yf=(e,t)=>I(e,t,Gf),Qf=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),li=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Qf(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>se(i)||s(i));if(!(n===void 0||se(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},Wt=(e,t)=>S(e.getFirstAncestor(s=>S(s,t)||se(s)),t),Xf=(e,t)=>S(e,t)||e.getFirstAncestor(s=>S(s,t))!==void 0,di=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return S(e,t)||Wt(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=li(e);return s!==void 0&&!Xf(s,t)}return!1},ui=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],Jf=e=>ui(e).some(t=>di(t,e)),Zf=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},eg=e=>ui(e).some(t=>di(t,e)||r.isBreakStatement(t)&&S(li(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Zf(t)&&Wt(t,e)),tg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>Wt(t,e)),sg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),ng=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",pt=(e,t)=>{const s=sg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||eg(e)||tg(e))return;const i=v(e);if(!(i.kind==="module"&&e.getFirstAncestor(se)!==void 0))return{file:t,kind:ng(e),line:e.getStartLineNumber(),scope:i}},ig=(e,t)=>[...ee(e,t,d.WhileStatement,pt),...ee(e,t,d.ForStatement,pt),...ee(e,t,d.DoStatement,pt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),rg=new Set(["when","where"]),mt=new Set(["definePolicy","defineShape"]),og=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return mt.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return mt.has(i)?i:void 0}const s=t.getText();return mt.has(s)?s:void 0},ag=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,fi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(ag(e))return"empty-object";if(r.isParenthesizedExpression(e))return fi(e.getExpression())}},qt=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),cg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>qt(t)===e),gi=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>qt(t)===e),lg=e=>{const t=cg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||gi(e).length>0},dg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>qt(t)===e),Rt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",ug=(e,t)=>Rt(e)||Rt(t),fg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Qs=e=>!Rt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),gg=(e,t,s)=>{const n=fg.get(e);if(n!==void 0)return ug(t,s)?n==="positive"?"negative":"positive":Qs(t)||Qs(s)?void 0:n},Ee=e=>{if(r.isParenthesizedExpression(e))return Ee(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=gg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=Ee(e.getLeft()),i=Ee(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Xs=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},pg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},mg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,hg=e=>{const t=[];for(const s of gi(e)){const n=Ee(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of dg(e)){const n=Ee(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Xs(s.getThenStatement()):Xs(s.getElseStatement())??pg(s);i!==void 0&&t.push(mg(i))}return t},vg=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},Eg=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!rg.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&lg(a))for(const c of hg(a)){const l=fi(c);l!==void 0&&i.push({exportName:vg(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},xg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=og(n);i!==void 0&&s.push(...Eg(n,i,t))}return s},Sg=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...xg(i,w(t,n)))}return s},Ag=new Set(["query","upsert","upsertMany","upsertNow"]),le=new Set,yg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Ag.has(t))return Y(e.getExpression(),["vectors"])?t:void 0},Ht=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},pi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},mi=e=>pi(e)?.getDeclarations()[0],bg=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},hi=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},Js=(e,t,s)=>{const n=pi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=hi(mi(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return jt(o,t,s-1)}return U(e)},jt=(e,t,s)=>{const n=Ht(e);return oe(n)?!1:r.isIdentifier(n)?Js(n,t,s):U(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>bg(i)&&Js(i,t,s))},vi=e=>{const t=hi(mi(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},J=(e,t)=>{const s=Ht(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...J(s.getWhenTrue(),t),...J(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...J(s.getLeft(),t),...J(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=vi(s);return n===void 0?[]:J(n,!1)}return[]},Ng=(e,t)=>{const s=J(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>$e(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Pg=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",wg=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),$e=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Ng(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Pg(n)&&(s=[wg(n)]);return s},Ig=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},Cg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return le;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return le;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Ft=(e,t=!0,s=le)=>{const n=Ht(e);if(r.isIdentifier(n)){const o=t?vi(n):void 0;return o===void 0?[{node:n,parameters:s}]:Ft(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Ft(o.getExpression(),t,s):J(o,!0).flatMap(a=>$e(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=jt(i.getExpression(),le,1)?Cg(o):le;return Ig(o).flatMap(c=>J(c,!0).flatMap(l=>$e(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Tg=(e,t)=>{const s=yg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Ft(n):J(n,!0).flatMap(o=>$e(o,!0).map(a=>({node:a,parameters:le})))).some(({node:o,parameters:a})=>jt(o,a,1))))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},Og=(e,t)=>I(e,t,Tg),kg=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:p,workflows:x}=s;return Qi({adminRoutes:na(e,t),aiRawRuns:fa(e,t),aiToolSideEffects:ba(e,t),argumentDerivedFetches:wa(e,t),argumentValidators:Wa(e,t),authApiCalls:Sr(e,t),authConfigs:ec(e,t),browserUrlAccesses:ic(e,t),callEdges:n.callEdges,configCalls:fc(e,t),containerKeyAccesses:pc(e,t),containerOverrides:Sc(e,t),containers:i,countReads:Pc(e,t,f.tables),cronTargets:o.flatMap(z=>z.functionPath===void 0?[]:[z.functionPath]),exportSinks:Tc(e,t),staleMigrationImports:$f(e,t),failOpenGuards:Lc(e,t),flagReads:Bc(e,t),flagSecurityDefaults:Uc(e,t),geoIndexUsages:Hc(e,t),httpActionGuards:il(e,t),httpHeaderWrites:pl(e,t),hyperdriveCalls:Ar(e,t),identityClaimReads:Pl(e,t),imageDeliveryUrlAccesses:Il(e,t),inserts:n.inserts,kvKeyAccesses:Tl(e,t,a),mailRecipientAccesses:Ll(e,t),maskProcedures:yr(e,t),maskStrategies:_l(e,t),mutatorWrites:Ul(e,t),nondeterministicCalls:Ir(e,t),normalizeIdAuthorizations:id(e,t),notifyCalls:Tr(e,t),notifyConfig:Cr(e,t),mutators:l,ownerFieldWrites:Zd(e,t,a,l),unrestrictedWhereBranches:Sg(e,t),paymentWebhooks:iu(e,t),privilegedDispatches:mu(e,t),procedureProtections:Ju(e,t),queries:n.queries,queues:u,r2sqlCalls:Or(e,t),ratelimitKeySelectors:of(e,t),rawRowReturns:gf(e,t),relationLoads:hf(e,t),rlsProcedures:kr(e,t),schema:f,secretLiterals:kf(e,t),modules:c,shapes:g,softDeleteReads:Ff(e,t),sqlInterpolations:Kf(e,t),storageKeyAccesses:Uf(e,t,a),storageUploads:Yf(e,t),tableWrites:n.tableWrites,rowEffects:wf(e,t,n.tableWrites,n.callEdges),unboundedLoops:ig(e,t),vectorNamespaceAccesses:Og(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:p})},Rg=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),Fg=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>Rg(i))]},Lg=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Dg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",Zs={error:"ERROR",info:"INFO",warn:"WARN"},en={ERROR:2,INFO:0,WARN:1},Mg=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"}),_g=(e,t)=>{const{advisor:s}=Pn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(Zs,n)?Zs[n]:void 0;return i===void 0?[...t,Mg(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>Dg(o)||en[o.level]>=en[i])},Kg=(e,t)=>{const{advisor:s}=Pn(e),n=Fg(t,s?.accept??[]);return _g(e,s?.acceptUnreadable===!0?[...n,Lg()]:n)},Bg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},zg="crons",$g=Br.replace(/\.ts$/u,""),ce=(e,t)=>`${Bt(e)}:${t}`,ht=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Vg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Bg[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...ht("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...ht("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...ht("workflow",t.workflow,"workflow name")}))],Ug=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Wg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Ug(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},qg=e=>Vg(e).flatMap(t=>Wg(t)),Hg=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:zg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],jg=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),me=(e,t)=>t===void 0?e:{...e,module:t},Gg=e=>{const t=new Map,s=new Map,n=jg(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(ce(c.file,c.exportName),l)};for(const c of e.functions){const l=ce(c.filePath,c.exportName),u=[...Rr(c.filePath),c.exportName].join(".");o(me({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Oe(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ce(c.filePath,c.exportName);o(me({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Oe(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(me({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(me({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Oe(e.modules,c.filePath)),ce(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(me({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Oe(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ce($g,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},Yg=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Qg=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ce(e.file,e.exportName))??{reason:Yg(e.exportName)},Xg=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Qg(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},vt=e=>`${e.from}|${e.kind}|${e.to}`,Jg=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Zg=e=>{const{nodes:t,sites:s}=Gg(e),n=new Map,i=new Map;for(const o of[...Hg(e),...qg(e)]){const a=Xg(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(vt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Jg(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>vt(o).localeCompare(vt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},ep=e=>`${Vr}export const architecture = ${$r(e,"Record<string, unknown>")};
|
|
4
|
-
`,tn=(e,t="api")=>{const s=new Map;for(const n of e){const i=Bt(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new G("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},tp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Cn(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=>Tn(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:Wr)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},sp=(e,t,s={})=>{if(t===void 0)return;const n=tp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
5
|
-
`);throw new G("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
6
|
-
${i}
|
|
7
|
-
|
|
8
|
-
Install them with your package manager, then re-run codegen.`)},np="env.ts",ip=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return He(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},rp=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&He(n.getModuleSpecifierValue())}return!1},op=e=>{if(r.isIdentifier(e))return ip(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&rp(t)}return!1},ap=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!op(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ye(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=Sn(s,"member");a!==void 0&&t.push({exportName:a})}return t},cp=(e,t)=>{const s=E(t,np);if(!L(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=ap(n);if(i.length!==0){if(i.length>1)throw ye(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},lp={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"typedWebSockets"},dp=new Set(["allowedHosts","deniedHosts","interceptHttps"]),up=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},fp=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(y(s));if(!r.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),gp=new Set(["durable"]),pp=new Set(["rollback"]),Ei=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},mp=new Map([["defineContainer",{keys:dp,signal:"containerEgressPolicy"}],["defineStep",{keys:pp,signal:"workflowRollback"}],["stream",{keys:gp,signal:"durableStreams"}]]),hp=(e,t)=>{const s=mp.get(Ei(t));if(s!==void 0)return t.getArguments().some(n=>fp(up(e,n),s.keys))?s.signal:void 0},vp=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,liveStreams:!1,secrets:!1,typedWebSockets:!1,workflowRollback:!1};for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Yr(i).has("secrets"));for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=hp(i,o);a!==void 0&&(s[a]=!0);const c=lp[Ei(o)];c!==void 0&&(s[c]=!0)}if(Object.values(s).every(Boolean))break}return s},Ep="createWorker",xp="extend",sn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,nn=e=>{const t=[],s=sn(C(e,"backupCron"));s!==void 0&&t.push(s);const n=C(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=sn(i.getNameNode());o!==void 0&&t.push(o)}return t},Sp=e=>{const t=b(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Ep)return r.isObjectLiteralExpression(s)?nn(s):[];if(t!==xp||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=pn(s.getBody());return n===void 0?[]:nn(n)},Ap=(e,t)=>{const s=[];for(const{filePath:n}of Ue(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression))s.push(...Sp(o))}return[...new Set(s)]},xi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:xi(e.inner)},yp=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=xi(n);return i!==void 0&&t.has(i)}))},bp=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new G("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new G("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Np=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=xl(s,t),a=cp(s,t),c=zr(s,t),{queues:l,topics:u}=Xr(s,t),f=Zr(n),g=Hr(s,t);bp(c,g);const p=jr(s,t),x=eo(s,t),z=Gr(s,t,c,g),q=Ap(s,t),R=vp(s,t),F=Jr(s,t),T=Qr(s,t);T.browser=T.browser||F.usesSandboxBrowser;const $=kn(n,e.target),N=to(T,$,{agents:g.length>0,commitOrderedTables:i.tables.some(k=>k.commitOrdered===!0),cronTriggers:z.length>0,crossShardFanout:i.tables.some(k=>ro(k)),containerEgressPolicy:R.containerEgressPolicy,containerRuntimeScheduling:p.some(k=>k.schedulingPolicy==="durable_object"),containerSandboxTools:p.some(k=>k.sandbox===!0),durableStreams:R.durableStreams,globalTables:i.tables.some(k=>k.shardMode==="global"),liveStreams:R.liveStreams,typedWebSockets:R.typedWebSockets,queues:l.length>0,relationGraph:yp(i),secrets:R.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:F.usesSandboxLoader,workflowRollback:R.workflowRollback,workflowSchedules:c.some(k=>k.schedules!==void 0)}),M=N.usage,H=qr(M),ne=N.signals.vectorStore!==!1,ue=N.signals.services===!1?[]:f,fe=On(n),j=fe??new Set,K=j.has("lunorash");sp(i,fe,{hasVectors:ne,scheduler:M.scheduler||z.length>0,storage:M.storage||x.rules.length>0||Object.keys(Rn(i)).length>0,usage:M});const B=L(E(t,"flags.ts")),be=L(E(t,"notify.ts"));return{agents:g,capabilities:H,containers:p,crons:z,dataModelContent:lo(i),declaredDependencies:fe,dependencies:j,entryCronTriggers:q,env:a,featureUsage:M,hasFlags:B,hasNotify:be,identity:o,platformGate:{...N,diagnostics:[...so(n,e.target),...N.diagnostics,...no($,i.vectorIndexes)]},queues:l,serverContent:ao({agents:g,capabilities:H,containers:p,env:a,hasVectors:ne,hasFlags:B,hasNotify:be,identity:o,queues:l,schema:i,services:ue,storageRuleBuckets:x.rules.map(k=>k.bucket),topics:u,useUmbrella:K,workflows:c}),services:ue,storageRulesMetadata:x,topics:u,usesSandbox:F.usesSandboxBrowser||F.usesSandboxContainer||F.usesSandboxFs,useUmbrella:K,workflows:c}},Si=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Pp=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},wp=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Ip=/^[\w$]+:[\w$]+$/u,Cp=(e,t)=>{const s=xn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},rn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Tp=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return rn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Ji.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?rn(s):void 0}}},Op=(e,t,s)=>({schedule:{argKeys:Tp(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),kp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(En.has(s))return Cp(s,n);if((s==="runAfter"||s==="runAt")&&Pp(t)){const l=xn(i)??(r.isStringLiteral(i)&&Ip.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Op(s,n,o)}}const a=wp.get(s),c=a===void 0?void 0:Si(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Rp=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Ai=e=>Xi.isOptionalChain(e.compilerNode),Fp=(e,t)=>r.isIfStatement(t)?!S(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?S(e,t.getStatement()):r.isForStatement(t)?S(e,t.getStatement())||S(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:se(t)?t.getFirstAncestor(se)!==void 0:r.isConditionalExpression(t)?!S(e,t.getCondition()):r.isBinaryExpression(t)?!S(e,t.getLeft())&&Rp.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Ai(t)?!S(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Jf(s)),Lp=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&S(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(se);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&S(o.getFirstAncestor(se),i))===!0},Dp=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&S(e,t.getStatement())||r.isForStatement(t)&&(S(e,t.getStatement())||S(t.getIncrementor(),e)),Mp=(e,t)=>{if(Ai(e)||t==="schedule"&&Lp(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Fp(s,i)){if(!Dp(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},on=(e,t,s)=>{if(s===void 0)return;const n=Mp(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:v(e)}},_p=(e,t)=>[...I(e,t,(s,n)=>on(s,n,kp(s))),...ee(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Si(s,"services");return on(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Kp=new Set(["boolean","number","object","string"]),Bp=e=>{const t=e.getName();if(!Kp.has(t))return;const s=e.getExpression();return Y(s,["flags"])||Y(s,["flags","details"])?t:void 0},zp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Bp(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},$p=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=zp(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Vp=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||uo(o))return;const a=e.getSourceFile().getFilePath();if(fo(i,e,a)){const c=go(i,e,a,0,new Set);return c===void 0&&po(o),c}return o},Up=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=hr(t.getNameNode());return s===void 0||s==="namespace"}),Wp=(e,t)=>{for(const{filePath:s}of Ue(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Up(a)))return i}}},qp="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Hp=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ye(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 (${qp}). 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})},jp=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Gp=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?jp(e):!0,yi=(e,t=!1)=>{for(const s of e.getProperties()){if(Gp(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||yi(n,!0))return!0}return!1},Yp=(e,t)=>{for(const s of A(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Fn(n))for(const o of Kt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||yi(a)))return!0}}return!1},Qp=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Me(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Me(a);c!==void 0&&s.push({column:c,strategy:In(a),table:i})}}return s},Xp=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Fn(i))for(const a of Kt(o))for(const c of Qp(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Jp=["providerSubscriptionId","state"],Zp=["providerEventId","processedAt"],an=(e,t)=>t.every(s=>s in e.shape),em=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&an(t,Jp)&&an(s,Zp)},tm=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],sm=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},nm=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},im="@lunora/privacy",bi="userId",rm=e=>e.replaceAll("\\","/"),om="privacy",am=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),Ye=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Qe=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Gt=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),cm=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},Xe=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},lm=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=cm(s,"tables"),i=Ye(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Gt(n).map(a=>Qe(a)))t.datasets.set(o,i)},dm=(e,t)=>{const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)?Gt(s):[],i=new Set(n.map(o=>Qe(o)));for(const o of tm)i.has(o)||t.datasets.set(o,"authDataset");for(const o of n){const a=r.isPropertyAssignment(o)?Ye(o.getInitializer()):void 0;a!==void 0&&t.datasets.set(a,"authDataset")}},cn=(e,t,s)=>{t.datasets.set(Ye(e.getArguments()[0])??s,s)},Yt=8,Ae=(e,t=0)=>{if(t>Yt)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Ae(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Ae(i,t+1)},um=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Qe(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Ni=(e,t=0)=>{const s=Ae(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Yt)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Ni(i.getExpression(),t+1):[um(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},fm=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Ni(t)},gm=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Ae(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Gt(n):[])t.excluded.set(Qe(i),r.isPropertyAssignment(i)?Ye(i.getInitializer())??"":"")},pm=(e,t)=>{switch(Xe(e)){case"actionCacheDataset":{cn(e,t,"actionCache");break}case"authDataset":{dm(e,t);break}case"defineDataset":{lm(e,t);break}case"documentHistoryDataset":{cn(e,t,"documentHistory");break}}},Qt=e=>e!==void 0&&r.isCallExpression(e)&&Xe(e)==="defineDataset",Pi=e=>e!==void 0&&r.isCallExpression(e)&&am.has(Xe(e)??""),mm=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(Qt(i)||Pi(i))?n:void 0},wi=(e,t,s=0)=>{const n=Ae(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Yt)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!wi(i.getExpression(),t,s+1))return!1}else if(!Qt(i)&&!Pi(i)){const o=r.isIdentifier(i)?mm(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},hm=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||wi(t,s)?s:void 0},vm=(e,t)=>{const s=[];for(const i of e.getDescendantsOfKind(d.CallExpression))if(pm(i,t),Xe(i)==="definePrivacy"){const o=fm(i);gm(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:hm(o)})}return{declared:e.getDescendantsOfKind(d.VariableDeclaration).filter(i=>Qt(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Em=(e,t)=>{const s=E(t,"schema.ts"),n=[...A(t),...L(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>rm(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},xm=(e,t,s)=>{if(s?.has(im)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[]};const n={datasets:new Map,excluded:new Map},i=[],o=[];for(const f of Em(e,t)){const g=vm(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:sm(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l}},Sm=e=>e.extensionKey!==om&&bi in e.shape,Am=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (it has a "${bi}" column) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,ym=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Sm(o)).map(o=>o.name),[n]=nm(s,t.classifications);if(n!==void 0)throw new G("PRIVACY_COVERAGE",Am(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new G("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},bm=(e,t)=>{const s=io(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Nm=new Set(["delete","hardDelete","patch","replace","restore"]),Pm=new Set(["insertMany","insertManyUnsafe","patchIf","patchWhere"]),wm=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),ln=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],i=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return i.length===n.length?i:[]},Im=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const i=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return i===void 0?[]:ln(i,e)}return ln(s,e)},dn="",Cm=(e,t)=>{if(t!=="patch"&&t!=="patchMany")return;const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=[];for(const i of s.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isShorthandPropertyAssignment(i))return;n.push(i.getName())}return n},Tm=(e,t)=>{if(Pm.has(e))return{method:e,tables:[t!==void 0&&r.isStringLiteral(t)?t.getLiteralText():dn]};if(Nm.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:Im(t,e);return{method:e,tables:s.length===0?[dn]:s}}},un=(e,t)=>e===void 0?void 0:{...e,fields:Cm(t,e.method)},Om=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(D(n))return un(Tm(s,e.getArguments()[0]),e);if(wm.has(s)&&r.isPropertyAccessExpression(n)&&D(n.getExpression()))return un({method:s,tables:[n.getName()]},e)},km=(e,t)=>I(e,t,(s,n)=>{const i=Om(s);if(i===void 0)return;const o=v(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Rm=(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"}),Fm=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||_(s,"args")===void 0)return!1}return $t(e,t).opaque},Lm=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=Z(a);c!==void 0&&Fm(a,c.receiver)&&s.push(Rm(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},Dm=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...Lm(i,w(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Mm=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."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ve=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Ii=e=>!e.isAny(),Ci=e=>{const t=e.getType();if(!Ii(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Mm.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},_m=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},Ti={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."},Km=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.`}),Bm={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},zm=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),$m={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},Vm=(e,t,s)=>{if(!t.some(i=>cr(i)))return Bm;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return zm.has(s.typeName)&&!n&&!t.some(i=>Po(i))?$m:Ti},Oi=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Km(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},Um=(e,t,s)=>{const n=[];for(const i of X(e)){const o=r.isIdentifier(i.getNameNode())?At(i):[i.getName()],c=o.some(u=>Ve(s,t,u))||!_m(i)?void 0:Ci(i),[l=i.getName()]=o;c!==void 0&&n.push(Oi(t,l,c,i.getStartLineNumber(),Vm(i,o,c)))}return n},Wm=(e,t,s)=>{if(Ve(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=Ci(i.getExpression());o!==void 0&&n.push(Oi(t,"default",o,i.getStartLineNumber(),Ti))}return n},qm=(e,t,s)=>[...Um(e,t,s),...Wm(e,t,s)],Hm=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>At(n).some(i=>Ve(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=At(n).find(o=>Ve(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),jm=({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"}),Gm=(e,t,s)=>{const n=[],i=[];for(const a of A(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...qm(c,l,s)),i.push(...Hm(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Ii(a.getType()))&&n.push(jm(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Ym=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},Qm=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Xm=(e,t)=>I(e,t,(s,n)=>Ym(s)?{file:n,line:s.getStartLineNumber(),scope:v(s),workflow:Qm(s)}:void 0),Je=(e,t)=>{L(e)&&Wi(e,"utf8")===t||qi(e,t,"utf8")},Jm=(e,t)=>{if(t===""){xt(e,{force:!0});return}Je(e,t)},Zm=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){xt(s,{force:!0,recursive:!0});return}if(L(s))for(const n of Hi(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[ji(e,i)]===void 0&&xt(i)}for(const[n,i]of Object.entries(t))fn(gn(E(e,n)),{recursive:!0}),Je(E(e,n),i)},eh=e=>{try{const t=Io(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},de=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Et=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,th=(e,t)=>{L(e)||fn(e,{recursive:!0});const s=[];for(const n of t)n.kind==="services"?(Zm(e,n.files),s.push(...Object.keys(n.files))):n.kind==="always"?(Je(E(e,n.name),n.content),s.push(n.name)):(Jm(E(e,n.name),n.content),n.content!==""&&s.push(n.name));return s},sh=e=>{const t=eh(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=To({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=ko({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
|
|
9
|
-
`,openApiModuleContent:Oo(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
|
|
10
|
-
`,openRpcModuleContent:Ro(i)}},nh=".lunora-schema.json",ih=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},rh=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new G("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new G("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new G("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},oh=8,ah=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lunoraDirectory:o,migrations:a,project:c,roomsSupported:l,shapes:u,usesSandbox:f,useUmbrella:g,workflows:p}=e,x=()=>ho(()=>{const T=vo(c,o),$=wr(c,o);return{functions:T,httpRoutes:Eo(c,o),mutators:$}});let{erased:z,value:{functions:q,httpRoutes:R,mutators:F}}=x();tn([...q,...F].map(T=>T.filePath)),tn(R.filter(T=>T.stream).map(T=>T.filePath),"http-stream");for(let T=1;;T+=1){const $=l?q:q.filter(ne=>ne.channel?.kind!=="room"),N=zo({agents:t,functions:$,httpRoutes:R,mutators:F,useUmbrella:g,workflows:p}),M=Yo({agents:t,functions:$,migrations:a,mutators:F,shapes:u,useUmbrella:g,usesSandbox:f}),H=$o({functions:q,useUmbrella:g});if(T>=oh||Et(c,s,N)&&Et(c,i,H)&&Et(c,n,M))return{apiContent:N,erased:z,functions:q,functionsContent:M,httpRoutes:R,internalContent:H,mutators:F};de(c,s,N),de(c,i,H),de(c,n,M),{erased:z,value:{functions:q,httpRoutes:R,mutators:F}}=x()}},bv=e=>{const t=ih(),s=t?ct.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=E(n,"schema.ts");if(!L(i))throw new G("INTERNAL",`schema.ts not found at ${i}`);const o=e.project??Ur(n);xr(Vp);const a=bo(o,i,e.projectRoot);ym(a.tables,xm(o,n,On(e.projectRoot)));const{agents:c,capabilities:l,containers:u,crons:f,dataModelContent:g,dependencies:p,entryCronTriggers:x,env:z,featureUsage:q,hasFlags:R,hasNotify:F,identity:T,platformGate:$,queues:N,serverContent:M,services:H,storageRulesMetadata:ne,topics:ue,usesSandbox:fe,useUmbrella:j,workflows:K}=Np({lunoraDirectory:n,project:o,projectRoot:e.projectRoot,schema:a,target:e.target});Hp(a,a.jurisdiction===void 0?void 0:Wp(o,n));const B=E(n,"_generated"),be=E(B,"dataModel.ts"),k=E(B,"server.ts"),ki=E(B,"api.ts"),Ri=E(B,"internal.ts"),Fi=E(B,"functions.ts");de(o,be,g),de(o,k,M);const Xt=Object.fromEntries(H.filter(m=>m.rpcEntrypoint!==void 0).flatMap(m=>Object.entries(co(m,B))));for(const[m,at]of Object.entries(Xt))de(o,E(B,m),at);const Ne=So(o,n),ae=No(o,n),Jt=$.signals.typedWebSockets!==!1,{apiContent:Zt,erased:Li,functions:ie,functionsContent:es,httpRoutes:Ze,internalContent:ts,mutators:et}=ah({agents:c,apiPath:ki,generatedFunctionsPath:Fi,internalPath:Ri,roomsSupported:Jt,lunoraDirectory:n,migrations:Ne,project:o,shapes:ae,useUmbrella:j,usesSandbox:fe,workflows:K}),ss=_r(o,n),tt=Kr(ss,a,[...ie,...Ze].map(m=>m.filePath)),Pe=ss.length>0,we=e.lint===!1&&!Pe?void 0:{callEdges:_p(o,n),inserts:xo(o,n),queries:Ao(o,n,ie),tableWrites:km(o,n),workflowCalls:Xm(o,n)},Ie=e.lint===!1||we===void 0?void 0:kg(o,n,{callSites:we,containers:u,crons:f,functions:ie,modules:tt,mutators:et,queues:N,schema:a,shapes:ae,workflows:K,wranglerVariables:e.wranglerVariables}),ns=Ie===void 0?[]:Kg(e.projectRoot,[...Gi(Ie,{source:"static"}),...Gm(o,n,{byName:new Set([...K,...N,...c,...u].map(m=>m.exportName)),byPath:new Set([...ie,...et,...ae,...Ne].map(m=>`${m.filePath}:${m.exportName}`))}),...Dm(o,n),...mo(Li,n),...Fo(N,e.wranglerQueueProducers)]),Di=yo(o,n),is=Xp(o,n);rh(ae,is,Yp(o,n));const Mi=R?$p(o,n):[],st=$.signals.vectorStore!==!1,ge=bm(q,{containerCount:u.length,cronCount:f.length,dependencies:p,hasPaymentTables:em(a.tables),queueCount:N.length,storageColumnCount:Object.keys(Rn(a)).length,storageRuleCount:ne.rules.length,vectorIndexCount:a.vectorIndexes.length,target:kn(e.projectRoot,e.target),vectorStoreSupported:st,workflowCount:K.length}),rs=t?ct.now():0,nt=Co(a,Ne.map(m=>m.id)),os=oo({advisories:ns.filter(m=>m.name!=="procedure_type_check_unavailable"),advisorProcedures:Ie?.procedureProtections??[],agents:c,capabilities:l,containers:u,env:z,flagKeys:Mi,hasFlags:R,hasNotify:F,hasRooms:Jt&&ie.some(m=>m.channel?.kind==="room"),hasVectors:st,maskMetadata:is,mutators:et,queues:N,rlsMetadata:Di,schema:a,schemaSnapshot:nt,shapes:ae,services:H,storageRules:ne,studioFeatures:ge,topics:ue,useUmbrella:j,workflows:K}),as=Ko(ae,p.has("@lunora/db"),j),cs=Lo(u,a.jurisdiction),ls=Do(K),ds=Mo(c),us=_o(N,e.wranglerQueueProducers),fs=Vo(f),_i=Uo(ge.scheduler),Ki=Wo(a.tables,j),Bi=vr(e.projectRoot)?qo(j):"",gs=Ho(a.vectorIndexes),Ce=Go(a,j),ps=Bo(p.has("@lunora/seed")),Te=e.apiSpec??"openapi",it=Te==="openapi"||Te==="both",rt=Te==="openrpc"||Te==="both",ms=wo({capabilities:l,emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({className:m.className,exportName:m.exportName})),hasAccess:p.has("@lunora/cloudflare-access"),hasAuth:p.has("@lunora/auth"),hasFramework:p.has("@lunora/astro")||p.has("@lunora/svelte")||p.has("@lunora/vue")||L(E(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(m=>Cn(m)),hasHyperdriveGlobal:a.tables.some(m=>Tn(m)),hasKvIntrospector:ge.kv,hasNotify:F,hasQueue:N.some(m=>m.mode==="push"),hasScheduler:ge.scheduler,hasSourcedTables:a.tables.some(m=>m.externalSource!==void 0),hasStorage:ge.storage,hasVectors:st,hasWorkflow:K.length>0,identity:T,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(m=>({name:m.name,shardMode:m.shardMode})),useUmbrella:j,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsArchitecture:Pe,wantsOpenApi:it,wantsOpenRpc:rt}),{openApiContent:hs,openApiModuleContent:vs,openRpcContent:Es,openRpcModuleContent:xs}=sh({functions:ie,httpRoutes:Ze,modules:tt,projectRoot:e.projectRoot,wantsArchitecture:Pe}),pe=Pe&&we!==void 0?Zg({...we,crons:f,functions:ie,httpRoutes:Ze,modules:tt,queues:N,schema:a,services:H,topics:ue,workflows:K}):void 0,ot=E(n,nh),zi=L(ot),$i=e.dryRun?[]:th(B,[{content:ms,kind:"always",name:"app.ts"},{content:g,kind:"always",name:"dataModel.ts"},{content:Zt,kind:"always",name:"api.ts"},{content:ts,kind:"always",name:"internal.ts"},{content:M,kind:"always",name:"server.ts"},{content:es,kind:"always",name:"functions.ts"},{content:os,kind:"always",name:"shard.ts"},{content:fs,kind:"always",name:"crons.ts"},{content:gs,kind:"always",name:"vectors.ts"},{content:Ce.global,kind:"always",name:"drizzle.global.ts"},{content:Ce.shard,kind:"always",name:"drizzle.shard.ts"},{content:cs,kind:"optional",name:"containers.ts"},{content:ls,kind:"optional",name:"workflows.ts"},{content:ds,kind:"optional",name:"agents.ts"},{content:us,kind:"optional",name:"queues.ts"},{content:_i,kind:"optional",name:"scheduler.ts"},{content:Ki,kind:"optional",name:"shardRegistry.ts"},{content:Bi,kind:"optional",name:"durableObjects.ts"},{content:ps,kind:"optional",name:"seed.ts"},{content:as,kind:"optional",name:"collections.ts"},{files:Xt,kind:"services"},{content:it?hs:"",kind:"optional",name:"openapi.json"},{content:it?vs:"",kind:"optional",name:"openapi.ts"},{content:rt?Es:"",kind:"optional",name:"openrpc.json"},{content:rt?xs:"",kind:"optional",name:"openrpc.ts"},{content:pe===void 0?"":`${JSON.stringify(pe,void 0,2)}
|
|
11
|
-
`,kind:"optional",name:"architecture.json"},{content:pe===void 0?"":ep(pe),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!zi||e.updateSchemaBaseline===!0)&&Je(ot,Yi(nt)),t){const m=ct.now(),at=Math.round(m-s),Vi=Math.round(rs-s),Ui=Math.round(m-rs);console.error(`@lunora/codegen: codegen took ${at.toString()}ms (discovery ${Vi.toString()}ms, emit ${Ui.toString()}ms)`)}return{advisories:ns,advisorContext:Ie,agents:c,architecture:pe,containers:u,cronTriggers:[...new Set([...jo(f),...x])],generated:{agents:ds,api:Zt,app:ms,collections:as,containers:cs,crons:fs,dataModel:g,drizzleGlobal:Ce.global,drizzleShard:Ce.shard,functions:es,internal:ts,openApi:hs,openApiModule:vs,openRpc:Es,openRpcModule:xs,queues:us,seed:ps,server:M,shard:os,vectors:gs,workflows:ls},migrations:Ne,outputDirectory:B,platformDiagnostics:$.diagnostics,queues:N,schemaSnapshot:nt,schemaSnapshotPath:ot,workflows:K,writtenFiles:$i}};export{nh as SCHEMA_SNAPSHOT_FILENAME,Ur as createCodegenProject,wv as findTsconfig,Iv as refreshCodegenProject,bv as runCodegen};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{w as a}from"./classify-procedure-call-CcgP-9I0.mjs";const l=s=>a(s,"use","rls");export{l as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Node as r,SyntaxKind as x}from"ts-morph";import{a as d}from"./module-specifiers-WF8iAydP.mjs";import{unwrapExpression as l}from"./isTestPath-B81lOULB.mjs";const F=e=>r.isIdentifier(e)?e.getText():r.isPropertyAccessExpression(e)?e.getName():void 0,C=(e,t,i=d)=>{const n=new Set;for(const o of e.getImportDeclarations())if(i(o.getModuleSpecifierValue()))for(const s of o.getNamedImports())s.getNameNode().getText()===t&&n.add(s.getAliasNode()?.getText()??s.getName());return n},E=(e,t)=>{if(r.isPropertyAccessExpression(e))return e.getName()===t;if(!r.isIdentifier(e))return!1;const i=e.getText();return i===t||C(e.getSourceFile(),t).has(i)},m=e=>{for(const t of e.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(t)&&d(t.getImportDeclaration().getModuleSpecifierValue()))return t.getNameNode().getText()},g=e=>e.getSymbol()?m(e):e.getText(),A=(e,t)=>r.isIdentifier(e)&&m(e)===t,y=e=>{const t=[];let i=l(e);for(;i&&r.isCallExpression(i);){const n=l(i.getExpression());if(!n||!r.isPropertyAccessExpression(n))return{root:void 0,steps:t};t.push({call:i,name:n.getName()}),i=l(n.getExpression())}return{root:i,steps:t}},v=e=>y(e).steps,I=(e,t,i)=>v(e).filter(n=>n.name===t).map(n=>n.call.getArguments()[0]).filter(n=>n!==void 0&&r.isCallExpression(n)&&i(n.getExpression())),T=(e,t,i)=>I(e,t,n=>E(n,i)),O=(e,t)=>v(e).some(i=>i.name===t),R=(e,t,i)=>T(e,t,i).length>0,p=new Set(["action","mutation","query","stream"]),N={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},w={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init",onWhisper:"whisper"},u={defineRoom:"room"},D=e=>e==="whisper"?"query":"mutation",h=e=>{const{root:t}=y(e);return t&&r.isIdentifier(t)?t:void 0},S=(e,t=!1)=>{const i=h(e);if(!i)return;const n=g(i);if(n===void 0){if(t)return;const o=i.getSymbol()?.getValueDeclaration();if(o&&r.isVariableDeclaration(o)){const s=o.getInitializer();return s?S(s,!0):void 0}return}return p.has(n)?"public":N[n]?"internal":void 0},b=(e,t=!1)=>{if(I(e,"use",s=>A(s,"platformAdmin")).length>0)return!0;if(t)return!1;const i=h(e)?.getSymbol(),n=(i?.isAlias()?i.getAliasedSymbol():i)?.getValueDeclaration(),o=n&&r.isVariableDeclaration(n)?n.getInitializer():void 0;return o!==void 0&&b(o,!0)},f=e=>b(e)?{adminOnly:!0}:{},k=e=>{const t=e.getName();if(!p.has(t))return;const i=e.getExpression(),n=l(i)??i,o=i===n?[n]:[i,n];if(o.some(a=>a.getType().getProperty("__lunoraProcedure"))){const a=o.some(c=>c.getType().getProperty("__lunoraVisibility"));return{kind:t,receiver:n,visibility:a?"internal":"public",...f(n)}}const s=S(n);if(s)return{kind:t,receiver:n,visibility:s,...f(n)}},P=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&d(t.getFirstAncestorByKind(x.ImportDeclaration)?.getModuleSpecifierValue()??"")),M=e=>{const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const a=t.getExpression(),c=u[t.getName()]&&r.isIdentifier(a)&&P(a)?u[t.getName()]:void 0;return c?{channel:c,kind:"mutation",visibility:"internal"}:k(t)}if(!r.isIdentifier(t))return;const i=g(t);if(!i)return;if(p.has(i))return{kind:i,visibility:"public"};const n=N[i];if(n)return{kind:n,visibility:"internal"};const o=u[i];if(o)return{channel:o,kind:"mutation",visibility:"internal"};const s=w[i];if(s)return{kind:D(s),lifecycle:s,visibility:"internal"}};export{F as a,v as b,M as c,R as d,A as e,O as f,C as i,T as w};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as A}from"ts-morph";import{d as O}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as p,bindingKeyName as L,listLunoraSourceFiles as F,lunoraRelativePath as C}from"./isTestPath-B81lOULB.mjs";import{e as z,i as w}from"./attribution-hVBriwzy.mjs";import{u as E,p as S,c as h,r as k}from"./unwrap-handler-return-CeaOifqX.mjs";import{b as v,c as I}from"./classify-procedure-call-CcgP-9I0.mjs";import{r as P,p as b,a as T}from"./parse-validator-IDBKIT7M.mjs";import{s as R}from"./dispatch-namespace-DwTjD7BU.mjs";const M=n=>{const t=n.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const e=p(t,"handler");if(!e||!s.isPropertyAssignment(e))return"unknown";const i=e.getInitializer();return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":E(i)},$=n=>{const t=n.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":E(t)},D=n=>{let t={};for(const e of v(n)){if(e.name!=="input")continue;const i=e.call.getArguments()[0],r=i!==void 0&&s.isExpression(i)?P(i):void 0;r!==void 0&&(t={...b(r),...t})}return t},V=n=>{const t=v(n).find(i=>i.name==="output");if(!t)return;const e=t.call.getArguments()[0];return e&&s.isExpression(e)?S(t.call,()=>T(e)):void 0},f=(n,t)=>{const e=p(n,t);if(e===void 0||!s.isPropertyAssignment(e))return;const i=e.getInitializer();return i!==void 0&&s.isStringLiteral(i)?i.getLiteralValue():void 0},x=(n,t)=>{const e=p(n,t);if(e===void 0||!s.isPropertyAssignment(e))return;const i=e.getInitializer();return i!==void 0&&s.isNumericLiteral(i)?i.getLiteralValue():void 0},j=n=>{const t=p(n,"cache");if(t===void 0||!s.isPropertyAssignment(t))return;const e=t.getInitializer();if(e===void 0||!s.isObjectLiteralExpression(e))return;const i=f(e,"scope"),r=x(e,"maxAge"),o=x(e,"staleWhileRevalidate"),a=f(e,"tag"),l=f(e,"vary"),c={...r===void 0?{}:{maxAge:r},...i==="private"||i==="public"?{scope:i}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},_=n=>{if(n===void 0||!s.isObjectLiteralExpression(n))return{};const t=j(n),e=p(n,"rest");return e!==void 0&&s.isPropertyAssignment(e)?{...t===void 0?{}:{cache:t},rest:e.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},B=n=>{const t=v(n).find(e=>e.name==="expose");return t?_(t.call.getArguments()[0]):void 0},q=n=>{const t=n.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const e=p(t,"args");if(!e||!s.isPropertyAssignment(e))return{};const i=e.getInitializer(),r=i===void 0?void 0:P(i);return r===void 0?{}:b(r)},W=8,m=(n,t=0)=>{if(t>W)return;if(s.isCallExpression(n))return n;if(s.isParenthesizedExpression(n)||s.isAsExpression(n)||s.isSatisfiesExpression(n)||s.isNonNullExpression(n))return m(n.getExpression(),t+1);if(!s.isIdentifier(n)&&!s.isPropertyAccessExpression(n))return;const e=n.getSymbol()?.getValueDeclaration();return e?d(e,t+1):void 0},d=(n,t)=>{if(s.isVariableDeclaration(n)||s.isPropertyAssignment(n)){const e=n.getInitializer();return e?m(e,t):void 0}if(s.isShorthandPropertyAssignment(n)){const e=n.getValueSymbol()?.getValueDeclaration();return e?d(e,t+1):void 0}if(s.isBindingElement(n)){const e=L(n),o=n.getFirstAncestorByKind(A.VariableDeclaration)?.getInitializer()?.getType().getProperty(e)?.getValueDeclaration();return o?d(o,t+1):void 0}},H=(n,t=()=>!0)=>{const e=n.getNameNode();if(s.isObjectBindingPattern(e)){const o=[];for(const a of e.getElements().filter(l=>t(l.getName()))){const l=m(a.getNameNode());l&&o.push([a.getName(),l])}return o}if(!t(n.getName()))return[];const i=n.getInitializer(),r=i&&(s.isCallExpression(i)?i:m(i));return r?[[n.getName(),r]]:[]},K=n=>{const t=n.getArguments()[0],e=s.isObjectLiteralExpression(t)?t.getProperty("name"):void 0,i=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!i||!s.isStringLiteral(i))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return i.getLiteralValue()},U=n=>{const t=I(n);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:K(n)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:e}=t;if(e){const i=B(e),r=h(()=>V(e)),o=h(()=>$(n)),a=O({kind:t.kind,output:r.value});return k(a?r.erased:o.erased),{args:D(e),...i?{expose:i}:{},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...r.value?{output:r.value}:{},returnType:o.value,visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:q(n),kind:t.kind,returnType:M(n),visibility:t.visibility}},N=(n,t,e)=>{const i=U(n);if(i)return{args:i.args,exportName:t,filePath:e,kind:i.kind,returnType:i.returnType,...i.output?{output:i.output}:{},visibility:i.visibility,...i.adminOnly?{adminOnly:!0}:{},...i.expose?{expose:i.expose}:{},...i.lifecycle?{lifecycle:i.lifecycle}:{},...i.channel?{channel:i.channel}:{}}},J=(n,t)=>{const e=[];for(const i of n.getExportAssignments()){if(i.isExportEquals())continue;const r=m(i.getExpression()),o=r?N(r,"default",t):void 0;o&&e.push(o)}return e},X=(n,t)=>{const e=z(n),i=new Map,r=n.getVariableStatements().flatMap(a=>a.getDeclarations()).flatMap(a=>H(a,l=>e.has(l))).flatMap(([a,l])=>(e.get(a)??[]).filter(c=>w(c)).flatMap(c=>{const u=N(l,c,t);if(u?.channel!==void 0){const y=i.get(u.channel.name);if(y!==void 0&&y!==l)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${u.channel.name}" in ${t}: two defineRoom calls share it. Room names must be unique.`);i.set(u.channel.name,l)}return u?[u]:[]})),o=new Set(r.map(a=>a.exportName));return r.push(...J(n,t).filter(a=>!o.has(a.exportName))),r},G=n=>{const t=new Map;for(const e of n){if(e.channel?.kind!=="room")continue;const i=t.get(e.channel.name);if(i!==void 0&&i.file!==e.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${e.channel.name}": defined in ${i.origin} and ${e.filePath}:${e.exportName}. Room names must be unique across the project.`);i===void 0&&t.set(e.channel.name,{file:e.filePath,origin:`${e.filePath}:${e.exportName}`})}},Q=n=>{const t=new Map;for(const e of n){const i=R(e.filePath),r=t.get(i);if(r&&r!==e.filePath)throw Object.assign(new Error(`Namespace collision: "${r}" and "${e.filePath}" both resolve to "${i}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[r,e.filePath],status:500});t.set(i,e.filePath)}},ae=(n,t)=>{const e=F(t),i=[];for(const r of e){const o=n.getSourceFile(r)??n.addSourceFileAtPath(r),a=C(t,r);i.push(...X(o,a))}return i.sort((r,o)=>`${r.filePath}:${r.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),Q(i),G(i),i};export{ae as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as o}from"./context-property-calls-Bw8u2Pz4.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./isTestPath-B81lOULB.mjs";import"./attribution-hVBriwzy.mjs";import"./database-calls-BnVUlTx_.mjs";import"./classify-procedure-call-CcgP-9I0.mjs";import{d as a}from"./index-DvmKcoFV.mjs";export{a as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as r}from"./context-property-calls-Bw8u2Pz4.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|