@lunora/codegen 1.0.0-alpha.214 → 1.0.0-alpha.216
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 +15 -2
- package/dist/index.d.ts +15 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{DEFAULT_TARGET-DtzlGawL.mjs → DEFAULT_TARGET-lXUZWR6a.mjs} +1 -1
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-BkkKjazl.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cg6WS68p.mjs +9 -0
- package/dist/packem_shared/{emitApp-DHEB4XFE.mjs → emitApp-911e45o8.mjs} +2 -0
- package/package.json +3 -3
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-D29yBg5X.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BtDKUUYV.mjs +0 -9
package/dist/index.d.mts
CHANGED
|
@@ -2632,7 +2632,8 @@ interface CodegenResult {
|
|
|
2632
2632
|
advisorContext?: LintContext;
|
|
2633
2633
|
/**
|
|
2634
2634
|
* Static schema advisor findings (e.g. unindexed foreign keys) produced
|
|
2635
|
-
* this run
|
|
2635
|
+
* this run, minus any below `lunora.config`'s `advisor.minSeverity` (never
|
|
2636
|
+
* an ERROR). Empty when `lint` is `false` or the schema is clean. Codegen
|
|
2636
2637
|
* does not print these itself — each caller presents them through its own
|
|
2637
2638
|
* channel (the CLI logger, the vite overlay, the studio Advisors table).
|
|
2638
2639
|
* `formatAdvisories` is exported for a plain multi-line rendering.
|
|
@@ -3627,6 +3628,16 @@ declare const PROJECT_CONFIG_FILENAMES: ReadonlyArray<string>;
|
|
|
3627
3628
|
* re-validating a fact this file already knew.
|
|
3628
3629
|
*/
|
|
3629
3630
|
interface ProjectConfigLiterals {
|
|
3631
|
+
/**
|
|
3632
|
+
* `advisor.minSeverity`, read the same way. `unreadable` when `advisor` is
|
|
3633
|
+
* declared but its `minSeverity` is not a string literal the parser can see,
|
|
3634
|
+
* kept apart from the top-level `unreadable`, which means "the target may
|
|
3635
|
+
* be wrong".
|
|
3636
|
+
*/
|
|
3637
|
+
advisor?: {
|
|
3638
|
+
minSeverity?: string;
|
|
3639
|
+
unreadable?: boolean;
|
|
3640
|
+
};
|
|
3630
3641
|
remote?: boolean;
|
|
3631
3642
|
target?: string;
|
|
3632
3643
|
/**
|
|
@@ -3639,6 +3650,8 @@ interface ProjectConfigLiterals {
|
|
|
3639
3650
|
}
|
|
3640
3651
|
/** The structural slice of `lunora.config.*` Lunora reads. Unvalidated on purpose — see {@link loadProjectConfig}. */
|
|
3641
3652
|
interface LunoraProjectConfig {
|
|
3653
|
+
/** Advisor settings for codegen (`minSeverity`). Read by `runCodegen` through {@link readProjectConfigLiterals}. */
|
|
3654
|
+
advisor?: unknown;
|
|
3642
3655
|
/** The `app` hook: receives the generated `defineApp()` builder and returns it. Read by `@lunora/vite`, not by the CLI. */
|
|
3643
3656
|
app?: unknown;
|
|
3644
3657
|
/** Remote-binding dev preference. */
|
|
@@ -3673,7 +3686,7 @@ declare const findProjectConfigFile: (projectRoot: string) => string | undefined
|
|
|
3673
3686
|
*/
|
|
3674
3687
|
declare const loadProjectConfig: (projectRoot: string) => Promise<LoadedProjectConfig>;
|
|
3675
3688
|
/**
|
|
3676
|
-
* The `target` and `
|
|
3689
|
+
* The `target`, `remote` and `advisor.minSeverity` LITERALS declared in the config, without evaluating
|
|
3677
3690
|
* it — see the module header for what this can and cannot see, and why.
|
|
3678
3691
|
*/
|
|
3679
3692
|
declare const readProjectConfigLiterals: (projectRoot: string) => ProjectConfigLiterals;
|
package/dist/index.d.ts
CHANGED
|
@@ -2632,7 +2632,8 @@ interface CodegenResult {
|
|
|
2632
2632
|
advisorContext?: LintContext;
|
|
2633
2633
|
/**
|
|
2634
2634
|
* Static schema advisor findings (e.g. unindexed foreign keys) produced
|
|
2635
|
-
* this run
|
|
2635
|
+
* this run, minus any below `lunora.config`'s `advisor.minSeverity` (never
|
|
2636
|
+
* an ERROR). Empty when `lint` is `false` or the schema is clean. Codegen
|
|
2636
2637
|
* does not print these itself — each caller presents them through its own
|
|
2637
2638
|
* channel (the CLI logger, the vite overlay, the studio Advisors table).
|
|
2638
2639
|
* `formatAdvisories` is exported for a plain multi-line rendering.
|
|
@@ -3627,6 +3628,16 @@ declare const PROJECT_CONFIG_FILENAMES: ReadonlyArray<string>;
|
|
|
3627
3628
|
* re-validating a fact this file already knew.
|
|
3628
3629
|
*/
|
|
3629
3630
|
interface ProjectConfigLiterals {
|
|
3631
|
+
/**
|
|
3632
|
+
* `advisor.minSeverity`, read the same way. `unreadable` when `advisor` is
|
|
3633
|
+
* declared but its `minSeverity` is not a string literal the parser can see,
|
|
3634
|
+
* kept apart from the top-level `unreadable`, which means "the target may
|
|
3635
|
+
* be wrong".
|
|
3636
|
+
*/
|
|
3637
|
+
advisor?: {
|
|
3638
|
+
minSeverity?: string;
|
|
3639
|
+
unreadable?: boolean;
|
|
3640
|
+
};
|
|
3630
3641
|
remote?: boolean;
|
|
3631
3642
|
target?: string;
|
|
3632
3643
|
/**
|
|
@@ -3639,6 +3650,8 @@ interface ProjectConfigLiterals {
|
|
|
3639
3650
|
}
|
|
3640
3651
|
/** The structural slice of `lunora.config.*` Lunora reads. Unvalidated on purpose — see {@link loadProjectConfig}. */
|
|
3641
3652
|
interface LunoraProjectConfig {
|
|
3653
|
+
/** Advisor settings for codegen (`minSeverity`). Read by `runCodegen` through {@link readProjectConfigLiterals}. */
|
|
3654
|
+
advisor?: unknown;
|
|
3642
3655
|
/** The `app` hook: receives the generated `defineApp()` builder and returns it. Read by `@lunora/vite`, not by the CLI. */
|
|
3643
3656
|
app?: unknown;
|
|
3644
3657
|
/** Remote-binding dev preference. */
|
|
@@ -3673,7 +3686,7 @@ declare const findProjectConfigFile: (projectRoot: string) => string | undefined
|
|
|
3673
3686
|
*/
|
|
3674
3687
|
declare const loadProjectConfig: (projectRoot: string) => Promise<LoadedProjectConfig>;
|
|
3675
3688
|
/**
|
|
3676
|
-
* The `target` and `
|
|
3689
|
+
* The `target`, `remote` and `advisor.minSeverity` LITERALS declared in the config, without evaluating
|
|
3677
3690
|
* it — see the module header for what this can and cannot see, and why.
|
|
3678
3691
|
*/
|
|
3679
3692
|
declare const readProjectConfigLiterals: (projectRoot: string) => ProjectConfigLiterals;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-DPIMTD_h.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-DsxeRYvh.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-EHm1O8uG.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-wDZs0S4p.mjs";import{default as h}from"./packem_shared/discoverCrons-B2GXsB-m.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-CQofXgIf.mjs";import{default as D}from"./packem_shared/discoverFunctions-7IsdPbJJ.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-HeBP7vhK.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-CzRlqv_N.mjs";import{default as y}from"./packem_shared/discoverInserts-BP0Gl37o.mjs";import{d as W}from"./packem_shared/index-D6xfnMEE.mjs";import{default as V}from"./packem_shared/discoverMigrations-BX86Fv9G.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-CE7K7DfT.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-CJYIXWPw.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-DbuOgja2.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-TZaLWhWq.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Dd781zOQ.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-emIgm3TF.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-CU7YMR3P.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-3Gs8U3ng.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-pJ42YuvL.mjs";import{default as xe}from"./packem_shared/discoverSchema-ClYGs0dx.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-BtuI2r7-.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-BFiKUo5m.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-v3AJcUjy.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-akFzQrlf.mjs";import{emitApp as We}from"./packem_shared/emitApp-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-DPIMTD_h.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-DsxeRYvh.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-EHm1O8uG.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-wDZs0S4p.mjs";import{default as h}from"./packem_shared/discoverCrons-B2GXsB-m.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-CQofXgIf.mjs";import{default as D}from"./packem_shared/discoverFunctions-7IsdPbJJ.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-HeBP7vhK.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-CzRlqv_N.mjs";import{default as y}from"./packem_shared/discoverInserts-BP0Gl37o.mjs";import{d as W}from"./packem_shared/index-D6xfnMEE.mjs";import{default as V}from"./packem_shared/discoverMigrations-BX86Fv9G.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-CE7K7DfT.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-CJYIXWPw.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-DbuOgja2.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-TZaLWhWq.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Dd781zOQ.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-emIgm3TF.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-CU7YMR3P.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-3Gs8U3ng.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-pJ42YuvL.mjs";import{default as xe}from"./packem_shared/discoverSchema-ClYGs0dx.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-BtuI2r7-.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-BFiKUo5m.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-v3AJcUjy.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-akFzQrlf.mjs";import{emitApp as We}from"./packem_shared/emitApp-911e45o8.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-sc25Dacj.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-ClwB3jCx.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-lXUZWR6a.mjs";import{PROJECT_CONFIG_FILENAMES as ir,findProjectConfigFile as mr,loadProjectConfig as dr,readProjectConfigLiterals as fr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-BkkKjazl.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,createCodegenProject as nr,findTsconfig as lr,refreshCodegenProject as Sr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cg6WS68p.mjs";import{SchemaSnapshotParseError as Ar,buildSchemaSnapshot as ur,evaluateSchemaDrift as vr,parseSchemaSnapshot as Nr}from"./packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs";import{schemaFromIr as Cr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Mr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as _r,SDK_TARGETS as hr,generateSdk as Lr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ir,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Gr,findSolutionByMessage as Ur}from"@lunora/errors";import{isTypedSchema as Hr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Gr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,ir as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,_r as SDK_LANGUAGES,hr as SDK_TARGETS,Ae as SHAPES_FILENAME,Ar as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,ur as buildSchemaSnapshot,nr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,vr as evaluateSchemaDrift,Ur as findLunoraSolution,mr as findProjectConfigFile,lr as findTsconfig,m as formatAdvisories,Lr as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,Hr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,dr as loadProjectConfig,Nr as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,fr as readProjectConfigLiterals,tr as readProjectTarget,Ir as redact,Sr as refreshCodegenProject,sr as resolveCodegenTarget,xr as runCodegen,Cr as schemaFromIr,Pr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Mr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h}from"@lunora/platform";import{readProjectConfigLiterals as m}from"./PROJECT_CONFIG_FILENAMES-
|
|
1
|
+
import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h}from"@lunora/platform";import{readProjectConfigLiterals as m}from"./PROJECT_CONFIG_FILENAMES-BkkKjazl.mjs";const c="cloudflare",v=t=>{const{target:e}=m(t);return e!==void 0&&e.length>0?e:void 0},x=(t,e)=>e??v(t)??c,L=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:o}=m(t);return o!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${c}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${c}" }\`), or pass \`--target\`.`,target:c}]},u={cloudflare:h,node:f},I=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),b={access:null,ai:"ai",analytics:"analytics",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:null},y=["agents","commitOrderedTables","cronTriggers","crossShardFanout","durableStreams","globalTables","queues","relationGraph","secrets","vectorStore"],g={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",vectorStore:"vector indexes (`.vectorize()`)"},S=(t,e,a)=>({level:"error",message:`${e.name} does not support ${g[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:a}),T=(t,e,a)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${g[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:a}),_=t=>{const{diagnostics:e,gatedSignals:a,matrix:o,reported:i,signals:d,target:n}=t;for(const s of y){if(d[s]!==!0)continue;const r=o.features[s]?.level;r!=="unsupported"&&r!==void 0||(a[s]=!1,!i.has(s)&&e.push(r==="unsupported"?S(s,o,n):T(s,o,n)))}},$=(t,e,a,o={})=>{const i={...t},d={...o},n=[],s=new Set;for(const[r,l]of Object.entries(b)){if(l===null||!t[r])continue;const p=e.features[l]?.level;p==="unsupported"?(i[r]=!1,s.add(l),n.push({feature:r,level:"error",message:`${e.name} does not support "${r}" (ctx.${r}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${r} usage, or deploy to a target whose capability matrix marks "${l}" as native or emulated.`,target:a})):p===void 0&&(i[r]=!1,s.add(l),n.push({feature:r,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${r}" (ctx.${r}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${l}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return _({diagnostics:n,gatedSignals:d,matrix:e,reported:s,signals:o,target:a}),{diagnostics:n,signals:d,usage:i}},O=(t,e,a={})=>{const o=u[e];return o===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],signals:{...a},usage:{...t}}:$(t,o,e,a)};export{b as CAPABILITY_TO_FEATURE,c as DEFAULT_TARGET,$ as gateAgainstMatrix,O as gatePlatformFeatures,I as platformMatrixIds,v as readProjectTarget,L as readTargetDiagnostics,x as resolveCodegenTarget};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as m,statSync as p,readFileSync as v}from"node:fs";import{resolve as E,basename as b}from"node:path";import{createJiti as h}from"jiti";import{Project as x,Node as t}from"ts-morph";const S=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],f=i=>S.map(r=>E(i,r)).find(r=>m(r)),g=new Map,D=async i=>{const r=f(i);if(r===void 0)return{};let e;try{const n=p(r);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=g.get(r);if(s?.key===e)return s.value;const l=(async()=>{try{const o=(await h(r,{interopDefault:!1,moduleCache:!1}).import(r))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return g.set(r,{key:e,value:l}),l},P=i=>{let e=i.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e)||t.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&t.isIdentifier(e))for(e=i.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e));)e=e.getExpression();return e!==void 0&&t.isObjectLiteralExpression(e)?e:void 0},d=i=>{const r=i.getNameNode();return t.isStringLiteral(r)?r.getLiteralValue():r.getText()},c=(i,r)=>t.isPropertyAssignment(i)?i.getInitializer():r.getVariableDeclaration(i.getName())?.getInitializer(),A=(i,r)=>{let e=i;for(;e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e)||t.isParenthesizedExpression(e));)e=e.getExpression();if(e===void 0||!t.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),l=s.filter(a=>t.isPropertyAssignment(a)&&!t.isComputedPropertyName(a.getNameNode())||t.isShorthandPropertyAssignment(a));if(l.length!==s.length)return{advisor:{unreadable:!0}};const n=l.find(a=>d(a)==="minSeverity");if(n===void 0)return{advisor:{}};const o=c(n,r);return o!==void 0&&t.isStringLiteral(o)?{advisor:{minSeverity:o.getLiteralValue()}}:{advisor:{unreadable:!0}}},L=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),y=(i,r)=>{if(t.isGetAccessorDeclaration(i)||t.isMethodDeclaration(i))return L.get(i.getName())??{};if(!t.isPropertyAssignment(i)&&!t.isShorthandPropertyAssignment(i))return{};const e=d(i);if(e==="advisor")return A(c(i,r),r);if(e!=="target"&&e!=="remote")return{};const s=c(i,r);return s===void 0?{unreadable:!0}:e==="target"?t.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:t.isTrueLiteral(s)||t.isFalseLiteral(s)?{remote:s.getLiteralValue()}:t.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},O=i=>{const r=f(i);if(r===void 0)return{};let e;try{e=v(r,"utf8")}catch{return{unreadable:!0}}const l=new x({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(b(r),e,{overwrite:!0}),n=P(l);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(a=>t.isSpreadAssignment(a)))return n.getProperties().some(u=>t.isPropertyAssignment(u)||t.isShorthandPropertyAssignment(u)?d(u)==="advisor":(t.isGetAccessorDeclaration(u)||t.isMethodDeclaration(u))&&u.getName()==="advisor")?{advisor:{unreadable:!0},unreadable:!0}:{unreadable:!0};let o={};for(const a of n.getProperties())o={...o,...y(a,l)};return o};export{S as PROJECT_CONFIG_FILENAMES,f as findProjectConfigFile,D as loadProjectConfig,O as readProjectConfigLiterals};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{existsSync as P,mkdirSync as Cs,readFileSync as _t,writeFileSync as Fs,rmSync as Os}from"node:fs";import{join as y,dirname as ne}from"node:path";import{performance as Ae}from"node:perf_hooks";import{runAdvisor as Rs}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as Ls,Project as ct}from"ts-morph";import{serializeSchemaSnapshot as Ds}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as ks}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as Ms}from"./PROJECT_CONFIG_FILENAMES-BkkKjazl.mjs";import{s as _s}from"./paths-C-9fwEgQ.mjs";import{C as re,o as Kt,j as Ks,f as zs,k as $s,b as Us,c as qs,m as Bs,e as Vs,p as Ws,d as js,i as Hs,l as Gs,g as Ys,q as Qs,n as Xs,a as Zs,h as Js}from"./emit-akFzQrlf.mjs";import{isD1GlobalTable as zt,isHyperdriveGlobalTable as $t}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as en}from"./AGENTS_FILENAME-DPIMTD_h.mjs";import{discoverContainers as tn}from"./CONTAINERS_FILENAME-wDZs0S4p.mjs";import sn from"./discoverCrons-B2GXsB-m.mjs";import{diagnosticAt as ue}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as de}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,unwrapExpression as G,listSecurityScanFiles as Re,objectLiteralFromCallbackBody as Ut,propertyInitializer as A,lunoraRelativePath as x,collectCallRows as T,collectSecurityCallRows as nn,limitNameOf as qt,optionsObjectLiteral as Bt,isContextIdentifier as we,handlerOf as rn,isDatabaseAccessor as M,readTargetOf as Vt,enclosingExportName as on}from"./listLunoraSourceFiles-DsxeRYvh.mjs";import an from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as cn}from"./QUEUES_FILENAME-Dd781zOQ.mjs";import{discoverSandboxUsage as ln}from"./discoverSandboxUsage-pJ42YuvL.mjs";import un from"./discoverStorageRulesMetadata-BFiKUo5m.mjs";import{a as S,c as _,d as Wt,e as dn}from"./classify-procedure-call-RjsZg8AH.mjs";import{discoverWorkflows as fn}from"./WORKFLOWS_FILENAME-v3AJcUjy.mjs";import{gatePlatformFeatures as gn,resolveCodegenTarget as pn,readTargetDiagnostics as mn}from"./DEFAULT_TARGET-lXUZWR6a.mjs";import{i as L,a as z,e as E,r as hn,b as vn,s as fe,c as xn,f as En,d as yn}from"./queries-TZaLWhWq.mjs";import{r as ge,s as Sn}from"./parse-validator-DW5RNi_6.mjs";import An from"./discoverAuthApiCalls-EHm1O8uG.mjs";import{i as Nn,a as bn,e as Pn,b as wn,d as In,c as Tn}from"./unwrap-handler-return-BEdusskg.mjs";import Cn from"./discoverFunctions-7IsdPbJJ.mjs";import Fn from"./discoverHttpRoutes-HeBP7vhK.mjs";import On from"./discoverHyperdriveCalls-CzRlqv_N.mjs";import Rn from"./discoverInserts-BP0Gl37o.mjs";import{m as Le,a as ie,s as jt,d as Ln}from"./index-D6xfnMEE.mjs";import{e as Ht}from"./exported-procedure-chains-CjlBrFjo.mjs";import Dn from"./discoverMigrations-BX86Fv9G.mjs";import{MUTATORS_FILENAME as kn,isDefineMutatorCallee as Mn,discoverMutators as _n}from"./MUTATORS_FILENAME-CE7K7DfT.mjs";import Kn from"./discoverNondeterministicCalls-CJYIXWPw.mjs";import{discoverNotifyConfig as zn,discoverNotifyCalls as $n}from"./NOTIFY_FILENAME-DbuOgja2.mjs";import Un from"./discoverR2sqlCalls-emIgm3TF.mjs";import qn from"./discoverRlsProcedures-CU7YMR3P.mjs";import Bn from"./discoverRlsMetadata-3Gs8U3ng.mjs";import Vn from"./discoverSchema-ClYGs0dx.mjs";import{secretKindOf as Wn,redact as jn,isHeuristicSecretKind as Hn,isSecretishName as Gn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Yn}from"./SHAPES_FILENAME-BtuI2r7-.mjs";import{emitApp as Qn}from"./emitApp-911e45o8.mjs";import{buildOpenApiDocument as Xn,emitOpenApiModule as Zn}from"./buildOpenApiDocument-sc25Dacj.mjs";import{buildOpenRpcDocument as Jn,emitOpenRpcModule as er}from"./OPENRPC_VERSION-ClwB3jCx.mjs";import{buildSchemaSnapshot as tr}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const lt={error:"ERROR",info:"INFO",warn:"WARN"},ut={ERROR:2,INFO:0,WARN:1},sr=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"}),nr=(e,t)=>{const{advisor:s}=Ms(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,o=n!==void 0&&Object.hasOwn(lt,n)?lt[n]:void 0;return o===void 0?[...t,sr(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(r=>ut[r.level]>=ut[o])},dt=(e,t="api")=>{const s=new Map;for(const n of e){const o=_s(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new k("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},rr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>zt(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=>$t(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`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:re)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},or=(e,t,s={})=>{if(t===void 0)return;const n=rr(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
2
|
+
`);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
+
${o}
|
|
4
|
+
|
|
5
|
+
Install them with your package manager, then re-run codegen.`)},ir="env.ts",ar=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},cr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},lr=e=>{if(i.isIdentifier(e))return ar(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&cr(t)}return!1},ur=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!lr(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ue(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},dr=(e,t)=>{const s=y(t,ir);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=ur(n);if(o.length!==0){if(o.length>1)throw ue(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},ft="ctx",Gt=e=>{const t=new Set,s=new Set([ft]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==ft)continue;const a=r.getNameNode();i.isIdentifier(a)?s.add(a.getText()):n(a)}const o=r=>i.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))o(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&o(a)&&n(r.getNameNode())}return t},fr=(e,t)=>{const s=Object.fromEntries(re.map(n=>[n.key,!1]));for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Gt(o);for(const c of re)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(re.every(c=>s[c.key]))break}return s},Yt="identity.ts",gr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},pr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},mr=e=>{if(i.isIdentifier(e))return gr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&pr(t)}return!1},hr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!mr(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ue(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},vr=(e,t)=>{const s=y(t,Yt);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=hr(n);if(o.length!==0){if(o.length>1)throw ue(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},xr=(e,t)=>{const s=G(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return G(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},Er=e=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!i.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||G(s)?.getText()!=="false"}),yr=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Gt(o).has("secrets")),s.durableStreams||(s.durableStreams=o.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(i.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>Er(xr(o,u)))})),s.durableStreams&&s.secrets)break}return s},Sr="createWorker",Ar="extend",gt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,pt=e=>{const t=[],s=gt(A(e,"backupCron"));s!==void 0&&t.push(s);const n=A(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)&&!i.isMethodDeclaration(o))continue;const r=gt(o.getNameNode());r!==void 0&&t.push(r)}return t},Nr=e=>{const t=S(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Sr)return i.isObjectLiteralExpression(s)?pt(s):[];if(t!==Ar||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=Ut(s.getBody());return n===void 0?[]:pt(n)},br=(e,t)=>{const s=[];for(const{filePath:n}of Re(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...Nr(r))}return[...new Set(s)]},Qt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Qt(e.inner)},Pr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=Qt(n);return o!==void 0&&t.has(o)}))},wr=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=o.get(r.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Ir=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=vr(s,t),a=dr(s,t),c=fn(s,t),u=cn(s,t),d=en(s,t);wr(c,d);const m=tn(s,t),h=un(s,t),F=sn(s,t,c,d),D=br(s,t),g=yr(s,t),w=ln(s,t),N=fr(s,t);N.browser=N.browser||w.usesSandboxBrowser;const C=gn(N,pn(n,e.target),{agents:d.length>0,commitOrderedTables:o.tables.some(b=>b.commitOrdered===!0),cronTriggers:F.length>0,crossShardFanout:o.tables.some(b=>typeof b.shardMode=="object"),durableStreams:g.durableStreams,globalTables:o.tables.some(b=>b.shardMode==="global"),queues:u.length>0,relationGraph:Pr(o),secrets:g.secrets,vectorStore:o.vectorIndexes.length>0}),v=C.usage,R=C.signals.vectorStore!==!1,$=an(n),W=$??new Set,X=W.has("lunorash");or(o,$,{hasVectors:R,scheduler:v.scheduler||F.length>0,storage:v.storage||h.rules.length>0||Object.keys(Kt(o)).length>0,usage:v});const K=P(y(t,"flags.ts")),O=P(y(t,"notify.ts"));return{agents:d,containers:m,crons:F,dataModelContent:zs(o),declaredDependencies:$,dependencies:W,entryCronTriggers:D,env:a,featureUsage:v,hasFlags:K,hasNotify:O,identity:r,platformGate:{...C,diagnostics:[...mn(n,e.target),...C.diagnostics]},queues:u,serverContent:Ks({agents:d,containers:m,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:v.browser,hasVectors:R,hasFlags:K,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:O,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:r,queues:u,schema:o,storageRuleBuckets:h.rules.map(b=>b.bucket),useUmbrella:X,workflows:c}),storageRulesMetadata:h,usesSandbox:w.usesSandboxBrowser||w.usesSandboxContainer||w.usesSandboxFs,useUmbrella:X,workflows:c}},Xt=new Set(["delete","get","head","options","patch","post","put"]),Tr=new Set(["handler","stream"]),Cr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,mt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Fr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Xt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Or=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||Xt.has(n.getName()))break;s=n.getExpression()}return Fr(s)},Rr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(mt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&mt.has(s.getText()))return!0}return!1},Lr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Tr.has(n.getName()))return;const o=Or(s);if(!o||!Cr.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&Rr(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Dr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Lr(o,t);r&&s.push(r)}return s},kr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Dr(o,x(t,n)))}return s},Mr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",_r=(e,t)=>{if(!Mr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)||z(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},Kr=(e,t)=>T(e,t,_r),zr=new Set(["generateText","streamText"]),$r=new Set(["messages","prompt","system"]),Ur=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],qr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of Ur)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Br=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=qr(t);if(s!==void 0)return s}},Vr=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Wr=e=>{if(hn(e))return!0;const t=Vr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},jr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!$r.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Wr(s))return!0}return!1},Hr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=S(n.getExpression());if(o===void 0||!zr.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(S(c.getExpression())==="tool"&&(a=Br(c),a!==void 0))break;a!==void 0&&s.push({exportName:E(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:jr(r)})}return s},Gr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hr(o,x(t,n)))}return s},Yr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Qr=(e,t)=>{if(!Yr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},Xr=(e,t)=>T(e,t,Qr),De=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=ge(s.getExpression());return n===void 0||De(n,t)})}finally{t.delete(e)}},Zr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),o=n===void 0?void 0:ge(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:De(o)}},Jr=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&i.isExpression(r)?ge(r):void 0;a===void 0?s=!0:(t.push(a),s||=De(a))}n=o.getExpression()}return{objects:t,opaque:s}},ke=(e,t)=>t?Jr(t):Zr(e),Zt=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=ge(s.getExpression());return n===void 0?[]:Zt(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[s.getName()]:[]})}finally{t.delete(e)}},eo=e=>e.flatMap(t=>Zt(t,new Set)),to=new Set(["check","length","max"]),Ie=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},so=e=>[e,...e.getDescendants()].filter(t=>Ie(t)!==void 0),no=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(to.has(s.getName()))return!0;t=n}},ro=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=so(r),c=o.getName();a.some(u=>Ie(u)==="any")?t.push(c):a.some(u=>Ie(u)==="string"&&!no(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},oo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=_(s);if(n?.visibility!=="public")return;const{objects:o}=ke(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=ro(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},io=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=oo(o,t);r&&s.push(r)}return s},ao=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...io(o,x(t,n)))}return s},Ne=e=>e?.getKind()===l.TrueKeyword,co=e=>e?.getKind()===l.FalseKeyword,lo=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,uo=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),fo=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),go=e=>e!==void 0&&i.isCallExpression(e)&&uo.has(S(e.getExpression())??""),po=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),mo=e=>{const t=A(e,"advanced"),s=A(e,"emailAndPassword"),n=A(e,"session");return{analyzable:!0,disableCsrfCheck:Ne(A(t,"disableCSRFCheck")),emailPasswordEnabled:Ne(A(s,"enabled")),requireEmailVerification:Ne(A(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:fo(A(e,"plugins"))&&go(A(e,"database")),secureCookiesDisabled:co(A(t,"useSecureCookies")),sessionFreshAgeZero:lo(A(n,"freshAge")),trustedOriginsWildcard:po(A(e,"trustedOrigins"))}},ho=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),vo=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?mo(s):ho();return{exportName:E(e),file:t,line:e.getStartLineNumber(),...o}},xo=(e,t)=>nn(e,t,vo),Eo=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},yo=(e,t,s)=>{const n=Eo(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!L(o)||z(o))&&!(s.requireUnmodifiedReach===!0&&!vn(o)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:n}},So=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=yo(o,t,s);r&&n.push(r)}return n},pe=(e,t,s)=>{const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...So(r,x(t,o),s))}return n},Ao=new Set(["content","pdf","scrape","screenshot"]),No=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ao}),bo=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Po=new Set(["RateLimiter"]),wo=new Set(["extend"]),ht="lunora",Io=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Jt=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Te=e=>e&&i.isObjectLiteralExpression(e)?Jt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},To=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Ut(t.getBody());return s?Jt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Co=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=S(n.getExpression());o!==void 0&&(bo.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])}):wo.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...To(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=S(n.getExpression());o===void 0||!Po.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])})}return s},Fo=(e,t)=>{for(const s of Io){const n=y(t,s);if(!P(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))S(a.getExpression())===ht&&r.push({callee:ht,file:s,line:a.getStartLineNumber(),...Te(a.getArguments()[0])});return r}return[]},Oo=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Re(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...Co(r,n))}return s.push(...Fo(e,ne(t))),s},vt="ctx.containers.",Ro=e=>{if(!e.startsWith(vt))return!1;const t=e.slice(vt.length);return t.length>0&&!t.includes(".")},Lo=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:Ro,methods:new Set(["get"])}),Do=new Set(["allow","deny","setAllowed"]),ko=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Mo=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!ko(e)))return{detail:"enableInternet: true",exportName:E(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},_o=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!Do.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:E(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Ko=(e,t)=>Mo(e,t)??_o(e,t),zo=(e,t)=>T(e,t,Ko),$o=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Uo=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return $o.has(s)?s:void 0},qo=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Bo=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Re(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Uo(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?qo(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Vo=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Wo=new Set(["dbRateLimit","rateLimit"]),jo=e=>{const t=Bt(e);if(!t)return!1;const s=t.getProperty("failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},Ho=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const n=Vo.get(s);if(n!==void 0)return{callee:s,exportName:E(e),failOpen:jo(e.getArguments()[n]),file:t,limitName:Wo.has(s)?qt(e):"",line:e.getStartLineNumber()}},Go=(e,t)=>T(e,t,Ho),Yo=new Set(["boolean","number","object","string"]),Qo=e=>{const t=e.getName();if(!Yo.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&we(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&we(n.getExpression()))return t},Xo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=Qo(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const o=n.getLiteralValue();return o.length>0?{key:o,type:s}:void 0},Zo=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=Xo(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,o])=>({key:n,type:o})).toSorted((n,o)=>n.key.localeCompare(o.key))},Jo=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=_(t);if(s?.kind!=="query")return;const n=rn(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},xt=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},ei=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=xt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=xt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},ti=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=ei(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},si=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Jo(o);r&&s.push(...ti(r,t))}return s},ni=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...si(o,x(t,n)))}return s},ri=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&we(t.getExpression())},oi=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},ii=(e,t)=>{if(!ri(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=oi(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:E(e),file:t,key:o,line:e.getStartLineNumber()}},ai=(e,t)=>T(e,t,ii),ci=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 o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||Nn(r))return;const a=e.getSourceFile().getFilePath();if(bn(o,e,a)){const c=Pn(o,e,a,0,new Set);return c===void 0&&wn(r),c}return r},li=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},ui=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},di=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))li(a)&&s.push({file:r,indexName:ui(a),line:a.getStartLineNumber()})}return s},Y=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,es=e=>{const t=e.getArguments()[0],s=Y(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&i.isPropertyAssignment(n)?Y(n.getInitializer()):void 0},fi=new Set(["delete","get","head","options","patch","post","put"]),gi=new Set(["handler","stream"]),pi=new Set(["runAction","runMutation"]),mi=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,ts=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if((s.getPropertyNameNode()?.getText()??s.getNameNode().getText())===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},Et=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:ts(s,"ctx")},yt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:ts(s,"request")},St=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(pi.has(a)&&Q(c,t))return a;if(mi.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},At=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Q(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!Q(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},hi=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,vi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Q(n.getExpression(),t)},xi=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],ss=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:xi(s)},Ei=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const o=n.getParent();if(!i.isCallExpression(o))return[];const r=o.getExpression();if(!i.isPropertyAccessExpression(r))return[];const a=r.getExpression();return i.isIdentifier(a)?ss(t,a.getText()):[]}return[]},yi=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=ss(s,t.getText());return n.length>0?n:Ei(t,s)},Nt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(o=>vi(o,t)&&yi(o).some(r=>hi.test(r)))},Si=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!gi.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(fi.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},Ai=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=Y(e.getArguments()[0]),u=c&&Et(c,!0);if(!c||u===void 0||Nt(c,yt(c,!0)))return;const d=St(c,u);return d===void 0?void 0:{exportName:E(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:At(c,u),sideEffect:d}}const n=Si(e);if(n===void 0)return;const o=Y(e.getArguments()[0]),r=o&&Et(o,!1);if(!o||r===void 0||Nt(o,yt(o,!1)))return;const a=St(o,r);return a===void 0?void 0:{exportName:E(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:At(o,r),sideEffect:a}},Ni=(e,t)=>T(e,t,Ai),bi=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Pi=new Set(["append","set"]),ns=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",bt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>bi.has(S(n.getExpression())??"")&&En(n,t)),wi=(e,t)=>{if(bt(e,t))return!0;const s=fe(e);return s!==void 0&&bt(s,t)},Ce=(e,t)=>xn(e,t)&&!wi(e,t),Ii=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=fe(e);return t!==void 0&&i.isNewExpression(t)&&S(t.getExpression())==="Headers"},ae=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=fe(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Me=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Ce(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:ns(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Ce(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=ae(n.getExpression());o!==void 0&&Me(o,t,s)}},rs=(e,t)=>{const s=ae(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=ae(n.getInitializer());o!==void 0&&Me(o,"response-init",t)},Ti=(e,t)=>{const s=S(e.getExpression());if(s==="Response")rs(e.getArguments()[1],t);else if(s==="Headers"){const n=ae(e.getArguments()[0]);n!==void 0&&Me(n,"headers-ctor",t)}},Ci=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){rs(e.getArguments()[1],t);return}if(Pi.has(n)&&Ii(o)){const r=e.getArguments()[1];r!==void 0&&Ce(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:ns(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Fi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Ti(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Ci(s,t)},Oi=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Y(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return Fi(n,{exportName:E(e),relativePath:t,requestName:r.getText(),rows:a}),a},Ri=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Oi(n,t));return s},Li=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ri(o,x(t,n)))}return s},Di=new Set(["auth","context.auth","ctx.auth"]),ki="userId",Mi=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},_i=(e,t)=>{const s=y(t,Yt);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(S(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Mi(r):void 0}},Pt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Di.has(e.getExpression().getText())?e:void 0},Ki=e=>{if(i.isPropertyAccessExpression(e)&&Pt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Pt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},zi=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=Ki(o);r!==void 0&&n.push({declared:r===ki||s.has(r),exportName:E(o),file:t,key:r,line:o.getStartLineNumber()})}return n},$i=(e,t)=>{const s=_i(e,t);if(s===void 0)return[];const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...zi(r,x(t,o),s))}return n},Ui=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=A(s,"key");if(!(!n||!L(n)||z(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},qi=(e,t)=>T(e,t,Ui),Bi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Vi=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:Bi}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Wi=new Set(["queue","send"]),wt=new Set(["bcc","cc","to"]),ji=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Wi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Hi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return wt.has(t.getName())&&L(n)&&!z(n)}if(!i.isPropertyAssignment(t)||!wt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&L(s)&&!z(s)}):!1,Gi=(e,t)=>{const s=ji(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Hi(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},Yi=(e,t)=>T(e,t,Gi),Qi=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,Xi=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?Qi(e):!0,os=(e,t=!1)=>{for(const s of e.getProperties()){if(Xi(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||os(n,!0))return!0}return!1},Zi=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of Ht(n))for(const r of Le(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||os(a)))return!0}}return!1},Ji=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=ie(n);if(o===void 0||!i.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!i.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=ie(a);c!==void 0&&s.push({column:c,strategy:jt(a),table:o})}}return s},ea=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Ht(o))for(const a of Le(r))for(const c of Ji(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},ta=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=ie(r);if(a===void 0||!i.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=ie(u);if(d===void 0)continue;const m=jt(u);m!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:m,table:a})}}return o},sa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?_(s):void 0;return n?.receiver?Le(n.receiver).flatMap(o=>ta(o,e.getName(),t)):[]},na=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...sa(c,r))}return s},ra=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return M(s)},oa=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},ia=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Mn(s.getExpression())?s:void 0},aa=e=>{const t=ia(e),s=t===void 0?void 0:oa(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>ra(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},ca=e=>e.getVariableDeclarations().flatMap(t=>aa(t)),la=(e,t)=>{const s=y(t,kn);if(!P(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return ca(n)},ua=new Set(["delete","get","patch"]),da=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),fa=new Set(["auth","identity","session","user"]),ga=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),pa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!M(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},ma=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},ha=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),va=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,xa=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>ha(s.getExpression(),t)&&va(s.getThenStatement())),Ea=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!ua.has(o))continue;const r=n.getExpression();if(!(M(r)||i.isPropertyAccessExpression(r)&&M(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},ya=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},Sa=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>ya(s)==="ctx")),Aa=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>ga.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Na=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(da.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&fa.has(t.getName()))return!0}return Sa(e)||Aa(e)},ba=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=es(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Wt(n.receiver,"use","rls"),a=Na(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const m=pa(d);if(m===void 0)continue;const h=ma(d);if(h===void 0||c.has(h)||!xa(o,h))continue;const F=Ea(o,h);F!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:F,table:m,usesRls:r,visibility:n.visibility}))}return u},Pa=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ba(c,r))}return s},wa=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Ia=new Set(["insert","insertManyUnsafe","patch","replace"]),Ta=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ia.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},Ca=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},It=(e,t)=>{if(i.isPropertyAccessExpression(e)){const s=e.getExpression();return i.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(i.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return i.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&i.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},Fa=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(i.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let o,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!i.isVariableDeclarationList(c)||c.getDeclarationKind()!==Ls.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(o=u,r=d)}return o},Oa=(e,t)=>{if(It(e,t))return!0;const s=Fa(e);return s!==void 0&&It(s,t)},Ra=(e,t,s,n,o)=>{const r=[];for(const a of e.getProperties()){let c,u;if(i.isPropertyAssignment(a)?(c=a.getName(),u=a.getInitializer()):i.isShorthandPropertyAssignment(a)&&(c=a.getName(),u=a.getNameNode()),!(c===void 0||u===void 0||!wa.has(c))&&L(u)&&!z(u)){const d=E(s),m=o(d)===c&&Oa(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...m&&{ownerScoped:!0}})}}return r},La=(e,t,s)=>{const n=Ta(e.getExpression());if(n===void 0)return[];const o=e.getArguments()[1];return o?Ca(o,n).flatMap(r=>Ra(r,n,e,t,s)):[]},Da=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of La(o,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},ka=(e,t,s=[],n=[])=>{const o=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of p(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);o.push(...Da(c,u,d=>r.get(`${u}:${d}`)??{}))}return o},Ma=["providerSubscriptionId","state"],_a=["providerEventId","processedAt"],Tt=(e,t)=>t.every(s=>s in e.shape),Ka=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Tt(t,Ma)&&Tt(s,_a)},za=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),$a=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Ua=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?$a(t.getInitializer()):void 0},qa=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!za.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?Ua(n):void 0;return{callee:s,exportName:E(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},Ba=(e,t)=>T(e,t,qa),Va=new Set(["defineQueue","defineWorkflow"]),Wa=new Set(["run","runAction","runMutation","runQuery"]),ja=new Set(["api","internal"]),Ha=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Ga=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},is=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},as=(e,t)=>e===t||e.startsWith(`${t}.`),cs=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Ct=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},ls=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Ct(s));return i.isIdentifier(e)&&Ct(e)&&t.push(e),t},Ya=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Qa=e=>{const t=is(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},Xa=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Qa(e),o=new Set,r=a=>cs(a).some(c=>n.some(u=>as(c.getText(),u)))?!0:ls(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of Ya(a))o.add(u)}return{names:o,prefixes:n}},Za=(e,t)=>cs(e).some(s=>t.prefixes.some(n=>as(s.getText(),n)))?!0:ls(e).some(s=>t.names.has(s.getText())),Ja=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!ja.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},ec=(e,t,s)=>{const n=is(e,0);if(n===void 0)return[];const o=Xa(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!Wa.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!Za(u,o))continue;const d=Ja(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:E(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},tc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Ha(n);if(o===void 0||!Va.has(o))continue;const r=Ga(n);r!==void 0&&s.push(...ec(r,o==="defineQueue"?"queue":"workflow",t))}return s},sc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tc(o,x(t,n)))}return s},Ft={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Ot=new Set(["account","credential","member","passkey","session","user"]),nc=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),rc=e=>{const s=nc(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Ot.has(s)||Ot.has(n)},oc=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ic=(e,t)=>{const{objects:s,opaque:n}=ke(e,t);return eo(s).some(o=>oc(o))?!0:n?void 0:!1},ac=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},cc=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},oe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},lc=e=>{const t=cc(e),s=t?S(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=ac(t);return{...oe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ft?{...oe,[Ft[s]]:!0}:oe},uc=e=>{const t={...oe};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=lc(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},dc=new Set(["insert","insertMany","insertManyUnsafe","replace"]),fc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!dc.has(t.getName()))return!1;const s=t.getExpression();if(!M(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:rc(o.getLiteralText())},gc=new Set(["create","runAfter","runAt","send","sendBatch"]),pc=new Set(["queues","scheduler","workflows"]),mc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!gc.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&pc.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},hc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return M(s)},us=new Set(["generateObject","generateText","streamObject","streamText"]),vc=e=>{const t=S(e.getExpression());return t!==void 0&&us.has(t)},xc=e=>{const t=S(e.getExpression());if(t===void 0||!us.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Ec=new Set(["log","span","trace"]),yc=new Set(["ai"]),Sc=new Set(["email","mail"]),Ac=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),be=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),Nc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),bc=new Set(["every","filter","flatMap","forEach","map","some"]),Pc=new Set(["all","allSettled","race"]),wc=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(bc.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&Pc.has(n))return t},Ic=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Nc.has(t.getKind())){const s=wc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Tc=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Cc=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Fc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Ac.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=Cc(n);r&&(t=!0,!Ic(r)&&!Tc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Oc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Rt="lunora-advisor-exempt",Rc=/^[\s*/]+/u,Lc=/[\w-]/u,Dc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
|
+
`);for(const n of s.split(`
|
|
7
|
+
`)){const o=n.replace(Rc,"");if(!o.startsWith(Rt))continue;const r=o.slice(Rt.length);if(Lc.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},kc=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Mc=(e,t)=>{const s=kc(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},_c=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(fc(u)&&(r=!0),mc(u)&&(t=!0),hc(u)&&(o=!0),vc(u)&&(s=!0),xc(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=Fc(e);return{callsMail:be(e,Sc),emitsEvent:be(e,Ec),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||be(e,yc),throwsBareError:Oc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},Kc=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=_(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?uc(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Mc(e,s);return{...r?_c(r):{},...Dc(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:ic(s,n.receiver),kind:n.kind,visibility:n.visibility}},zc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Kc(o,t);r&&s.push(r)}return s},$c=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...zc(o,x(t,n)))}return s},Uc=new Set(["dbRateLimit","rateLimit"]),qc=e=>i.isArrowFunction(e)?e.getBody():e,Bc=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},ds=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},fs=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const o=n.getParent();return!(i.isPropertyAccessExpression(o)&&o.getNameNode()===n)})},Vc=(e,t)=>L(e)||t!==void 0&&fs(e,t).some(s=>ds(s)),Wc=(e,t)=>t===void 0?z(e):fs(e,t).some(s=>!ds(s)),jc=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!Uc.has(s))return;const n=A(Bt(e.getArguments()[2]),"key");if(!n)return;const o=qc(n),r=Bc(n);if(!(!Vc(o,r)||Wc(o,r)))return{callee:s,exportName:E(e),file:t,limitName:qt(e),line:e.getStartLineNumber()}},Hc=(e,t)=>T(e,t,jc),Gc=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Yc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Gc.has(t.getName()))return;const s=t.getExpression();if(M(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&M(s.getExpression()))return s.getName()},Qc=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&M(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Xc=e=>{let t=G(e)??e;for(;i.isAwaitExpression(t);)t=G(t.getExpression())??t.getExpression();return t},gs=(e,t=!1)=>{const s=Xc(e);if(i.isIdentifier(s)){if(t)return;const n=fe(s);return n===void 0?void 0:gs(n,!0)}if(i.isCallExpression(s))return Yc(s)??Qc(s)},Zc=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},Jc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query")return[];const o=es(s);if(o===void 0)return[];const r=n.receiver!==void 0&&dn(n.receiver,"output"),a=n.receiver!==void 0&&Wt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of Zc(o)){const m=gs(d);m===void 0||c.has(m)||(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:m,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},el=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Jc(c,r))}return s},tl=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},sl=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?_(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Vt(r);if(a===void 0)continue;const c=tl(A(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},nl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...sl(c,r))}return s},ce=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ce(e.getLeft()),s=ce(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},rl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ce(t)!==void 0},ol=/(?:^|\/)__tests__\//u,il=/\.(?:spec|test)$/u,al=e=>ol.test(e)||il.test(e),cl=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},ll=(e,t,s)=>Hn(e)?!al(s)&&Gn(cl(t)):!0,ul=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(rl(r))continue;const a=ce(r);if(a===void 0)continue;const c=Wn(a);if(c===void 0||!ll(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:jn(a)}))}return s},dl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ul(o,x(t,n)))}return s},fl=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?_(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Vt(r);if(a===void 0)continue;const c=A(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&L(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},gl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...fl(c,r))}return s},pl=new Set(["query","unsafe"]),ml=e=>{if(!i.isPropertyAccessExpression(e)||!pl.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},hl=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),vl=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",xl=(e,t)=>{if(!ml(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!hl(s)))return{exportName:vl(e),file:t,line:s.getStartLineNumber()}},El=(e,t)=>T(e,t,xl),yl=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Sl=e=>{for(const[t,s]of yl)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Al=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Sl(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Nl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),bl=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Nl,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Pl=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),wl=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Il=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=wl(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Tl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Pl.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Cl=(e,t)=>{const s=Tl(e.getExpression());if(s!==void 0)return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s.method,...Il(e.getArguments()[s.optionsIndex])}},Fl=(e,t)=>T(e,t,Cl),Ol=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),Rl=(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"}),Ll=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||s.getProperty("args")===void 0)return!1}return ke(e,t).opaque},Dl=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=_(a);c!==void 0&&Ll(a,c.receiver)&&s.push(Rl(t,r,a.getStartLineNumber()))};for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations())n(r,r.getName());return s},kl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...Dl(o,x(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},Ml=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),me=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),ps=e=>!e.isAny(),_e=e=>{const t=e.getType();if(!ps(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Ml.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},ms=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},hs={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."},_l=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.`}),Kl={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},Ke=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,m=d===void 0?o:_l(d),h=c===void 0?m.remediation:`${c} ${m.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${m.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},zl=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(me(s,t,a)||!ms(r))continue;const c=_e(r);c!==void 0&&n.push(Ke(t,a,c,r.getStartLineNumber(),hs))}return n},$l=(e,t,s)=>{if(me(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=_e(o.getExpression());r!==void 0&&n.push(Ke(t,"default",r,o.getStartLineNumber(),hs))}return n},Ul=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(me(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!ms(c))continue;const u=_e(c);u!==void 0&&n.push(Ke(t,a,u,r.getStartLineNumber(),Kl))}return n},ql=(e,t,s)=>[...zl(e,t,s),...$l(e,t,s),...Ul(e,t,s)],Bl=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>me(s,t,n.getName())).filter(n=>{const o=n.getInitializer();return o!==void 0&&i.isCallExpression(o)&&i.isPropertyAccessExpression(o.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),Vl=({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"}),Wl=(e,t,s)=>{const n=[],o=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...ql(c,u,s)),o.push(...Bl(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!ps(a.getType()))&&n.push(Vl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},jl=new Set(["when","where"]),Pe=new Set(["definePolicy","defineShape"]),Hl=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return Pe.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return Pe.has(o)?o:void 0}const s=t.getText();return Pe.has(s)?s:void 0},Gl=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,vs=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Gl(e))return"empty-object";if(i.isParenthesizedExpression(e))return vs(e.getExpression())}},ze=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Yl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>ze(t)===e),xs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>ze(t)===e),Ql=e=>{const t=Yl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||xs(e).length>0},Xl=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>ze(t)===e),Fe=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",Zl=(e,t)=>Fe(e)||Fe(t),Jl=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Lt=e=>!Fe(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),eu=(e,t,s)=>{const n=Jl.get(e);if(n!==void 0)return Zl(t,s)?n==="positive"?"negative":"positive":Lt(t)||Lt(s)?void 0:n},H=e=>{if(i.isParenthesizedExpression(e))return H(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=eu(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=H(e.getLeft()),o=H(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},Dt=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},tu=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},su=e=>i.isReturnStatement(e)?e.getExpression()??e:e,nu=e=>{const t=[];for(const s of xs(e)){const n=H(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Xl(e)){const n=H(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?Dt(s.getThenStatement()):Dt(s.getElseStatement())??tu(s);o!==void 0&&t.push(su(o))}return t},ru=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},ou=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!jl.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Ql(a))for(const c of nu(a)){const u=vs(c);u!==void 0&&o.push({exportName:ru(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},iu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Hl(n);o!==void 0&&s.push(...ou(n,o,t))}return s},au=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...iu(o,x(t,n)))}return s},cu=new Set(["query","upsert","upsertNow"]),lu=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(cu.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},uu=(e,t)=>{const s=lu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=A(n,"namespace");if(!(!o||!L(o)||z(o)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},du=(e,t)=>T(e,t,uu),fu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},gu=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},pu=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!fu(a))continue;const c=on(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:gu(a)})}}return s},mu=".lunora-schema.json",Oe=(e,t)=>{P(e)&&_t(e,"utf8")===t||Fs(e,t,"utf8")},hu=(e,t)=>{if(t===""){Os(e,{force:!0});return}Oe(e,t)},vu=e=>{const t=y(e,"package.json");if(P(t))try{const s=JSON.parse(_t(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},xu=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Eu=e=>{let t=P(e)?e:ne(e);for(;t&&t!==ne(t);){const s=y(t,"tsconfig.json");if(P(s))return s;t=ne(t)}},kt=e=>e.replaceAll("\\","/"),yu=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},le=(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)},Mt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Su=8,Au=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:m}=e,h=()=>Tn(()=>{const N=Cn(a,o),C=_n(a,o);return{functions:N,httpRoutes:Fn(a,o),mutators:C}});let{erased:F,value:{functions:D,httpRoutes:g,mutators:w}}=h();dt([...D,...w].map(N=>N.filePath)),dt(g.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const C=Zs({agents:t,functions:D,httpRoutes:g,mutators:w,useUmbrella:d,workflows:m}),v=Js({agents:t,functions:D,migrations:r,mutators:w,shapes:c,useUmbrella:d,usesSandbox:u});if(N>=Su||Mt(a,s,C)&&Mt(a,n,v))return{apiContent:C,erased:F,functions:D,functionsContent:v,httpRoutes:g,mutators:w};le(a,s,C),le(a,n,v),{erased:F,value:{functions:D,httpRoutes:g,mutators:w}}=h()}},Nu=e=>{const t=Eu(e);return t?new ct({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new ct({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Ed=(e,t)=>{const s=p(t),n=y(t,"schema.ts");P(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>kt(c))),r=kt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},yd=e=>{const t=xu(),s=t?Ae.now():0,n=y(e.projectRoot,e.lunoraDirectory??"lunora"),o=y(n,"schema.ts");if(!P(o))throw new k("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??Nu(n);Sn(ci);const a=Vn(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:m,dependencies:h,entryCronTriggers:F,env:D,featureUsage:g,hasFlags:w,hasNotify:N,identity:C,platformGate:v,queues:R,serverContent:$,storageRulesMetadata:W,usesSandbox:X,useUmbrella:K,workflows:O}=Ir({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),b=y(n,"_generated"),Es=y(b,"dataModel.ts"),ys=y(b,"server.ts"),Ss=y(b,"api.ts"),As=y(b,"functions.ts");le(r,Es,m),le(r,ys,$);const Z=Dn(r,n),q=Yn(r,n),{apiContent:$e,erased:Ns,functions:B,functionsContent:Ue,httpRoutes:bs,mutators:J}=Au({agents:c,apiPath:Ss,generatedFunctionsPath:As,lunoraDirectory:n,migrations:Z,project:r,shapes:q,useUmbrella:K,usesSandbox:X,workflows:O}),ee=e.lint===!1?void 0:ks({adminRoutes:kr(r,n),aiRawRuns:Kr(r,n),aiToolSideEffects:Gr(r,n),argumentDerivedFetches:Xr(r,n),argumentValidators:ao(r,n),authApiCalls:An(r,n),authConfigs:xo(r,n),browserUrlAccesses:No(r,n),configCalls:Oo(r,n),containerKeyAccesses:Lo(r,n),containerOverrides:zo(r,n),containers:u,exportSinks:Bo(r,n),staleMigrationImports:Al(r,n),failOpenGuards:Go(r,n),flagReads:ni(r,n),flagSecurityDefaults:ai(r,n),geoIndexUsages:di(r,n),httpActionGuards:Ni(r,n),httpHeaderWrites:Li(r,n),hyperdriveCalls:On(r,n),identityClaimReads:$i(r,n),imageDeliveryUrlAccesses:qi(r,n),inserts:Rn(r,n),kvKeyAccesses:Vi(r,n,B),mailRecipientAccesses:Yi(r,n),maskProcedures:Ln(r,n),maskStrategies:na(r,n),mutatorWrites:la(r,n),nondeterministicCalls:Kn(r,n),normalizeIdAuthorizations:Pa(r,n),notifyCalls:$n(r,n),notifyConfig:zn(r,n),mutators:J,ownerFieldWrites:ka(r,n,B,J),unrestrictedWhereBranches:au(r,n),paymentWebhooks:Ba(r,n),privilegedDispatches:sc(r,n),procedureProtections:$c(r,n),queries:yn(r,n),queues:R,r2sqlCalls:Un(r,n),ratelimitKeySelectors:Hc(r,n),rawRowReturns:el(r,n),relationLoads:nl(r,n),rlsProcedures:qn(r,n),schema:a,secretLiterals:dl(r,n),shapes:q,softDeleteReads:gl(r,n),sqlInterpolations:El(r,n),storageKeyAccesses:bl(r,n,B),storageUploads:Fl(r,n),vectorNamespaceAccesses:du(r,n),workflowCalls:pu(r,n),workflows:O,wranglerVariables:e.wranglerVariables}),qe=ee===void 0?[]:nr(e.projectRoot,[...Rs(ee,{source:"static"}),...Wl(r,n,{byName:new Set([...O,...R,...c,...u].map(f=>f.exportName)),byPath:new Set([...B,...J,...q,...Z].map(f=>`${f.filePath}:${f.exportName}`))}),...kl(r,n),...In(Ns,n)]),Ps=Bn(r,n),Be=ea(r,n);yu(q,Be,Zi(r,n));const ws=w?Zo(r,n):[],he=v.signals.vectorStore!==!1,j=Ol(g,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:Ka(a.tables),queueCount:R.length,storageColumnCount:Object.keys(Kt(a)).length,storageRuleCount:W.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:he,workflowCount:O.length}),Ve=t?Ae.now():0,ve=tr(a,Z.map(f=>f.id)),We=$s({advisories:qe.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:ee?.procedureProtections??[],agents:c,containers:u,env:D,flagKeys:ws,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:w,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:N,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:he,hasX402:g.x402,maskMetadata:Be,mutators:J,queues:R,rlsMetadata:Ps,schema:a,schemaSnapshot:ve,shapes:q,storageRules:W,studioFeatures:j,useUmbrella:K,workflows:O}),je=Us(q,h.has("@lunora/db"),K),He=qs(u,a.jurisdiction),Ge=Bs(O),Ye=Vs(c),Qe=Ws(R),Xe=js(d),Is=Hs(j.scheduler),Ze=Gs(a.vectorIndexes),te=Ys(a,K),Je=Qs(h.has("@lunora/seed")),se=e.apiSpec??"openapi",xe=se==="openapi"||se==="both",Ee=se==="openrpc"||se==="both",et=Qn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue"),hasGlobal:a.tables.some(f=>zt(f)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>$t(f)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:j.kv,hasNotify:N,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:R.some(f=>f.mode==="push"),hasScheduler:j.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:j.storage,hasVectors:he,hasWorkflow:O.length>0,hasX402:g.x402,identity:C,jurisdiction:a.jurisdiction,tableNames:a.tables.map(f=>f.name),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:xe,wantsOpenRpc:Ee}),tt=vu(e.projectRoot),st=Xn({functions:B,httpRoutes:bs,version:tt}),nt=Jn({functions:B,version:tt}),rt=`${JSON.stringify(st,void 0,2)}
|
|
8
|
+
`,ot=`${JSON.stringify(nt,void 0,2)}
|
|
9
|
+
`,it=Zn(st),at=er(nt),ye=y(n,mu),Ts=P(ye),Se=[];if(!e.dryRun){P(b)||Cs(b,{recursive:!0});const f=(U,V)=>{Oe(y(b,U),V),Se.push(U)},I=(U,V)=>{hu(y(b,U),V),V!==""&&Se.push(U)};f("app.ts",et),f("dataModel.ts",m),f("api.ts",$e),f("server.ts",$),f("functions.ts",Ue),f("shard.ts",We),f("crons.ts",Xe),f("vectors.ts",Ze),f("drizzle.global.ts",te.global),f("drizzle.shard.ts",te.shard),I("containers.ts",He),I("workflows.ts",Ge),I("agents.ts",Ye),I("queues.ts",Qe),I("scheduler.ts",Is),I("seed.ts",Je),I("collections.ts",je),I("openapi.json",xe?rt:""),I("openapi.ts",xe?it:""),I("openrpc.json",Ee?ot:""),I("openrpc.ts",Ee?at:""),(!Ts||e.updateSchemaBaseline===!0)&&Oe(ye,Ds(ve))}if(t){const f=Ae.now(),I=Math.round(f-s),U=Math.round(Ve-s),V=Math.round(f-Ve);console.error(`@lunora/codegen: codegen took ${I.toString()}ms (discovery ${U.toString()}ms, emit ${V.toString()}ms)`)}return{advisories:qe,advisorContext:ee,agents:c,containers:u,cronTriggers:[...new Set([...Xs(d),...F])],generated:{agents:Ye,api:$e,app:et,collections:je,containers:He,crons:Xe,dataModel:m,drizzleGlobal:te.global,drizzleShard:te.shard,functions:Ue,openApi:rt,openApiModule:it,openRpc:ot,openRpcModule:at,queues:Qe,seed:Je,server:$,shard:We,vectors:Ze,workflows:Ge},migrations:Z,outputDirectory:b,platformDiagnostics:v.diagnostics,queues:R,schemaSnapshot:ve,schemaSnapshotPath:ye,workflows:O,writtenFiles:Se}};export{mu as SCHEMA_SNAPSHOT_FILENAME,Nu as createCodegenProject,Eu as findTsconfig,Ed as refreshCodegenProject,yd as runCodegen};
|
|
@@ -813,6 +813,8 @@ ${H(t.hasGlobal)}
|
|
|
813
813
|
* bundled into the worker, and a runtime import in that file ships with it.
|
|
814
814
|
*/
|
|
815
815
|
interface LunoraConfig<Env extends object = object> {
|
|
816
|
+
/** Codegen's static advisor. \`minSeverity\` is the lowest level it reports and writes into \`_generated/shard.ts\`; an \`"error"\` is never dropped, so the gate that fails codegen stays on. A literal, for the same reason as \`target\`. */
|
|
817
|
+
advisor?: { minSeverity?: "error" | "info" | "warn" };
|
|
816
818
|
/** Receives this project's \`defineApp()\` builder and returns it — where a Vite-first app makes the builder calls its generated entry cannot derive. */
|
|
817
819
|
app?: (app: AppBuilder<Env>) => AppBuilder<Env>;
|
|
818
820
|
/** Opt into remote-binding dev without \`--remote\` or \`LUNORA_REMOTE\` on every run. A literal, for the same reason as \`target\`. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.216",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.157",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.138",
|
|
51
51
|
"@lunora/container": "1.0.0-alpha.56",
|
|
52
52
|
"@lunora/errors": "1.0.0-alpha.41",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.38",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as g,statSync as f,readFileSync as d}from"node:fs";import{resolve as m,basename as p}from"node:path";import{createJiti as x}from"jiti";import{Project as E,Node as i}from"ts-morph";const b=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],u=r=>b.map(t=>m(r,t)).find(t=>g(t)),l=new Map,F=async r=>{const t=u(r);if(t===void 0)return{};let e;try{const s=f(t);e=`${String(s.mtimeMs)}:${String(s.size)}`}catch{return{}}const n=l.get(t);if(n?.key===e)return n.value;const o=(async()=>{try{const a=(await x(t,{interopDefault:!1,moduleCache:!1}).import(t))?.default;return{config:a!==null&&typeof a=="object"?a:void 0}}catch(s){return{error:s instanceof Error?s.message:String(s)}}})();return l.set(t,{key:e,value:o}),o},v=r=>{let e=r.getExportAssignments().find(n=>!n.isExportEquals())?.getExpression();for(;e!==void 0&&(i.isSatisfiesExpression(e)||i.isAsExpression(e)||i.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&i.isIdentifier(e))for(e=r.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(i.isSatisfiesExpression(e)||i.isAsExpression(e));)e=e.getExpression();return e!==void 0&&i.isObjectLiteralExpression(e)?e:void 0},y=r=>{const t=r.getNameNode();return i.isStringLiteral(t)?t.getLiteralValue():t.getText()},S=(r,t)=>i.isPropertyAssignment(r)?r.getInitializer():t.getVariableDeclaration(r.getName())?.getInitializer(),h=(r,t)=>{if(i.isGetAccessorDeclaration(r)||i.isMethodDeclaration(r)){const o=r.getName();return o==="target"||o==="remote"?{unreadable:!0}:{}}if(!i.isPropertyAssignment(r)&&!i.isShorthandPropertyAssignment(r))return{};const e=y(r);if(e!=="target"&&e!=="remote")return{};const n=S(r,t);return n===void 0?{unreadable:!0}:e==="target"?i.isStringLiteral(n)?{target:n.getLiteralValue()}:{unreadable:!0}:i.isTrueLiteral(n)||i.isFalseLiteral(n)?{remote:n.getLiteralValue()}:i.isObjectLiteralExpression(n)?{remote:!0}:{unreadable:!0}},N=r=>{const t=u(r);if(t===void 0)return{};let e;try{e=d(t,"utf8")}catch{return{unreadable:!0}}const o=new E({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(p(t),e,{overwrite:!0}),s=v(o);if(s===void 0)return{unreadable:!0};if(s.getProperties().some(c=>i.isSpreadAssignment(c)))return{unreadable:!0};let a={};for(const c of s.getProperties())a={...a,...h(c,o)};return a};export{b as PROJECT_CONFIG_FILENAMES,u as findProjectConfigFile,F as loadProjectConfig,N as readProjectConfigLiterals};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{existsSync as P,mkdirSync as ws,readFileSync as kt,writeFileSync as Ts,rmSync as Cs}from"node:fs";import{join as S,dirname as ne}from"node:path";import{performance as Ae}from"node:perf_hooks";import{runAdvisor as Fs}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as Os,Project as ct}from"ts-morph";import{serializeSchemaSnapshot as Rs}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Ls}from"./formatAdvisories-DwmUKYuc.mjs";import{s as Ds}from"./paths-C-9fwEgQ.mjs";import{C as re,o as Mt,j as ks,f as Ms,k as Ks,b as _s,c as zs,m as $s,e as Us,p as qs,d as Bs,i as Vs,l as Ws,g as js,q as Hs,n as Gs,a as Ys,h as Qs}from"./emit-akFzQrlf.mjs";import{isD1GlobalTable as Kt,isHyperdriveGlobalTable as _t}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Xs}from"./AGENTS_FILENAME-DPIMTD_h.mjs";import{discoverContainers as Zs}from"./CONTAINERS_FILENAME-wDZs0S4p.mjs";import Js from"./discoverCrons-B2GXsB-m.mjs";import{diagnosticAt as ue}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as de}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,unwrapExpression as G,listSecurityScanFiles as Re,objectLiteralFromCallbackBody as zt,propertyInitializer as A,lunoraRelativePath as v,collectCallRows as T,collectSecurityCallRows as en,limitNameOf as $t,optionsObjectLiteral as Ut,isContextIdentifier as Ie,handlerOf as tn,isDatabaseAccessor as M,readTargetOf as qt,enclosingExportName as sn}from"./listLunoraSourceFiles-DsxeRYvh.mjs";import nn from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as rn}from"./QUEUES_FILENAME-Dd781zOQ.mjs";import{discoverSandboxUsage as on}from"./discoverSandboxUsage-pJ42YuvL.mjs";import an from"./discoverStorageRulesMetadata-BFiKUo5m.mjs";import{a as y,c as K,d as Bt,e as cn}from"./classify-procedure-call-RjsZg8AH.mjs";import{discoverWorkflows as ln}from"./WORKFLOWS_FILENAME-v3AJcUjy.mjs";import{gatePlatformFeatures as un,resolveCodegenTarget as dn,readTargetDiagnostics as fn}from"./DEFAULT_TARGET-DtzlGawL.mjs";import{i as L,a as z,e as E,r as gn,b as pn,s as fe,c as mn,f as hn,d as xn}from"./queries-TZaLWhWq.mjs";import{r as ge,s as vn}from"./parse-validator-DW5RNi_6.mjs";import En from"./discoverAuthApiCalls-EHm1O8uG.mjs";import{i as Sn,a as yn,e as An,b as Nn,d as bn,c as Pn}from"./unwrap-handler-return-BEdusskg.mjs";import In from"./discoverFunctions-7IsdPbJJ.mjs";import wn from"./discoverHttpRoutes-HeBP7vhK.mjs";import Tn from"./discoverHyperdriveCalls-CzRlqv_N.mjs";import Cn from"./discoverInserts-BP0Gl37o.mjs";import{m as Le,a as ie,s as Vt,d as Fn}from"./index-D6xfnMEE.mjs";import{e as Wt}from"./exported-procedure-chains-CjlBrFjo.mjs";import On from"./discoverMigrations-BX86Fv9G.mjs";import{MUTATORS_FILENAME as Rn,isDefineMutatorCallee as Ln,discoverMutators as Dn}from"./MUTATORS_FILENAME-CE7K7DfT.mjs";import kn from"./discoverNondeterministicCalls-CJYIXWPw.mjs";import{discoverNotifyConfig as Mn,discoverNotifyCalls as Kn}from"./NOTIFY_FILENAME-DbuOgja2.mjs";import _n from"./discoverR2sqlCalls-emIgm3TF.mjs";import zn from"./discoverRlsProcedures-CU7YMR3P.mjs";import $n from"./discoverRlsMetadata-3Gs8U3ng.mjs";import Un from"./discoverSchema-ClYGs0dx.mjs";import{secretKindOf as qn,redact as Bn,isHeuristicSecretKind as Vn,isSecretishName as Wn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as jn}from"./SHAPES_FILENAME-BtuI2r7-.mjs";import{emitApp as Hn}from"./emitApp-DHEB4XFE.mjs";import{buildOpenApiDocument as Gn,emitOpenApiModule as Yn}from"./buildOpenApiDocument-sc25Dacj.mjs";import{buildOpenRpcDocument as Qn,emitOpenRpcModule as Xn}from"./OPENRPC_VERSION-ClwB3jCx.mjs";import{buildSchemaSnapshot as Zn}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const lt=(e,t="api")=>{const s=new Map;for(const n of e){const o=Ds(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new k("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Jn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>Kt(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=>_t(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`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:re)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},er=(e,t,s={})=>{if(t===void 0)return;const n=Jn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
2
|
-
`);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
-
${o}
|
|
4
|
-
|
|
5
|
-
Install them with your package manager, then re-run codegen.`)},tr="env.ts",sr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},nr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},rr=e=>{if(i.isIdentifier(e))return sr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&nr(t)}return!1},or=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!rr(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ue(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},ir=(e,t)=>{const s=S(t,tr);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=or(n);if(o.length!==0){if(o.length>1)throw ue(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},ut="ctx",jt=e=>{const t=new Set,s=new Set([ut]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==ut)continue;const a=r.getNameNode();i.isIdentifier(a)?s.add(a.getText()):n(a)}const o=r=>i.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))o(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&o(a)&&n(r.getNameNode())}return t},ar=(e,t)=>{const s=Object.fromEntries(re.map(n=>[n.key,!1]));for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=jt(o);for(const c of re)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(re.every(c=>s[c.key]))break}return s},Ht="identity.ts",cr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},lr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},ur=e=>{if(i.isIdentifier(e))return cr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&lr(t)}return!1},dr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!ur(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ue(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},fr=(e,t)=>{const s=S(t,Ht);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=dr(n);if(o.length!==0){if(o.length>1)throw ue(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},gr=(e,t)=>{const s=G(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return G(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},pr=e=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!i.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||G(s)?.getText()!=="false"}),mr=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=jt(o).has("secrets")),s.durableStreams||(s.durableStreams=o.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(i.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>pr(gr(o,u)))})),s.durableStreams&&s.secrets)break}return s},hr="createWorker",xr="extend",dt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,ft=e=>{const t=[],s=dt(A(e,"backupCron"));s!==void 0&&t.push(s);const n=A(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)&&!i.isMethodDeclaration(o))continue;const r=dt(o.getNameNode());r!==void 0&&t.push(r)}return t},vr=e=>{const t=y(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===hr)return i.isObjectLiteralExpression(s)?ft(s):[];if(t!==xr||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=zt(s.getBody());return n===void 0?[]:ft(n)},Er=(e,t)=>{const s=[];for(const{filePath:n}of Re(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...vr(r))}return[...new Set(s)]},Gt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Gt(e.inner)},Sr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=Gt(n);return o!==void 0&&t.has(o)}))},yr=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=o.get(r.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Ar=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=fr(s,t),a=ir(s,t),c=ln(s,t),u=rn(s,t),d=Xs(s,t);yr(c,d);const m=Zs(s,t),h=an(s,t),F=Js(s,t,c,d),D=Er(s,t),g=mr(s,t),I=on(s,t),N=ar(s,t);N.browser=N.browser||I.usesSandboxBrowser;const C=un(N,dn(n,e.target),{agents:d.length>0,commitOrderedTables:o.tables.some(b=>b.commitOrdered===!0),cronTriggers:F.length>0,crossShardFanout:o.tables.some(b=>typeof b.shardMode=="object"),durableStreams:g.durableStreams,globalTables:o.tables.some(b=>b.shardMode==="global"),queues:u.length>0,relationGraph:Sr(o),secrets:g.secrets,vectorStore:o.vectorIndexes.length>0}),x=C.usage,R=C.signals.vectorStore!==!1,$=nn(n),W=$??new Set,X=W.has("lunorash");er(o,$,{hasVectors:R,scheduler:x.scheduler||F.length>0,storage:x.storage||h.rules.length>0||Object.keys(Mt(o)).length>0,usage:x});const _=P(S(t,"flags.ts")),O=P(S(t,"notify.ts"));return{agents:d,containers:m,crons:F,dataModelContent:Ms(o),declaredDependencies:$,dependencies:W,entryCronTriggers:D,env:a,featureUsage:x,hasFlags:_,hasNotify:O,identity:r,platformGate:{...C,diagnostics:[...fn(n,e.target),...C.diagnostics]},queues:u,serverContent:ks({agents:d,containers:m,env:a,hasAccessFacade:x.access,hasAi:x.ai,hasAnalytics:x.analytics,hasBrowser:x.browser,hasVectors:R,hasFlags:_,hasHyperdrive:x.hyperdrive,hasImages:x.images,hasKv:x.kv,hasNotify:O,hasPayments:x.payments,hasPipelines:x.pipelines,hasR2sql:x.r2sql,hasX402:x.x402,identity:r,queues:u,schema:o,storageRuleBuckets:h.rules.map(b=>b.bucket),useUmbrella:X,workflows:c}),storageRulesMetadata:h,usesSandbox:I.usesSandboxBrowser||I.usesSandboxContainer||I.usesSandboxFs,useUmbrella:X,workflows:c}},Yt=new Set(["delete","get","head","options","patch","post","put"]),Nr=new Set(["handler","stream"]),br=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,gt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Pr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Yt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Ir=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||Yt.has(n.getName()))break;s=n.getExpression()}return Pr(s)},wr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(gt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&>.has(s.getText()))return!0}return!1},Tr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Nr.has(n.getName()))return;const o=Ir(s);if(!o||!br.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&wr(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Cr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Tr(o,t);r&&s.push(r)}return s},Fr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Cr(o,v(t,n)))}return s},Or=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Rr=(e,t)=>{if(!Or(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)||z(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},Lr=(e,t)=>T(e,t,Rr),Dr=new Set(["generateText","streamText"]),kr=new Set(["messages","prompt","system"]),Mr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Kr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of Mr)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},_r=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Kr(t);if(s!==void 0)return s}},zr=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},$r=e=>{if(gn(e))return!0;const t=zr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Ur=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!kr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&$r(s))return!0}return!1},qr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());if(o===void 0||!Dr.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(y(c.getExpression())==="tool"&&(a=_r(c),a!==void 0))break;a!==void 0&&s.push({exportName:E(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Ur(r)})}return s},Br=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...qr(o,v(t,n)))}return s},Vr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Wr=(e,t)=>{if(!Vr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},jr=(e,t)=>T(e,t,Wr),De=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=ge(s.getExpression());return n===void 0||De(n,t)})}finally{t.delete(e)}},Hr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),o=n===void 0?void 0:ge(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:De(o)}},Gr=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&i.isExpression(r)?ge(r):void 0;a===void 0?s=!0:(t.push(a),s||=De(a))}n=o.getExpression()}return{objects:t,opaque:s}},ke=(e,t)=>t?Gr(t):Hr(e),Qt=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=ge(s.getExpression());return n===void 0?[]:Qt(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[s.getName()]:[]})}finally{t.delete(e)}},Yr=e=>e.flatMap(t=>Qt(t,new Set)),Qr=new Set(["check","length","max"]),we=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Xr=e=>[e,...e.getDescendants()].filter(t=>we(t)!==void 0),Zr=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(Qr.has(s.getName()))return!0;t=n}},Jr=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=Xr(r),c=o.getName();a.some(u=>we(u)==="any")?t.push(c):a.some(u=>we(u)==="string"&&!Zr(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},eo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=K(s);if(n?.visibility!=="public")return;const{objects:o}=ke(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=Jr(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},to=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=eo(o,t);r&&s.push(r)}return s},so=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...to(o,v(t,n)))}return s},Ne=e=>e?.getKind()===l.TrueKeyword,no=e=>e?.getKind()===l.FalseKeyword,ro=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,oo=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),io=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&y(t.getExpression())==="scim"),ao=e=>e!==void 0&&i.isCallExpression(e)&&oo.has(y(e.getExpression())??""),co=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),lo=e=>{const t=A(e,"advanced"),s=A(e,"emailAndPassword"),n=A(e,"session");return{analyzable:!0,disableCsrfCheck:Ne(A(t,"disableCSRFCheck")),emailPasswordEnabled:Ne(A(s,"enabled")),requireEmailVerification:Ne(A(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:io(A(e,"plugins"))&&ao(A(e,"database")),secureCookiesDisabled:no(A(t,"useSecureCookies")),sessionFreshAgeZero:ro(A(n,"freshAge")),trustedOriginsWildcard:co(A(e,"trustedOrigins"))}},uo=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),fo=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?lo(s):uo();return{exportName:E(e),file:t,line:e.getStartLineNumber(),...o}},go=(e,t)=>en(e,t,fo),po=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},mo=(e,t,s)=>{const n=po(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!L(o)||z(o))&&!(s.requireUnmodifiedReach===!0&&!pn(o)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:n}},ho=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=mo(o,t,s);r&&n.push(r)}return n},pe=(e,t,s)=>{const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...ho(r,v(t,o),s))}return n},xo=new Set(["content","pdf","scrape","screenshot"]),vo=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:xo}),Eo=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),So=new Set(["RateLimiter"]),yo=new Set(["extend"]),pt="lunora",Ao=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Xt=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Te=e=>e&&i.isObjectLiteralExpression(e)?Xt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},No=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&zt(t.getBody());return s?Xt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},bo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());o!==void 0&&(Eo.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])}):yo.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...No(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=y(n.getExpression());o===void 0||!So.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])})}return s},Po=(e,t)=>{for(const s of Ao){const n=S(t,s);if(!P(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))y(a.getExpression())===pt&&r.push({callee:pt,file:s,line:a.getStartLineNumber(),...Te(a.getArguments()[0])});return r}return[]},Io=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Re(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...bo(r,n))}return s.push(...Po(e,ne(t))),s},mt="ctx.containers.",wo=e=>{if(!e.startsWith(mt))return!1;const t=e.slice(mt.length);return t.length>0&&!t.includes(".")},To=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:wo,methods:new Set(["get"])}),Co=new Set(["allow","deny","setAllowed"]),Fo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Oo=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Fo(e)))return{detail:"enableInternet: true",exportName:E(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Ro=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!Co.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:E(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Lo=(e,t)=>Oo(e,t)??Ro(e,t),Do=(e,t)=>T(e,t,Lo),ko=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Mo=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return ko.has(s)?s:void 0},Ko=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},_o=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Re(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Mo(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?Ko(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},zo=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),$o=new Set(["dbRateLimit","rateLimit"]),Uo=e=>{const t=Ut(e);if(!t)return!1;const s=t.getProperty("failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},qo=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=zo.get(s);if(n!==void 0)return{callee:s,exportName:E(e),failOpen:Uo(e.getArguments()[n]),file:t,limitName:$o.has(s)?$t(e):"",line:e.getStartLineNumber()}},Bo=(e,t)=>T(e,t,qo),Vo=new Set(["boolean","number","object","string"]),Wo=e=>{const t=e.getName();if(!Vo.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Ie(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Ie(n.getExpression()))return t},jo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=Wo(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const o=n.getLiteralValue();return o.length>0?{key:o,type:s}:void 0},Ho=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=jo(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,o])=>({key:n,type:o})).toSorted((n,o)=>n.key.localeCompare(o.key))},Go=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=K(t);if(s?.kind!=="query")return;const n=tn(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},ht=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Yo=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=ht(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=ht(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},Qo=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=Yo(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},Xo=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Go(o);r&&s.push(...Qo(r,t))}return s},Zo=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xo(o,v(t,n)))}return s},Jo=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Ie(t.getExpression())},ei=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},ti=(e,t)=>{if(!Jo(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=ei(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:E(e),file:t,key:o,line:e.getStartLineNumber()}},si=(e,t)=>T(e,t,ti),ni=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 o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||Sn(r))return;const a=e.getSourceFile().getFilePath();if(yn(o,e,a)){const c=An(o,e,a,0,new Set);return c===void 0&&Nn(r),c}return r},ri=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},oi=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},ii=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))ri(a)&&s.push({file:r,indexName:oi(a),line:a.getStartLineNumber()})}return s},Y=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Zt=e=>{const t=e.getArguments()[0],s=Y(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&i.isPropertyAssignment(n)?Y(n.getInitializer()):void 0},ai=new Set(["delete","get","head","options","patch","post","put"]),ci=new Set(["handler","stream"]),li=new Set(["runAction","runMutation"]),ui=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,Jt=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if((s.getPropertyNameNode()?.getText()??s.getNameNode().getText())===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},xt=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:Jt(s,"ctx")},vt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:Jt(s,"request")},Et=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(li.has(a)&&Q(c,t))return a;if(ui.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},St=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Q(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!Q(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},di=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,fi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Q(n.getExpression(),t)},gi=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],es=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:gi(s)},pi=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const o=n.getParent();if(!i.isCallExpression(o))return[];const r=o.getExpression();if(!i.isPropertyAccessExpression(r))return[];const a=r.getExpression();return i.isIdentifier(a)?es(t,a.getText()):[]}return[]},mi=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=es(s,t.getText());return n.length>0?n:pi(t,s)},yt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(o=>fi(o,t)&&mi(o).some(r=>di.test(r)))},hi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ci.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(ai.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},xi=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=Y(e.getArguments()[0]),u=c&&xt(c,!0);if(!c||u===void 0||yt(c,vt(c,!0)))return;const d=Et(c,u);return d===void 0?void 0:{exportName:E(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:St(c,u),sideEffect:d}}const n=hi(e);if(n===void 0)return;const o=Y(e.getArguments()[0]),r=o&&xt(o,!1);if(!o||r===void 0||yt(o,vt(o,!1)))return;const a=Et(o,r);return a===void 0?void 0:{exportName:E(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:St(o,r),sideEffect:a}},vi=(e,t)=>T(e,t,xi),Ei=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Si=new Set(["append","set"]),ts=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",At=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Ei.has(y(n.getExpression())??"")&&hn(n,t)),yi=(e,t)=>{if(At(e,t))return!0;const s=fe(e);return s!==void 0&&At(s,t)},Ce=(e,t)=>mn(e,t)&&!yi(e,t),Ai=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=fe(e);return t!==void 0&&i.isNewExpression(t)&&y(t.getExpression())==="Headers"},ae=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=fe(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Me=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Ce(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:ts(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Ce(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=ae(n.getExpression());o!==void 0&&Me(o,t,s)}},ss=(e,t)=>{const s=ae(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=ae(n.getInitializer());o!==void 0&&Me(o,"response-init",t)},Ni=(e,t)=>{const s=y(e.getExpression());if(s==="Response")ss(e.getArguments()[1],t);else if(s==="Headers"){const n=ae(e.getArguments()[0]);n!==void 0&&Me(n,"headers-ctor",t)}},bi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){ss(e.getArguments()[1],t);return}if(Si.has(n)&&Ai(o)){const r=e.getArguments()[1];r!==void 0&&Ce(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:ts(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Pi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Ni(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))bi(s,t)},Ii=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Y(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return Pi(n,{exportName:E(e),relativePath:t,requestName:r.getText(),rows:a}),a},wi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Ii(n,t));return s},Ti=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wi(o,v(t,n)))}return s},Ci=new Set(["auth","context.auth","ctx.auth"]),Fi="userId",Oi=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Ri=(e,t)=>{const s=S(t,Ht);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(y(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Oi(r):void 0}},Nt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Ci.has(e.getExpression().getText())?e:void 0},Li=e=>{if(i.isPropertyAccessExpression(e)&&Nt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Nt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Di=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=Li(o);r!==void 0&&n.push({declared:r===Fi||s.has(r),exportName:E(o),file:t,key:r,line:o.getStartLineNumber()})}return n},ki=(e,t)=>{const s=Ri(e,t);if(s===void 0)return[];const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Di(r,v(t,o),s))}return n},Mi=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=A(s,"key");if(!(!n||!L(n)||z(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},Ki=(e,t)=>T(e,t,Mi),_i=new Set(["delete","get","getRaw","getWithMetadata","put"]),zi=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:_i}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},$i=new Set(["queue","send"]),bt=new Set(["bcc","cc","to"]),Ui=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!$i.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},qi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return bt.has(t.getName())&&L(n)&&!z(n)}if(!i.isPropertyAssignment(t)||!bt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&L(s)&&!z(s)}):!1,Bi=(e,t)=>{const s=Ui(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!qi(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},Vi=(e,t)=>T(e,t,Bi),Wi=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,ji=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?Wi(e):!0,ns=(e,t=!1)=>{for(const s of e.getProperties()){if(ji(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||ns(n,!0))return!0}return!1},Hi=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of Wt(n))for(const r of Le(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||ns(a)))return!0}}return!1},Gi=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=ie(n);if(o===void 0||!i.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!i.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=ie(a);c!==void 0&&s.push({column:c,strategy:Vt(a),table:o})}}return s},Yi=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Wt(o))for(const a of Le(r))for(const c of Gi(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Qi=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=ie(r);if(a===void 0||!i.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=ie(u);if(d===void 0)continue;const m=Vt(u);m!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:m,table:a})}}return o},Xi=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?K(s):void 0;return n?.receiver?Le(n.receiver).flatMap(o=>Qi(o,e.getName(),t)):[]},Zi=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Xi(c,r))}return s},Ji=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return M(s)},ea=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},ta=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Ln(s.getExpression())?s:void 0},sa=e=>{const t=ta(e),s=t===void 0?void 0:ea(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>Ji(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},na=e=>e.getVariableDeclarations().flatMap(t=>sa(t)),ra=(e,t)=>{const s=S(t,Rn);if(!P(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return na(n)},oa=new Set(["delete","get","patch"]),ia=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),aa=new Set(["auth","identity","session","user"]),ca=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),la=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!M(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},ua=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},da=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),fa=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,ga=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>da(s.getExpression(),t)&&fa(s.getThenStatement())),pa=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!oa.has(o))continue;const r=n.getExpression();if(!(M(r)||i.isPropertyAccessExpression(r)&&M(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},ma=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},ha=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>ma(s)==="ctx")),xa=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>ca.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),va=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(ia.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&aa.has(t.getName()))return!0}return ha(e)||xa(e)},Ea=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=K(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=Zt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Bt(n.receiver,"use","rls"),a=va(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const m=la(d);if(m===void 0)continue;const h=ua(d);if(h===void 0||c.has(h)||!ga(o,h))continue;const F=pa(o,h);F!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:F,table:m,usesRls:r,visibility:n.visibility}))}return u},Sa=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ea(c,r))}return s},ya=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Aa=new Set(["insert","insertManyUnsafe","patch","replace"]),Na=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Aa.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},ba=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},Pt=(e,t)=>{if(i.isPropertyAccessExpression(e)){const s=e.getExpression();return i.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(i.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return i.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&i.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},Pa=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(i.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let o,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!i.isVariableDeclarationList(c)||c.getDeclarationKind()!==Os.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(o=u,r=d)}return o},Ia=(e,t)=>{if(Pt(e,t))return!0;const s=Pa(e);return s!==void 0&&Pt(s,t)},wa=(e,t,s,n,o)=>{const r=[];for(const a of e.getProperties()){let c,u;if(i.isPropertyAssignment(a)?(c=a.getName(),u=a.getInitializer()):i.isShorthandPropertyAssignment(a)&&(c=a.getName(),u=a.getNameNode()),!(c===void 0||u===void 0||!ya.has(c))&&L(u)&&!z(u)){const d=E(s),m=o(d)===c&&Ia(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...m&&{ownerScoped:!0}})}}return r},Ta=(e,t,s)=>{const n=Na(e.getExpression());if(n===void 0)return[];const o=e.getArguments()[1];return o?ba(o,n).flatMap(r=>wa(r,n,e,t,s)):[]},Ca=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of Ta(o,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Fa=(e,t,s=[],n=[])=>{const o=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of p(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=v(t,a);o.push(...Ca(c,u,d=>r.get(`${u}:${d}`)??{}))}return o},Oa=["providerSubscriptionId","state"],Ra=["providerEventId","processedAt"],It=(e,t)=>t.every(s=>s in e.shape),La=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&It(t,Oa)&&It(s,Ra)},Da=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ka=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Ma=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ka(t.getInitializer()):void 0},Ka=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Da.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?Ma(n):void 0;return{callee:s,exportName:E(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},_a=(e,t)=>T(e,t,Ka),za=new Set(["defineQueue","defineWorkflow"]),$a=new Set(["run","runAction","runMutation","runQuery"]),Ua=new Set(["api","internal"]),qa=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Ba=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},rs=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},os=(e,t)=>e===t||e.startsWith(`${t}.`),is=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},wt=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},as=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>wt(s));return i.isIdentifier(e)&&wt(e)&&t.push(e),t},Va=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Wa=e=>{const t=rs(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ja=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Wa(e),o=new Set,r=a=>is(a).some(c=>n.some(u=>os(c.getText(),u)))?!0:as(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of Va(a))o.add(u)}return{names:o,prefixes:n}},Ha=(e,t)=>is(e).some(s=>t.prefixes.some(n=>os(s.getText(),n)))?!0:as(e).some(s=>t.names.has(s.getText())),Ga=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!Ua.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Ya=(e,t,s)=>{const n=rs(e,0);if(n===void 0)return[];const o=ja(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!$a.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!Ha(u,o))continue;const d=Ga(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:E(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},Qa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=qa(n);if(o===void 0||!za.has(o))continue;const r=Ba(n);r!==void 0&&s.push(...Ya(r,o==="defineQueue"?"queue":"workflow",t))}return s},Xa=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qa(o,v(t,n)))}return s},Tt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Ct=new Set(["account","credential","member","passkey","session","user"]),Za=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Ja=e=>{const s=Za(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Ct.has(s)||Ct.has(n)},ec=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},tc=(e,t)=>{const{objects:s,opaque:n}=ke(e,t);return Yr(s).some(o=>ec(o))?!0:n?void 0:!1},sc=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},nc=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},oe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},rc=e=>{const t=nc(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=sc(t);return{...oe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Tt?{...oe,[Tt[s]]:!0}:oe},oc=e=>{const t={...oe};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=rc(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},ic=new Set(["insert","insertMany","insertManyUnsafe","replace"]),ac=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ic.has(t.getName()))return!1;const s=t.getExpression();if(!M(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:Ja(o.getLiteralText())},cc=new Set(["create","runAfter","runAt","send","sendBatch"]),lc=new Set(["queues","scheduler","workflows"]),uc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!cc.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&lc.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},dc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return M(s)},cs=new Set(["generateObject","generateText","streamObject","streamText"]),fc=e=>{const t=y(e.getExpression());return t!==void 0&&cs.has(t)},gc=e=>{const t=y(e.getExpression());if(t===void 0||!cs.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},pc=new Set(["log","span","trace"]),mc=new Set(["ai"]),hc=new Set(["email","mail"]),xc=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),be=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),vc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Ec=new Set(["every","filter","flatMap","forEach","map","some"]),Sc=new Set(["all","allSettled","race"]),yc=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Ec.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&Sc.has(n))return t},Ac=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(vc.has(t.getKind())){const s=yc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Nc=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},bc=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Pc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!xc.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=bc(n);r&&(t=!0,!Ac(r)&&!Nc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ic=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Ft="lunora-advisor-exempt",wc=/^[\s*/]+/u,Tc=/[\w-]/u,Cc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
|
-
`);for(const n of s.split(`
|
|
7
|
-
`)){const o=n.replace(wc,"");if(!o.startsWith(Ft))continue;const r=o.slice(Ft.length);if(Tc.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Fc=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Oc=(e,t)=>{const s=Fc(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},Rc=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(ac(u)&&(r=!0),uc(u)&&(t=!0),dc(u)&&(o=!0),fc(u)&&(s=!0),gc(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=Pc(e);return{callsMail:be(e,hc),emitsEvent:be(e,pc),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||be(e,mc),throwsBareError:Ic(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},Lc=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=K(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?oc(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Oc(e,s);return{...r?Rc(r):{},...Cc(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:tc(s,n.receiver),kind:n.kind,visibility:n.visibility}},Dc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Lc(o,t);r&&s.push(r)}return s},kc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Dc(o,v(t,n)))}return s},Mc=new Set(["dbRateLimit","rateLimit"]),Kc=e=>i.isArrowFunction(e)?e.getBody():e,_c=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},ls=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},us=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const o=n.getParent();return!(i.isPropertyAccessExpression(o)&&o.getNameNode()===n)})},zc=(e,t)=>L(e)||t!==void 0&&us(e,t).some(s=>ls(s)),$c=(e,t)=>t===void 0?z(e):us(e,t).some(s=>!ls(s)),Uc=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Mc.has(s))return;const n=A(Ut(e.getArguments()[2]),"key");if(!n)return;const o=Kc(n),r=_c(n);if(!(!zc(o,r)||$c(o,r)))return{callee:s,exportName:E(e),file:t,limitName:$t(e),line:e.getStartLineNumber()}},qc=(e,t)=>T(e,t,Uc),Bc=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Vc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Bc.has(t.getName()))return;const s=t.getExpression();if(M(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&M(s.getExpression()))return s.getName()},Wc=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&M(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},jc=e=>{let t=G(e)??e;for(;i.isAwaitExpression(t);)t=G(t.getExpression())??t.getExpression();return t},ds=(e,t=!1)=>{const s=jc(e);if(i.isIdentifier(s)){if(t)return;const n=fe(s);return n===void 0?void 0:ds(n,!0)}if(i.isCallExpression(s))return Vc(s)??Wc(s)},Hc=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},Gc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=K(s);if(n?.kind!=="query")return[];const o=Zt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&cn(n.receiver,"output"),a=n.receiver!==void 0&&Bt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of Hc(o)){const m=ds(d);m===void 0||c.has(m)||(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:m,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},Yc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Gc(c,r))}return s},Qc=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Xc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?K(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=qt(r);if(a===void 0)continue;const c=Qc(A(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},Zc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Xc(c,r))}return s},ce=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ce(e.getLeft()),s=ce(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Jc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ce(t)!==void 0},el=/(?:^|\/)__tests__\//u,tl=/\.(?:spec|test)$/u,sl=e=>el.test(e)||tl.test(e),nl=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},rl=(e,t,s)=>Vn(e)?!sl(s)&&Wn(nl(t)):!0,ol=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(Jc(r))continue;const a=ce(r);if(a===void 0)continue;const c=qn(a);if(c===void 0||!rl(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:Bn(a)}))}return s},il=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ol(o,v(t,n)))}return s},al=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?K(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=qt(r);if(a===void 0)continue;const c=A(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&L(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},cl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...al(c,r))}return s},ll=new Set(["query","unsafe"]),ul=e=>{if(!i.isPropertyAccessExpression(e)||!ll.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},dl=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),fl=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",gl=(e,t)=>{if(!ul(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!dl(s)))return{exportName:fl(e),file:t,line:s.getStartLineNumber()}},pl=(e,t)=>T(e,t,gl),ml=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],hl=e=>{for(const[t,s]of ml)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},xl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=hl(a);c!==void 0&&s.push({file:v(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},vl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),El=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:vl,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Sl=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),yl=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Al=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=yl(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Nl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Sl.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},bl=(e,t)=>{const s=Nl(e.getExpression());if(s!==void 0)return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s.method,...Al(e.getArguments()[s.optionsIndex])}},Pl=(e,t)=>T(e,t,bl),Il=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),wl=(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"}),Tl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||s.getProperty("args")===void 0)return!1}return ke(e,t).opaque},Cl=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=K(a);c!==void 0&&Tl(a,c.receiver)&&s.push(wl(t,r,a.getStartLineNumber()))};for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations())n(r,r.getName());return s},Fl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...Cl(o,v(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},Ol=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),me=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),fs=e=>!e.isAny(),Ke=e=>{const t=e.getType();if(!fs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Ol.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},gs=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},ps={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."},Rl=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.`}),Ll={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},_e=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,m=d===void 0?o:Rl(d),h=c===void 0?m.remediation:`${c} ${m.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${m.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},Dl=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(me(s,t,a)||!gs(r))continue;const c=Ke(r);c!==void 0&&n.push(_e(t,a,c,r.getStartLineNumber(),ps))}return n},kl=(e,t,s)=>{if(me(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ke(o.getExpression());r!==void 0&&n.push(_e(t,"default",r,o.getStartLineNumber(),ps))}return n},Ml=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(me(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!gs(c))continue;const u=Ke(c);u!==void 0&&n.push(_e(t,a,u,r.getStartLineNumber(),Ll))}return n},Kl=(e,t,s)=>[...Dl(e,t,s),...kl(e,t,s),...Ml(e,t,s)],_l=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>me(s,t,n.getName())).filter(n=>{const o=n.getInitializer();return o!==void 0&&i.isCallExpression(o)&&i.isPropertyAccessExpression(o.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),zl=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),$l=(e,t,s)=>{const n=[],o=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=v(t,a);n.push(...Kl(c,u,s)),o.push(..._l(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!fs(a.getType()))&&n.push(zl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Ul=new Set(["when","where"]),Pe=new Set(["definePolicy","defineShape"]),ql=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return Pe.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return Pe.has(o)?o:void 0}const s=t.getText();return Pe.has(s)?s:void 0},Bl=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,ms=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Bl(e))return"empty-object";if(i.isParenthesizedExpression(e))return ms(e.getExpression())}},ze=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Vl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>ze(t)===e),hs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>ze(t)===e),Wl=e=>{const t=Vl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||hs(e).length>0},jl=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>ze(t)===e),Fe=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",Hl=(e,t)=>Fe(e)||Fe(t),Gl=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Ot=e=>!Fe(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),Yl=(e,t,s)=>{const n=Gl.get(e);if(n!==void 0)return Hl(t,s)?n==="positive"?"negative":"positive":Ot(t)||Ot(s)?void 0:n},H=e=>{if(i.isParenthesizedExpression(e))return H(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Yl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=H(e.getLeft()),o=H(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},Rt=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},Ql=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Xl=e=>i.isReturnStatement(e)?e.getExpression()??e:e,Zl=e=>{const t=[];for(const s of hs(e)){const n=H(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of jl(e)){const n=H(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?Rt(s.getThenStatement()):Rt(s.getElseStatement())??Ql(s);o!==void 0&&t.push(Xl(o))}return t},Jl=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},eu=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!Ul.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Wl(a))for(const c of Zl(a)){const u=ms(c);u!==void 0&&o.push({exportName:Jl(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},tu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=ql(n);o!==void 0&&s.push(...eu(n,o,t))}return s},su=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tu(o,v(t,n)))}return s},nu=new Set(["query","upsert","upsertNow"]),ru=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(nu.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},ou=(e,t)=>{const s=ru(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=A(n,"namespace");if(!(!o||!L(o)||z(o)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},iu=(e,t)=>T(e,t,ou),au=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},cu=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},lu=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!au(a))continue;const c=sn(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:cu(a)})}}return s},uu=".lunora-schema.json",Oe=(e,t)=>{P(e)&&kt(e,"utf8")===t||Ts(e,t,"utf8")},du=(e,t)=>{if(t===""){Cs(e,{force:!0});return}Oe(e,t)},fu=e=>{const t=S(e,"package.json");if(P(t))try{const s=JSON.parse(kt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},gu=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},pu=e=>{let t=P(e)?e:ne(e);for(;t&&t!==ne(t);){const s=S(t,"tsconfig.json");if(P(s))return s;t=ne(t)}},Lt=e=>e.replaceAll("\\","/"),mu=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},le=(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)},Dt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,hu=8,xu=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:m}=e,h=()=>Pn(()=>{const N=In(a,o),C=Dn(a,o);return{functions:N,httpRoutes:wn(a,o),mutators:C}});let{erased:F,value:{functions:D,httpRoutes:g,mutators:I}}=h();lt([...D,...I].map(N=>N.filePath)),lt(g.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const C=Ys({agents:t,functions:D,httpRoutes:g,mutators:I,useUmbrella:d,workflows:m}),x=Qs({agents:t,functions:D,migrations:r,mutators:I,shapes:c,useUmbrella:d,usesSandbox:u});if(N>=hu||Dt(a,s,C)&&Dt(a,n,x))return{apiContent:C,erased:F,functions:D,functionsContent:x,httpRoutes:g,mutators:I};le(a,s,C),le(a,n,x),{erased:F,value:{functions:D,httpRoutes:g,mutators:I}}=h()}},vu=e=>{const t=pu(e);return t?new ct({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new ct({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},gd=(e,t)=>{const s=p(t),n=S(t,"schema.ts");P(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>Lt(c))),r=Lt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},pd=e=>{const t=gu(),s=t?Ae.now():0,n=S(e.projectRoot,e.lunoraDirectory??"lunora"),o=S(n,"schema.ts");if(!P(o))throw new k("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??vu(n);vn(ni);const a=Un(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:m,dependencies:h,entryCronTriggers:F,env:D,featureUsage:g,hasFlags:I,hasNotify:N,identity:C,platformGate:x,queues:R,serverContent:$,storageRulesMetadata:W,usesSandbox:X,useUmbrella:_,workflows:O}=Ar({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),b=S(n,"_generated"),xs=S(b,"dataModel.ts"),vs=S(b,"server.ts"),Es=S(b,"api.ts"),Ss=S(b,"functions.ts");le(r,xs,m),le(r,vs,$);const Z=On(r,n),q=jn(r,n),{apiContent:$e,erased:ys,functions:B,functionsContent:Ue,httpRoutes:As,mutators:J}=xu({agents:c,apiPath:Es,generatedFunctionsPath:Ss,lunoraDirectory:n,migrations:Z,project:r,shapes:q,useUmbrella:_,usesSandbox:X,workflows:O}),ee=e.lint===!1?void 0:Ls({adminRoutes:Fr(r,n),aiRawRuns:Lr(r,n),aiToolSideEffects:Br(r,n),argumentDerivedFetches:jr(r,n),argumentValidators:so(r,n),authApiCalls:En(r,n),authConfigs:go(r,n),browserUrlAccesses:vo(r,n),configCalls:Io(r,n),containerKeyAccesses:To(r,n),containerOverrides:Do(r,n),containers:u,exportSinks:_o(r,n),staleMigrationImports:xl(r,n),failOpenGuards:Bo(r,n),flagReads:Zo(r,n),flagSecurityDefaults:si(r,n),geoIndexUsages:ii(r,n),httpActionGuards:vi(r,n),httpHeaderWrites:Ti(r,n),hyperdriveCalls:Tn(r,n),identityClaimReads:ki(r,n),imageDeliveryUrlAccesses:Ki(r,n),inserts:Cn(r,n),kvKeyAccesses:zi(r,n,B),mailRecipientAccesses:Vi(r,n),maskProcedures:Fn(r,n),maskStrategies:Zi(r,n),mutatorWrites:ra(r,n),nondeterministicCalls:kn(r,n),normalizeIdAuthorizations:Sa(r,n),notifyCalls:Kn(r,n),notifyConfig:Mn(r,n),mutators:J,ownerFieldWrites:Fa(r,n,B,J),unrestrictedWhereBranches:su(r,n),paymentWebhooks:_a(r,n),privilegedDispatches:Xa(r,n),procedureProtections:kc(r,n),queries:xn(r,n),queues:R,r2sqlCalls:_n(r,n),ratelimitKeySelectors:qc(r,n),rawRowReturns:Yc(r,n),relationLoads:Zc(r,n),rlsProcedures:zn(r,n),schema:a,secretLiterals:il(r,n),shapes:q,softDeleteReads:cl(r,n),sqlInterpolations:pl(r,n),storageKeyAccesses:El(r,n,B),storageUploads:Pl(r,n),vectorNamespaceAccesses:iu(r,n),workflowCalls:lu(r,n),workflows:O,wranglerVariables:e.wranglerVariables}),qe=ee===void 0?[]:[...Fs(ee,{source:"static"}),...$l(r,n,{byName:new Set([...O,...R,...c,...u].map(f=>f.exportName)),byPath:new Set([...B,...J,...q,...Z].map(f=>`${f.filePath}:${f.exportName}`))}),...Fl(r,n),...bn(ys,n)],Ns=$n(r,n),Be=Yi(r,n);mu(q,Be,Hi(r,n));const bs=I?Ho(r,n):[],he=x.signals.vectorStore!==!1,j=Il(g,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:La(a.tables),queueCount:R.length,storageColumnCount:Object.keys(Mt(a)).length,storageRuleCount:W.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:he,workflowCount:O.length}),Ve=t?Ae.now():0,xe=Zn(a,Z.map(f=>f.id)),We=Ks({advisories:qe.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:ee?.procedureProtections??[],agents:c,containers:u,env:D,flagKeys:bs,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:I,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:N,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:he,hasX402:g.x402,maskMetadata:Be,mutators:J,queues:R,rlsMetadata:Ns,schema:a,schemaSnapshot:xe,shapes:q,storageRules:W,studioFeatures:j,useUmbrella:_,workflows:O}),je=_s(q,h.has("@lunora/db"),_),He=zs(u,a.jurisdiction),Ge=$s(O),Ye=Us(c),Qe=qs(R),Xe=Bs(d),Ps=Vs(j.scheduler),Ze=Ws(a.vectorIndexes),te=js(a,_),Je=Hs(h.has("@lunora/seed")),se=e.apiSpec??"openapi",ve=se==="openapi"||se==="both",Ee=se==="openrpc"||se==="both",et=Hn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue"),hasGlobal:a.tables.some(f=>Kt(f)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>_t(f)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:j.kv,hasNotify:N,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:R.some(f=>f.mode==="push"),hasScheduler:j.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:j.storage,hasVectors:he,hasWorkflow:O.length>0,hasX402:g.x402,identity:C,jurisdiction:a.jurisdiction,tableNames:a.tables.map(f=>f.name),useUmbrella:_,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:ve,wantsOpenRpc:Ee}),tt=fu(e.projectRoot),st=Gn({functions:B,httpRoutes:As,version:tt}),nt=Qn({functions:B,version:tt}),rt=`${JSON.stringify(st,void 0,2)}
|
|
8
|
-
`,ot=`${JSON.stringify(nt,void 0,2)}
|
|
9
|
-
`,it=Yn(st),at=Xn(nt),Se=S(n,uu),Is=P(Se),ye=[];if(!e.dryRun){P(b)||ws(b,{recursive:!0});const f=(U,V)=>{Oe(S(b,U),V),ye.push(U)},w=(U,V)=>{du(S(b,U),V),V!==""&&ye.push(U)};f("app.ts",et),f("dataModel.ts",m),f("api.ts",$e),f("server.ts",$),f("functions.ts",Ue),f("shard.ts",We),f("crons.ts",Xe),f("vectors.ts",Ze),f("drizzle.global.ts",te.global),f("drizzle.shard.ts",te.shard),w("containers.ts",He),w("workflows.ts",Ge),w("agents.ts",Ye),w("queues.ts",Qe),w("scheduler.ts",Ps),w("seed.ts",Je),w("collections.ts",je),w("openapi.json",ve?rt:""),w("openapi.ts",ve?it:""),w("openrpc.json",Ee?ot:""),w("openrpc.ts",Ee?at:""),(!Is||e.updateSchemaBaseline===!0)&&Oe(Se,Rs(xe))}if(t){const f=Ae.now(),w=Math.round(f-s),U=Math.round(Ve-s),V=Math.round(f-Ve);console.error(`@lunora/codegen: codegen took ${w.toString()}ms (discovery ${U.toString()}ms, emit ${V.toString()}ms)`)}return{advisories:qe,advisorContext:ee,agents:c,containers:u,cronTriggers:[...new Set([...Gs(d),...F])],generated:{agents:Ye,api:$e,app:et,collections:je,containers:He,crons:Xe,dataModel:m,drizzleGlobal:te.global,drizzleShard:te.shard,functions:Ue,openApi:rt,openApiModule:it,openRpc:ot,openRpcModule:at,queues:Qe,seed:Je,server:$,shard:We,vectors:Ze,workflows:Ge},migrations:Z,outputDirectory:b,platformDiagnostics:x.diagnostics,queues:R,schemaSnapshot:xe,schemaSnapshotPath:Se,workflows:O,writtenFiles:ye}};export{uu as SCHEMA_SNAPSHOT_FILENAME,vu as createCodegenProject,pu as findTsconfig,gd as refreshCodegenProject,pd as runCodegen};
|